From bacbf97228683524742d55b809de846418c108f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 11:11:06 +0500 Subject: [PATCH 001/215] =?UTF-8?q?PEP-148:=20ChatGPT=20sign-in=20wizard?= =?UTF-8?q?=20=E2=80=94=20the=20page=20checks=20the=20sign-in=20by=20itsel?= =?UTF-8?q?f,=20says=20so=20when=20it=20is=20not=20confirmed=20yet,=20expl?= =?UTF-8?q?ains=20the=20=C2=ABordinary=20chat=C2=BB=20detour;=20an=20extra?= =?UTF-8?q?=20subscription=20is=20not=20shown=20as=20=C2=ABnothing=20conne?= =?UTF-8?q?cted=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- apps/web/app/(app)/p/[key]/page.tsx | 8 +++--- apps/web/components/SubscriptionSetup.tsx | 30 ++++++++++++++++++----- packages/shared/src/i18n/en/merge.ts | 1 - packages/shared/src/i18n/en/settings.ts | 12 ++++++++- packages/shared/src/i18n/kk/merge.ts | 1 - packages/shared/src/i18n/kk/settings.ts | 12 ++++++++- 6 files changed, 50 insertions(+), 14 deletions(-) diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx index 6d3ea3c6..6c7818bb 100644 --- a/apps/web/app/(app)/p/[key]/page.tsx +++ b/apps/web/app/(app)/p/[key]/page.tsx @@ -79,10 +79,10 @@ function EnvLine({ name, r, t }: { name: string; r: Release | null | undefined; ); } -export default async function ProjectPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string; created?: string; tab?: string; epic?: string; weeks?: string; actor?: string; channel?: string; edit?: string; saved?: string }> }) { +export default async function ProjectPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string; created?: string; checked?: string; tab?: string; epic?: string; weeks?: string; actor?: string; channel?: string; edit?: string; saved?: string }> }) { const user = await requireUser(); const { key } = await params; - const { error, created, tab: tabParam, epic: epicParam, weeks, actor, channel, edit, saved } = await searchParams; + const { error, created, checked, tab: tabParam, epic: epicParam, weeks, actor, channel, edit, saved } = await searchParams; const t = await getT(); // PEP-119: «Продакт» sees the board, epics and bugs; the developer's tabs belong to «Инженер». const w = await words(); @@ -520,9 +520,9 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr {mayChoose && (ownLogins.length > 0 || (agentWarning && !connected)) && ( - + )} - {agentWarning && !(mayChoose && (ownLogins.length > 0 || !pool)) && ( + {agentWarning && !(mayChoose && (ownLogins.length > 0 || !pool || !connected)) && (

{t("Агенты не запустятся:")} {t.text(agentWarning)}. {pool ? (superadmin ? {t("Подписки")} → : {t("Смените подписку в «⋯ Настройки проекта → Подписки» или попросите суперадмина проверить её.")}) : null} diff --git a/apps/web/components/SubscriptionSetup.tsx b/apps/web/components/SubscriptionSetup.tsx index 2c386da1..c339319e 100644 --- a/apps/web/components/SubscriptionSetup.tsx +++ b/apps/web/components/SubscriptionSetup.tsx @@ -6,6 +6,7 @@ import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { getT } from "@/lib/i18n"; import { CopyCode } from "@/components/CopyCode"; +import { AutoRefresh } from "@/components/AutoRefresh"; const step = "flex gap-2.5"; const num = "grid size-5.5 shrink-0 place-items-center rounded-full bg-primary/15 text-xs font-semibold text-primary"; @@ -14,14 +15,27 @@ const num = "grid size-5.5 shrink-0 place-items-center rounded-full bg-primary/1 * PEP-82: connecting the owner's own subscription without a terminal, in plain steps, right on * the project page — «Подключить Claude» / «Подключить ChatGPT», then the link and the code. */ -export async function SubscriptionSetup({ projectId, back, logins, shared = false, requested = false, direct = false, failed = [] }: { projectId: number; back: string; logins: OwnLogin[]; shared?: boolean; /** The owner already asked for the factory's subscription. */ requested?: boolean; /** A superadmin switches without a request. */ direct?: boolean; /** PEP-128: earlier sign-ins that did not finish. */ failed?: Array<{ provider: string; timedOut: boolean }> }) { +export async function SubscriptionSetup({ projectId, back, logins, shared = false, requested = false, direct = false, failed = [], checked = false, extra = false }: { projectId: number; back: string; logins: OwnLogin[]; /** PEP-148: the person pressed «проверить» and the sign-in is still not confirmed. */ checked?: boolean; /** PEP-148: the project already works on a subscription — this one is an extra. */ extra?: boolean; shared?: boolean; /** The owner already asked for the factory's subscription. */ requested?: boolean; /** A superadmin switches without a request. */ direct?: boolean; /** PEP-128: earlier sign-ins that did not finish. */ failed?: Array<{ provider: string; timedOut: boolean }> }) { const t = await getT(); if (logins.length) { return (

{logins.map((l) => (
-

{l.provider === "claude" ? t("Подключаем Claude — осталось три шага") : t("Подключаем ChatGPT — осталось три шага")}

+

+ {extra + ? l.provider === "claude" ? t("Добавляем ещё одну подписку Claude") : t("Добавляем ещё одну подписку ChatGPT") + : l.provider === "claude" ? t("Подключаем Claude — осталось три шага") : t("Подключаем ChatGPT — осталось три шага")} +

+ {extra &&

{t("Агенты уже работают на подключённой подписке. Вторая нужна только про запас — если она не нужна, нажмите «Отменить» внизу.")}

} + {/* PEP-148: the page asks ChatGPT itself every few seconds — the person does not have to press anything. */} + {l.provider !== "claude" && } + {l.provider !== "claude" && checked && ( +

+ {t("ChatGPT пока не подтвердил вход.")}{" "} + {t("Проверьте, что на странице ChatGPT вы вставили код и увидели сообщение о выполненном входе. Если после входа открылся обычный чат — вернитесь к шагу 2 и нажмите кнопку ещё раз. Эта страница проверяет сама каждые несколько секунд.")} +

+ )} {l.provider === "claude" && (
1 @@ -69,12 +83,16 @@ export async function SubscriptionSetup({ projectId, back, logins, shared = fals
2
- {t("Откройте страницу ChatGPT, войдите в свой аккаунт и вставьте код.")} + {t("Откройте страницу ChatGPT. Она покажет поле для кода — вставьте код и нажмите «Продолжить».")} + + {t("ChatGPT сначала попросил войти, а потом открыл обычный чат?")}{" "} + {t("Так бывает, если вы не были в нём авторизованы. Поля для кода в чате нет: вернитесь на эту вкладку и нажмите «Открыть страницу ChatGPT» ещё раз — теперь откроется страница с полем для кода.")} + {t("ChatGPT покажет «Предупреждение безопасности» — это обычная осторожность: вход начали вы сами, здесь, поэтому смело нажимайте «Продолжить». Страница Peppa FACTORY останется открытой в соседней вкладке.")} @@ -83,9 +101,9 @@ export async function SubscriptionSetup({ projectId, back, logins, shared = fals
3
- {t("Когда ChatGPT скажет, что вход выполнен, вернитесь на эту вкладку.")} + {t("Когда ChatGPT скажет, что вход выполнен, вернитесь на эту вкладку. Она обновится сама за несколько секунд; если не обновилась — нажмите кнопку.")} {/* PEP-126: ChatGPT refuses the code until this is switched on in the account — say so here. */}
@@ -108,7 +126,7 @@ export async function SubscriptionSetup({ projectId, back, logins, shared = fals )}
- +
))} diff --git a/packages/shared/src/i18n/en/merge.ts b/packages/shared/src/i18n/en/merge.ts index 0536f561..09f1400d 100644 --- a/packages/shared/src/i18n/en/merge.ts +++ b/packages/shared/src/i18n/en/merge.ts @@ -308,7 +308,6 @@ export const merge: Dict = { "Скопируйте этот код": "Copy this code", "— его попросит ChatGPT на следующем шаге.": "— ChatGPT will ask for it in the next step.", "ChatGPT назовёт его «9-значный код, отображаемый в вашем терминале». Терминал вам не нужен: код — вот этот, из Peppa FACTORY.": "ChatGPT will call it the “9-digit code shown in your terminal”. You don't need a terminal: this is the code, from Peppa FACTORY.", - "Откройте страницу ChatGPT, войдите в свой аккаунт и вставьте код.": "Open the ChatGPT page, sign in to your account and paste the code.", "Открыть страницу ChatGPT": "Open ChatGPT page", "ChatGPT покажет «Предупреждение безопасности» — это обычная осторожность: вход начали вы сами, здесь, поэтому смело нажимайте «Продолжить». Страница Peppa FACTORY останется открытой в соседней вкладке.": "ChatGPT will show a “Security warning” — that's just routine caution: you started the sign-in yourself, here, so go ahead and click “Continue”. The Peppa FACTORY page stays open in the neighbouring tab.", "Когда ChatGPT скажет, что вход выполнен, вернитесь на эту вкладку.": "When ChatGPT says you're signed in, come back to this tab.", diff --git a/packages/shared/src/i18n/en/settings.ts b/packages/shared/src/i18n/en/settings.ts index 9d96ba85..23c8c0cf 100644 --- a/packages/shared/src/i18n/en/settings.ts +++ b/packages/shared/src/i18n/en/settings.ts @@ -122,7 +122,6 @@ export const settings: Dict = { "Код от Claude": "Code from Claude", "На той странице введите код": "On that page, enter the code", "и подтвердите вход.": "and confirm the sign-in.", - "Я вошёл — проверить": "I've signed in — check", "Отменить и начать заново": "Cancel and start over", "Подключение подписки": "Connecting a subscription", "Подключите подписку — и агенты начнут работать": "Connect a subscription and the agents get to work", @@ -271,4 +270,15 @@ export const settings: Dict = { Канал: "Channel", "Все каналы": "All channels", Показать: "Show", + "Добавляем ещё одну подписку Claude": "Adding one more Claude subscription", + "Добавляем ещё одну подписку ChatGPT": "Adding one more ChatGPT subscription", + "Агенты уже работают на подключённой подписке. Вторая нужна только про запас — если она не нужна, нажмите «Отменить» внизу.": "Agents already work on the connected subscription. A second one is only a spare — if you don't need it, press “Cancel” below.", + "ChatGPT пока не подтвердил вход.": "ChatGPT has not confirmed the sign-in yet.", + "Проверьте, что на странице ChatGPT вы вставили код и увидели сообщение о выполненном входе. Если после входа открылся обычный чат — вернитесь к шагу 2 и нажмите кнопку ещё раз. Эта страница проверяет сама каждые несколько секунд.": "Check that you pasted the code on the ChatGPT page and saw the message that you are signed in. If an ordinary chat opened after signing in, go back to step 2 and press the button again. This page checks by itself every few seconds.", + "Откройте страницу ChatGPT. Она покажет поле для кода — вставьте код и нажмите «Продолжить».": "Open the ChatGPT page. It shows a field for the code — paste the code and press “Continue”.", + "ChatGPT сначала попросил войти, а потом открыл обычный чат?": "ChatGPT asked you to sign in first and then opened an ordinary chat?", + "Так бывает, если вы не были в нём авторизованы. Поля для кода в чате нет: вернитесь на эту вкладку и нажмите «Открыть страницу ChatGPT» ещё раз — теперь откроется страница с полем для кода.": "This happens when you were not signed in to it. The chat has no field for the code: come back to this tab and press “Open the ChatGPT page” again — now the page with the code field opens.", + "Когда ChatGPT скажет, что вход выполнен, вернитесь на эту вкладку. Она обновится сама за несколько секунд; если не обновилась — нажмите кнопку.": "When ChatGPT says you are signed in, come back to this tab. It refreshes by itself within a few seconds; if it does not, press the button.", + "Готово — проверить вход": "Done — check the sign-in", + "Отменить": "Cancel", }; diff --git a/packages/shared/src/i18n/kk/merge.ts b/packages/shared/src/i18n/kk/merge.ts index 31bd6eb2..329b6690 100644 --- a/packages/shared/src/i18n/kk/merge.ts +++ b/packages/shared/src/i18n/kk/merge.ts @@ -299,7 +299,6 @@ export const merge: Dict = { "Скопируйте этот код": "Осы кодты көшіріп алыңыз", "— его попросит ChatGPT на следующем шаге.": "— келесі қадамда ChatGPT оны сұрайды.", "ChatGPT назовёт его «9-значный код, отображаемый в вашем терминале». Терминал вам не нужен: код — вот этот, из Peppa FACTORY.": "ChatGPT оны «терминалыңызда көрсетілген 9 таңбалы код» деп атайды. Терминал сізге керек емес: код — осы, Peppa FACTORY-дегі.", - "Откройте страницу ChatGPT, войдите в свой аккаунт и вставьте код.": "ChatGPT бетін ашып, аккаунтыңызға кіріңіз де, кодты қойыңыз.", "Открыть страницу ChatGPT": "ChatGPT бетін ашу", "ChatGPT покажет «Предупреждение безопасности» — это обычная осторожность: вход начали вы сами, здесь, поэтому смело нажимайте «Продолжить». Страница Peppa FACTORY останется открытой в соседней вкладке.": "ChatGPT «Қауіпсіздік туралы ескерту» көрсетеді — бұл әдеттегі сақтық: кіруді осында өзіңіз бастадыңыз, сондықтан «Продолжить» (Continue) батырмасын батыл басыңыз. Peppa FACTORY беті көрші қойындыда ашық қалады.", "Когда ChatGPT скажет, что вход выполнен, вернитесь на эту вкладку.": "ChatGPT кіру орындалғанын айтқанда, осы қойындыға оралыңыз.", diff --git a/packages/shared/src/i18n/kk/settings.ts b/packages/shared/src/i18n/kk/settings.ts index 157cc279..3a4d6eb0 100644 --- a/packages/shared/src/i18n/kk/settings.ts +++ b/packages/shared/src/i18n/kk/settings.ts @@ -106,7 +106,6 @@ export const settings: Dict = { "Код от Claude": "Claude берген код", "На той странице введите код": "Сол бетте кодты енгізіңіз", "и подтвердите вход.": "және кіруді растаңыз.", - "Я вошёл — проверить": "Кірдім — тексеру", "Отменить и начать заново": "Бас тартып, қайта бастау", "Подключение подписки": "Жазылымды қосу", "Подключите подписку — и агенты начнут работать": "Жазылымды қосыңыз — агенттер жұмысқа кіріседі", @@ -240,4 +239,15 @@ export const settings: Dict = { "Канал": "Арна", "Все каналы": "Барлық арналар", "Показать": "Көрсету", + "Добавляем ещё одну подписку Claude": "Тағы бір Claude жазылымын қосып жатырмыз", + "Добавляем ещё одну подписку ChatGPT": "Тағы бір ChatGPT жазылымын қосып жатырмыз", + "Агенты уже работают на подключённой подписке. Вторая нужна только про запас — если она не нужна, нажмите «Отменить» внизу.": "Агенттер қосылған жазылыммен жұмыс істеп жатыр. Екіншісі тек қосалқы ретінде керек — қажет болмаса, төмендегі «Болдырмау» түймесін басыңыз.", + "ChatGPT пока не подтвердил вход.": "ChatGPT кіруді әлі растаған жоқ.", + "Проверьте, что на странице ChatGPT вы вставили код и увидели сообщение о выполненном входе. Если после входа открылся обычный чат — вернитесь к шагу 2 и нажмите кнопку ещё раз. Эта страница проверяет сама каждые несколько секунд.": "ChatGPT бетінде кодты қойып, кіру орындалғаны туралы хабарды көргеніңізді тексеріңіз. Кіргеннен кейін қарапайым чат ашылса — 2-қадамға қайтып, түймені тағы бір рет басыңыз. Бұл бет бірнеше секунд сайын өзі тексереді.", + "Откройте страницу ChatGPT. Она покажет поле для кода — вставьте код и нажмите «Продолжить».": "ChatGPT бетін ашыңыз. Онда код өрісі көрсетіледі — кодты қойып, «Продолжить» түймесін басыңыз.", + "ChatGPT сначала попросил войти, а потом открыл обычный чат?": "ChatGPT алдымен кіруді сұрап, содан кейін қарапайым чатты ашты ма?", + "Так бывает, если вы не были в нём авторизованы. Поля для кода в чате нет: вернитесь на эту вкладку и нажмите «Открыть страницу ChatGPT» ещё раз — теперь откроется страница с полем для кода.": "Бұл сіз оған кірмеген кезде болады. Чатта код өрісі жоқ: осы қойындыға қайтып, «ChatGPT бетін ашу» түймесін тағы бір рет басыңыз — енді код өрісі бар бет ашылады.", + "Когда ChatGPT скажет, что вход выполнен, вернитесь на эту вкладку. Она обновится сама за несколько секунд; если не обновилась — нажмите кнопку.": "ChatGPT кіру орындалғанын айтқанда, осы қойындыға қайтыңыз. Ол бірнеше секундта өзі жаңарады; жаңармаса — түймені басыңыз.", + "Готово — проверить вход": "Дайын — кіруді тексеру", + "Отменить": "Болдырмау", }; -- 2.45.2 From 517f65e1ecf7a6366512f790dc83f19cc8524137 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 11:23:25 +0500 Subject: [PATCH 002/215] PEP-157: CI runner takes four jobs at once instead of two Co-Authored-By: Claude Fable 5.2 --- infra/act-runner/config.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/infra/act-runner/config.yaml b/infra/act-runner/config.yaml index 03fe7506..1bb93df3 100644 --- a/infra/act-runner/config.yaml +++ b/infra/act-runner/config.yaml @@ -3,8 +3,8 @@ log: level: info runner: file: .runner - # Mac — и сборка, и стенды: не больше 2 job одновременно на регистрацию. - capacity: 2 + # Mac (24 ядра, 64 ГБ) — и сборка, и стенды. Было 2: при 13 открытых PR очередь проверок росла на часы (PEP-157). + capacity: 4 timeout: 1h fetch_timeout: 5s fetch_interval: 2s -- 2.45.2 From 4c8251d6833ed7cce316ef0c157e05fd4e98a471 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 10:32:49 +0500 Subject: [PATCH 003/215] =?UTF-8?q?PEP-145:=20proposal=20=E2=80=94=20the?= =?UTF-8?q?=20product=20of=20a=20project=20always=20opens=20by=20a=20link?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- .../.openspec.yaml | 2 + .../pep-145-product-link-always/design.md | 22 ++++ .../pep-145-product-link-always/proposal.md | 24 ++++ .../specs/product-link/spec.md | 104 ++++++++++++++++++ .../pep-145-product-link-always/tasks.md | 25 +++++ 5 files changed, 177 insertions(+) create mode 100644 openspec/changes/pep-145-product-link-always/.openspec.yaml create mode 100644 openspec/changes/pep-145-product-link-always/design.md create mode 100644 openspec/changes/pep-145-product-link-always/proposal.md create mode 100644 openspec/changes/pep-145-product-link-always/specs/product-link/spec.md create mode 100644 openspec/changes/pep-145-product-link-always/tasks.md diff --git a/openspec/changes/pep-145-product-link-always/.openspec.yaml b/openspec/changes/pep-145-product-link-always/.openspec.yaml new file mode 100644 index 00000000..90080a92 --- /dev/null +++ b/openspec/changes/pep-145-product-link-always/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-16 diff --git a/openspec/changes/pep-145-product-link-always/design.md b/openspec/changes/pep-145-product-link-always/design.md new file mode 100644 index 00000000..40966c94 --- /dev/null +++ b/openspec/changes/pep-145-product-link-always/design.md @@ -0,0 +1,22 @@ +# Design + +## Context +Выкладку делает workflow проекта (`.gitea/peppa-deploy.sh`), Peppa только записывает отчёты в `releases` (`recordRelease`) и ставит теги `deploy-prod-*` / `deploy-staging-*`. Без `deploy.compose` в `.peppa/project.json` шаг пропускается — отсюда проекты без ссылки. Карточка — `projectProduct` (core/product.ts) + `ProductCard`. + +## Decisions +1. **Заглушка — в шаблоне, без зависимостей.** `template/product/server.mjs` (node:http, `$PORT`, `GET /healthz` → 200, остальное — `index.html`) + `template/product/index.html` + `template/Dockerfile` (`node:22-alpine`). Агент первой задачи заменяет их своим продуктом. Альтернатива (nginx) требует шаблонизации порта — отказ. +2. **`deploy` пишет `provisionProject`, только новому репозиторию** (`repo.empty`): `{compose: "deploy/compose.yml", service: "web", port: 3000, health: "/healthz"}`. Подключаемому существующему репозиторию заглушка (`Dockerfile`, `product/`) не копируется и `deploy` не пишется — его не ломаем; ссылку ему добудет системная задача. +3. **Первая выкладка — тегом.** Bootstrap-коммит пушится до `setupCi` (нет секрета и вебхука), поэтому после успешного `setupCi` Peppa ставит `deploy-staging-<время>` на голову основной ветки (механизм PEP-112). Сбой тега не валит создание проекта. +4. **Системная задача — `productLinkTick`** (runner/product-link.ts, из тика вачдога; `PEPPA_PRODUCT_LINK=off`). Состояние — `settings` `product.link:` `{taskId, at}`. Нужна, когда (а) есть принятые задачи и нет здоровой версии для проверки и ни одна выкладка сейчас не идёт, или (б) последняя завершившаяся выкладка версии для проверки `failed`/`rolled_back`. Не заводится: платформа, открытая прежняя задача (не `done`, не в архиве), прошло меньше суток (`PEPPA_PRODUCT_LINK_HOURS`, 24). Описание — что случилось, причина и хвост журнала последней выкладки, что сделать. Intake — `done` (уже сформулирована). Первой: `reorderTask(top)` + `readyBacklog` ставит её перед багами. Событие `product_link_task`. +5. **«Показывать всем»** — `settings` `product.publish:` `"auto" | "button"`; нет строки = «по кнопке» (как раньше). `provisionProject` ставит `auto`. `autoPublish(db, project)`: режим `auto`, есть здоровая версия для проверки новее рабочей, все её задачи `done` (или задач нет), рабочая не обновляется, для этого коммита ещё не пробовали (`product.published:` = sha) → `deployProd(by: "Peppa FACTORY")`. Зовётся из `recordRelease` (тогда вопрос «Показать всем?» не шлётся) и из тика (задачи приняли позже). Привязки к уровню автономности нет: условие «все задачи приняты» одинаково верно для «Автомата» и «Сам берёт» — отдельная настройка проще и понятнее продакту. +6. **Предложение существующим** — тот же тик: нет строки настройки, есть здоровая версия для проверки, ещё не предлагали (`product.publish.offered:`) → вопрос с кнопками «Показывать сразу» / «Оставить по кнопке»; ответ ловит `onPublishAnswer` (как `onReleaseAnswer`). +7. **Карточка.** `projectProduct` дополняется: `fix` (открытая системная задача: ключ, в работе ли), `broken` (последняя выкладка упала), `preparing` (нет ссылки, но выкладка идёт / есть принятые задачи / есть `fix`), `shot` (последний скриншот «/» превью проекта — их снимает PEP-44 только у превью). Кнопка одна — «Открыть продукт» (рабочая версия, иначе версия для проверки). `productUrls` для Главной — прежний. Карточка-строка на Главной — в `ProgressOverview` (кнопка вместо мелкой плашки, «Готовим ссылку» при `preparing`). +8. **Сообщения.** «Задача принята» (автозакрытие, отложенное «Принять») — строка «Посмотреть: <ссылка продукта>». «Задача готова» уже несёт «👀 Посмотреть» превью (PEP-44). Страница задачи: нет превью (задача принята) → «Посмотреть результат» ведёт на продукт. + +## Risks / Trade-offs +- Тик заведёт задачи сразу 16 проектам после выкатки → это и требуется; у проектов «Ручной» задача ждёт первой в бэклоге. Ограничение — одна на проект в сутки. +- Тесты с принятыми задачами и без выкладок получили бы лишнюю задачу в бэклоге → в общем окружении тестов тик выключен (`PEPPA_PRODUCT_LINK=off`), свой тест включает. +- Скриншот берётся с превью, а не с самой рабочей версии — может отставать на одну задачу; приемлемо. + +## Моки +Docker, Gitea — `mock-docker`, `mock-gitea` (как в `deploy.test.ts`); настоящая первая выкладка нового проекта проверяется координатором после `push-template`. diff --git a/openspec/changes/pep-145-product-link-always/proposal.md b/openspec/changes/pep-145-product-link-always/proposal.md new file mode 100644 index 00000000..03f93e66 --- /dev/null +++ b/openspec/changes/pep-145-product-link-always/proposal.md @@ -0,0 +1,24 @@ +# PEP-145: продукт проекта всегда открывается по ссылке + +## Why +Продакт ставит задачи, агенты их закрывают, а открыть продукт нельзя: на живой системе 16.11 рабочая ссылка есть у 3 проектов из 19. Карточка «Ваш продукт» (PEP-111) честно говорит «проект пока не открывается по ссылке» и отправляет к аналитику — продакт этого делать не должен. Ссылка должна появляться сама, начиная с первого дня проекта. + +## What Changes +- **Новый проект готов к показу сразу.** Шаблон несёт заглушку продукта (страница «Продукт создаётся», отвечает на проверку здоровья), `provisionProject` пишет рабочий `deploy` в `.peppa/project.json` и после подключения проверок просит первую выкладку версии для проверки. +- **Правило агентам** (`template/RULES.md`): задача не готова, пока продукт с её изменениями не открывается по ссылке версии для проверки; выкладку агент настраивает сам; у продукта без сайта — страница продукта. +- **Peppa сама чинит отсутствие ссылки.** Тик вачдога: есть принятые задачи, но нет здоровой версии для проверки, или последняя выкладка упала/откатилась → системная задача «Продукт должен открываться по ссылке» первой в бэклоге (одна открытая на проект, не чаще раза в сутки). +- **«Показывать всем: сам / по кнопке».** В режиме «сам» здоровая версия для проверки, все задачи которой приняты, сама становится рабочей версией. Новым проектам — «сам»; существующим — одно сообщение владельцу с кнопками. +- **Карточка «Ваш продукт»**: крупная «Открыть продукт», когда обновлён, какие задачи вошли, скриншот; без ссылки — «Готовим ссылку на продукт» со ссылкой на системную задачу; упала выкладка — прошлая версия и «чиним». Карточка на Главной; ссылка «Посмотреть» в сообщениях о принятой задаче; на странице задачи «Посмотреть результат» открывает продукт. +- `/help`, AGENTS.md, память. + +## Capabilities + +### New Capabilities +- `product-link`: продукт проекта открывается по ссылке без действий продакта — заглушка с первого дня, системная задача при сбое, показ всем по настройке, карточка «Ваш продукт». + +### Modified Capabilities +- нет (поведение `delivery-pipeline` и `project-provisioning` дополняется новыми требованиями в `product-link`). + +## Impact +- `template/` (заглушка, Dockerfile, RULES.md, AGENTS.md), `packages/runner` (provision, deploy, новый `product-link.ts`, watchdog, autonomy, flow), `packages/core` (product, новый `product-link.ts`), `apps/web` (ProductCard, Главная, страница задачи, настройки проекта, help), переводы en/kk, `docs/glossary.md`. +- Живую базу, docker хоста и существующие репозитории change не трогает: системные задачи существующим проектам заведёт вачдог после выкатки; `push-template` делает координатор. diff --git a/openspec/changes/pep-145-product-link-always/specs/product-link/spec.md b/openspec/changes/pep-145-product-link-always/specs/product-link/spec.md new file mode 100644 index 00000000..732956ff --- /dev/null +++ b/openspec/changes/pep-145-product-link-always/specs/product-link/spec.md @@ -0,0 +1,104 @@ +# Spec Delta + +## Purpose + +Продукт проекта открывается по ссылке без действий продакта: заглушка с первого дня, системная задача при отсутствии или сбое выкладки, показ всем по настройке и карточка «Ваш продукт» с честным статусом. + +## ADDED Requirements + +### Requirement: Новый проект открывается по ссылке с первого дня +Новый проект SHALL создаваться с настроенной выкладкой и заглушкой продукта, а Peppa SHALL сама запросить первую выкладку версии для проверки. Подключаемый существующий репозиторий SHALL оставаться без изменений выкладки. + +#### Scenario: Новый проект получает заглушку и первую выкладку +- **GIVEN** пользователь создаёт новый проект «shop» с ключом «SHP» +- **WHEN** создание проекта завершилось +- **THEN** в `.peppa/project.json` репозитория есть `deploy` с `compose` «deploy/compose.yml» и `health` «/healthz» +- **AND** в репозитории есть `Dockerfile` и страница «Продукт создаётся» +- **AND** на голове основной ветки стоит тег `deploy-staging-…` + +#### Scenario: Существующий репозиторий не получает заглушку +- **GIVEN** репозиторий «legacy» со своим кодом и без `Dockerfile` +- **WHEN** его подключают как существующий +- **THEN** в нём нет заглушки продукта и `deploy` в `.peppa/project.json` +- **AND** теги `deploy-staging-…` не ставятся + +### Requirement: Системная задача при отсутствии ссылки +Peppa SHALL сама заводить задачу «Продукт должен открываться по ссылке» первой в бэклоге, когда у проекта есть принятые задачи и нет здоровой версии для проверки или последняя выкладка упала либо откатилась; не более одной открытой на проект и не чаще раза в сутки. + +#### Scenario: Принятые задачи без выкладки +- **GIVEN** проект с 2 принятыми задачами и без единой выкладки +- **WHEN** проходит тик вачдога +- **THEN** первой в бэклоге стоит задача «Продукт должен открываться по ссылке» +- **AND** диспетчер проекта с автономностью берёт её раньше остальных + +#### Scenario: Упавшая выкладка +- **GIVEN** последняя выкладка версии для проверки упала с причиной «сборка образа не удалась» +- **WHEN** проходит тик вачдога +- **THEN** заведена системная задача, в описании которой есть «сборка образа не удалась» + +#### Scenario: Вторая задача не заводится +- **GIVEN** системная задача проекта уже открыта +- **WHEN** проходит ещё один тик вачдога +- **THEN** в проекте по-прежнему одна такая задача + +#### Scenario: Не чаще раза в сутки +- **GIVEN** системную задачу приняли 2 часа назад, а выкладка снова упала +- **WHEN** проходит тик вачдога +- **THEN** новая системная задача не заведена + +### Requirement: Показ всем без нажатий +У проекта SHALL быть настройка «Показывать всем: сам / по кнопке». В режиме «сам» здоровая версия для проверки, все задачи которой приняты, SHALL становиться рабочей версией без действий пользователя; в режиме «по кнопке» — только по «Показать всем». Новый проект SHALL получать «сам», существующий — оставаться «по кнопке», пока владелец не выберет. + +#### Scenario: Режим «сам» +- **GIVEN** проект в режиме «сам» и задача «SHP-1» принята +- **WHEN** версия для проверки с «SHP-1» стала здоровой +- **THEN** запущено обновление рабочей версии на тот же коммит +- **AND** вопрос «Показать её всем пользователям?» не приходит + +#### Scenario: Режим «по кнопке» +- **GIVEN** проект в режиме «по кнопке» +- **WHEN** версия для проверки стала здоровой +- **THEN** рабочая версия не обновляется +- **AND** приходит вопрос с кнопкой «🚀 Показать всем» + +#### Scenario: Не все задачи приняты +- **GIVEN** проект в режиме «сам», в версии для проверки задача «SHP-2» в ревью +- **WHEN** версия для проверки стала здоровой +- **THEN** рабочая версия не обновляется, пока «SHP-2» не принята + +#### Scenario: Существующему проекту — предложение один раз +- **GIVEN** существующий проект без выбранного режима и со здоровой версией для проверки +- **WHEN** проходят два тика вачдога +- **THEN** владельцу пришло одно сообщение с кнопками «Показывать сразу» и «Оставить по кнопке» + +### Requirement: Карточка «Ваш продукт» с честным статусом +Карточка SHALL показывать кнопку «Открыть продукт», время обновления и вошедшие задачи, когда ссылка есть; без ссылки — «Готовим ссылку на продукт» со ссылкой на системную задачу; при упавшей выкладке — прошлую работающую версию и статус «чиним». Совета «попросите аналитика» в карточке SHALL NOT быть. + +#### Scenario: Ссылка есть +- **GIVEN** здоровая версия для проверки по адресу «shop-staging.telecom.quest» +- **WHEN** продакт открывает страницу проекта +- **THEN** он видит кнопку «Открыть продукт», ведущую на «https://shop-staging.telecom.quest» + +#### Scenario: Ссылки нет +- **GIVEN** проект с принятыми задачами, без выкладок и с системной задачей «SHP-7» +- **WHEN** продакт открывает страницу проекта +- **THEN** он видит «Готовим ссылку на продукт» и ссылку на «SHP-7» +- **AND** не видит слов «попросите аналитика» + +#### Scenario: Выкладка упала, прошлая версия работает +- **GIVEN** прошлая версия для проверки здорова, а последняя выкладка откатилась +- **WHEN** продакт открывает страницу проекта +- **THEN** он видит «Открыть продукт» на прошлую версию и статус «чиним» + +### Requirement: Ссылка на продукт у принятой задачи +Сообщение о принятой задаче и страница принятой задачи в виде «Продакт» SHALL вести на продукт проекта, когда ссылка есть. + +#### Scenario: Сообщение о принятой задаче +- **GIVEN** у проекта есть рабочая версия «https://shop-prod.telecom.quest» +- **WHEN** задача закрывается автоматически после проверок +- **THEN** в сообщении есть строка «Посмотреть: https://shop-prod.telecom.quest» + +#### Scenario: Ссылки нет +- **GIVEN** у проекта нет ни одной здоровой выкладки +- **WHEN** задача закрывается автоматически +- **THEN** в сообщении нет строки «Посмотреть» diff --git a/openspec/changes/pep-145-product-link-always/tasks.md b/openspec/changes/pep-145-product-link-always/tasks.md new file mode 100644 index 00000000..445be6f2 --- /dev/null +++ b/openspec/changes/pep-145-product-link-always/tasks.md @@ -0,0 +1,25 @@ +## 1. Шаблон и новый проект +- [ ] 1.1 Заглушка продукта в `template/` (`product/server.mjs`, `product/index.html`, `Dockerfile`), README заготовки +- [ ] 1.2 `provisionProject`: `deploy` в `.peppa/project.json` новому репозиторию, заглушка не копируется существующему, тег первой выкладки после `setupCi`, режим показа «сам» +- [ ] 1.3 Правило агентам в `template/RULES.md` и `template/AGENTS.md` + +## 2. Ядро +- [ ] 2.1 `core/product-link.ts`: настройка показа, состояние системной задачи, текст задачи +- [ ] 2.2 `core/product.ts`: `fix`, `broken`, `preparing`, `shot` в `projectProduct` + +## 3. Вачдог +- [ ] 3.1 `runner/product-link.ts`: `productLinkTick` (системная задача), `autoPublish`, предложение режима, `onPublishAnswer`; подключить в тик, `recordRelease`, обработчики ответов; `readyBacklog` — системная задача первой +- [ ] 3.2 Ссылка «Посмотреть» в сообщениях о принятой задаче + +## 4. Веб +- [ ] 4.1 `ProductCard`: «Открыть продукт», скриншот, «Готовим ссылку», «чиним»; Главная +- [ ] 4.2 Настройка «Показывать всем» в настройках проекта; «Посмотреть результат» на странице задачи +- [ ] 4.3 `/help` (вид «Продакт»), словарь, переводы en/kk + +## 5. Проверка +- [ ] 5.1 Тест `product-link.test.ts` по сценариям спеки; правки существующих тестов +- [ ] 5.2 Экраны в браузере на копии данных, сверка текстов со словарём +- [ ] 5.3 lint, typecheck, build, тесты зелёные + +## 6. Завершение +- [ ] 6.1 AGENTS.md, память проекта, архив change, PR -- 2.45.2 From 117dc6ea9c1cc8d27e8a70acdb9582ffcfe328af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 10:35:55 +0500 Subject: [PATCH 004/215] =?UTF-8?q?PEP-145:=20product=20placeholder=20in?= =?UTF-8?q?=20the=20template,=20first=20deploy=20of=20a=20new=20project,?= =?UTF-8?q?=20the=20system=20story=20and=20=C2=AB=D0=9F=D0=BE=D0=BA=D0=B0?= =?UTF-8?q?=D0=B7=D1=8B=D0=B2=D0=B0=D1=82=D1=8C=20=D0=B2=D1=81=D0=B5=D0=BC?= =?UTF-8?q?:=20=D1=81=D0=B0=D0=BC=C2=BB=20in=20the=20watchdog?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- packages/core/src/index.ts | 1 + packages/core/src/product-link.ts | 108 +++++++++++++++++++++++ packages/core/src/product.ts | 49 ++++++++++- packages/core/src/progress.ts | 7 +- packages/runner/src/accept-pending.ts | 4 +- packages/runner/src/autonomy.ts | 8 +- packages/runner/src/deploy.ts | 46 +++++++++- packages/runner/src/index.ts | 1 + packages/runner/src/product-link.ts | 122 ++++++++++++++++++++++++++ packages/runner/src/provision.ts | 32 ++++++- packages/runner/src/watchdog.ts | 4 + template/AGENTS.md | 7 ++ template/Dockerfile | 10 +++ template/RULES.md | 14 +++ template/product/index.html | 26 ++++++ template/product/server.mjs | 16 ++++ 16 files changed, 442 insertions(+), 13 deletions(-) create mode 100644 packages/core/src/product-link.ts create mode 100644 packages/runner/src/product-link.ts create mode 100644 template/Dockerfile create mode 100644 template/product/index.html create mode 100644 template/product/server.mjs diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 1d69ab95..d32cfffe 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -32,6 +32,7 @@ export * from "./help-texts.ts"; export * from "./connect-texts.ts"; export * from "./story-product.ts"; export * from "./product.ts"; +export * from "./product-link.ts"; export * from "./story-refine.ts"; export * from "./local-users.ts"; export * from "./new-users.ts"; diff --git a/packages/core/src/product-link.ts b/packages/core/src/product-link.ts new file mode 100644 index 00000000..729fb9f5 --- /dev/null +++ b/packages/core/src/product-link.ts @@ -0,0 +1,108 @@ +// PEP-145: the product of a project always opens by a link. Here: the «Показывать всем» +// setting (auto / by the button), the state of the system story «Продукт должен открываться +// по ссылке» that Peppa files itself, and its text. The watchdog side is runner/product-link.ts. +import { m as tr } from "@peppa/shared/i18n"; +import { tasks, type Db } from "@peppa/db"; +import { eq } from "drizzle-orm"; +import { PeppaError } from "./errors.ts"; +import { deleteSetting, getSetting, setSetting } from "./settings.ts"; + +/** "auto": a healthy version to check whose stories are all accepted goes to everyone by itself. */ +export type PublishMode = "auto" | "button"; +export const PUBLISH_MODES: readonly PublishMode[] = ["auto", "button"]; +/** What a newly created project starts with (existing ones keep «по кнопке» until the owner chooses). */ +export const NEW_PROJECT_PUBLISH: PublishMode = "auto"; + +export const PUBLISH_MODE_RU: Record = { + auto: tr("Сам"), + button: tr("По кнопке"), +}; +export const PUBLISH_MODE_HINT: Record = { + auto: tr("Когда все задачи новой версии приняты, Peppa FACTORY сама показывает её всем пользователям."), + button: tr("Новую версию сначала видите только вы; всем она открывается по кнопке «Показать всем»."), +}; + +/** Options of the one-time offer to an existing project. */ +export const PUBLISH_AUTO_OPTION = tr("Показывать сразу"); +export const PUBLISH_BUTTON_OPTION = tr("Оставить по кнопке"); + +const modeKey = (projectId: number) => `product.publish:${projectId}`; + +/** The chosen mode; null — nobody chose yet (behaves as "button"). */ +export async function getPublishChoice(db: Db, projectId: number): Promise { + const v = await getSetting(db, modeKey(projectId)); + return v === "auto" || v === "button" ? v : null; +} + +export async function getPublishMode(db: Db, projectId: number): Promise { + return (await getPublishChoice(db, projectId)) ?? "button"; +} + +export async function setPublishMode(db: Db, projectId: number, mode: PublishMode): Promise { + if (!PUBLISH_MODES.includes(mode)) throw new PeppaError(tr("Показывать всем: выберите «Сам» или «По кнопке».")); + await setSetting(db, modeKey(projectId), mode); + return mode; +} + +/** The system story Peppa filed last for a project and when. */ +export interface ProductLinkState { + taskId: number; + at: number; +} + +const linkKey = (projectId: number) => `product.link:${projectId}`; + +export const getProductLinkState = (db: Db, projectId: number) => getSetting(db, linkKey(projectId)); + +export async function setProductLinkState(db: Db, projectId: number, state: ProductLinkState | null): Promise { + if (state) await setSetting(db, linkKey(projectId), state); + else await deleteSetting(db, linkKey(projectId)); +} + +/** The open system story of a project (not accepted, not archived), if any. */ +export async function openProductLinkTask(db: Db, projectId: number): Promise<{ id: number; number: number; status: string } | null> { + const state = await getProductLinkState(db, projectId); + if (!state) return null; + const [t] = await db.select({ id: tasks.id, number: tasks.number, status: tasks.status, archivedAt: tasks.archivedAt, projectId: tasks.projectId }).from(tasks).where(eq(tasks.id, state.taskId)); + if (!t || t.projectId !== projectId || t.archivedAt || t.status === "done") return null; + return { id: t.id, number: t.number, status: t.status }; +} + +// glossary-user: название и описание задачи читает владелец проекта +export const PRODUCT_LINK_TITLE = "Продукт должен открываться по ссылке"; + +export interface ProductLinkProblem { + /** Accepted stories of the project. */ + doneStories: number; + /** The last finished update of the version to check, when it did not come up. */ + failed?: { status: string; sha: string; reason: string | null; logTail: string | null; runUrl: string | null } | null; +} + +/** The story text: what happened in plain words, then what the agent has to do. */ +export function productLinkDescription(p: ProductLinkProblem): string { + const what = p.failed + ? // glossary-user: описание задачи читает владелец проекта + `Последнее обновление версии для проверки не запустилось${p.failed.status === "rolled_back" ? " — возвращена прежняя версия" : ""}, поэтому новые изменения нельзя открыть и посмотреть.` + : // glossary-user: описание задачи читает владелец проекта + `В проекте принято задач: ${p.doneStories}, но продукт не открывается по ссылке — посмотреть результат негде.`; + const lines = [ + "## Зачем", + what, + "", + "## Что сделать", + "Продукт открывается по ссылке версии для проверки и показывает результат принятых задач. Вопросов владельцу не задавать: это техническая задача, её заводит сама Peppa FACTORY.", + "", + "## Условия готовности", + "- Обновление версии для проверки проходит, ссылка открывается.", + "- На странице виден продукт; у продукта без сайта — страница продукта: что это, как пользоваться, как проверить.", + "", + "## Для агента", + "- Правила: разделы «Завершение» и «CD: деплой». Нужны `Dockerfile`, `deploy/compose.yml`, `deploy` в `.peppa/project.json`; приложение слушает `$PORT` и отвечает 200 на `GET /healthz`.", + "- Проверь локально: `docker build .`, запуск образа с `PORT=3000`, `curl /healthz`.", + ]; + if (p.failed) { + lines.push(`- Коммит: ${p.failed.sha.slice(0, 12)}; причина: ${p.failed.reason ?? "неизвестна"}${p.failed.runUrl ? `; запуск: ${p.failed.runUrl}` : ""}.`); + if (p.failed.logTail) lines.push("", "### Журнал сбоя", "```", p.failed.logTail.split("\n").slice(-60).join("\n").slice(-4000), "```"); + } + return lines.join("\n"); +} diff --git a/packages/core/src/product.ts b/packages/core/src/product.ts index c8ac1ef6..6242d354 100644 --- a/packages/core/src/product.ts +++ b/packages/core/src/product.ts @@ -1,8 +1,11 @@ // PEP-111: «Ваш продукт» — where the result of the project lives, in words for a product // manager: the working version everyone sees (prod), the version to check (staging), or the // fact that the project is not deployed as a site at all. -import { releases, tasks, type Db } from "@peppa/db"; -import { and, desc, eq, inArray, isNull } from "drizzle-orm"; +import { m as tr } from "@peppa/shared/i18n"; +import { formatTaskKey } from "@peppa/shared"; +import { projects, releases, tasks, type Db } from "@peppa/db"; +import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm"; +import { openProductLinkTask } from "./product-link.ts"; export interface ProductVersion { url: string; @@ -18,21 +21,59 @@ export interface ProjectProduct { check: ProductVersion | null; /** Stories accepted so far (a product without a site still has results). */ doneStories: number; + /** PEP-145: the open system story «Продукт должен открываться по ссылке». */ + fix: { key: string; working: boolean } | null; + /** PEP-145: the last update of the version to check did not come up (the earlier one still runs). */ + broken: boolean; + /** PEP-145: no link yet, but it is on its way — an update is running or the system story is open. */ + preparing: boolean; + /** PEP-145: a screenshot of the first page (taken on a story's version to check, PEP-44). */ + shot: { releaseId: number; n: number } | null; } +/** An update that reported «начато» and nothing since is not «идёт» for ever. */ +const DEPLOYING_MS = 30 * 60_000; + export async function projectProduct(db: Db, projectId: number): Promise { const latest = async (env: "prod" | "staging") => (await db.select().from(releases).where(and(eq(releases.projectId, projectId), eq(releases.env, env), eq(releases.status, "healthy"))).orderBy(desc(releases.id)).limit(1))[0]; const [prod, staging] = [await latest("prod"), await latest("staging")]; const version = (r: NonNullable): ProductVersion | null => (r.host ? { url: `https://${r.host}`, at: r.updatedAt ?? r.createdAt, stories: r.tasks } : null); const done = await db.select({ id: tasks.id }).from(tasks).where(and(eq(tasks.projectId, projectId), eq(tasks.status, "done"), isNull(tasks.archivedAt))); + const live = prod ? version(prod) : null; + const check = staging && (!prod || (staging.id > prod.id && staging.sha !== prod.sha)) ? version(staging) : null; + const recent = await db.select({ status: releases.status, createdAt: releases.createdAt }).from(releases).where(and(eq(releases.projectId, projectId), eq(releases.env, "staging"))).orderBy(desc(releases.id)).limit(5); + const deploying = recent.some((r) => r.status === "deploying" && Date.now() - r.createdAt.getTime() < DEPLOYING_MS); + const lastFinished = recent.find((r) => r.status !== "deploying" && r.status !== "removed"); + const open = await openProductLinkTask(db, projectId); + const [project] = open ? await db.select({ key: projects.key }).from(projects).where(eq(projects.id, projectId)) : []; + const [shot] = await db + .select({ id: releases.id, screenshots: releases.screenshots }) + .from(releases) + .where(and(eq(releases.projectId, projectId), eq(releases.env, "preview"), sql`json_array_length(${releases.screenshots}) > 0`)) + .orderBy(desc(releases.id)) + .limit(1); + const fix = open && project ? { key: formatTaskKey(project.key, open.number), working: open.status !== "backlog" } : null; return { - live: prod ? version(prod) : null, - check: staging && (!prod || (staging.id > prod.id && staging.sha !== prod.sha)) ? version(staging) : null, + live, + check, doneStories: done.length, + fix, + broken: !!lastFinished && (lastFinished.status === "failed" || lastFinished.status === "rolled_back"), + preparing: !live && !check && (deploying || !!fix), + shot: shot ? { releaseId: shot.id, n: Math.max(0, shot.screenshots.findIndex((s) => s.path === "/")) } : null, }; } +/** + * PEP-145: the «Посмотреть» line for a message about an accepted story — the product link, if + * the project has one ("" otherwise). The new version takes a few minutes to come up. + */ +export async function productLookLine(db: Db, projectId: number): Promise { + const product = (await productUrls(db, [projectId])).get(projectId); + return product ? `\n${tr("Посмотреть: {url} — продукт обновится через несколько минут", { url: product.url })}` : ""; +} + /** Product links of several projects at once (the Home page): projectId → URL of the best version. */ export async function productUrls(db: Db, projectIds: number[]): Promise> { const out = new Map(); diff --git a/packages/core/src/progress.ts b/packages/core/src/progress.ts index ded1ec6b..3fb928b2 100644 --- a/packages/core/src/progress.ts +++ b/packages/core/src/progress.ts @@ -2,6 +2,7 @@ // in work right now (agent, tasks.md progress). import { m as tr } from "@peppa/shared/i18n"; import { productUrls } from "./product.ts"; +import { openProductLinkTask } from "./product-link.ts"; import { projects, tasks, users, type Db } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; import { and, asc, eq, inArray, isNull } from "drizzle-orm"; @@ -35,6 +36,8 @@ export interface ProjectProgress { reviewKeys: string[]; /** PEP-111: where the product runs (prod, else the version to check), if it is deployed. */ product: { url: string; live: boolean } | null; + /** PEP-145: no link yet — the key of the system story that makes the product open by a link. */ + productFix: string | null; } export interface ProgressOverview { @@ -59,7 +62,9 @@ export async function progressOverview(db: Db, userId: number): Promise t.projectId === p.id); const agentsOf = own.some((t) => column(t.status) === "inProgress") ? await taskAgentNames(db, p.id) : new Map(); for (const t of own) { diff --git a/packages/runner/src/accept-pending.ts b/packages/runner/src/accept-pending.ts index 17cbb081..f56983f1 100644 --- a/packages/runner/src/accept-pending.ts +++ b/packages/runner/src/accept-pending.ts @@ -1,7 +1,7 @@ // PEP-127: «Принять» remembered over a conflict is carried through by the watchdog — the agent // rebases (flow.ts `deferAccept`), and once the story is back in review with green checks the PR // is merged and the story closed. The PM hears when it closed, or once if it could not be done. -import { answerQuestion, askPm, clearPendingAccept, giteaForBot, listPendingAccepts, listSessions, logEvent, prGate, setPendingAccept, taskPrNumber, type GiteaClient, type PendingAccept, type TaskRef } from "@peppa/core"; +import { answerQuestion, askPm, clearPendingAccept, productLookLine, giteaForBot, listPendingAccepts, listSessions, logEvent, prGate, setPendingAccept, taskPrNumber, type GiteaClient, type PendingAccept, type TaskRef } from "@peppa/core"; import { questions, type Db } from "@peppa/db"; import { m } from "@peppa/shared/i18n"; import { and, eq, isNull } from "drizzle-orm"; @@ -85,7 +85,7 @@ async function finish(db: Db, ref: TaskRef, log: (m: string) => void) { for (const s of await listSessions(db, { taskId: ref.task.id })) if (s.workspacePath && ["done", "failed"].includes(s.status)) await cleanupWorktree(db, s).catch(() => {}); await syncWorkspace(db, ref).catch(() => {}); await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "accept_completed", payload: { pr: ref.task.prUrl } }); - await notifyPm(db, ref.project.id, `accept:done:${ref.task.id}:${ref.task.prUrl ?? "no-pr"}`, m("✅ {key} «{title}» принята и закрыта: агент обновил изменения, проверки пройдены.", { key: ref.key, title: ref.task.title })); + await notifyPm(db, ref.project.id, `accept:done:${ref.task.id}:${ref.task.prUrl ?? "no-pr"}`, `${m("✅ {key} «{title}» принята и закрыта: агент обновил изменения, проверки пройдены.", { key: ref.key, title: ref.task.title })}${await productLookLine(db, ref.project.id)}`); log(`${ref.key}: accepted story merged and closed`); } diff --git a/packages/runner/src/autonomy.ts b/packages/runner/src/autonomy.ts index eb5b75d6..f28aca66 100644 --- a/packages/runner/src/autonomy.ts +++ b/packages/runner/src/autonomy.ts @@ -36,6 +36,8 @@ import { projectAgentWarning, intakePendingTasks, productUrls, + productLookLine, + getProductLinkState, pendingRefinements, } from "@peppa/core"; import { goals, incidents, questions, tasks, type Db } from "@peppa/db"; @@ -156,7 +158,7 @@ async function autoMergeReviews(db: Db, project: Project, a: AutonomySettings, c async function afterMerge(db: Db, ref: TaskRef, a: AutonomySettings, state: MergeState, log: (m: string) => void) { if (a.close === "after_merge") { await closeStory(db, ref, m("✅ Закрыто автоматически: изменения приняты")); - await notifyPm(db, ref.project.id, `auto:closed:${ref.task.id}:${ref.task.prUrl ?? "no-pr"}`, m("🤖 {key} «{title}»: изменения приняты, задача закрыта автоматически.", { key: ref.key, title: ref.task.title })); + await notifyPm(db, ref.project.id, `auto:closed:${ref.task.id}:${ref.task.prUrl ?? "no-pr"}`, `${m("🤖 {key} «{title}»: изменения приняты, задача закрыта автоматически.", { key: ref.key, title: ref.task.title })}${await productLookLine(db, ref.project.id)}`); log(`${ref.key}: closed after merge`); return; } @@ -310,7 +312,9 @@ export async function readyBacklog(db: const ready = list.filter((t) => !blocked.has(t.id) && !refining.has(t.id) && !commented.has(t.id)); // PEP-103: fixing errors comes first — bug stories, then the rest, each in board order. const bugs = await bugTaskIds(db, projectId); - return [...ready.filter((t) => bugs.has(t.id)), ...ready.filter((t) => !bugs.has(t.id))]; + // PEP-145: before everything — the system story that makes the product open by a link. + const link = (await getProductLinkState(db, projectId))?.taskId; + return [...ready.filter((t) => t.id === link), ...ready.filter((t) => t.id !== link && bugs.has(t.id)), ...ready.filter((t) => t.id !== link && !bugs.has(t.id))]; } /** Bug stories of a project: made from a production error (PEP-58) or in the «Стабильность» epic. */ diff --git a/packages/runner/src/deploy.ts b/packages/runner/src/deploy.ts index 34e70b38..3e3fd6b2 100644 --- a/packages/runner/src/deploy.ts +++ b/packages/runner/src/deploy.ts @@ -3,7 +3,7 @@ // here; Peppa keeps the releases, tells the PM, and starts prod by the PM's button — a // `deploy-prod-*` tag at the healthy staging commit (Gitea 1.22 has no workflow_dispatch API). import { m } from "@peppa/shared/i18n"; -import { answerQuestion, askPmProject, deleteSetting, giteaForBot, logEvent, markSecretsRestart, needsLine, openNeeds, PeppaError, projectSecretMasker, queueProductReview, runLink, type GiteaClient, type Project, type Question } from "@peppa/core"; +import { answerQuestion, askPmProject, deleteSetting, getPublishMode, getSetting, setSetting, resolveTask, giteaForBot, logEvent, markSecretsRestart, needsLine, openNeeds, PeppaError, projectSecretMasker, queueProductReview, runLink, type GiteaClient, type Project, type Question } from "@peppa/core"; import { projects, questions, releases, settings, type Db } from "@peppa/db"; import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm"; import { deployPlatform, isPlatform } from "./platform-release.ts"; @@ -134,6 +134,8 @@ async function notifyRelease(db: Db, project: Project, rel: Release) { }); } else if (rel.status === "healthy" && rel.env === "staging") { await expireProdOffers(db, project.id); + // PEP-145: «Показывать всем: сам» — the version goes to everyone without a question. + if (await autoPublish(db, project).catch(() => false)) return; await askPmProject(db, project, { kind: "question", options: [PROD_OPTION], @@ -184,6 +186,48 @@ export async function deployProd(db: Db, project: Project, by: string, client?: return rel!; } +const publishedKey = (projectId: number) => `product.published:${projectId}`; +/** A failed automatic start is tried again not sooner than this. */ +const AUTO_PUBLISH_RETRY_MS = 10 * 60_000; + +/** + * PEP-145: «Показывать всем: сам». The healthy version to check, newer than the working one and + * with every story accepted, becomes the working version without anyone pressing a button. + * Called when a staging deploy turns healthy and from the watchdog (stories accepted later). + * Returns true when the update of the working version was started. + */ +export async function autoPublish(db: Db, project: Project, o: { now?: Date; client?: GiteaClient; log?: (m: string) => void } = {}): Promise { + if (isPlatform(project) || (await getPublishMode(db, project.id)) !== "auto") return false; + const { staging, prod } = await currentReleases(db, project.id); + if (!staging || prod?.sha === staging.sha) return false; + const now = (o.now ?? new Date()).getTime(); + const tried = await getSetting<{ sha: string; at: number; ok: boolean }>(db, publishedKey(project.id)); + if (tried?.sha === staging.sha && (tried.ok || now - tried.at < AUTO_PUBLISH_RETRY_MS)) return false; + const [running] = await db.select({ id: releases.id }).from(releases).where(and(eq(releases.projectId, project.id), eq(releases.env, "prod"), eq(releases.status, "deploying"))).limit(1); + if (running) return false; + // Every story that would reach everyone is accepted: this version and the ones skipped before it. + const since = await db + .select({ tasks: releases.tasks }) + .from(releases) + .where(and(eq(releases.projectId, project.id), eq(releases.env, "staging"), eq(releases.status, "healthy"), prod ? sql`${releases.id} > ${prod.id}` : undefined)); + for (const key of new Set([...since.flatMap((r) => r.tasks), ...staging.tasks])) { + const ref = await resolveTask(db, key, project.key).catch(() => null); + if (ref && ref.project.id === project.id && ref.task.status !== "done" && !ref.task.archivedAt) return false; + } + try { + await deployProd(db, project, "Peppa FACTORY", o.client); + } catch (e) { + await setSetting(db, publishedKey(project.id), { sha: staging.sha, at: now, ok: false }); + o.log?.(`auto publish ${project.key}: ${(e as Error).message}`); + return false; + } + await setSetting(db, publishedKey(project.id), { sha: staging.sha, at: now, ok: true }); + await expireProdOffers(db, project.id, m("(неактуально: Peppa FACTORY сама показывает эту версию всем)")); + await logEvent(db, { projectId: project.id, type: "product_auto_published", payload: { sha: staging.sha, tasks: staging.tasks } }); + o.log?.(`auto publish ${project.key}: ${staging.sha.slice(0, 7)}`); + return true; +} + const REDEPLOY_PREFIX = "product.redeploy:"; /** diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts index 77cc5cfa..64bb5f6d 100644 --- a/packages/runner/src/index.ts +++ b/packages/runner/src/index.ts @@ -20,6 +20,7 @@ export * from "./feedback.ts"; export * from "./triage.ts"; export * from "./ci-feedback.ts"; export * from "./deploy.ts"; +export * from "./product-link.ts"; export * from "./platform-release.ts"; export * from "./platform-build.ts"; export * from "./code.ts"; diff --git a/packages/runner/src/product-link.ts b/packages/runner/src/product-link.ts new file mode 100644 index 00000000..507eafcd --- /dev/null +++ b/packages/runner/src/product-link.ts @@ -0,0 +1,122 @@ +// PEP-145: the product of a project always opens by a link — the watchdog side. Per project +// (not Peppa itself): the system story «Продукт должен открываться по ссылке» when accepted +// stories have nowhere to be seen or the last update of the version to check did not come up; +// «Показывать всем: сам» carried through when stories are accepted after the deploy; and the +// one-time offer of that mode to projects created before it existed. +import { m } from "@peppa/shared/i18n"; +import { + askPmProject, + createTask, + getProductLinkState, + getPublishChoice, + getSetting, + listProjects, + logEvent, + openProductLinkTask, + productLinkDescription, + PRODUCT_LINK_TITLE, + PUBLISH_AUTO_OPTION, + PUBLISH_BUTTON_OPTION, + reorderTask, + setIntakeState, + setProductLinkState, + setPublishMode, + setSetting, + type GiteaClient, + type Project, + type Question, +} from "@peppa/core"; +import { projects, releases, tasks, type Db } from "@peppa/db"; +import { and, desc, eq, isNull } from "drizzle-orm"; +import { autoPublish, currentReleases } from "./deploy.ts"; +import { isPlatform } from "./platform-release.ts"; +import { onAnswer } from "./sessions.ts"; + +export interface ProductLinkTickOptions { + now?: Date; + log?: (m: string) => void; + client?: GiteaClient; +} + +/** A deploy that said «начато» and nothing since does not hold the story back for ever. */ +const DEPLOYING_MS = 30 * 60_000; +const minGapMs = () => Math.max(0, Number(process.env.PEPPA_PRODUCT_LINK_HOURS ?? 24)) * 3_600_000; +const offeredKey = (projectId: number) => `product.publish.offered:${projectId}`; + +export async function productLinkTick(db: Db, o: ProductLinkTickOptions = {}): Promise { + if (process.env.PEPPA_PRODUCT_LINK === "off") return; + const log = o.log ?? (() => {}); + for (const project of await listProjects(db)) { + if (isPlatform(project)) continue; + try { + await ensureProductLinkTask(db, project, o); + await offerPublishMode(db, project); + await autoPublish(db, project, o); + } catch (e) { + log(`product link ${project.key}: ${(e as Error).message}`); + } + } +} + +/** + * Files the system story when the project has accepted stories and no healthy version to check, + * or the last finished update failed or was rolled back. One open story per project, not more + * often than once a day. Returns the new story's key, or null. + */ +export async function ensureProductLinkTask(db: Db, project: Project, o: ProductLinkTickOptions = {}): Promise { + const now = (o.now ?? new Date()).getTime(); + if (await openProductLinkTask(db, project.id)) return null; + const state = await getProductLinkState(db, project.id); + if (state && now - state.at < minGapMs()) return null; + const recent = await db.select().from(releases).where(and(eq(releases.projectId, project.id), eq(releases.env, "staging"))).orderBy(desc(releases.id)).limit(10); + // An update is on its way: its result decides. + if (recent.some((r) => r.status === "deploying" && now - r.createdAt.getTime() < DEPLOYING_MS)) return null; + const last = recent.find((r) => r.status !== "deploying" && r.status !== "removed"); + const failed = last && (last.status === "failed" || last.status === "rolled_back") ? last : null; + const done = await db.select({ id: tasks.id }).from(tasks).where(and(eq(tasks.projectId, project.id), eq(tasks.status, "done"), isNull(tasks.archivedAt))); + const healthy = recent.some((r) => r.status === "healthy") || !!(await currentReleases(db, project.id)).staging; + if (!failed && (healthy || done.length === 0)) return null; + + const description = productLinkDescription({ doneStories: done.length, failed: failed ? { status: failed.status, sha: failed.sha, reason: failed.reason, logTail: failed.logTail, runUrl: failed.runUrl } : null }); + const ref = await createTask(db, { projectId: project.id, title: PRODUCT_LINK_TITLE, description }); + // Already formulated: «продакт» and «аналитик» of the intake skip it. + await setIntakeState(db, ref.task.id, { stage: "done", original: { title: PRODUCT_LINK_TITLE, description }, attempts: 0, note: "заведена Peppa FACTORY: продукт не открывается по ссылке" }); + await reorderTask(db, ref, { to: "top" }); + await setProductLinkState(db, project.id, { taskId: ref.task.id, at: now }); + await logEvent(db, { projectId: project.id, taskId: ref.task.id, type: "product_link_task", payload: { key: ref.key, failed: failed ? { sha: failed.sha, status: failed.status, reason: failed.reason } : null, doneStories: done.length } }); + o.log?.(`product link ${project.key}: filed ${ref.key}${failed ? ` (${failed.status} ${failed.sha.slice(0, 7)})` : " (no version to check)"}`); + return ref.key; +} + +/** + * A project created before «Показывать всем» existed stays «по кнопке»; once it has a version + * to check, its people get one message with two buttons. + */ +export async function offerPublishMode(db: Db, project: Project): Promise { + if ((await getPublishChoice(db, project.id)) || (await getSetting(db, offeredKey(project.id)))) return false; + if (!(await currentReleases(db, project.id)).staging) return false; + const q = await askPmProject(db, project, { + kind: "question", + options: [PUBLISH_AUTO_OPTION, PUBLISH_BUTTON_OPTION], + text: [ + m("💡 {project}: показывать новые версии продукта всем пользователям сразу?", { project: project.name }), + m("Сейчас новую версию сначала видите только вы, а всем она открывается по кнопке «Показать всем». Можно иначе: как только задачи приняты, Peppa FACTORY сама обновляет продукт для всех."), + m("Изменить выбор можно в настройках проекта."), + ].join("\n"), + }); + await setSetting(db, offeredKey(project.id), { questionId: q.id, at: Date.now() }); + return true; +} + +/** The answer to the offer above (`onAnswer` registry). */ +export async function onPublishAnswer(db: Db, q: Question, answer: string): Promise { + if (q.taskId || q.sessionId || !(q.options ?? []).includes(PUBLISH_AUTO_OPTION)) return false; + const a = answer.trim(); + if (a !== PUBLISH_AUTO_OPTION && a !== PUBLISH_BUTTON_OPTION) return false; + const [project] = await db.select().from(projects).where(eq(projects.id, q.projectId)); + if (!project) return false; + await setPublishMode(db, project.id, a === PUBLISH_AUTO_OPTION ? "auto" : "button"); + if (a === PUBLISH_AUTO_OPTION) await autoPublish(db, project).catch(() => false); + return true; +} +onAnswer(onPublishAnswer); diff --git a/packages/runner/src/provision.ts b/packages/runner/src/provision.ts index 16ea824a..ce1898e9 100644 --- a/packages/runner/src/provision.ts +++ b/packages/runner/src/provision.ts @@ -5,7 +5,7 @@ import { m } from "@peppa/shared/i18n"; import { cpSync, existsSync, mkdtempSync, readdirSync, rmSync, writeFileSync, mkdirSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { createProject, NEW_PROJECT_AUTONOMY, ownPool, setAutonomy, setIntakeSettings, setProjectPool, giteaForBot, giteaForUser, isLocalUser, PeppaError, type GiteaClient, type Project, type User } from "@peppa/core"; +import { createProject, NEW_PROJECT_AUTONOMY, NEW_PROJECT_PUBLISH, setPublishMode, logEvent, ownPool, setAutonomy, setIntakeSettings, setProjectPool, giteaForBot, giteaForUser, isLocalUser, PeppaError, type GiteaClient, type Project, type User } from "@peppa/core"; import { projects, type Db } from "@peppa/db"; import { loadEnv } from "@peppa/shared"; import { eq, or } from "drizzle-orm"; @@ -34,6 +34,11 @@ export interface ProvisionOptions { // Template files that stay in the template repo (RULES.md is loaded live by the runner). const TEMPLATE_SKIP = new Set([".git", "RULES.md", "README.md"]); +// PEP-145: the product placeholder («Продукт создаётся») — only for a new, empty repository; +// a connected repository keeps its own code and deploy untouched. +const PLACEHOLDER = new Set(["Dockerfile", "product"]); +/** `deploy` of a new project: the placeholder opens by the link before the first story. */ +export const NEW_PROJECT_DEPLOY = { compose: "deploy/compose.yml", service: "web", port: 3000, health: "/healthz" }; /** * Where a user's new project goes: their namespace (or an org) with their Gitea client; a local @@ -102,6 +107,8 @@ export async function provisionProject(db: Db, o: ProvisionOptions): Promise log(`ci: ${(e as Error).message}`)); + const ci = await setupCi(db, project).then(() => true, (e) => (log(`ci: ${(e as Error).message}`), false)); + // PEP-145: new versions reach everyone without a visit to the settings; the bootstrap commit + // was pushed before the runner and the secret existed, so the first deploy of the version to + // check is asked for with a tag (the PEP-112 mechanism). Best effort: the watchdog and the + // first merged story deploy it anyway. + await setPublishMode(db, project.id, NEW_PROJECT_PUBLISH); + if (ci && firstDeploy) { + log("first deploy"); + try { + const { stdout: head } = await git(dest, "rev-parse", "HEAD"); + const tag = `deploy-staging-${new Date().toISOString().replace(/\D/g, "").slice(0, 17)}`; + await o.gitea.createTag(repo.owner.login, repo.name, tag, head.trim(), "Первая версия для проверки: заглушка продукта"); + await logEvent(db, { projectId: project.id, type: "first_deploy_requested", payload: { tag } }); + } catch (e) { + log(`first deploy: ${(e as Error).message}`); + } + } return project; } catch (e) { rmSync(dest, { recursive: true, force: true }); diff --git a/packages/runner/src/watchdog.ts b/packages/runner/src/watchdog.ts index 651609c8..2ad0be4c 100644 --- a/packages/runner/src/watchdog.ts +++ b/packages/runner/src/watchdog.ts @@ -44,6 +44,7 @@ import { analystChatTick } from "./analyst-chat.ts"; import { productReviewTick } from "./product-review.ts"; import { feedbackTick } from "./feedback.ts"; import { productRedeployTick } from "./deploy.ts"; +import { productLinkTick } from "./product-link.ts"; import { budgetTick } from "./budgets.ts"; import { getWatchdogSettings, idleStopTick, onRunnerCrash, patchWatch, remindTick, restartStalled, restartTick, type WatchdogSettings } from "./recovery.ts"; import { serveRunnerCommands, type RunnerService } from "./runner-service.ts"; @@ -104,6 +105,9 @@ async function tickInner(db: Db, opts: WatchdogOptions): Promise { await storyRefineTick(db, { now: opts.now, log }).catch(failed(db, log, "story refine")); // PEP-127: accepts remembered over a conflict — merge and close once the agent has rebased. await pendingAcceptTick(db, { now: opts.now, log }).catch(failed(db, log, "pending accepts")); + // PEP-145: a project whose product does not open by a link gets a story for that, first in the + // backlog — before the dispatcher looks; «Показывать всем: сам» is carried through. + await productLinkTick(db, { now: opts.now, log }).catch(failed(db, log, "product link")); await autonomyTick(db, { now: opts.now, log }).catch(failed(db, log, "autonomy")); // PEP-110: the analyst answers people in the projects' discussions. await analystChatTick(db, { log }).catch(failed(db, log, "analyst chat")); diff --git a/template/AGENTS.md b/template/AGENTS.md index 3be88e30..108e53b9 100644 --- a/template/AGENTS.md +++ b/template/AGENTS.md @@ -13,3 +13,10 @@ ## Проект + +## Продукт по ссылке + +Продукт проекта всегда открывается по ссылке (`-staging.telecom.quest`). Сейчас там +заглушка из `product/` и `Dockerfile` — первая стори с настоящим продуктом заменяет её своим +приложением (слушает `$PORT`, отвечает 200 на `GET /healthz`). Подробности — общие правила, +разделы «Завершение» и «CD: деплой». diff --git a/template/Dockerfile b/template/Dockerfile new file mode 100644 index 00000000..32b96e17 --- /dev/null +++ b/template/Dockerfile @@ -0,0 +1,10 @@ +# Заглушка продукта (PEP-145): страница «Продукт создаётся» из product/. Проект открывается +# по ссылке с первого дня. Первая задача с настоящим продуктом заменяет этот файл своим +# (заготовки — deploy/Dockerfile.node, deploy/Dockerfile.python): приложение слушает $PORT +# и отвечает 200 на GET /healthz. +FROM node:22-alpine +WORKDIR /app +COPY product/ ./product/ +ENV NODE_ENV=production PORT=3000 +EXPOSE 3000 +CMD ["node", "product/server.mjs"] diff --git a/template/RULES.md b/template/RULES.md index e3fee551..3736d5a1 100644 --- a/template/RULES.md +++ b/template/RULES.md @@ -66,6 +66,14 @@ git, тесты, раннеры — решаешь ты сам и пишешь, `remember` сообщает о пределе — ужми память (`get_memory`, затем `remember` с `replace: true`: объедини похожее, убери устаревшее). Закоммить файл в ветке стори. В сессиях Пеппы память уже в системном промпте (раздел «Память проекта»). +- **Продукт открывается по ссылке (PEP-145).** Стори не готова, пока продукт с её изменениями + не открывается по ссылке версии для проверки (preview PR, после мержа — staging). Проверь + сам: образ собирается, `GET /healthz` отвечает 200, на странице виден результат стори. + Проект ещё не выкладывается (нет `deploy` в `.peppa/project.json`, нет `Dockerfile`, стоит + заглушка «Продукт создаётся») — сначала настрой выкладку (Dockerfile, `deploy/compose.yml`, + health): это часть твоей стори, PM об этом не спрашивай. Продукт без сайта (бот, библиотека, + скрипт) — сделай страницу продукта, которая открывается по той же ссылке: что это, как + пользоваться, как проверить. - `openspec archive <имя>` — delta-специфики вливаются в `openspec/specs/`. - Запушь ветку и открой PR в Gitea (ссылка на стори и резюме change). - `peppa.update_task` → `status: review`, `pr_url: …` и закончи ход. PM получит «готово @@ -122,6 +130,12 @@ git, тесты, раннеры — решаешь ты сам и пишешь, "health": "/healthz", "migrate": "pnpm db:migrate" } } ``` +- Новый проект создаётся с заглушкой: `Dockerfile` + `product/` (страница «Продукт создаётся») + и готовый `deploy` — ссылка работает с первого дня. Первая стори с настоящим продуктом + заменяет заглушку своим приложением (тот же порт и `/healthz`), а не оставляет её рядом. +- Стори «Продукт должен открываться по ссылке» заводит сама Пеппа, когда у проекта нет + здоровой версии для проверки или выкладка упала: причина и хвост журнала — в описании. + Почини причину, доведи до зелёной выкладки; `.gitea/` и проверки не ослабляй. - Приложение слушает `$PORT` и отвечает 200 на `GET /healthz` (`deploy.health`) — без этого деплой считается неудачным и откатывается. - PR получает preview `-pr.telecom.quest`, мерж в main — staging diff --git a/template/product/index.html b/template/product/index.html new file mode 100644 index 00000000..d65b66f9 --- /dev/null +++ b/template/product/index.html @@ -0,0 +1,26 @@ + + + + + + Продукт создаётся + + + +
+

Продукт создаётся

+

Агенты уже работают над первой задачей. Когда она будет готова, результат появится на этой странице — адрес останется тем же.

+

Өнім жасалып жатыр. Бірінші тапсырма дайын болғанда нәтиже осы бетте пайда болады.

+

The product is being built. The result of the first task will appear on this page.

+
+ + diff --git a/template/product/server.mjs b/template/product/server.mjs new file mode 100644 index 00000000..67e22141 --- /dev/null +++ b/template/product/server.mjs @@ -0,0 +1,16 @@ +// Заглушка продукта (PEP-145): пока в проекте нет своего приложения, по ссылке открывается +// страница «Продукт создаётся». Слушает $PORT, отвечает 200 на GET /healthz. Первая задача, +// которая делает настоящий продукт, заменяет этот каталог и Dockerfile своими. +import { createServer } from "node:http"; +import { readFileSync } from "node:fs"; + +const page = readFileSync(new URL("./index.html", import.meta.url)); +const port = Number(process.env.PORT ?? 3000); + +createServer((req, res) => { + if (req.url === "/healthz") { + res.writeHead(200, { "content-type": "text/plain; charset=utf-8" }).end("ok"); + return; + } + res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" }).end(page); +}).listen(port, "0.0.0.0", () => console.log(`product placeholder on :${port}`)); -- 2.45.2 From 81f62c9a69d2a6fd2e2f7325489a4d0a3978167d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 10:39:16 +0500 Subject: [PATCH 005/215] =?UTF-8?q?PEP-145:=20the=20=C2=AB=D0=92=D0=B0?= =?UTF-8?q?=D1=88=20=D0=BF=D1=80=D0=BE=D0=B4=D1=83=D0=BA=D1=82=C2=BB=20car?= =?UTF-8?q?d=20with=20one=20big=20button=20and=20an=20honest=20status,=20?= =?UTF-8?q?=C2=AB=D0=9F=D0=BE=D0=BA=D0=B0=D0=B7=D1=8B=D0=B2=D0=B0=D1=82?= =?UTF-8?q?=D1=8C=20=D0=B2=D1=81=D0=B5=D0=BC=C2=BB=20setting,=20links=20fo?= =?UTF-8?q?r=20accepted=20stories,=20translations,=20tests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- apps/web/app/(app)/actions.ts | 16 +- apps/web/app/(app)/help/page.tsx | 1 + apps/web/app/(app)/p/[key]/page.tsx | 10 +- apps/web/app/(app)/t/[key]/page.tsx | 3 +- apps/web/components/ProductCard.tsx | 84 ++++--- apps/web/components/ProgressOverview.tsx | 12 +- apps/web/components/PublishPanel.tsx | 26 +++ apps/web/components/StoryProduct.tsx | 13 +- packages/core/src/help-texts.ts | 5 + packages/core/src/product.ts | 2 +- packages/shared/src/i18n/en/project.ts | 28 +++ packages/shared/src/i18n/kk/project.ts | 28 +++ packages/testkit/test/helpers.ts | 3 + packages/testkit/test/product-help.test.ts | 2 +- packages/testkit/test/product-link.test.ts | 241 +++++++++++++++++++++ packages/testkit/test/product.test.ts | 2 +- packages/testkit/test/web.test.ts | 19 ++ 17 files changed, 450 insertions(+), 45 deletions(-) create mode 100644 apps/web/components/PublishPanel.tsx create mode 100644 packages/testkit/test/product-link.test.ts diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index 6a3861eb..3def96ff 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -47,6 +47,8 @@ import { setTaskAgentSettings, cleanBudget, logEvent, + setPublishMode, + type PublishMode, setProjectBudget, setTaskBudget, type Budget, @@ -63,7 +65,7 @@ import { import { fixFeedback, linkFeedback, rejectFeedback } from "@peppa/core"; import { bugsinkFromEnv } from "@peppa/bugsink"; import { loadEnv } from "@peppa/shared"; -import { acceptStory, fixStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProjectOnce, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, managesProject, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, removeOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription } from "@peppa/runner"; +import { acceptStory, autoPublish, fixStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProjectOnce, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, managesProject, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, removeOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription } from "@peppa/runner"; import { revalidatePath } from "next/cache"; import { redirect } from "next/navigation"; import { asWebActor, requireUser, words } from "@/lib/auth"; @@ -354,6 +356,18 @@ export async function deployProdAction(f: FormData) { }); } +/** PEP-145: «Показывать всем: сам / по кнопке» (owner or member). */ +export async function setPublishModeAction(f: FormData) { + const user = asWebActor(await requireUser()); + await attempt(f, async () => { + const p = await projectForUser(db, user.id, Number(str(f, "projectId"))); + const mode = await setPublishMode(db, p.id, str(f, "mode") as PublishMode); + await logEvent(db, { projectId: p.id, type: "publish_mode_set", payload: { mode, login: user.login } }); + // «Сам» chosen with an accepted version waiting: it goes to everyone right away. + if (mode === "auto") await autoPublish(db, p).catch(() => false); + }); +} + export async function moveTaskCard(f: FormData) { const user = asWebActor(await requireUser()); await attempt(f, async () => { diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx index 3bf63614..c12d0429 100644 --- a/apps/web/app/(app)/help/page.tsx +++ b/apps/web/app/(app)/help/page.tsx @@ -101,6 +101,7 @@ async function ProductHelp() { ))}

{t.question}

+

{t.product}

{t.problem}{" "} {tr("Ваши обращения")} diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx index 6d3ea3c6..ac962dc3 100644 --- a/apps/web/app/(app)/p/[key]/page.tsx +++ b/apps/web/app/(app)/p/[key]/page.tsx @@ -1,9 +1,10 @@ import { Fragment } from "react"; import { ProductCard } from "@/components/ProductCard"; +import { PublishPanel } from "@/components/PublishPanel"; import { notFound } from "next/navigation"; import { ExternalLink, Plus, Rocket, SquareTerminal } from "lucide-react"; import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, ownPendingLogins, readAgentsMd, repoOverview, type Release, sharedRequest } from "@peppa/runner"; -import { 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, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, taskAgentNames, getIntakeSettings, intakePendingTasks, projectAgentWarning, memoryStats, readMemory, projectPool, sharedPool, ownPool, poolOverview, repoAudience, repoVisibilityLabel } from "@peppa/core"; +import { 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, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, taskAgentNames, getIntakeSettings, intakePendingTasks, projectAgentWarning, memoryStats, readMemory, projectPool, sharedPool, ownPool, poolOverview, repoAudience, repoVisibilityLabel } from "@peppa/core"; import { productNeeds, lastProductReview } from "@peppa/core"; import { LiveRefresh } from "@/components/LiveRefresh"; import { PanelSection } from "@/components/ActivityAside"; @@ -165,6 +166,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr const specs = tab === "specs" ? listSpecs(p) : []; const agentsMd = tab === "agents" ? await readAgentsMd(db, p) : null; const product = await projectProduct(db, p.id); + const publish = await getPublishMode(db, p.id); const [productNeedList, productReview] = await Promise.all([productNeeds(db, p.id), lastProductReview(db, p.id)]); // 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); @@ -222,6 +224,10 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr + + + + {engineer && ( @@ -529,7 +535,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr

)} - {tab === "board" && } + {tab === "board" && } -
- {!master && ( - +
+ {threads && ( +
+ +
)} -
+
+ {!master && ( + + {t("← К списку")} + + )} {current && (
🧵 {t.text(current)} + {openRow?.status && } + {openRow?.agentName && } {taskThread && }
)} @@ -276,23 +287,6 @@ export default async function ChatPage({ params, searchParams }: { params: Promi ); } -async function ThreadLink({ href, active, title, meta, open = 0 }: { href: string; active: boolean; title: string; meta?: string; open?: number }) { - const t = await getT(); - return ( - - - {title} - {open > 0 && {open}} - - {meta && {meta}} - - ); -} - function TaskLink({ messages, label }: { messages: ChatMessageView[]; label: string }) { const key = messages.find((m) => m.threadTitle)?.threadTitle?.split(" · ")[0]; return key ? {label} : null; diff --git a/apps/web/components/ChatThreadList.tsx b/apps/web/components/ChatThreadList.tsx new file mode 100644 index 00000000..9ff610c4 --- /dev/null +++ b/apps/web/components/ChatThreadList.tsx @@ -0,0 +1,162 @@ +import Link from "next/link"; +import { Search, X } from "lucide-react"; +import type { ThreadList, ThreadRow } from "@peppa/core"; +import { AgentBadge } from "@/components/AgentBadge"; +import { ago, StatusBadge } from "@/components/common"; +import { Hidden } from "@/components/cards"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { getT } from "@/lib/i18n"; +import { words } from "@/lib/auth"; +import { cn } from "@/lib/utils"; + +const COUNT = "rounded-full px-1.5 font-mono text-[11px] leading-4 font-semibold tabular-nums"; + +/** + * PEP-155: the conversations of a project chat — the chat with the analyst and the agents' events + * on top, then story threads in groups «Ждут вас», «В работе», «Готово» (folded), with a search. + */ +export async function ChatThreadList({ + base, + list, + active, + discussion, + feed, + raw, +}: { + /** `/chats/` */ + base: string; + list: ThreadList; + /** The open thread's key, if a thread is open. */ + active: string | null; + discussion: boolean; + feed: boolean; + /** The `thread` parameter as it is in the URL: the search keeps the open conversation. */ + raw: string | null; +}) { + const t = await getT(); + const w = await words(); + const q = list.q; + const href = (thread: string | null) => { + const p = new URLSearchParams(); + if (thread) p.set("thread", thread); + if (q) p.set("q", q); + return p.size ? `${base}?${p}` : base; + }; + const total = list.waiting.length + list.working.length + list.done.length; + const rows = (items: ThreadRow[]) => items.map((r) => ); + return ( + + ); +} + +function GroupTitle({ children, count, tone = "bg-muted text-muted-foreground" }: { children: React.ReactNode; count: number; tone?: string }) { + return ( +

+ {children} + {count > 0 && {count}} +

+ ); +} + +function Plain({ href, active, title, meta }: { href: string; active: boolean; title: string; meta: string }) { + return ( + + {title} + {meta} + + ); +} + +async function Row({ r, href, active }: { r: ThreadRow; href: string; active: boolean }) { + const t = await getT(); + const title = r.taskKey ? r.title : t.text(r.title); + return ( + + + {r.taskKey && {r.taskKey}} + 0) && "font-medium")} title={title}> + {title} + + {r.open > 0 && ( + + ? + + )} + {r.unread > 0 && ( + + {r.unread > 99 ? "99+" : r.unread} + + )} + + {(r.status || r.agentName || r.lastAt) && ( + + {r.status && } + {r.agentName && } + {r.lastAt && {ago(r.lastAt, t)}} + + )} + {r.last && ( + + {r.last.mine && t("вы") + ": "} + {r.last.system ? t.text(r.last.text) : r.last.text} + + )} + + ); +} diff --git a/packages/core/src/chat-threads.ts b/packages/core/src/chat-threads.ts new file mode 100644 index 00000000..c5acfc71 --- /dev/null +++ b/packages/core/src/chat-threads.ts @@ -0,0 +1,203 @@ +// PEP-155: the list of a project chat's conversations for a product manager — story threads in +// three groups («Ждут вас», «В работе», «Готово»), each with the story's status, its agent, the +// last message in one plain line, the unread count; and a search over keys, titles and texts. +// Data only: group names and status labels are the web's (lib/status.ts). +import { agents, chatMessages, projects, questions, sessions, tasks, type Db } from "@peppa/db"; +import { formatTaskKey } from "@peppa/shared"; +import { and, asc, desc, eq, inArray, isNotNull, isNull, sql } from "drizzle-orm"; +import { listPendingAccepts } from "./accept-pending.ts"; +import { threadTitle, type Chat } from "./chats.ts"; +import { getSetting, setSetting } from "./settings.ts"; +import { TECHNICAL_TEXT } from "./story-product.ts"; +import type { User } from "./users.ts"; + +export type ThreadGroup = "waiting" | "working" | "done"; + +export interface ThreadRow { + /** Thread key: `task:` (or `release:` / `incident:` with an open question). */ + key: string; + /** "PAY-7"; null — not a story thread. */ + taskKey: string | null; + title: string; + /** Story status; null — not a story thread. */ + status: string | null; + archived: boolean; + /** PEP-127: «Принять» is pressed already, the factory finishes by itself. */ + accepted: boolean; + agentName: string | null; + /** The last message in one plain line (or the found one, when searching); null — nothing readable. */ + last: { text: string; /** Written by the factory itself: a translatable text. */ system: boolean; mine: boolean } | null; + lastAt: Date | null; + unread: number; + /** Open questions that need the person's answer. */ + open: number; + group: ThreadGroup; +} + +export interface ThreadList { + waiting: ThreadRow[]; + working: ThreadRow[]; + done: ThreadRow[]; + /** The search the list is narrowed by; null — the whole list. */ + q: string | null; +} + +/** Question kinds a person has to answer; `attention` is a notice («готово» is the `review` status). */ +const ASKS = ["question", "approval", "permission"] as const; +const ACTIVE = new Set(["proposing", "awaiting_approval", "in_progress", "review", "blocked"]); +const SCAN = 3000; +const SCAN_SEARCH = 20_000; +const LINE = 140; + +/** Which group a story thread belongs to. */ +export function threadGroup(t: { status: string | null; archived?: boolean; accepted?: boolean; open: number }): ThreadGroup { + if (t.open > 0) return "waiting"; + if (t.status === "done" || t.archived) return "done"; + if (t.status === "awaiting_approval" || (t.status === "review" && !t.accepted)) return "waiting"; + return "working"; +} + +const cut = (s: string, n = LINE) => (s.length > n ? `${s.slice(0, n - 1).trimEnd()}…` : s); + +/** + * A message as one line a product manager can read: its first meaningful line without markup; + * null when that line is technical (code, paths, identifiers). + */ +export function plainLine(text: string | null | undefined): string | null { + for (const raw of (text ?? "").split("\n")) { + const line = raw.replace(/^[\s>#*\-•]+/, "").replace(/\*\*|__/g, "").replace(/\s+/g, " ").trim(); + if (line.length < 2) continue; + if (line.includes("`") || TECHNICAL_TEXT.test(line)) return null; + return cut(line); + } + return null; +} + +/** The piece of a message around the found word, in one line. */ +function snippet(text: string, at: number, len: number): string { + const start = Math.max(0, text.lastIndexOf("\n", at) + 1, at - 60); + const s = text.slice(start, Math.max(at + len, start + LINE)).split("\n")[0]!.replace(/\s+/g, " ").trim(); + return `${start > 0 && text[start - 1] !== "\n" ? "…" : ""}${cut(s)}`; +} + +interface ThreadRead { + /** Messages up to this id were there before the user first saw the list — never «new». */ + base: number; + seen: Record; +} +const readKey = (userId: number, chatId: number) => `chat.threads.read:${userId}:${chatId}`; + +/** The user has opened the thread: its messages so far are read. */ +export async function markThreadRead(db: Db, userId: number, chatId: number, threadKey: string): Promise { + const [last] = await db.select({ id: sql`max(${chatMessages.id})` }).from(chatMessages).where(and(eq(chatMessages.chatId, chatId), eq(chatMessages.threadKey, threadKey))); + const id = Number(last?.id ?? 0); + const st = (await getSetting(db, readKey(userId, chatId))) ?? { base: 0, seen: {} }; + if (!id || id <= Math.max(st.base, st.seen[threadKey] ?? 0)) return; + await setSetting(db, readKey(userId, chatId), { ...st, seen: { ...st.seen, [threadKey]: id } } satisfies ThreadRead); +} + +/** + * The conversations of a project chat in groups, most recent first. With `q` — only the threads + * whose story key, title or message text has it (case-insensitive; in JS: SQLite does not fold + * Cyrillic), archived stories included. + */ +export async function projectThreadList(db: Db, user: Pick, chat: Pick, o: { q?: string | null } = {}): Promise { + const q = (o.q ?? "").trim().toLocaleLowerCase().slice(0, 100) || null; + const empty: ThreadList = { waiting: [], working: [], done: [], q }; + if (!chat.projectId) return empty; + const [project] = await db.select({ id: projects.id, key: projects.key }).from(projects).where(eq(projects.id, chat.projectId)); + if (!project) return empty; + + const [last] = await db.select({ id: sql`max(${chatMessages.id})` }).from(chatMessages).where(eq(chatMessages.chatId, chat.id)); + let read = await getSetting(db, readKey(user.id, chat.id)); + if (!read) { + // First look at the list: what is already there does not become «unread» all at once. + read = { base: Number(last?.id ?? 0), seen: {} }; + await setSetting(db, readKey(user.id, chat.id), read); + } + + const taskRows = await db.select({ id: tasks.id, number: tasks.number, title: tasks.title, status: tasks.status, archivedAt: tasks.archivedAt, updatedAt: tasks.updatedAt }).from(tasks).where(eq(tasks.projectId, project.id)); + const stats = new Map( + ( + await db + .select({ key: chatMessages.threadKey, lastAt: sql`max(${chatMessages.createdAt})` }) + .from(chatMessages) + .where(and(eq(chatMessages.chatId, chat.id), isNotNull(chatMessages.threadKey))) + .groupBy(chatMessages.threadKey) + ).map((r) => [r.key!, new Date(Number(r.lastAt))]), + ); + const openRows = await db.select({ taskId: questions.taskId, id: questions.id }).from(questions).where(and(eq(questions.projectId, project.id), isNull(questions.answeredAt), inArray(questions.kind, [...ASKS]))); + const openByTask = new Map(); + for (const r of openRows) if (r.taskId != null) openByTask.set(r.taskId, (openByTask.get(r.taskId) ?? 0) + 1); + // Questions without a story (a version, a product error) live in their own threads. + const loose = openRows.filter((r) => r.taskId == null).map((r) => r.id); + const looseThreads = new Map(); + if (loose.length) { + const rows = await db.select({ key: chatMessages.threadKey }).from(chatMessages).where(and(eq(chatMessages.chatId, chat.id), isNotNull(chatMessages.threadKey), inArray(chatMessages.questionId, loose))); + for (const r of rows) if (!r.key!.startsWith("task:")) looseThreads.set(r.key!, (looseThreads.get(r.key!) ?? 0) + 1); + } + + // The agent of a story: the one working now, else the one of its last run. + const agentByTask = new Map(); + const runs = await db.select({ taskId: sessions.taskId, status: sessions.status, name: agents.name }).from(sessions).innerJoin(agents, eq(sessions.agentId, agents.id)).where(and(eq(sessions.projectId, project.id), isNotNull(sessions.taskId))).orderBy(asc(sessions.id)); + for (const r of runs) { + const live = r.status !== "done" && r.status !== "failed"; + if (live || !agentByTask.get(r.taskId!)?.live) agentByTask.set(r.taskId!, { name: r.name, live }); + } + const accepted = await listPendingAccepts(db); + + // The newest messages of the threads: the last readable line, the unread count, the search. + const msgs = await db + .select({ id: chatMessages.id, key: chatMessages.threadKey, text: chatMessages.text, authorKind: chatMessages.authorKind, authorUserId: chatMessages.authorUserId }) + .from(chatMessages) + .where(and(eq(chatMessages.chatId, chat.id), isNotNull(chatMessages.threadKey))) + .orderBy(desc(chatMessages.id)) + .limit(q ? SCAN_SEARCH : SCAN); + const lastLine = new Map(); + const found = new Map(); + const unread = new Map(); + for (const m of msgs) { + const key = m.key!; + const mine = m.authorUserId === user.id; + const said = (text: string) => ({ text, system: m.authorKind === "system", mine }); + if (!mine && m.id > Math.max(read.base, read.seen[key] ?? 0)) unread.set(key, (unread.get(key) ?? 0) + 1); + if (!lastLine.has(key)) { + const line = plainLine(m.text); + if (line) lastLine.set(key, said(line)); + } + if (q && !found.has(key)) { + const at = m.text.toLocaleLowerCase().indexOf(q); + if (at >= 0) found.set(key, said(snippet(m.text, at, q.length))); + } + } + + const out: ThreadList = { ...empty }; + const sortAt = new Map(); + const add = (row: Omit, at: number) => { + const full = { ...row, group: threadGroup(row) }; + out[full.group].push(full); + sortAt.set(full, at); + }; + for (const t of taskRows) { + const key = `task:${t.id}`; + const taskKey = formatTaskKey(project.key, t.number); + const open = openByTask.get(t.id) ?? 0; + const archived = t.archivedAt != null; + const lastAt = stats.get(key) ?? null; + if (q) { + if (!found.has(key) && !taskKey.toLocaleLowerCase().includes(q) && !t.title.toLocaleLowerCase().includes(q)) continue; + } else if (open === 0 && (archived || (!lastAt && !ACTIVE.has(t.status)))) continue; + add( + { key, taskKey, title: t.title, status: t.status, archived, accepted: accepted.has(t.id), agentName: agentByTask.get(t.id)?.name ?? null, last: found.get(key) ?? lastLine.get(key) ?? null, lastAt, unread: unread.get(key) ?? 0, open }, + (lastAt ?? t.updatedAt).getTime(), + ); + } + for (const [key, open] of looseThreads) { + const title = (await threadTitle(db, key)) ?? key; + if (q && !found.has(key) && !title.toLocaleLowerCase().includes(q)) continue; + const lastAt = stats.get(key) ?? null; + add({ key, taskKey: null, title, status: null, archived: false, accepted: false, agentName: null, last: found.get(key) ?? lastLine.get(key) ?? null, lastAt, unread: unread.get(key) ?? 0, open }, lastAt?.getTime() ?? 0); + } + for (const g of ["waiting", "working", "done"] as const) out[g].sort((a, b) => sortAt.get(b)! - sortAt.get(a)!); + return out; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index d32cfffe..b0ead52a 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -65,6 +65,7 @@ export * from "./memory.ts"; export * from "./agent-model.ts"; export * from "./onboarding.ts"; export * from "./chats.ts"; +export * from "./chat-threads.ts"; export * from "./subscription-care.ts"; export * from "./subscription-names.ts"; export * from "./transcribe.ts"; diff --git a/packages/core/src/story-product.ts b/packages/core/src/story-product.ts index 40a51c92..13e9424a 100644 --- a/packages/core/src/story-product.ts +++ b/packages/core/src/story-product.ts @@ -57,7 +57,8 @@ export const STORY_PRODUCT_TEXT = { }; /** File names, paths, identifiers and commands — not for a product manager's screen. */ -const TECHNICAL = /[/\\_$<>{}=]|\w\.\w|\w\(|[a-z][A-Z]|--\w|\b(?:tmux|git|npm|pnpm|sql|api|json|mcp|ci|pr|cli|env)\b/i; +/** Code, paths, identifiers — text a product manager cannot read. */ +export const TECHNICAL_TEXT = /[/\\_$<>{}=]|\w\.\w|\w\(|[a-z][A-Z]|--\w|\b(?:tmux|git|npm|pnpm|sql|api|json|mcp|ci|pr|cli|env)\b/i; /** * The current tasks.md item for the product view: the leading «1.2», code in backticks and @@ -67,7 +68,7 @@ export function plainStep(text: string | null | undefined): string | null { if (!text) return null; if (text.includes("`")) return null; const s = text.replace(/^\s*\d+(?:\.\d+)*\.?\s+/, "").replace(/\s+/g, " ").trim(); - if (s.length < 3 || s.length > 140 || TECHNICAL.test(s)) return null; + if (s.length < 3 || s.length > 140 || TECHNICAL_TEXT.test(s)) return null; return s; } diff --git a/packages/shared/src/i18n/en/story.ts b/packages/shared/src/i18n/en/story.ts index 8a984261..de599143 100644 --- a/packages/shared/src/i18n/en/story.ts +++ b/packages/shared/src/i18n/en/story.ts @@ -416,4 +416,14 @@ export const story: Dict = { "ждёт сброса лимита": "waiting for the limit reset", закончил: "finished", "остановился с ошибкой": "stopped with an error", + // PEP-155: the list of a project chat's conversations + "Ждут вас": "Waiting for you", + "Сейчас от вас ничего не нужно.": "Nothing is needed from you right now.", + "Найти в переписке…": "Search the conversations…", + "Поиск по переписке": "Search the conversations", + "Найти": "Search", + "Сбросить поиск": "Clear the search", + "Ничего не нашлось. Попробуйте другое слово.": "Nothing found. Try another word.", + "← К списку": "← Back to the list", + "Новых сообщений: {n}": "New messages: {n}", }; diff --git a/packages/shared/src/i18n/kk/story.ts b/packages/shared/src/i18n/kk/story.ts index 6735bea4..0cd45266 100644 --- a/packages/shared/src/i18n/kk/story.ts +++ b/packages/shared/src/i18n/kk/story.ts @@ -381,4 +381,14 @@ export const story: Dict = { "ждёт сброса лимита": "лимит тасталуын күтуде", "закончил": "аяқтады", "остановился с ошибкой": "қатемен тоқтады", + // PEP-155: the list of a project chat's conversations + "Ждут вас": "Сізді күтуде", + "Сейчас от вас ничего не нужно.": "Қазір сізден ештеңе қажет емес.", + "Найти в переписке…": "Хат алмасудан іздеу…", + "Поиск по переписке": "Хат алмасудан іздеу", + "Найти": "Іздеу", + "Сбросить поиск": "Іздеуді тазарту", + "Ничего не нашлось. Попробуйте другое слово.": "Ештеңе табылмады. Басқа сөзді қолданып көріңіз.", + "← К списку": "← Тізімге", + "Новых сообщений: {n}": "Жаңа хабарлар: {n}", }; diff --git a/packages/testkit/test/chats.test.ts b/packages/testkit/test/chats.test.ts index 38f8562b..f45ff3e4 100644 --- a/packages/testkit/test/chats.test.ts +++ b/packages/testkit/test/chats.test.ts @@ -6,7 +6,7 @@ import { after, before, describe, test } from "node:test"; // helpers must load first: it sets the isolated test env that runner modules read on load. import { core, db, runner, teardown, waitFor } from "./helpers.ts"; import { MockTelegram } from "../src/mock-telegram.ts"; -import { chatMessages, users } from "@peppa/db"; +import { chatMessages, tasks, users } from "@peppa/db"; import { eq } from "drizzle-orm"; import type { Bot } from "@peppa/bot"; @@ -126,6 +126,121 @@ describe("project chat", () => { }); }); +// PEP-155: the list of a project chat's conversations. +describe("Список переписки проекта", () => { + const setStatus = (taskId: number, status: "in_progress" | "review" | "done" | "backlog") => db.update(tasks).set({ status }).where(eq(tasks.id, taskId)); + const say = (chatId: number, taskId: number, text: string, authorKind: "agent" | "system" = "agent") => core.addChatMessage(db, { chatId, threadKey: threadOf(taskId), kind: "event", authorKind, text }); + const keys = (rows: Array<{ taskKey: string | null }>) => rows.map((r) => r.taskKey); + + test("Три группы", async () => { + const p = await newProject(); + const chat = await core.ensureProjectChat(db, p.id); + const asked = await newTask(p, "Формат даты"); + const working = await newTask(p, "Экспорт в CSV"); + const review = await newTask(p, "Отчёт"); + const done = await newTask(p, "Вход"); + const idle = await newTask(p, "Ещё не начата"); + await core.askPm(db, asked, { kind: "question", text: "Какой формат даты?" }); + await setStatus(working.task.id, "in_progress"); + await setStatus(review.task.id, "review"); + await setStatus(done.task.id, "done"); + await core.syncChats(db); + await say(chat.id, done.task.id, "Вход работает"); + const list = await core.projectThreadList(db, pm, chat); + assert.deepEqual(keys(list.waiting).sort(), [asked.key, review.key].sort()); + assert.deepEqual(keys(list.working), [working.key]); + assert.deepEqual(keys(list.done), [done.key]); + assert.ok(![...list.waiting, ...list.working, ...list.done].some((r) => r.taskKey === idle.key), "a backlog story nobody wrote about is not in the list"); + assert.equal(list.waiting.find((r) => r.taskKey === asked.key)!.open, 1); + }); + + test("Уведомление не делает тред ждущим", async () => { + const p = await newProject(); + const chat = await core.ensureProjectChat(db, p.id); + const ref = await newTask(p); + await setStatus(ref.task.id, "in_progress"); + await core.askPm(db, ref, { kind: "attention", text: "Агент перезапущен после сбоя" }); + await core.syncChats(db); + const list = await core.projectThreadList(db, pm, chat); + assert.deepEqual(keys(list.working), [ref.key]); + assert.equal(list.waiting.length, 0); + // PEP-127: «Принять» is pressed already — nothing is waited from the person. + await setStatus(ref.task.id, "review"); + assert.deepEqual(keys((await core.projectThreadList(db, pm, chat)).waiting), [ref.key]); + await core.setPendingAccept(db, ref.task.id, { at: Date.now(), via: "web", rebases: 0 } as Parameters[2]); + assert.deepEqual(keys((await core.projectThreadList(db, pm, chat)).working), [ref.key]); + await core.clearPendingAccept(db, ref.task.id); + }); + + test("Статус и агент; техническое сообщение не показывается", async () => { + const p = await newProject(); + const chat = await core.ensureProjectChat(db, p.id); + const ref = await newTask(p); + await setStatus(ref.task.id, "in_progress"); + const session = await core.createSession(db, { projectId: p.id, taskId: ref.task.id }); + const agent = await core.ensureSessionAgent(db, session.id); + await say(chat.id, ref.task.id, "Экспорт готов наполовину"); + await say(chat.id, ref.task.id, "Поправил `src/export.ts`, запустил pnpm test"); + const [row] = (await core.projectThreadList(db, pm, chat)).working; + assert.equal(row!.taskKey, ref.key); + assert.equal(row!.title, "Экспорт в CSV"); + assert.equal(row!.status, "in_progress"); + assert.equal(row!.agentName, agent!.name); + assert.equal(row!.last!.text, "Экспорт готов наполовину"); + assert.equal(core.plainLine("**Готово:** проверил вход\nвторая строка"), "Готово: проверил вход"); + assert.equal(core.plainLine("update_task(status: review)"), null); + }); + + test("Непрочитанное", async () => { + const p = await newProject(); + const chat = await core.ensureProjectChat(db, p.id); + const ref = await newTask(p); + await setStatus(ref.task.id, "in_progress"); + await say(chat.id, ref.task.id, "Старое сообщение"); + // The first look: what was there before is not «new». + assert.equal((await core.projectThreadList(db, pm, chat)).working[0]!.unread, 0); + await say(chat.id, ref.task.id, "Первое новое"); + await say(chat.id, ref.task.id, "Второе новое"); + await core.addChatMessage(db, { chatId: chat.id, threadKey: threadOf(ref.task.id), kind: "user", authorKind: "user", authorUserId: pm.id, authorLogin: pm.login, text: "моё сообщение" }); + const mine = (await core.projectThreadList(db, pm, chat)).working[0]!; + assert.equal(mine.unread, 2, "own messages are not «new»"); + assert.equal(mine.last!.mine, true); + await core.markThreadRead(db, pm.id, chat.id, threadOf(ref.task.id)); + assert.equal((await core.projectThreadList(db, pm, chat)).working[0]!.unread, 0); + // Bob has his own marks. + await core.projectThreadList(db, bob, chat); + await say(chat.id, ref.task.id, "Третье новое"); + assert.equal((await core.projectThreadList(db, bob, chat)).working[0]!.unread, 1); + assert.equal((await core.projectThreadList(db, pm, chat)).working[0]!.unread, 1); + assert.equal((await core.projectThreadList(db, eve, chat)).working[0]!.unread, 0); + }); + + test("Поиск: слово из сообщения, ключ, название; чужой проект", async () => { + const p = await newProject(); + const other = await newProject(); + const chat = await core.ensureProjectChat(db, p.id); + const otherChat = await core.ensureProjectChat(db, other.id); + const done = await newTask(p, "Отчёты"); + const working = await newTask(p, "Оплата картой"); + const foreign = await newTask(other, "Склад"); + await setStatus(done.task.id, "done"); + await setStatus(working.task.id, "in_progress"); + await say(chat.id, done.task.id, "Проверил вход\nДобавил выгрузку в Эксель"); + await say(chat.id, working.task.id, "Подключаю оплату"); + await say(otherChat.id, foreign.task.id, "Самолёт и Эксель"); + + const byText = await core.projectThreadList(db, pm, chat, { q: "эксель" }); + assert.equal(byText.q, "эксель"); + assert.deepEqual(keys(byText.done), [done.key]); + assert.equal(byText.done[0]!.last!.text, "Добавил выгрузку в Эксель"); + assert.equal(byText.working.length + byText.waiting.length, 0); + assert.deepEqual(keys((await core.projectThreadList(db, pm, chat, { q: "ОПЛАТА" })).working), [working.key]); + assert.deepEqual(keys((await core.projectThreadList(db, pm, chat, { q: done.key.toLowerCase() })).done), [done.key]); + const none = await core.projectThreadList(db, pm, chat, { q: "самолёт" }); + assert.equal(none.waiting.length + none.working.length + none.done.length, 0); + }); +}); + describe("master chat", () => { test("Сбой раннера в мастер-чате; команды /task и неизвестная", async () => { const p = await newProject(); -- 2.45.2 From c80a31f5cb93fb2892f055ea4cf9a6c421c1193a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 13:23:45 +0500 Subject: [PATCH 026/215] =?UTF-8?q?PEP-154:=20=D1=84=D0=B8=D0=BB=D1=8C?= =?UTF-8?q?=D1=82=D1=80=20=D1=81=D0=BB=D1=83=D0=B6=D0=B5=D0=B1=D0=BD=D0=BE?= =?UTF-8?q?=D0=B3=D0=BE=20=D1=82=D0=B5=D0=BA=D1=81=D1=82=D0=B0,=20=D0=BE?= =?UTF-8?q?=D1=82=D0=B2=D0=B5=D1=82=20=E2=80=94=20=D1=82=D0=BE=D0=BB=D1=8C?= =?UTF-8?q?=D0=BA=D0=BE=20=D0=B2=D0=B2=D0=BE=D0=B4=20=D1=87=D0=B5=D0=BB?= =?UTF-8?q?=D0=BE=D0=B2=D0=B5=D0=BA=D0=B0,=20=D0=BE=D1=88=D0=B8=D0=B1?= =?UTF-8?q?=D0=BA=D0=B8=20=D0=BF=D0=BB=D0=B0=D1=82=D1=84=D0=BE=D1=80=D0=BC?= =?UTF-8?q?=D1=8B=20=E2=80=94=20=D1=81=D1=83=D0=BF=D0=B5=D1=80=D0=B0=D0=B4?= =?UTF-8?q?=D0=BC=D0=B8=D0=BD=D1=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- apps/bot/package.json | 2 +- apps/bot/src/bot.ts | 5 +- apps/bot/src/render.ts | 12 +- apps/web/app/(app)/t/[key]/page.tsx | 2 +- apps/web/components/AgentSteps.tsx | 27 ++- apps/web/components/cards.tsx | 15 +- packages/core/src/chats.ts | 11 + packages/core/src/index.ts | 2 + packages/core/src/platform-failure.ts | 39 ++++ packages/core/src/sessions.ts | 5 + packages/core/src/tasks.ts | 15 +- packages/core/src/user-text.ts | 142 +++++++++++++ packages/runner/src/autonomy.ts | 20 +- packages/runner/src/deploy.ts | 6 +- packages/runner/src/hook.ts | 18 +- packages/runner/src/recovery.ts | 5 +- packages/shared/src/i18n/en/runner.ts | 4 + packages/shared/src/i18n/en/story.ts | 11 + packages/shared/src/i18n/kk/runner.ts | 4 + packages/shared/src/i18n/kk/story.ts | 11 + packages/testkit/test/service-text.test.ts | 229 +++++++++++++++++++++ 21 files changed, 558 insertions(+), 27 deletions(-) create mode 100644 packages/core/src/platform-failure.ts create mode 100644 packages/core/src/user-text.ts create mode 100644 packages/testkit/test/service-text.test.ts diff --git a/apps/bot/package.json b/apps/bot/package.json index 5e87285a..1313b8b1 100644 --- a/apps/bot/package.json +++ b/apps/bot/package.json @@ -3,7 +3,7 @@ "version": "0.0.0", "private": true, "type": "module", - "exports": { ".": "./src/bot.ts", "./telegram": "./src/telegram.ts" }, + "exports": { ".": "./src/bot.ts", "./telegram": "./src/telegram.ts", "./render": "./src/render.ts" }, "bin": { "peppa-bot": "./bin/peppa-bot" }, "scripts": { "start": "node src/index.ts", "typecheck": "tsc -p ." }, "dependencies": { diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts index 6f0f0cad..b98f7456 100644 --- a/apps/bot/src/bot.ts +++ b/apps/bot/src/bot.ts @@ -39,6 +39,7 @@ import { markOutboxRetry, markOutboxSent, pendingQuestions, + getUiMode, questionByTelegramMessage, setOffset, setSetting, @@ -312,11 +313,12 @@ export function createBot(o: BotOptions) { if (!audience.length) continue; const ctx = await context(q); const event = questionEvent(q, { taskStatus: ctx.taskStatus, sessionStatus: ctx.session?.status }); - const r = renderQuestion(q, ctx); // A push is a "now" signal: questions older than this don't pop up on a fresh subscription. const fresh = Date.now() - q.createdAt.getTime() < PUSH_MAX_AGE_MS; const url = ctx.taskKey ? `/t/${ctx.taskKey}` : `/p/${await projectKey(q.projectId)}`; for (const u of audience) { + // PEP-154: the terminal command is for the «Инженер» view only. + const r = renderQuestion(q, { ...ctx, engineer: (await getUiMode(db, u.id)) === "engineer" }); await deliverToUser(db, u, { event, projectId: q.projectId, @@ -331,6 +333,7 @@ export function createBot(o: BotOptions) { // fresh text and its buttons back, at most once in `repeatEditMs`. const repeats = states.get(q.id)?.repeats ?? 0; if (!repeats) continue; + const r = renderQuestion(q, ctx); for (const sent of await sentQuestionMessages(db, q.id)) { const key = repeatEditKey(sent.id, repeats); if (await getOutbox(db, key)) continue; diff --git a/apps/bot/src/render.ts b/apps/bot/src/render.ts index 5536a560..cb2df129 100644 --- a/apps/bot/src/render.ts +++ b/apps/bot/src/render.ts @@ -1,5 +1,5 @@ // Telegram message texts and buttons for PM questions. HTML parse mode. -import type { Question, SessionView } from "@peppa/core"; +import { stripServiceBlocks, userText, type Question, type SessionView } from "@peppa/core"; import type { InlineButton } from "./telegram.ts"; import { m as tr } from "@peppa/shared/i18n"; @@ -22,12 +22,13 @@ export interface Rendered { // callback_data (≤64 bytes): "q::", "s::" or "i::" (core/incidents.ts) export function renderQuestion( q: Question, - ctx: { taskKey: string | null; taskTitle: string | null; taskStatus?: string | null; session: SessionView | null; webUrl: string }, + ctx: { taskKey: string | null; taskTitle: string | null; taskStatus?: string | null; session: SessionView | null; webUrl: string; /** PEP-154: the reader's view is «Инженер» — the terminal command is shown. */ engineer?: boolean }, ): Rendered { const head = ["" + esc(ctx.taskKey ?? (q.sessionId ? tr("Агент №{id}", { id: q.sessionId }) : tr("Обновления продукта"))) + "", ctx.taskTitle ? `${esc(clip(ctx.taskTitle, 80))}` : null] .filter(Boolean) .join(" · "); - const body = esc(clip(q.text, 3300)); + // PEP-154: no service text in the message (a permission request keeps its command). + const body = esc(clip(q.kind === "permission" ? q.text : userText(q.text) || q.text, 3300)); const lines = [head, KIND[q.kind], "", body]; const buttons: InlineButton[][] = []; @@ -59,7 +60,7 @@ export function renderQuestion( lines.push("", italic(tr("Или ответьте на это сообщение — текст уйдёт агенту."))); } } - if (ctx.session) lines.push(`tmux attach -t ${esc(ctx.session.tmuxName)}`); + if (ctx.session && ctx.engineer) lines.push(`tmux attach -t ${esc(ctx.session.tmuxName)}`); return { text: lines.join("\n"), buttons }; } @@ -67,7 +68,8 @@ export function renderQuestion( export function renderAnswered(original: string, q: Question): string { const mark = q.answeredVia === "system" ? "⌛" : "✅"; const via = { telegram: tr("в Telegram"), web: tr("в вебе"), terminal: tr("в терминале"), system: "" }[q.answeredVia ?? "telegram"]; - const said = q.answeredVia === "system" ? esc(q.answer ?? "") : tr("Ответ {via}: {answer}", { via, answer: esc(clip(q.answer ?? "", 500)) }); + const answer = stripServiceBlocks(q.answer ?? ""); + const said = q.answeredVia === "system" ? esc(answer) : tr("Ответ {via}: {answer}", { via, answer: esc(clip(answer, 500)) }); return `${original}\n\n${mark} ${said}`; } diff --git a/apps/web/app/(app)/t/[key]/page.tsx b/apps/web/app/(app)/t/[key]/page.tsx index b75d6fce..7b07875c 100644 --- a/apps/web/app/(app)/t/[key]/page.tsx +++ b/apps/web/app/(app)/t/[key]/page.tsx @@ -309,7 +309,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom {live ? ( // PEP-9 terminal + PEP-33 step feed of the newest unfinished runner. - + ) : (
diff --git a/apps/web/components/AgentSteps.tsx b/apps/web/components/AgentSteps.tsx index 9cd8ccb6..b240cb92 100644 --- a/apps/web/components/AgentSteps.tsx +++ b/apps/web/components/AgentSteps.tsx @@ -19,6 +19,19 @@ const KIND: Record = { other: { icon: Wrench, label: m("инструмент") }, }; +// PEP-154: a step for the «Продакт» view — what the agent does, in words: no command, file name or path. +const STEP_PLAIN: Record = { + command: m("Выполняет действие в проекте"), + test: m("Запускает проверки"), + edit: m("Вносит изменения"), + read: m("Изучает проект"), + search: m("Ищет нужное в проекте"), + web: m("Смотрит в интернете"), + agent: m("Поручил часть работы помощнику"), + mcp: m("Сверяется с задачей"), + other: m("Работает над задачей"), +}; + const KEEP = 30; function since(iso: string, now: number, t: Translator): string { @@ -32,7 +45,7 @@ function since(iso: string, now: number, t: Translator): string { * What the agent is doing now (PEP-33): its latest tool calls, newest first. Initial steps * come from the server, new ones from the live channel (PEP-37, `steps:`). */ -export function AgentSteps({ sessionId, initial, live, hooks = true }: { sessionId: number; initial: StepView[]; live: boolean; hooks?: boolean }) { +export function AgentSteps({ sessionId, initial, live, hooks = true, plain = false }: { sessionId: number; initial: StepView[]; live: boolean; hooks?: boolean; /** PEP-154: «Продакт» — what the agent does in words, no commands, file names or paths. */ plain?: boolean }) { const [steps, setSteps] = useState(initial); const [now, setNow] = useState(() => Date.now()); const t = useT(); @@ -59,7 +72,7 @@ export function AgentSteps({ sessionId, initial, live, hooks = true }: { session if (!steps.length) return (

- {hooks ? (live ? t("Агент ещё ничего не сделал — шаги появятся здесь.") : t("Шагов не записано.")) : t("Этот агент не сообщает шаги (нет хуков) — смотри терминал.")} + {hooks ? (live ? t("Агент ещё ничего не сделал — шаги появятся здесь.") : t("Шагов не записано.")) : plain ? t("Этот агент не сообщает о шагах.") : t("Этот агент не сообщает шаги (нет хуков) — смотри терминал.")}

); return ( @@ -70,9 +83,13 @@ export function AgentSteps({ sessionId, initial, live, hooks = true }: { session return (
  • - - {s.text} - + {plain ? ( + {t(STEP_PLAIN[s.kind] ?? STEP_PLAIN.other)} + ) : ( + + {s.text} + + )} {!s.ok && {t("ошибка")}} {since(s.at, now, t)}
  • diff --git a/apps/web/components/cards.tsx b/apps/web/components/cards.tsx index ac09bb01..1f271405 100644 --- a/apps/web/components/cards.tsx +++ b/apps/web/components/cards.tsx @@ -1,7 +1,7 @@ // Domain cards shared by pages: agent questions, runners, project list. import Link from "next/link"; import { BellRing, CircleCheck, CircleHelp, FileCheck, Hourglass, Play, RotateCcw, Send, ShieldQuestion, Square, SquareTerminal } from "lucide-react"; -import { questionState, type Project, type Question, type SessionView, type StepView } from "@peppa/core"; +import { questionDetails, questionState, type Project, type Question, type SessionView, type StepView } from "@peppa/core"; import { db } from "@/lib/db"; import { SubscriptionName } from "@/components/SubscriptionName"; import { answerQuestion, messageSession, resumeTaskSession, stopTaskSession } from "@/app/(app)/actions"; @@ -15,6 +15,7 @@ import { RunnerTerminal } from "@/components/RunnerTerminal"; import { SessionUsageLine } from "@/components/Accounting"; import { cn } from "@/lib/utils"; import { getT } from "@/lib/i18n"; +import { subscriptionNamesVisible, uiMode } from "@/lib/auth"; import { m } from "@peppa/shared/i18n"; const KIND = { @@ -42,6 +43,8 @@ export async function QuestionCard({ q, taskKey, taskStatus, back, compact = fal // PEP-151: the same state came again — one message with the time it was last refreshed. const state = await questionState(db, q.id).catch(() => null); const updatedAt = state?.updatedAt ? new Date(state.updatedAt) : null; + // PEP-154: what the filter removed (command output, paths) — for «Инженер» and a superadmin only. + const original = (await uiMode()) === "engineer" || (await subscriptionNamesVisible()) ? await questionDetails(db, q.id).catch(() => null) : null; return (
    @@ -70,6 +73,12 @@ export async function QuestionCard({ q, taskKey, taskStatus, back, compact = fal

    {t("Повторов: {n} · первое сообщение {ago}", { n: state.repeats, ago: ago(q.createdAt, t) })}

    )} + {original && ( +
    + {t("Подробнее: исходный текст")} +
    {original}
    +
    + )} {answered ? (

    {q.answeredVia === "system" ? : } @@ -152,7 +161,7 @@ export function AttachCommand({ name }: { name: string }) { } /** `steps` (PEP-33): the live step feed of the agent, shown with the terminal. */ -export async function SessionCard({ s, back, showTitle = false, terminal = false, steps }: { s: SessionView; back: string; showTitle?: boolean; terminal?: boolean; steps?: StepView[] }) { +export async function SessionCard({ s, back, showTitle = false, terminal = false, steps, plainSteps = false }: { s: SessionView; back: string; showTitle?: boolean; terminal?: boolean; steps?: StepView[]; /** PEP-154: «Продакт» — steps in words. */ plainSteps?: boolean }) { const t = await getT(); return (

    @@ -179,7 +188,7 @@ export async function SessionCard({ s, back, showTitle = false, terminal = false )} - {steps && } + {steps && } {terminal && }
    ); diff --git a/packages/core/src/chats.ts b/packages/core/src/chats.ts index c9d1bc4e..77067015 100644 --- a/packages/core/src/chats.ts +++ b/packages/core/src/chats.ts @@ -13,6 +13,7 @@ import { notify } from "./notify.ts"; import { deleteSetting, getSetting, setSetting } from "./settings.ts"; import { projectForUser, userProjectIds, type User } from "./users.ts"; import type { OutboxRow } from "./telegram.ts"; +import { pruneQuestionDetails, userText } from "./user-text.ts"; import { chatRepeatKey, chatRepeats, normalizeMessage, pruneMessageStates, questionStates, type ChatRepeat } from "./message-state.ts"; export type Chat = typeof chats.$inferSelect; @@ -101,6 +102,13 @@ export async function listChats(db: Db, user: Pick): Promise { + // PEP-154: what an agent or Peppa says goes through the service-text filter; nothing left — no message. + // A question's text was filtered when it was asked (a permission request keeps its command). + if (m.authorKind !== "user" && !m.questionId) { + const text = userText(m.text); + if (!text) return null; + m = { ...m, text }; + } if (m.threadKey && m.threadTitle == null) { const [prev] = await db .select({ t: chatMessages.threadTitle }) @@ -462,6 +470,8 @@ export async function syncChats(db: Db, o: { now?: Date } = {}): Promise let repeated = 0; const add = async (m: NewChatMessage) => { // PEP-151: the same event of a story again in a row is a counter on the line already there. + if (m.authorKind !== "user" && !m.questionId) m.text = userText(m.text); // PEP-154: compared and stored without service text + if (!m.text) return; if (await repeatsLastEvent(db, m)) return void repeated++; if (m.threadKey) m.threadTitle = await titleOf(m.threadKey); if (await addChatMessage(db, m)) added++; @@ -570,6 +580,7 @@ export async function pruneChats(db: Db, o: { now?: Date } = {}): Promise void; + now?: Date; +} + +/** + * What to tell the project owner about a failure: the text of a clear refusal, or null — it is + * a platform error (reported to the error tracker and to the superadmins, one message per error + * a day) and the owner gets nothing. Never throws. + */ +export async function platformFailure(db: Db, e: unknown, ctx: FailureContext): Promise { + if (e instanceof PeppaError) return e.message; + const message = (e as Error)?.message ?? String(e); + try { + await reportPlatformError(db, e, { service: ctx.service, where: ctx.where }); + // The same error of the same part (numbers aside) is one message a day. + const fp = createHash("sha1").update(`${ctx.service}|${normalizeMessage(ctx.where)}|${normalizeMessage(message)}`).digest("hex").slice(0, 12); + const day = (ctx.now ?? new Date()).toISOString().slice(0, 10); + // glossary-ignore: read by superadmins only + const text = tr("⚠️ Сбой в Peppa FACTORY ({where}): {error}", { where: ctx.where, error: message.length > 300 ? `${message.slice(0, 300)}…` : message }); + await alertAdmins(db, `fail:${fp}:${day}`, text, ctx.log ?? (() => {})); + } catch {} + return null; +} diff --git a/packages/core/src/sessions.ts b/packages/core/src/sessions.ts index ec796bea..47309f95 100644 --- a/packages/core/src/sessions.ts +++ b/packages/core/src/sessions.ts @@ -7,6 +7,7 @@ import { actorColumns } from "./actor.ts"; import type { Question, QuestionKind } from "./tasks.ts"; import { userProjectIds } from "./users.ts"; import { questionStates, raiseOnce, type MessageTopic } from "./message-state.ts"; +import { keepQuestionDetails, messageText } from "./user-text.ts"; export type Session = typeof sessions.$inferSelect; export type SessionStatus = (typeof sessionStatus.enumValues)[number]; @@ -182,6 +183,9 @@ export async function raiseSessionQuestion( awaitingHook = false, o: { topic?: MessageTopic; head?: string | null } = {}, ): Promise { + // PEP-154: no service text (tags, command output, paths) in what the person reads. + const original = text; + text = messageText(kind, text); const row = await raiseOnce(db, { projectId: s.projectId, taskId: s.taskId, sessionId: s.id, kind, text, options, awaitingHook, ...o }, async () => { const [created] = await db .insert(questions) @@ -189,6 +193,7 @@ export async function raiseSessionQuestion( .returning(); return created!; }); + await keepQuestionDetails(db, row.id, original, text).catch(() => {}); await notify(db, { type: "question", questionId: row.id }); return row; } diff --git a/packages/core/src/tasks.ts b/packages/core/src/tasks.ts index aeba839e..f4d551a1 100644 --- a/packages/core/src/tasks.ts +++ b/packages/core/src/tasks.ts @@ -15,6 +15,7 @@ import { blockersOf, dependentsOf, type Blocker } from "./deps.ts"; import { taskBudgetView, type TaskBudgetView } from "./budgets.ts"; import { productNeeds, type ProductNeedView } from "./product-needs.ts"; import { raiseOnce, type MessageTopic } from "./message-state.ts"; +import { keepQuestionDetails, messageText, stripServiceBlocks } from "./user-text.ts"; export type Task = typeof tasks.$inferSelect; export type TaskStatus = (typeof taskStatus.enumValues)[number]; @@ -310,6 +311,9 @@ export interface NewQuestion { /** Records a question for the PM and broadcasts it (the bot forwards it to Telegram). */ export async function askPm(db: Db, ref: TaskRef, { topic, head, ...q }: NewQuestion): Promise { + // PEP-154: no service text (tags, command output, paths) in what the person reads. + const original = q.text; + q = { ...q, text: messageText(q.kind, q.text) }; // PEP-151: the same state of the story again refreshes the earlier message instead of adding one. const row = await raiseOnce(db, { projectId: ref.project.id, taskId: ref.task.id, sessionId: q.sessionId ?? null, kind: q.kind, text: q.text, options: q.options, topic, head }, async () => { const [created] = await db @@ -318,6 +322,7 @@ export async function askPm(db: Db, ref: TaskRef, { topic, head, ...q }: NewQues .returning(); return created!; }); + await keepQuestionDetails(db, row.id, original, q.text).catch(() => {}); if (q.kind === "approval") await updateTask(db, ref, { status: "awaiting_approval" }, q.sessionId); await notify(db, { type: "question", questionId: row.id }); return row; @@ -325,7 +330,9 @@ export async function askPm(db: Db, ref: TaskRef, { topic, head, ...q }: NewQues /** A message for the PM about the project as a whole (releases), not about a task. */ export async function askPmProject(db: Db, project: Project, q: { kind: QuestionKind; text: string; options?: string[] }): Promise { - const [row] = await db.insert(questions).values({ projectId: project.id, ...q }).returning(); + const text = messageText(q.kind, q.text); + const [row] = await db.insert(questions).values({ projectId: project.id, ...q, text }).returning(); + await keepQuestionDetails(db, row!.id, q.text, text).catch(() => {}); await notify(db, { type: "question", questionId: row!.id }); return row!; } @@ -344,6 +351,12 @@ export async function answerQuestion( answer: string, via: NonNullable, ): Promise { + // PEP-154: an answer is a person's words — service blocks never land in it. + if (via !== "system") { + const said = stripServiceBlocks(answer); + if (!said && answer.trim()) throw new PeppaError(`Question #${questionId}: the answer is service text only`); + answer = said; + } const [row] = await db .update(questions) .set({ answer, answeredVia: via, answeredAt: new Date() }) diff --git a/packages/core/src/user-text.ts b/packages/core/src/user-text.ts new file mode 100644 index 00000000..1f6cbe19 --- /dev/null +++ b/packages/core/src/user-text.ts @@ -0,0 +1,142 @@ +// PEP-154: what a person reads must not carry service text. One filter for everything shown to +// the user from an agent's mouth or from a terminal: service blocks (, +// , any XML/HTML-like tag), ANSI sequences, code and command output, shell +// prompt lines, stack traces, absolute paths. The original stays under «Подробнее» for a +// superadmin and the «Инженер» view (`question.details:`), never in the main text. +import { settings, type Db } from "@peppa/db"; +import { and, like, lt } from "drizzle-orm"; +import { PeppaError } from "./errors.ts"; +import { deleteSetting, getSetting, setSetting } from "./settings.ts"; + +/** Blocks Claude Code and Peppa put into a conversation for the model, never for a person. */ +const SERVICE_TAGS = [ + "task-notification", + "system-reminder", + "local-command-stdout", + "local-command-stderr", + "local-command-caveat", + "command-name", + "command-message", + "command-args", + "command-contents", + "bash-input", + "bash-stdout", + "bash-stderr", + "user-prompt-submit-hook", + "user-memory-input", + "persisted-output", + "tool_use_error", + "function_calls", + "function_results", + "new-diagnostics", + "ide_opened_file", + "ide_selection", + "pasted_content", +].join("|"); + +// CSI / OSC / two-byte escapes, then the other control characters (tab, \n and \r stay). +const ANSI_RE = /\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-Z\\-_]|[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g; +const SERVICE_BLOCK_RE = new RegExp(`<(${SERVICE_TAGS})\\b[^>]*>[\\s\\S]*?`, "gi"); +/** A service block cut off before its closing tag (clipped text): everything after it is its body. */ +const SERVICE_OPEN_RE = new RegExp(`<(?:${SERVICE_TAGS})\\b[^>]*>[\\s\\S]*$`, "i"); + +/** + * Removes only what is certainly not a person's words: known service blocks and terminal + * escape sequences. Safe for a person's own text (an answer, input typed into a terminal). + */ +export function stripServiceBlocks(text: string): string { + return text.replace(/\r\n?/g, "\n").replace(ANSI_RE, "").replace(SERVICE_BLOCK_RE, "").replace(SERVICE_OPEN_RE, "").trim(); +} + +/** Input that reached a session but was not typed by anyone: nothing is left without service blocks. */ +export const isServiceInput = (text: string) => !!text.trim() && !stripServiceBlocks(text); + +// Where a removed block stood (private-use character: never in real text). +const CUT = ""; +// Any paired block whose tag name has a hyphen or an underscore — nobody writes prose like that. +const CUSTOM_BLOCK_RE = /<([a-z][\w.]*[-_][\w.-]*)\b[^>]*>[\s\S]*?<\/\1\s*>/gi; +const FENCE_RE = /^[ \t]*(```|~~~)[^\n]*\n[\s\S]*?(?:^[ \t]*\1[ \t]*$|(?![\s\S]))/gm; +const TAG_RE = /<\/?[a-zA-Z][\w:.-]*(?:\s[^<>]*)?\/?>/g; +const PROMPT_LINE_RE = /^\s*(?:[\w.-]+@[\w.-]+[^\n$#%]*[$#%]|\$|❯|➜|>>>|PS [A-Za-z]:\\[^>\n]*>)\s+\S.*$/; +const TRACE_LINE_RE = /^\s*(?:at\s.+(?::\d+:\d+\)?|\))\s*$|File ".+", line \d+.*$|Traceback \(most recent call last\):?\s*$|\.{3} \d+ more\s*$|Caused by: .+$)/; +const ERROR_HEAD_RE = /^\s*(?:Uncaught\s+)?(?:[\w$]+\.)*[\w$]*(?:Error|Exception)\b.*$/; +const PATH_SRC = String.raw`(?()\[\],;]*`; +const PATH_RE = new RegExp(PATH_SRC, "g"); +const HAS_PATH_RE = new RegExp(PATH_SRC); +const INLINE_CODE_RE = /`[^`\n]*`/g; +const HAS_WORD_RE = /[\p{L}\p{N}]/u; + +/** + * Text of an agent or a terminal, as a person may read it: without service blocks, tags, code + * and command output, shell prompts, stack traces and absolute paths. Idempotent. An empty + * result means there was nothing for a person in it. + */ +export function userText(text: string): string { + const src = stripServiceBlocks(text); + let s = src.replace(CUSTOM_BLOCK_RE, "").replace(FENCE_RE, `${CUT}\n`); + const lines = s.split("\n"); + const kept: string[] = []; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]!; + const cutLine = PROMPT_LINE_RE.test(line) || TRACE_LINE_RE.test(line) || (ERROR_HEAD_RE.test(line) && TRACE_LINE_RE.test(lines[i + 1] ?? "")); + kept.push(cutLine ? CUT : line); + } + s = kept.join("\n"); + s = s.replace(INLINE_CODE_RE, (code) => (HAS_PATH_RE.test(code) ? "" : code)).replace(PATH_RE, (path) => /[.!?]$/.test(path) ? path.slice(-1) : "").replace(TAG_RE, ""); + const out: string[] = []; + const srcLines = new Set(src.split("\n").map((l) => l.trim())); + for (const raw of s.split("\n")) { + if (raw.includes(CUT)) { + // «Вот вывод:» before a removed block: the colon promises what is no longer there. + for (let j = out.length - 1; j >= 0; j--) { + if (!out[j]) continue; + if (/[::]$/.test(out[j]!)) out[j] = `${out[j]!.slice(0, -1)}.`; + break; + } + out.push(""); + continue; + } + const line = raw + .replace(/[ \t]+$/g, "") + .replace(/(\S)[ \t]{2,}/g, "$1 ") + .replace(/\(\s*[,;:]?\s*\)|\[\s*\]|«\s*»|"\s*"|``/g, "") + .replace(/[ \t]+([.,;:!?)»])/g, "$1") + .replace(/([(«])[ \t]+/g, "$1") + .replace(/[ \t]+$/g, ""); + // A line the filter emptied (a bullet with only a path) goes away; an untouched one stays. + if (line.trim() && !HAS_WORD_RE.test(line) && !srcLines.has(raw.trim())) continue; + out.push(line); + } + return out.join("\n").replace(/\n{3,}/g, "\n\n").trim(); +} + +/** + * The text of a message for the user as it is stored. A permission request keeps its command + * (that is what the person allows; «Продакт» has it under «Подробнее», PEP-120). Nothing left + * after the filter — no message: PeppaError (an agent's `ask_pm` gets it as a hint). + */ +export function messageText(kind: string, text: string): string { + if (kind === "permission") return text; + const shown = userText(text); + // i18n-ignore: read by the agent (ask_pm) or the log, not by the user + if (!shown) throw new PeppaError("В сообщении только служебный текст (теги, вывод команд, пути) — показать пользователю нечего. Напиши его простыми словами."); + return shown; +} + +const DETAILS_PREFIX = "question.details:"; +const detailsKey = (questionId: number) => `${DETAILS_PREFIX}${questionId}`; + +/** Keeps the original of a filtered message for «Подробнее» (superadmin, «Инженер»); none when nothing was cut. */ +export async function keepQuestionDetails(db: Db, questionId: number, original: string, shown: string): Promise { + if (original.trim() === shown.trim()) await deleteSetting(db, detailsKey(questionId)); + else await setSetting(db, detailsKey(questionId), { text: original.slice(0, 8000) }); +} + +/** The unfiltered text of a message, if the filter removed something. Show only to a superadmin or in «Инженер». */ +export async function questionDetails(db: Db, questionId: number): Promise { + return (await getSetting<{ text: string }>(db, detailsKey(questionId)))?.text ?? null; +} + +export async function pruneQuestionDetails(db: Db, before: Date): Promise { + await db.delete(settings).where(and(like(settings.key, `${DETAILS_PREFIX}%`), lt(settings.updatedAt, before))); +} diff --git a/packages/runner/src/autonomy.ts b/packages/runner/src/autonomy.ts index f28aca66..86599800 100644 --- a/packages/runner/src/autonomy.ts +++ b/packages/runner/src/autonomy.ts @@ -24,6 +24,7 @@ import { projectPoolExhausted, questionRecipients, raiseSessionQuestion, + platformFailure, setSetting, taskPrNumber, type AutonomySettings, @@ -213,7 +214,9 @@ async function autoCloseReviews(db: Db, project: Project, a: AutonomySettings, n const key = `auto:closefail:${q.id}`; if (!(await getSetting(db, key))) { await setSetting(db, key, true); - await askPm(db, ref, { kind: "question", text: m("⚠️ {key}: не получилось закрыть автоматически — {error}", { key: ref.key, error: (e as Error).message }) }); + // PEP-154: a platform error goes to the superadmins and the error tracker, not to the owner. + const why = await platformFailure(db, e, { service: "watchdog", where: `auto-close ${ref.key}`, log }); + if (why) await askPm(db, ref, { kind: "question", text: m("⚠️ {key}: не получилось закрыть автоматически — {error}", { key: ref.key, error: why }) }); } log(`${ref.key}: auto-close failed — ${(e as Error).message}`); } @@ -268,10 +271,13 @@ async function dispatch(db: Db, project: Project, a: AutonomySettings, now: Date const fresh = await resolveTaskById(db, task.id).catch(() => null); if (fresh && fresh.task.status === "in_progress") await moveTask(db, fresh, "backlog").catch(() => {}); await setIdle(db, project.id, { ...state, failUntil: now.getTime() + DISPATCH_RETRY_MS }); - await askPmProject(db, project, { - kind: "attention", - text: `${m("⚠️ {project}: диспетчер не смог запустить агента на {key} — {error}", { project: project.name, key: ref.key, error: (e as Error).message })}\n${m("Повторю через {n} мин.", { n: DISPATCH_RETRY_MS / 60_000 })}`, - }); + // PEP-154: a platform error goes to the superadmins and the error tracker, not to the owner. + const why = await platformFailure(db, e, { service: "watchdog", where: `dispatch ${ref.key}`, log, now }); + if (why) + await askPmProject(db, project, { + kind: "attention", + text: `${m("⚠️ {project}: диспетчер не смог запустить агента на {key} — {error}", { project: project.name, key: ref.key, error: why })}\n${m("Повторю через {n} мин.", { n: DISPATCH_RETRY_MS / 60_000 })}`, + }); log(`${ref.key}: dispatch failed — ${(e as Error).message}`); return; } @@ -374,7 +380,9 @@ export async function onIdleAnswer(db: Db, q: Question, answer: string): Promise try { await moveTask(db, ref, "in_progress"); } catch (e) { - await askPmProject(db, ref.project, { kind: "attention", text: m("⚠️ {key} не запущена: {error}", { key: ref.key, error: (e as Error).message }) }); + // PEP-154: the person pressed a button and gets an answer, but never the text of an exception. + const why = await platformFailure(db, e, { service: "runner", where: `start ${ref.key}` }); + await askPmProject(db, ref.project, { kind: "attention", text: why ? m("⚠️ {key} не запущена: {error}", { key: ref.key, error: why }) : m("⚠️ {key} не запущена. Мы уже разбираемся — попробуйте ещё раз позже.", { key: ref.key }) }); } return true; } diff --git a/packages/runner/src/deploy.ts b/packages/runner/src/deploy.ts index 5f781a13..e9dfc265 100644 --- a/packages/runner/src/deploy.ts +++ b/packages/runner/src/deploy.ts @@ -3,7 +3,7 @@ // here; Peppa keeps the releases, tells the PM, and starts prod by the PM's button — a // `deploy-prod-*` tag at the healthy staging commit (Gitea 1.22 has no workflow_dispatch API). import { m } from "@peppa/shared/i18n"; -import { answerQuestion, askPmProject, deleteSetting, getPublishMode, getSetting, setSetting, resolveTask, giteaForBot, logEvent, markSecretsRestart, needsLine, openNeeds, PeppaError, projectSecretMasker, queueProductReview, runLink, type GiteaClient, type Project, type Question } from "@peppa/core"; +import { answerQuestion, askPmProject, platformFailure, deleteSetting, getPublishMode, getSetting, setSetting, resolveTask, giteaForBot, logEvent, markSecretsRestart, needsLine, openNeeds, PeppaError, projectSecretMasker, queueProductReview, runLink, type GiteaClient, type Project, type Question } from "@peppa/core"; import { projects, questions, releases, settings, type Db } from "@peppa/db"; import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm"; import { deployPlatform, isPlatform } from "./platform-release.ts"; @@ -288,7 +288,9 @@ export async function onReleaseAnswer(db: Db, q: Question, answer: string, by: s try { await deployProd(db, project, by); } catch (e) { - await askPmProject(db, project, { kind: "attention", text: m("Обновление рабочей версии не запущено: {error}", { error: (e as Error).message }) }); + // PEP-154: the person pressed a button and gets an answer, but never the text of an exception. + const why = await platformFailure(db, e, { service: "runner", where: `deploy prod ${project.key}` }); + await askPmProject(db, project, { kind: "attention", text: why ? m("Обновление рабочей версии не запущено: {error}", { error: why }) : m("Обновление рабочей версии не запущено. Мы уже разбираемся — попробуйте ещё раз позже.") }); } return true; } diff --git a/packages/runner/src/hook.ts b/packages/runner/src/hook.ts index c355aaa6..68f87e46 100644 --- a/packages/runner/src/hook.ts +++ b/packages/runner/src/hook.ts @@ -34,6 +34,9 @@ import { logSessionEvent, peppaInputSentAt, pendingSessionQuestions, + isServiceInput, + userText, + reportPlatformError, raiseSessionQuestion, releaseHookQuestion, updateSession, @@ -197,6 +200,8 @@ const NUDGE = (key: string) => */ async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue: boolean): Promise { await logSessionEvent(db, s, "turn_end", { text }); + // PEP-154: a reply that is service text only (a tag block, command output) says nothing to a person. + if (text && !userText(text)) text = null; // PEP-43: the story's budget is spent — the PM was asked; don't push the agent further. if (s.taskId && (await getBudgetState(db, s.taskId))) { await logSessionEvent(db, s, "budget_hold", {}); @@ -326,9 +331,17 @@ async function handle(event: string, input: HookInput): Promise { // pending for this session is now answered — except hook-held questions, and, // when Peppa typed this text itself, questions raised after it did (e.g. a CI // failure pasted while the PM is being asked about the next one). + // PEP-154: a service notification of the CLI (…) is nobody's answer — + // the questions stay open and the nudge counter keeps counting. + if (isServiceInput(input.prompt ?? "")) { + await updateSession(db, s.id, { status: "running", lastActivityAt: now }); + break; + } const sentAt = input.prompt ? await peppaInputSentAt(db, s.id, input.prompt) : null; for (const q of await pendingSessionQuestions(db, s.id, { excludeHook: true, createdBefore: sentAt ?? undefined })) { - await answerQuestion(db, q.id, input.prompt ?? "", "terminal").catch(() => {}); + // What Peppa typed itself (a red check, «лимит сброшен») makes earlier messages stale; it is not an answer. + if (sentAt) await answerQuestion(db, q.id, m("(неактуально: агент продолжил работу)"), "system").catch(() => {}); + else await answerQuestion(db, q.id, input.prompt ?? "", "terminal").catch(() => {}); } await updateSession(db, s.id, { status: "running", autoNudges: 0, lastActivityAt: now }); break; @@ -425,5 +438,8 @@ try { else await handle(event, raw ? (JSON.parse(raw) as HookInput) : {}); } catch (e) { log(`${event} session=${process.env.PEPPA_SESSION_ID}: ${(e as Error).stack ?? e}`); + // PEP-154: the hook's own failure goes to the error tracker, never to the project owner. + // A clear refusal (PeppaError) is not a failure of the platform. + if ((e as Error)?.name !== "PeppaError") await reportPlatformError(createDb(), e, { service: "hook", where: event }).catch(() => {}); } process.exit(0); diff --git a/packages/runner/src/recovery.ts b/packages/runner/src/recovery.ts index 61a699a8..d3cff078 100644 --- a/packages/runner/src/recovery.ts +++ b/packages/runner/src/recovery.ts @@ -16,6 +16,7 @@ import { PeppaError, projectAudience, raiseSessionQuestion, + platformFailure, touchQuestion, sendProjectMessage, setSetting, @@ -184,7 +185,9 @@ export async function restartTick(db: Db, o: { now: Date; cfg: WatchdogSettings; o.log(`#${s.id} ${s.taskKey ?? ""}: restarted automatically (${restarts.length}/${o.cfg.restartMax})`); } catch (e) { await logSessionEvent(db, s, "restart_failed", { error: (e as Error).message }); - await raiseSessionQuestion(db, s, "attention", m("{who}: не удалось перезапустить автоматически — {error}", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), error: (e as Error).message })); + // PEP-154: a platform error goes to the superadmins and the error tracker, not to the owner. + const why = await platformFailure(db, e, { service: "watchdog", where: `restart ${s.taskKey ?? `#${s.id}`}`, log: o.log, now: o.now }); + if (why) await raiseSessionQuestion(db, s, "attention", m("{who}: не удалось перезапустить автоматически — {error}", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), error: why })); } } } diff --git a/packages/shared/src/i18n/en/runner.ts b/packages/shared/src/i18n/en/runner.ts index 09db54cf..a26831fb 100644 --- a/packages/shared/src/i18n/en/runner.ts +++ b/packages/shared/src/i18n/en/runner.ts @@ -329,6 +329,10 @@ export const runner: Dict = { "Не удалось подготовить рабочую копию для агента: {error}": "Could not prepare a working copy for the agent: {error}", "(неактуально: агент перезапущен)": "(no longer relevant: the agent was restarted)", "(неактуально: агент остановлен)": "(no longer relevant: the agent was stopped)", + "(неактуально: агент продолжил работу)": "(no longer relevant: the agent went on working)", + "Обновление рабочей версии не запущено. Мы уже разбираемся — попробуйте ещё раз позже.": "The update of the live version did not start. We are already looking into it — please try again later.", + "⚠️ {key} не запущена. Мы уже разбираемся — попробуйте ещё раз позже.": "⚠️ {key} was not started. We are already looking into it — please try again later.", + "⚠️ Сбой в Peppa FACTORY ({where}): {error}": "⚠️ Failure in Peppa FACTORY ({where}): {error}", // Sharing and visibility "Участниками управляет только владелец проекта": "Only the project owner manages members", diff --git a/packages/shared/src/i18n/en/story.ts b/packages/shared/src/i18n/en/story.ts index 8a984261..53e4fe96 100644 --- a/packages/shared/src/i18n/en/story.ts +++ b/packages/shared/src/i18n/en/story.ts @@ -236,6 +236,17 @@ export const story: Dict = { инструмент: "tool", "Агент ещё ничего не сделал — шаги появятся здесь.": "The agent hasn't done anything yet — steps will appear here.", "Шагов не записано.": "No steps recorded.", + "Этот агент не сообщает о шагах.": "This agent does not report its steps.", + "Выполняет действие в проекте": "Doing something in the project", + "Запускает проверки": "Running the checks", + "Вносит изменения": "Making changes", + "Изучает проект": "Studying the project", + "Ищет нужное в проекте": "Searching the project", + "Смотрит в интернете": "Looking it up on the web", + "Поручил часть работы помощнику": "Handed part of the work to a helper", + "Сверяется с задачей": "Checking against the task", + "Работает над задачей": "Working on the task", + "Подробнее: исходный текст": "Details: the original text", "Этот агент не сообщает шаги (нет хуков) — смотри терминал.": "This agent doesn't report steps (no hooks) — watch the terminal.", "Шаги агента": "Agent steps", ошибка: "error", diff --git a/packages/shared/src/i18n/kk/runner.ts b/packages/shared/src/i18n/kk/runner.ts index 07de1745..c6c329cd 100644 --- a/packages/shared/src/i18n/kk/runner.ts +++ b/packages/shared/src/i18n/kk/runner.ts @@ -252,6 +252,10 @@ export const runner: Dict = { "Не удалось подготовить рабочую копию для агента: {error}": "Агентке жұмыс көшірмесін дайындау мүмкін болмады: {error}", "(неактуально: агент перезапущен)": "(өзекті емес: агент қайта іске қосылды)", "(неактуально: агент остановлен)": "(өзекті емес: агент тоқтатылды)", + "(неактуально: агент продолжил работу)": "(өзекті емес: агент жұмысын жалғастырды)", + "Обновление рабочей версии не запущено. Мы уже разбираемся — попробуйте ещё раз позже.": "Жұмыс нұсқасын жаңарту іске қосылмады. Біз себебін анықтап жатырмыз — кейінірек қайталап көріңіз.", + "⚠️ {key} не запущена. Мы уже разбираемся — попробуйте ещё раз позже.": "⚠️ {key} іске қосылмады. Біз себебін анықтап жатырмыз — кейінірек қайталап көріңіз.", + "⚠️ Сбой в Peppa FACTORY ({where}): {error}": "⚠️ Peppa FACTORY жүйесінде ақау ({where}): {error}", "Участниками управляет только владелец проекта": "Қатысушыларды тек жоба иесі басқарады", "Укажите логин участника": "Қатысушының логинін көрсетіңіз", "Нет доступа к коду проекта — войдите заново": "Жоба кодына қолжетімділік жоқ — қайта кіріңіз", diff --git a/packages/shared/src/i18n/kk/story.ts b/packages/shared/src/i18n/kk/story.ts index 6735bea4..57b9a8ea 100644 --- a/packages/shared/src/i18n/kk/story.ts +++ b/packages/shared/src/i18n/kk/story.ts @@ -220,6 +220,17 @@ export const story: Dict = { "инструмент": "құрал", "Агент ещё ничего не сделал — шаги появятся здесь.": "Агент әлі ештеңе жасаған жоқ — қадамдар осында пайда болады.", "Шагов не записано.": "Қадамдар жазылмаған.", + "Этот агент не сообщает о шагах.": "Бұл агент қадамдары туралы хабарламайды.", + "Выполняет действие в проекте": "Жобада әрекет орындап жатыр", + "Запускает проверки": "Тексерулерді іске қосып жатыр", + "Вносит изменения": "Өзгерістер енгізіп жатыр", + "Изучает проект": "Жобаны зерттеп жатыр", + "Ищет нужное в проекте": "Жобадан керегін іздеп жатыр", + "Смотрит в интернете": "Интернеттен қарап жатыр", + "Поручил часть работы помощнику": "Жұмыстың бір бөлігін көмекшіге тапсырды", + "Сверяется с задачей": "Тапсырмамен салыстырып жатыр", + "Работает над задачей": "Тапсырмамен жұмыс істеп жатыр", + "Подробнее: исходный текст": "Толығырақ: бастапқы мәтін", "Этот агент не сообщает шаги (нет хуков) — смотри терминал.": "Бұл агент қадамдарын хабарламайды (хуктар жоқ) — терминалды қараңыз.", "Шаги агента": "Агент қадамдары", "ошибка": "қате", diff --git a/packages/testkit/test/service-text.test.ts b/packages/testkit/test/service-text.test.ts new file mode 100644 index 00000000..2f761c0b --- /dev/null +++ b/packages/testkit/test/service-text.test.ts @@ -0,0 +1,229 @@ +// PEP-154: service text never reaches the person. Blocks like , command +// output, shell prompts, stack traces and absolute paths are cut out of messages and answers; +// an exception inside Peppa goes to the superadmins and the error tracker, not to the owner. +// Tests are named after the spec scenarios. +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { after, before, describe, test } from "node:test"; +// helpers must load first: it sets the isolated test env that runner modules read on load. +import { core, db, project, runner, teardown } from "./helpers.ts"; +import { MockBugsink } from "../src/mock-bugsink.ts"; +import { projects, questions, sessions, telegramOutbox, users } from "@peppa/db"; +import { and, eq, isNull, sql } from "drizzle-orm"; + +const { createBugsinkClient } = await import("@peppa/bugsink"); +const { renderQuestion, renderAnswered } = await import("@peppa/bot/render"); + +process.env.PEPPA_SECRET = "mock-secret-for-tests"; +const ROOT = join(dirname(fileURLToPath(import.meta.url)), "../../.."); +const bugsink = await new MockBugsink().start(); +process.env.BUGSINK_URL = bugsink.url; + +const NOTIFICATION = "\nb7f3\n/private/tmp/claude-501/tasks/b7f3.output\ncompleted\nBackground command finished\n"; +const TERMINAL_REPLY = [ + "Проверки не прошли, нужен ваш ответ.", + "", + "$ pnpm test", + "```", + "FAIL src/app.test.ts", + " ● оплата › считает сумму", + "```", + "TypeError: total is not a function", + " at sum (/Users/telecom/Dev/pay/src/app.ts:12:5)", + " at async run (node:internal/process/task_queues:95:5)", + "Файл: /Users/telecom/Dev/pay/src/app.ts", + "\x1b[31mЧто выбрать: чинить сейчас или отложить?\x1b[0m", +].join("\n"); + +let owner: Awaited>; +let admin: Awaited>; +let seq = 0; + +/** A story at work with its agent's session (no tmux: messages are raised as the hook does). */ +async function story() { + const key = `F${String.fromCharCode(65 + seq++)}`; + const p = await core.createProject(db, { slug: key.toLowerCase(), key, name: `Проект ${key}`, giteaOwner: "test", workspacePath: "/tmp/none", ownerId: owner.id }); + const created = await core.createTask(db, { projectId: p.id, title: "Оплата картой" }); + await core.updateTask(db, await core.resolveTask(db, created.key), { status: "in_progress" }); + const [s] = await db.insert(sessions).values({ projectId: p.id, taskId: created.task.id, tmuxName: `mock-${key}`, status: "waiting_input" }).returning(); + return { + project: p, + key: created.key, + taskId: created.task.id, + sessionId: s!.id, + session: () => core.getSession(db, s!.id), + ref: () => core.resolveTask(db, created.key), + asked: () => db.select().from(questions).where(eq(questions.taskId, created.task.id)).orderBy(questions.id), + thread: async () => { + await core.syncChats(db); + return core.chatMessagesView(db, (await core.ensureProjectChat(db, p.id)).id, { threadKey: `task:${created.task.id}` }); + }, + }; +} + +/** Runs the real peppa-hook like Claude Code does: payload on stdin. */ +function hook(event: string, payload: unknown, sessionId: number): Promise { + return new Promise((done) => { + const p = spawn(join(ROOT, "packages/runner/bin/peppa-hook"), [event], { env: { ...process.env, PEPPA_SESSION_ID: String(sessionId), PEPPA_GENERATION: "0" }, stdio: ["pipe", "ignore", "inherit"] }); + p.on("close", (code) => { + assert.equal(code, 0); + done(); + }); + p.stdin.end(JSON.stringify(payload)); + }); +} + +const outboxTo = async (chatId: number) => + (await db.select().from(telegramOutbox).where(sql`cast(json_extract(${telegramOutbox.params}, '$.chat_id') as text) = ${String(chatId)}`).orderBy(telegramOutbox.id)).map((r) => String(r.params.text)); +const openOf = (projectId: number) => db.select().from(questions).where(and(eq(questions.projectId, projectId), isNull(questions.answeredAt))); + +before(async () => { + owner = await core.upsertUserFromGitea(db, { id: 541, login: "mock-owner" }, { access_token: "x" }); + admin = await core.upsertUserFromGitea(db, { id: 542, login: "mock-admin" }, { access_token: "x" }); + await db.update(users).set({ telegramChatId: 5410, telegramUserId: 5410 }).where(eq(users.id, owner.id)); + await db.update(users).set({ telegramChatId: 5420, telegramUserId: 5420 }).where(eq(users.id, admin.id)); + await core.setPlatformAdmins(db, [admin.login]); +}); +after(async () => { + await bugsink.stop(); + await teardown(); +}); + +describe("PEP-154: фильтр служебного текста", () => { + test("userText: блоки, ANSI, вывод команд, приглашение оболочки, трассировка и пути убираются; адреса остаются", () => { + const out = core.userText(TERMINAL_REPLY); + assert.equal(out, "Проверки не прошли, нужен ваш ответ.\n\nФайл:\nЧто выбрать: чинить сейчас или отложить?"); + assert.equal(core.userText(out), out, "idempotent"); + assert.equal(core.userText(NOTIFICATION), ""); + assert.equal(core.userText("Готово. не для людей Результат: https://git.example.com/pay/pulls/7"), "Готово. Результат: https://git.example.com/pay/pulls/7"); + assert.equal(core.userText("Поправил `packages/core/src/chats.ts` и C:\\Users\\pm\\app.ts, проверил."), "Поправил и, проверил."); + // A person's own words are not rewritten: only what is certainly service text. + assert.equal(core.stripServiceBlocks("Синий, как в /Users/me/макет.png"), "Синий, как в /Users/me/макет.png"); + assert.equal(core.isServiceInput(NOTIFICATION), true); + assert.equal(core.isServiceInput("Синий"), false); + }); + + test("Реплика агента с выводом терминала и путём", async () => { + const st = await story(); + await hook("stop", { last_assistant_message: TERMINAL_REPLY }, st.sessionId); + // Two automatic nudges first (the story is at work), then the message for the person. + await hook("stop", { last_assistant_message: TERMINAL_REPLY }, st.sessionId); + await hook("stop", { last_assistant_message: TERMINAL_REPLY }, st.sessionId); + const [q] = await st.asked(); + assert.ok(q, "the owner got a message"); + assert.match(q.text, /Проверки не прошли, нужен ваш ответ\./); + assert.match(q.text, /чинить сейчас или отложить/); + for (const bad of ["/Users/", "pnpm test", "FAIL", "TypeError", "at sum", "\x1b", "```"]) assert.ok(!q.text.includes(bad), `no «${bad}» in the message`); + const thread = await st.thread(); + assert.ok(thread.some((m) => m.text.includes("Проверки не прошли"))); + assert.ok(!thread.some((m) => m.text.includes("/Users/") || m.text.includes("pnpm test"))); + const tg = renderQuestion(q, { taskKey: st.key, taskTitle: "Оплата картой", taskStatus: "in_progress", session: await st.session(), webUrl: "http://peppa.test" }); + assert.ok(!tg.text.includes("/Users/") && !tg.text.includes("tmux attach"), "Telegram: no path, no terminal command"); + assert.ok(renderQuestion(q, { taskKey: st.key, taskTitle: null, session: await st.session(), webUrl: "http://peppa.test", engineer: true }).text.includes("tmux attach"), "«Инженер» keeps the terminal command"); + }); + + test("Исходный текст для инженера", async () => { + const st = await story(); + const q = await core.raiseSessionQuestion(db, await st.session(), "attention", "Нужен ваш ответ. Файл /Users/telecom/Dev/pay/src/app.ts не открывается."); + assert.ok(!q.text.includes("/Users/")); + assert.match((await core.questionDetails(db, q.id)) ?? "", /\/Users\/telecom\/Dev\/pay\/src\/app\.ts/); + const clean = await core.askPm(db, await st.ref(), { kind: "question", text: "Какой цвет кнопки?", options: ["Синий", "Зелёный"] }); + assert.equal(await core.questionDetails(db, clean.id), null, "nothing was cut — nothing to keep"); + // A permission request keeps its command: that is what the person allows. + const perm = await core.raiseSessionQuestion(db, await st.session(), "permission", "Разрешить Bash: rm /Users/telecom/Dev/pay/tmp.txt", ["allow", "deny"]); + assert.match(perm.text, /\/Users\/telecom/); + }); + + test("От реплики ничего не осталось", async () => { + const st = await story(); + await assert.rejects(core.askPm(db, await st.ref(), { kind: "question", text: "только служебное" }), /служебный текст/); + assert.equal((await st.asked()).length, 0); + // The end of a turn with nothing for a person: the plain «агент ждёт» line, not the block. + for (let i = 0; i < 3; i++) await hook("stop", { last_assistant_message: NOTIFICATION }, st.sessionId); + const [q] = await st.asked(); + assert.equal(q?.text, "Агент закончил ход и ждёт вашего ответа."); + assert.equal(await core.addChatMessage(db, { chatId: (await core.ensureProjectChat(db, st.project.id)).id, kind: "event", authorKind: "agent", text: NOTIFICATION, dedupeKey: `mock:${st.key}` }), null); + }); +}); + +describe("PEP-154: ответом вопроса считается только ввод человека", () => { + test("Служебное уведомление в терминале", async () => { + const st = await story(); + const q = await core.askPm(db, await st.ref(), { kind: "question", text: "Какой цвет кнопки?", sessionId: st.sessionId }); + await hook("prompt", { prompt: NOTIFICATION }, st.sessionId); + const after = await core.getQuestion(db, q.id); + assert.equal(after.answeredAt, null, "the question stays open"); + assert.equal(after.answer, null); + const thread = await st.thread(); + assert.ok(!thread.some((m) => m.text.includes("task-notification") || (m.question?.answer ?? "").includes("task-notification")), "not in the chat: neither text nor answer"); + // Even if such a block came glued to a person's words, only the words are the answer. + const answered = await core.answerQuestion(db, q.id, `Синий\n${NOTIFICATION}`, "terminal"); + assert.equal(answered.answer, "Синий"); + assert.ok(!renderAnswered("Вопрос", answered).includes("task-notification")); + await assert.rejects(core.answerQuestion(db, (await core.askPm(db, await st.ref(), { kind: "question", text: "А размер?", sessionId: st.sessionId })).id, NOTIFICATION, "web")); + }); + + test("Человек печатает в терминале", async () => { + const st = await story(); + const q = await core.askPm(db, await st.ref(), { kind: "question", text: "Какой цвет кнопки?", sessionId: st.sessionId }); + await hook("prompt", { prompt: "Синий" }, st.sessionId); + const after = await core.getQuestion(db, q.id); + assert.equal(after.answer, "Синий"); + assert.equal(after.answeredVia, "terminal"); + }); + + test("Peppa сама пишет агенту", async () => { + const st = await story(); + const q = await core.raiseSessionQuestion(db, await st.session(), "attention", "Агент закончил ход и ждёт вашего ответа."); + const report = "Проверки PR красные: test\n$ pnpm test\nFAIL src/app.test.ts"; + await core.logSessionEvent(db, await st.session(), "input_sent", { text: report }); + await hook("prompt", { prompt: report }, st.sessionId); + const after = await core.getQuestion(db, q.id); + assert.equal(after.answeredVia, "system", "closed as stale, not answered"); + assert.ok(!(after.answer ?? "").includes("FAIL")); + }); +}); + +describe("PEP-154: ошибки платформы не идут владельцу проекта", () => { + const NO_QUIET = { quietFrom: null, quietTo: null }; + const autonomy = (now = new Date()) => runner.autonomyTick(db, { now, log: () => {} }); + + test("Диспетчер упал с исключением; та же ошибка повторяется", async () => { + // The platform project is connected to the error tracker (mock). + const platform = await project({ turns: [] }); + process.env.PEPPA_PLATFORM_KEY = platform.key; + core.resetErrorReporting(); + const client = createBugsinkClient({ url: bugsink.url, token: bugsink.token, teamId: bugsink.teamId, publicUrl: bugsink.url }); + await runner.connectErrorTracking(db, await core.getProject(db, platform.key), client, "http://peppa.test"); + + const tp = await project({ turns: [] }); + const p = await core.getProject(db, tp.key); + await db.update(projects).set({ ownerId: owner.id }).where(eq(projects.id, p.id)); + await core.setAutonomy(db, p.id, { level: "auto", ...NO_QUIET }); + // The start blows up inside Peppa: the sessions table is gone for one tick. + const now = new Date(); + const ingested = bugsink.ingested.length; + db.run(sql`ALTER TABLE runner_tasks RENAME TO runner_tasks_x`); + try { + await autonomy(now); + assert.equal((await openOf(p.id)).length, 0, "the owner gets no message"); + assert.equal((await outboxTo(5410)).length, 0, "nothing for the owner in Telegram"); + const alerts = (await outboxTo(5420)).filter((t) => t.includes("Сбой в Peppa FACTORY")); + assert.equal(alerts.length, 1, "the superadmin gets one message"); + assert.ok(bugsink.ingested.length > ingested, "the error tracker has the exception"); + // Ten minutes later the same error: no second message. + await autonomy(new Date(now.getTime() + 10 * 60_000)); + assert.equal((await outboxTo(5420)).filter((t) => t.includes("Сбой в Peppa FACTORY")).length, 1); + assert.equal((await openOf(p.id)).length, 0); + } finally { + db.run(sql`ALTER TABLE runner_tasks_x RENAME TO runner_tasks`); + } + }); + + test("Понятный отказ", async () => { + assert.equal(await core.platformFailure(db, new core.PeppaError("Подписка не выбрана — выберите её в настройках проекта."), { service: "watchdog", where: "dispatch PAY-7" }), "Подписка не выбрана — выберите её в настройках проекта."); + assert.equal(await core.platformFailure(db, new Error("SQLITE_ERROR: no such column: x"), { service: "watchdog", where: "dispatch PAY-7" }), null); + }); +}); -- 2.45.2 From dc6eb424a9894ec1ad96266cb76cfbee7332d845 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 13:24:37 +0500 Subject: [PATCH 027/215] PEP-155: plain last line, phone layout, AGENTS.md Co-Authored-By: Claude Fable 5.2 --- .peppa/memory.md | 1 + AGENTS.md | 1 + apps/web/app/(app)/chats/[chat]/page.tsx | 4 ++-- apps/web/components/ChatThreadList.tsx | 2 +- .../changes/pep-155-chat-thread-list/tasks.md | 16 ++++++++-------- packages/core/src/chat-threads.ts | 13 ++++++++----- packages/testkit/test/chats.test.ts | 3 ++- 7 files changed, 23 insertions(+), 17 deletions(-) diff --git a/.peppa/memory.md b/.peppa/memory.md index aedf6b99..9c3d4814 100644 --- a/.peppa/memory.md +++ b/.peppa/memory.md @@ -44,3 +44,4 @@ - Обращения (PEP-143): вся логика в `core/feedback.ts`, агент — `feedbackTick` (runner/feedback.ts, одна попытка, сбой → суперадмину без разбора); новый текст — в `i18n/{en,kk}/feedback.ts`; файл в Telegram — outbox-метод `sendPhoto` с `params.photo_path`; слово «команда» (люди) словарь запрещает — перефразируй или `glossary-ignore`; загрузка файлов из веба — route handler с multipart, не server action (предел 1 МБ). - Без повторов (PEP-151): `raiseSessionQuestion`/`askPm` при том же состоянии задачи (отпечаток, `core/message-state.ts`) не создают вопрос, а обновляют прежний и возвращают его id (закрытый открывается снова); свободный текст агента — `topic: "turn"`, «готово» — `topic: "review"`. Состояние — settings `question.state:`, `chat.repeat:`. В тесте нужен второй вопрос — меняй статус, коммит в check_runs или текст. - Продукт по ссылке (PEP-145): ссылка и её статус — только через `projectProduct` (`fix`/`broken`/`preparing`) и `productUrls`/`productLookLine`; системную стори заводит `productLinkTick` (в тестах выключен в helpers.ts, свой тест делает `delete process.env.PEPPA_PRODUCT_LINK`); «Показывать всем» — `getPublishMode`/`autoPublish` (вернул true — вопрос с кнопкой не слать). Менял `template/` — после мержа `scripts/push-template.sh`. +- Список переписки проекта (PEP-155): группы и строка треда — только `projectThreadList`/`threadGroup`/`plainLine` (core/chat-threads.ts); непрочитанное — `chat.threads.read::`; поиск по кириллице — в JS, не LIKE; телефон — `?list=1`. diff --git a/AGENTS.md b/AGENTS.md index 577e31f0..ae2b255e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,6 +38,7 @@ - **Чаты (PEP-62)**: таблицы `chats` (master на пользователя / project на проект, связанная Telegram-группа `tg_chat_id`) и `chat_messages` (тред = `thread_key` `task:|incident:|release:`, null — канал; `important` → мастер-лента; `dedupe_key`), `telegram_outbox.chat_message_id` (миграция 0015). `core/chats.ts`: `syncChats` — идемпотентная проекция `events` (курсор `chat.cursor.events`, список `EVENT_TEXT`), `questions`, `releases`/`incidents` (по `updated_at`, ключ `<вид>::<статус>`) в чаты; зовут бот (`reconcile`), вачдог (`tick`) и страница `/chats`; `masterFeed` = свои сообщения мастер-чата ∪ `important` проектов; `pruneChats` — TTL `PEPPA_CHAT_TTL_DAYS` (14) в вачдоге раз в час; мониторинг и дайджест из `deliverToUser` пишутся в мастер-чат. `runner/chats.ts` `postToChat`: тред стори → `answerAndDeliver` открытого вопроса, иначе `addStoryComment` (`chatMessageId` в payload, проекция не дублирует) + `sendToSession`; `/status|/task|/move|/help` без LLM. Telegram (бот): связка кодом (`createChatLinkCode`, `c…`, 10 мин; `t.me/?startgroup=<код>` или `/link <код>`), зеркало по курсору `chat.mirror.cursor` (тред — реплаем на первое сообщение: `threadAnchor` при отправке), в группу принимаются только реплаи и команды от пользователя с личной привязкой (`telegramAccountUser`) и доступом; кнопки вопросов работают в группе. Веб `/chats/[master|KEY]?thread=`, live-область `chats`. Тест `chats.test.ts` - **Группы чатов через свой бот (PEP-109)**: «Связать с Telegram» в чате — через собственного бота пользователя (PEP-85): `chats.tg_bot_user_id` (миграция 0018; null — общий бот, им связывает только суперадмин без своего бота: `createChatLinkCode(…, { sharedBot })`, остальным без бота — отказ с подсказкой). Код привязан к боту (`botUserId` в настройке кода): `acceptChatLink` принимает только от него и чужим ботом не сжигается; на `/link` без `@бота` с чужим кодом бот молчит (`chatLinkCodeBot`). Бот: `ownByChat` дополняется группами (`chatGroupBots` в `syncOwnBots`) — исходящие в группу идут через бота связки; входящие сообщения и кнопки группы обрабатывает только он (`linkedHere`). `clearUserBot` / `setUserBot` с другим ботом отвязывают его группы. Тест `chats-own-bot.test.ts` - **Обсуждение проекта (PEP-106)**: чат проекта открывается на «Обсуждении» — только сообщения людей в канале (`discussionMessages`: `thread_key` null, `kind` user, не команда); события агентов — `/chats/KEY?thread=feed`. `markDiscussionRead`/`discussionUnread` (`chat.read::`) → счётчик `navCounts.chats`, плашки чатов, ссылка «Обсуждение» после «Доски» на странице проекта. `postToChat` в канал проекта уведомляет остальных (`projectAudience`) событием уведомлений `chat`. `pruneChats` обсуждение не удаляет. Агентам обсуждение не уходит. Тест `discussion.test.ts` +- **Список переписки проекта (PEP-155)**: `/chats/KEY` слева — `components/ChatThreadList.tsx` из `projectThreadList(db, user, chat, { q })` (`core/chat-threads.ts`; `chatThreads` остался для прочих): «Чат с аналитиком» и «События агентов» сверху, ниже треды задач группами «Ждут вас» (открытый вопрос вида question/approval/permission, `review` без отложенного «Принять», `awaiting_approval`; `attention` сам тред ждущим не делает) · «В работе» · «Готово» (`
    `, свёрнуто; архивные — только в поиске) — правило в `threadGroup`. Строка: ключ, название, `StatusBadge`, `AgentBadge` (живой агент задачи, иначе агент последнего запуска), последнее сообщение одной строкой (`plainLine`: без значка события, код/пути/идентификаторы пропускаются — берётся сообщение раньше; у вопроса — сам вопрос), время, непрочитанное. Непрочитанное по тредам — `settings` `chat.threads.read::` `{base, seen}` (первый взгляд на список ставит `base`, `markThreadRead` при открытии треда; свои сообщения не считаются). Поиск `?q=` — ключ, название, текст сообщений чата (в JS: SQLite не сворачивает регистр кириллицы; последние 20 000 сообщений), в строке — найденный кусок. Телефон: `?list=1` — список вместо сообщений, без него — открытая переписка и «← К списку» (на широком экране обе колонки). Тест `chats.test.ts` - **Чат с аналитиком (PEP-110)**: сообщение человека в обсуждении проекта (PEP-106) → `analystChatTick` в тике вачдога (`runner/analyst-chat.ts`): `claudePrint` на подписке проекта (`PEPPA_INTAKE_BIN`, `PEPPA_ANALYST_CHAT_MODEL`), контекст `core/analyst-chat.ts` (`intakeContext` + `projectStatusBlock` со ссылками «где что смотреть»), ответ `{reply, create[]}` → сообщение `kind: user, authorKind: agent, authorLogin: «Аналитик»` в то же обсуждение + событие уведомлений `chat`; стори из `create` — только по явной просьбе, intake у них `done`. Курсор `chat.analyst:`, `analystPending` («печатает…»), сообщения старше `PEPPA_ANALYST_CHAT_MAX_AGE_MIN` (60) пропускаются, сбой — одна заметка без повторов, `PEPPA_ANALYST_CHAT=off`. Мок — роль `chat` в `mock-intake`; тест `analyst-chat.test.ts` - **Без повторов (PEP-151)**: одно состояние задачи — одно сообщение. `core/message-state.ts`: отпечаток (`messageFingerprint`: задача · вид вопроса · тип · статус · адрес результата · головной коммит и состояние проверок из `check_runs` · нормализованный текст без чисел и хэшей), `raiseOnce` внутри `raiseSessionQuestion` и `askPm`: отпечаток совпал с открытым сообщением задачи или с её последним — новый вопрос не создаётся, прежний получает свежий текст, снова открывается и считает повторы (`settings` `question.state:` `{fp, repeats, updatedAt}`; без миграции; вопросы без такой строки — старые, не сравниваются; окно 7 дней). Тип сообщения — `topic` у вызова: `turn` (конец хода агента, Stop-хук) и `review` («готово», `sendReviewCard` с головой PR — ищется среди всех сообщений задачи): с ним текст в отпечаток не входит. Виды `question`/`permission`/`approval` совпадают только с открытым. Новое место, которое шлёт пользователю свободный текст агента, — передавай `topic`. Чат: `syncChats` не вставляет событие с тем же текстом, что последняя строка треда задачи, а считает его на ней (`chat.repeat:`); виды сообщений отдают `repeats`/`updatedAt`. Telegram: `reconcile` бота правит уже отправленное сообщение (`qe::<повтор>`, не чаще `repeatEditMs` = 5 мин), «отвечено» после повтора — ключ `qa::r<повтор>:<чат>`. `remindTick` обновляет время сообщения (`touchQuestion`). Веб: `QuestionCard` — «обновлено …», «Повторов: N» под «Подробнее»; в чате у события «×N». Тест `no-repeats.test.ts` - **Чаты для продакта (PEP-117)**: `/chats` — обзор (`chatOverview` в core/chats.ts: карточка проекта — непрочитанное, открытые вопросы, последнее сообщение; сверху `inbox` «Ждут вашего ответа»); журнал — `/chats/master` («Все события»). В журналах (`master`, `?thread=feed`) поля ввода нет. `EVENT_TEXT`: смена статуса словами по `to` (и `from` для «на доработку»), сбои, которые Peppa чинит сама, не `important`. Подписи: `attention` — «Сообщение от фабрики» diff --git a/apps/web/app/(app)/chats/[chat]/page.tsx b/apps/web/app/(app)/chats/[chat]/page.tsx index 718db789..f1a8874b 100644 --- a/apps/web/app/(app)/chats/[chat]/page.tsx +++ b/apps/web/app/(app)/chats/[chat]/page.tsx @@ -225,9 +225,9 @@ export default async function ChatPage({ params, searchParams }: { params: Promi ))} -
    +
    {threads && ( -
    +
    )} diff --git a/apps/web/components/ChatThreadList.tsx b/apps/web/components/ChatThreadList.tsx index 9ff610c4..6bf2a195 100644 --- a/apps/web/components/ChatThreadList.tsx +++ b/apps/web/components/ChatThreadList.tsx @@ -46,7 +46,7 @@ export async function ChatThreadList({ const total = list.waiting.length + list.working.length + list.done.length; const rows = (items: ThreadRow[]) => items.map((r) => ); return ( -