From 218f35af86a8d855f59df79b636b2eea992ef691 Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Tue, 17 Nov 2026 17:55:09 +0500 Subject: [PATCH 01/73] =?UTF-8?q?PEP-197:=20=D1=84=D0=B0=D0=B1=D1=80=D0=B8?= =?UTF-8?q?=D0=BA=D0=B0=20=D0=BD=D0=B5=20=D1=81=D1=82=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D1=82=20=D1=81=D0=B5=D0=B1=D0=B5=20=D0=B7=D0=B0=D0=B4=D0=B0?= =?UTF-8?q?=D1=87=D0=B8=20=D0=BF=D0=BE=20=D0=BA=D1=80=D1=83=D0=B3=D1=83=20?= =?UTF-8?q?=E2=80=94=20=C2=AB=D0=9F=D1=80=D0=B5=D0=B4=D0=BB=D0=BE=D0=B6?= =?UTF-8?q?=D0=B5=D0=BD=D0=BE=C2=BB,=20=D0=BF=D1=80=D0=B5=D0=B4=D0=B5?= =?UTF-8?q?=D0=BB=D1=8B,=20=D0=B4=D1=83=D0=B1=D0=BB=D0=B8,=20=D0=B2=D0=B5?= =?UTF-8?q?=D1=80=D1=81=D0=B8=D1=8F=20=D1=81=20=D1=84=D0=B8=D0=BD=D0=B8?= =?UTF-8?q?=D1=88=D0=B5=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- AGENTS.md | 1 + apps/bot/src/bot.ts | 17 +- apps/web/app/(app)/actions.ts | 23 +- apps/web/app/(app)/chats/[chat]/page.tsx | 4 +- apps/web/app/(app)/p/[key]/page.tsx | 4 + apps/web/app/(app)/page.tsx | 10 +- apps/web/components/AgentTaskSummary.tsx | 41 + apps/web/components/Autonomy.tsx | 14 +- apps/web/components/Board.tsx | 90 +- apps/web/components/ProductCard.tsx | 5 +- apps/web/components/ProposalList.tsx | 62 + docs/glossary.md | 1 + .../changes/pep-197-no-task-loop/design.md | 10 + .../pep-197-no-task-loop/live-table.md | 28 + .../changes/pep-197-no-task-loop/proposal.md | 15 + .../specs/agent-task-origin/spec.md | 49 + .../changes/pep-197-no-task-loop/tasks.md | 16 + packages/cli/src/index.ts | 35 +- packages/core/src/autonomy.ts | 12 +- packages/core/src/incidents.ts | 3 + packages/core/src/index.ts | 2 + packages/core/src/message-intent.ts | 25 +- packages/core/src/product-review.ts | 18 +- packages/core/src/product.ts | 7 + packages/core/src/task-dedup.ts | 51 + packages/core/src/task-origin.ts | 272 + packages/core/src/tasks.ts | 10 +- .../migrations/0023_curious_steel_serpent.sql | 6 + .../db/migrations/meta/0023_snapshot.json | 4605 +++++++++++++++++ packages/db/migrations/meta/_journal.json | 7 + packages/db/src/schema.ts | 6 + packages/mcp/src/manager.ts | 2 + packages/runner/src/analyst-chat.ts | 6 +- packages/runner/src/autonomy.ts | 19 +- packages/runner/src/flow.ts | 7 +- packages/runner/src/hook.ts | 3 +- packages/runner/src/index.ts | 3 + packages/runner/src/intake.ts | 2 +- packages/runner/src/message-intent.ts | 2 +- packages/runner/src/product-link.ts | 2 +- packages/runner/src/product-review.ts | 132 +- packages/runner/src/proposals.ts | 21 + packages/runner/src/task-dedup.ts | 50 + packages/runner/src/task-tidy.ts | 67 + packages/shared/src/i18n/en/index.ts | 3 +- packages/shared/src/i18n/en/proposals.ts | 43 + packages/shared/src/i18n/kk/index.ts | 3 +- packages/shared/src/i18n/kk/proposals.ts | 43 + packages/testkit/src/mock-intake.ts | 13 +- packages/testkit/test/agent-task-tidy.test.ts | 48 + packages/testkit/test/autonomy-levels.test.ts | 70 +- .../testkit/test/product-acceptance.test.ts | 159 +- 52 files changed, 6094 insertions(+), 53 deletions(-) create mode 100644 apps/web/components/AgentTaskSummary.tsx create mode 100644 apps/web/components/ProposalList.tsx create mode 100644 openspec/changes/pep-197-no-task-loop/design.md create mode 100644 openspec/changes/pep-197-no-task-loop/live-table.md create mode 100644 openspec/changes/pep-197-no-task-loop/proposal.md create mode 100644 openspec/changes/pep-197-no-task-loop/specs/agent-task-origin/spec.md create mode 100644 openspec/changes/pep-197-no-task-loop/tasks.md create mode 100644 packages/core/src/task-dedup.ts create mode 100644 packages/core/src/task-origin.ts create mode 100644 packages/db/migrations/0023_curious_steel_serpent.sql create mode 100644 packages/db/migrations/meta/0023_snapshot.json create mode 100644 packages/runner/src/proposals.ts create mode 100644 packages/runner/src/task-dedup.ts create mode 100644 packages/runner/src/task-tidy.ts create mode 100644 packages/shared/src/i18n/en/proposals.ts create mode 100644 packages/shared/src/i18n/kk/proposals.ts create mode 100644 packages/testkit/test/agent-task-tidy.test.ts diff --git a/AGENTS.md b/AGENTS.md index 24acc19b..349fefe3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -56,6 +56,7 @@ - **Вложения (PEP-159)**: таблица `attachments` (миграция 0021: проект, загрузивший, `task_id`/`chat_message_id`/`event_id`, имя для показа, имя на диске, mime, размер), всё в `core/attachments.ts`: `sniffAttachment` (тип по содержимому — PNG/JPEG/WebP/GIF, PDF, DOCX/XLSX/PPTX по ZIP, текст TXT/MD/CSV/JSON; SVG/HTML/скрипт/архив/исполняемый — отказ), файлы `$PEPPA_HOME/files///.`, ≤5 файлов по ≤20 МБ. Загрузка двухшаговая: `POST /api/attachments` (multipart, `projectId`) сразу после выбора → id, форма несёт скрытые `attachment=`, действия (`postChatAction`/`postToChat`, `commentStoryAction`, `addTask`) зовут `linkAttachments` (только свои неотправленные файлы того же проекта); висящие старше суток убирает `pruneAttachments` (вачдог, раз в час). Отдача `GET /api/attachments/` (владелец/участник/суперадмин, иначе 404; nosniff, картинки и PDF inline, прочее скачиванием). UI: `components/AttachField.tsx` (скрепка, перетаскивание и Ctrl+V на поле), `components/Attachments.tsx` (миниатюры и строки). Аналитик: `attachmentsForModel` → `claudePrint({files})` для картинок и PDF, текст файлов (≤20 КБ) в промпт, Office — по имени; чат берёт файлы сообщений после курсора, `storyRefineTick` — новых комментариев и самой стори. Агент: `launch` и `syncSessionAttachments` копируют файлы стори в `<рабочая копия>/.peppa/attachments/` (внутри свой `.gitignore` с `*`), `get_task` — раздел «Приложенные файлы»; на отдельном хосте не копируется. Не сделано (второй PR): Telegram-бот, извлечение текста из Office. Тест `attachments.test.ts` - **«Взять в работу?» (PEP-185)**: `runner/pick-question.ts` — `pickQuestionTick` (тик вачдога после `autonomyTick`; `PEPPA_PICK_QUESTION=off`, в тестах выключен в `helpers.ts`): готовая задача бэклога (`readyBacklog`; проект не на паузе, `pick` не `auto`) → вопрос question «В работу» / «Пока нет», не больше `PEPPA_PICK_QUESTION_MAX` (3) открытых на проект; состояние — `settings` `pick.state:`; ушла из бэклога — закрывается системным ответом; ответ — `onPickAnswer` (`moveTask`). Тест `pick-question.test.ts` - **Памятка для ИИ-клиентов (PEP-190)**: `core/mcp-guide.ts` — один текст (`MCP_GUIDE`, английский): инструмент удалённого MCP `get_started`, начало `MANAGER_INSTRUCTIONS`, публичная страница `/mcp-guide` (вне `(app)`, кнопка `GuideCopy`); `GET_STARTED_HINT` — первая строка ответов `list_projects`/`get_task`. Новый инструмент удалённого MCP — добавить в список в `oauth.test.ts`. Тест `mcp-guide.test.ts` +- **Фабрика не ставит себе задачи по кругу (PEP-197)**: `tasks.origin` (`human` | `acceptance` | `incident` | `analyst`; миграция 0023 проставила старым по признакам), `tasks.proposed` («Предложено»: `status` остаётся `backlog`, `readyBacklog`, диспетчер и «всё сделано» такие задачи не видят; `moveTask` снимает флаг — человек решил) и `tasks.severity` (`breakage` «Поломка» | `important` | `minor`). `core/task-origin.ts`: пределы (`project.agent-limits:` `{inWork: 3, perPass: 5}`, меняет суперадмин — `peppa project agent-limits`; диспетчер не берёт задачу агента, когда `agentTasksInWork` ≥ предела, задачу человека предел не держит), `approveProposal`/`rejectProposal` («Не надо» → архив + `product.rejected:`, агент приёмки больше не предлагает), `mayAutoAccept` (настройка автономности `acceptOwn`: `mine` | `mine_breakage` по умолчанию | `all`; автомерж, автозакрытие и хук «готово к ревью» учитывают — задача агента без разрешения ждёт «Принять» владельца), версия проекта (`product.version:` `{ids, doneAt}`: задачи человека открываются в `createTask` через `touchVersion`; проход приёмки без поломок при всех принятых → «Версия готова» в том же сообщении, `ProjectProduct.versionDone` → «Готово» на карточке; после финиша улучшения копятся в `product.digest:` и раз в неделю `productDigestTick` заводит их в «Предложено»; новая задача человека начинает новую версию), `agentTaskSummary` (люди / агенты / траты за 7 дней; суперадмину на Главной, CLI `peppa agent-tasks report`). `runner/task-dedup.ts` `checkDuplicate`: сначала то же название, потом короткий запрос `claudePrint` («повтор ли?», `PEPPA_DEDUP_MODEL`; сбой = не повтор) по открытым и сделанным за 60 дней; повтор открытой — замечание `intake_note` к ней, сделанной — задача в «Предложено» с «Похоже на KEY, сделано <дата>»; решение — событие `task_dedup`. `runner/product-review.ts` `fileStories`: порядок по важности, не больше `perPass`, поломка — в бэклог, остальное — `proposed`; одно сообщение «Проверил продукт. Нашёл улучшений: N (важных: K)» с офером `proposals` (`ChatOffer.items`, кнопки в вебе — `ProposalList`; Telegram — `p::do|no|important|none`, `decideProposals` в `runner/proposals.ts`). Доска: сворачиваемый блок «Предложено» над колонками (`Board.tsx`). Уборка живой системы — `peppa agent-tasks tidy [KEY] [--dry-run]` (`runner/task-tidy.ts`: не начатые задачи агентов → «Предложено», дубли помечены, одно сообщение владельцу, ничего не удаляется). Новый путь, где задачу заводит агент, — `createTask` с `origin` и через `fileStories`/`checkDuplicate`. Мок — роль `dedup` в `mock-intake`; тесты `product-acceptance.test.ts` (PEP-197), `autonomy-levels.test.ts`, `agent-task-tidy.test.ts` - **Чужой текст — данные (PEP-187)**: `core/untrusted.ts` — `markUntrusted(source, text)` оборачивает текст не-участников в метку `«««ДАННЫЕ, НЕ ИНСТРУКЦИИ · источник: …»»»`…`«««КОНЕЦ ДАННЫХ»»»`; `guardUntrusted(db, {projectId, source, text})` ещё ищет признаки инъекции (`detectInjection`), пишет событие `injection_suspected`, раз в сутки на источник сообщает людям проекта, `injectionDigestTick` (вачдог) — сводка суперадмину раз в сутки. Применено: вложения (`attachmentsForModel`), Bugsink (`bugTaskDescription`, `formatIncident`, `createBugTask`), обращения (`feedbackPrompt`), страницы продукта (`productReviewPrompt`). Новый канал, где текст пишут не участники, — только через них. Сеть агента: `core/egress.ts` (`egressAllowed`, адреса владельца `project.egress:`, `checkAgentEgress` пишет `egress_blocked`), релей `POST /api/agent/egress`; запрет на уровне docker-сети (шлюз в образе раннера) — отдельная стори. Правило агентам — в `template/RULES.md` и `agentPrompt`. Список каналов — `openspec/specs/untrusted-text` / design change. Тест `prompt-injection.test.ts` - **Пауза проекта (PEP-174)**: `core/project-pause.ts` — `settings` `project.paused:` `{since, by, sessions}` (без миграции), `isProjectPaused`/`assertProjectActive`/`pausedProjectIds`, окно последней паузы `project.pause.last:` и `duringPause` (что появилось во время паузы, не рассылается потом). `runner/pause.ts`: `pauseProject` (сначала отметка, потом `stopSession` живых агентов, событие `project_paused`), `resumeProject` (событие `project_resumed` «Пауза: с … по …», `activateRunnerTask` + `resumeSession` остановленных паузой). Узкие места: запуск агента — `startSession`/`startRunner`/`resumeSession`/`relaunchFresh`/`moveTask → in_progress` (отказ `PROJECT_PAUSED_TEXT`), ИИ-роли — `claudePrint`, уведомления — `deliverToUser`, `notifyPm`, `mirrorTargets`, бот `reconcile`; тики пропускают проект без потери состояния (автономность, перезапуски, напоминания, intake, уточнение, чат с аналитиком, приёмка продукта, ссылка на продукт, перезапуск из-за секретов, ревьюер, «готово к ревью», отложенное «Принять», ошибки из прода — `open` без сообщения), вебхуки (красные проверки, комментарии Gitea) записываются без запуска агента; живой агент проекта на паузе вачдог останавливает сам и дописывает в `sessions`. Веб: `components/ProjectPause.tsx` (кнопка с подтверждением, плашка, метка «На паузе»), «⋯ Настройки проекта → Пауза», «Ждут вашего ответа»/счётчики/дайджест без проектов на паузе. CLI `peppa project pause|resume `. Новое место, которое запускает агента, зовёт модель или пишет человеку по проекту, — через эти узкие места или с `isProjectPaused`. Тест `project-pause.test.ts` - **Прогресс на Главной (PEP-77)**: `progressOverview` (core/progress.ts: стори по колонкам доски без архивных, стори в работе с агентом и прогрессом tasks.md, ждущие «Принять»; итог — только свои проекты, суперадмину отдельно `others`), раздел «Прогресс» — `components/ProgressOverview.tsx` diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts index a13c039c..8252a97f 100644 --- a/apps/bot/src/bot.ts +++ b/apps/bot/src/bot.ts @@ -78,7 +78,7 @@ import { } from "@peppa/core"; import { projects, tasks, type Db } from "@peppa/db"; import { formatTaskKey, voiceStoriesEnabled } from "@peppa/shared"; -import { acceptTask, answerAndDeliver, classifyMessage, decideIncident, moveTask, postToChat, REQUEST_SENT_TEXT, requestSubscription, resumeSession, stopSession } from "@peppa/runner"; +import { acceptTask, answerAndDeliver, classifyMessage, decideIncident, decideProposals, moveTask, postToChat, REQUEST_SENT_TEXT, requestSubscription, resumeSession, stopSession } from "@peppa/runner"; import { INTENT_TEXT, statusAnswer } from "@peppa/core"; import { AsyncLocalStorage } from "node:async_hooks"; import { eq, sql } from "drizzle-orm"; @@ -701,6 +701,15 @@ export function createBot(o: BotOptions) { return "done"; } + /** PEP-197: the owner decides on stories the factory suggested. */ + async function onProposalButton(user: User, c: TgCallbackQuery, parts: string[]): Promise { + const ids = (parts[1] ?? "").split(",").map(Number).filter((n) => Number.isInteger(n) && n > 0); + const choice = parts[2]; + if (choice !== "do" && choice !== "no" && choice !== "important" && choice !== "none") return tr("Неизвестная кнопка"); + const n = await decideProposals(db, user, ids, choice); + return choice === "do" || choice === "important" ? tr("Принято, задач: {n}", { n }) : tr("Отклонено: {n}", { n }); + } + /** A superadmin's buttons under a report: `f::o` (a story from option N), `dup`, `no`. */ async function onFeedbackButton(user: User, c: TgCallbackQuery, parts: string[]): Promise { const id = Number(parts[1]); @@ -976,6 +985,12 @@ export function createBot(o: BotOptions) { await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`)); return "done"; } + // PEP-197: «Делать» / «Не надо» under the acceptance agent's message: `p::do|no|important|none`. + if (parts[0] === "p") { + const toast = await onProposalButton(user, c, parts).catch((e) => (e instanceof PeppaError ? e.message : (log(`proposal: ${(e as Error).stack ?? e}`), tr("Ошибка")))); + await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`)); + return "done"; + } if (parts[0] === "f") { const toast = await onFeedbackButton(user, c, parts).catch((e) => (log(`feedback: ${(e as Error).stack ?? e}`), tr("Ошибка"))); wakeOutbox?.(); diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index c9dff167..4146f638 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -63,7 +63,7 @@ import { setUiMode, } from "@peppa/core"; import { attachmentLabel, fixFeedback, linkAttachments, linkFeedback, parseAttachmentIds, rejectFeedback, restoreProject } from "@peppa/core"; -import { deleteProject } from "@peppa/runner"; +import { deleteProject, decideProposals } from "@peppa/runner"; import { bugsinkFromEnv } from "@peppa/bugsink"; import { loadEnv } from "@peppa/shared"; import { pauseProject, resumeProject, acceptStory, autoPublish, fixStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProjectOnce, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, syncSessionAttachments, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, managesProject, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, removeOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription, requestSubscription } from "@peppa/runner"; @@ -473,6 +473,7 @@ export async function setAutonomyAction(f: FormData) { merge: str(f, "merge") as AutonomySettings["merge"], close: str(f, "close") as AutonomySettings["close"], closeAfterHours: Number(str(f, "closeAfterHours")), + acceptOwn: (str(f, "acceptOwn") || undefined) as AutonomySettings["acceptOwn"], idlePush: f.get("idlePush") === "on", idlePushHours: Number(str(f, "idlePushHours")), quietFrom: quiet ? hour("quietFrom") : null, @@ -481,6 +482,26 @@ export async function setAutonomyAction(f: FormData) { }); } +/** PEP-197: «Делать» / «Не надо» on a suggested story (board, chat). */ +export async function proposalAction(f: FormData) { + const user = asWebActor(await requireUser()); + await attempt(f, async () => { + const choice = str(f, "choice"); + if (choice !== "do" && choice !== "no" && choice !== "important" && choice !== "none") throw new PeppaError(m("Эта кнопка уже не работает.")); + const ids = str(f, "ids").split(",").map(Number).filter((n) => Number.isInteger(n) && n > 0); + await decideProposals(db, user, ids, choice); + }); +} + +/** PEP-197: «Принимать сами» — whose stories are accepted without the owner. */ +export async function setAcceptOwnAction(f: FormData) { + const user = asWebActor(await requireUser()); + await attempt(f, async () => { + const p = await projectForUser(db, user.id, Number(str(f, "projectId"))); + await setAutonomy(db, p.id, { acceptOwn: str(f, "acceptOwn") as AutonomySettings["acceptOwn"] }); + }); +} + export async function removeProjectMember(f: FormData) { const user = asWebActor(await requireUser()); await attempt(f, async () => { diff --git a/apps/web/app/(app)/chats/[chat]/page.tsx b/apps/web/app/(app)/chats/[chat]/page.tsx index b082145d..6ae2ef79 100644 --- a/apps/web/app/(app)/chats/[chat]/page.tsx +++ b/apps/web/app/(app)/chats/[chat]/page.tsx @@ -11,6 +11,7 @@ import { AgentBadge } from "@/components/AgentBadge"; import { ChatThreadList } from "@/components/ChatThreadList"; import { ago, Empty, Flash, linkify, PageHeader, StatusBadge } from "@/components/common"; import { Hidden, QuestionCard } from "@/components/cards"; +import { ProposalList } from "@/components/ProposalList"; import { Dictate } from "@/components/Dictate"; import { Attachments } from "@/components/Attachments"; import { AttachField } from "@/components/AttachField"; @@ -354,7 +355,8 @@ async function MessageItem({ m, q, back, showThread, masterView, mine = false, f )} {/* PEP-153: a question is answered, not filed — the task is one press away. */} - {m.offer && ( + {m.offer?.kind === "proposals" && } + {m.offer && m.offer.kind !== "proposals" && (
{m.offer.kind === "task" && ( diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx index 2933cd4b..f6cafa70 100644 --- a/apps/web/app/(app)/p/[key]/page.tsx +++ b/apps/web/app/(app)/p/[key]/page.tsx @@ -164,6 +164,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr const pr = columnOf(x.status) === "in_progress" ? taskProgress(p, x.openspecChange) : null; return { key: `${p.key}-${x.number}`, + id: x.id, title: x.title, status: x.status, column: columnOf(x.status), @@ -175,6 +176,9 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr accepted: accepted.has(x.id) ? t.text(PENDING_ACCEPT_LABEL) : null, delayed: delayed.has(x.id) && x.status !== "done" ? t.text(PLATFORM_DELAY_LABEL) : null, queued: queued.get(x.id) ?? null, + proposed: x.proposed, + severity: (x.severity as Card["severity"]) ?? null, + agentMade: x.origin !== "human", refining: refining.has(x.id) ? (refining.get(x.id) === "waiting" ? t("ждёт ваших ответов") : t("уточняется")) : null, }; }); diff --git a/apps/web/app/(app)/page.tsx b/apps/web/app/(app)/page.tsx index 25327f82..c93c7f44 100644 --- a/apps/web/app/(app)/page.tsx +++ b/apps/web/app/(app)/page.tsx @@ -1,7 +1,8 @@ import { redirect } from "next/navigation"; -import { claimWelcome, isSuperadmin, listUserProjects, onboardingChecklist, pendingFeedback, platformDelayOverview, progressOverview } from "@peppa/core"; +import { agentTaskSummary, claimWelcome, isSuperadmin, listUserProjects, onboardingChecklist, pendingFeedback, platformDelayOverview, progressOverview } from "@peppa/core"; import { AdminFeedbackCard } from "@/components/Feedback"; import { PlatformDelays } from "@/components/PlatformDelays"; +import { AgentTaskSummary } from "@/components/AgentTaskSummary"; import { ProgressOverview } from "@/components/ProgressOverview"; import { OnboardingChecklist } from "@/components/Onboarding"; import { PugBanner } from "@/components/PugMascot"; @@ -26,6 +27,8 @@ export default async function Home({ searchParams }: { searchParams: Promise<{ e const reports = (await isSuperadmin(db, user)) ? await pendingFeedback(db) : []; // PEP-150: delays on the platform's side are the superadmin's to watch, not the owners'. const delays = (await isSuperadmin(db, user)) ? await platformDelayOverview(db) : []; + // PEP-197: people against factory-made tasks per project — the superadmin's view. + const agentTasks = (await isSuperadmin(db, user)) ? (await agentTaskSummary(db)).filter((r) => r.agents > 0).slice(0, 15) : []; return ( }> @@ -51,6 +54,11 @@ export default async function Home({ searchParams }: { searchParams: Promise<{ e )} + {agentTasks.length > 0 && ( +
+ +
+ )}
diff --git a/apps/web/components/AgentTaskSummary.tsx b/apps/web/components/AgentTaskSummary.tsx new file mode 100644 index 00000000..73792f14 --- /dev/null +++ b/apps/web/components/AgentTaskSummary.tsx @@ -0,0 +1,41 @@ +import Link from "next/link"; +import type { AgentTaskRow } from "@peppa/core"; +import { Badge } from "@/components/ui/badge"; +import { getT } from "@/lib/i18n"; + +/** + * PEP-197: for the superadmin — per project, tasks of people and of agents, how many of the + * agents' wait for a decision, and where agents made more than people. Money only in «Инженер». + */ +export async function AgentTaskSummary({ rows, engineer }: { rows: AgentTaskRow[]; engineer: boolean }) { + const t = await getT(); + return ( +
+ + + + + + + + {/* glossary-ignore: сумма показана только в режиме «Инженер» */} + {engineer && } + + + + {rows.map((r) => ( + + + + + + {engineer && } + + ))} + +
{t("Проект")}{t("Люди")}{t("Фабрика")}{t("Ждут решения")}{t("За неделю, $")}
+ {r.name} {r.agentsMoreThanHuman && {t("фабрика завела больше")}} + {r.human}{r.agents}{r.proposed}{r.agentCostWeek.toFixed(2)}
+
+ ); +} diff --git a/apps/web/components/Autonomy.tsx b/apps/web/components/Autonomy.tsx index 9100309a..eef1dc62 100644 --- a/apps/web/components/Autonomy.tsx +++ b/apps/web/components/Autonomy.tsx @@ -1,6 +1,6 @@ // PEP-23: project autonomy in «⋯ Настройки проекта» — preset levels and the individual settings. import { AUTONOMY_LEVEL_HINT, AUTONOMY_LEVEL_RU, AUTONOMY_LEVELS, autonomyLevel, type AutonomyLevel, type AutonomySettings } from "@peppa/core"; -import { setAutonomyAction } from "@/app/(app)/actions"; +import { setAcceptOwnAction, setAutonomyAction } from "@/app/(app)/actions"; import { Hidden } from "@/components/cards"; import { Button } from "@/components/ui/button"; import { Input, Label, NativeSelect } from "@/components/ui/input"; @@ -28,6 +28,18 @@ export async function AutonomyPanel({ projectId, settings, back, engineer = fals )}

{current === "custom" ? t("Своя комбинация настроек ниже.") : t.text(AUTONOMY_LEVEL_HINT[current])}

+ + + + + {engineer && (
{t("Настроить подробно")} diff --git a/apps/web/components/Board.tsx b/apps/web/components/Board.tsx index 73d01066..a01be5b1 100644 --- a/apps/web/components/Board.tsx +++ b/apps/web/components/Board.tsx @@ -5,7 +5,7 @@ import Link from "next/link"; import { useRouter } from "next/navigation"; import { useEffect, useState, useTransition } from "react"; import { ChevronDown, ChevronRight, ChevronsDown, ChevronsUp, Lock } from "lucide-react"; -import { moveTaskCard } from "@/app/(app)/actions"; +import { moveTaskCard, proposalAction } from "@/app/(app)/actions"; import { reorderTaskInline } from "@/app/(app)/board-actions"; import { Button } from "@/components/ui/button"; import { Badge } from "@/components/ui/badge"; @@ -17,6 +17,8 @@ import { m } from "@peppa/shared/i18n"; export type Column = "backlog" | "in_progress" | "review" | "done"; export interface Card { key: string; + /** PEP-197: the task id (the buttons of «Предложено» send ids). */ + id?: number; title: string; status: string; column: Column; @@ -36,6 +38,12 @@ export interface Card { delayed?: string | null; /** PEP-182: place in the queue for a free agent (in work, no agent yet). */ queued?: number | null; + /** PEP-197: a story of an agent the owner has not decided on — shown in «Предложено», not in the backlog. */ + proposed?: boolean; + /** PEP-197: «Поломка» / «Важно» / «Мелочь» on stories of the acceptance agent. */ + severity?: "breakage" | "important" | "minor" | null; + /** PEP-197: made by an agent, not by a person. */ + agentMade?: boolean; } export interface CardProgress { done: number; @@ -122,6 +130,7 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) { }); return (
+ x.proposed)} back={back} /> {error && (

{t.text(error)} @@ -129,7 +138,7 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) { )}

{COLUMNS.map((c) => { - const list = cards.filter((x) => x.column === c.id); + const list = cards.filter((x) => x.column === c.id && !x.proposed); const collapsed = c.id === "done" && doneCollapsed; return (
)} + {card.severity === "breakage" && !card.proposed && ( + + {t("Поломка")} + + )} {card.agent && } {card.progress && } {(STATUS[card.status] || NEXT[c.id] || card.epic || card.blocked) && ( @@ -255,3 +269,75 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) {
); } + +const SEVERITY: Record = { + breakage: { label: m("Поломка"), variant: "danger" }, + important: { label: m("Важно"), variant: "warn" }, + minor: { label: m("Мелочь"), variant: "muted" }, +}; + +/** + * PEP-197: «Предложено» — what the factory suggests on its own. Folded, with a counter; the + * dispatcher takes nothing from here. «Делать» sends a story to the backlog, «Не надо» archives + * it and the acceptance agent will not suggest it again. Buttons are at least 44 px for a thumb. + */ +function Proposed({ cards, back }: { cards: Card[]; back: string }) { + const t = useT(); + if (!cards.length) return null; + const ids = cards.map((c) => c.id).join(","); + const important = cards.filter((c) => c.severity !== "minor"); + return ( +
+ + {t("Предложено")} + {cards.length} + +

{t("Это придумала сама фабрика. Пока вы не нажмёте «Делать», агенты за эти задачи не возьмутся.")}

+
+ {cards.map((card) => ( +
+ + {card.key} {card.title} + + {card.severity && SEVERITY[card.severity] && ( + + {t(SEVERITY[card.severity]!.label)} + + )} +
+ + + + +
+ ))} +
+
+ + + {important.length > 0 && ( + + )} + +
+
+ ); +} + +function ProposalButtons() { + const t = useT(); + return ( + <> + + + + ); +} diff --git a/apps/web/components/ProductCard.tsx b/apps/web/components/ProductCard.tsx index ff0597f4..b56c2908 100644 --- a/apps/web/components/ProductCard.tsx +++ b/apps/web/components/ProductCard.tsx @@ -71,7 +71,10 @@ export async function ProductCard({ {link ? (
- {live ? t("Ваш продукт работает") : t("Ваш продукт готов — пока его видите только вы")} + + {live ? t("Ваш продукт работает") : t("Ваш продукт готов — пока его видите только вы")} + {product.versionDone && {t("Готово")}} + {live ? t("Открыт для всех по адресу") : t("Адрес:")} {host(link.url)} · {t("обновлён {when}", { when: ago(link.at, t) })} {link.stories.length > 0 && <> · {t("вошли {tasks} {keys}", { tasks: task("pl"), keys: link.stories.slice(0, 6).join(", ") })}} diff --git a/apps/web/components/ProposalList.tsx b/apps/web/components/ProposalList.tsx new file mode 100644 index 00000000..8d93c0ff --- /dev/null +++ b/apps/web/components/ProposalList.tsx @@ -0,0 +1,62 @@ +// PEP-197: the acceptance agent's list in the project chat — per item «Делать» / «Не надо», +// below «Делать важные» / «Отклонить всё». Once an item is decided the buttons give way to the outcome. +import { proposalAction } from "@/app/(app)/actions"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { getT } from "@/lib/i18n"; +import type { ProposalItem } from "@peppa/core"; +import { m } from "@peppa/shared/i18n"; + +const SEVERITY = { + breakage: { label: m("Поломка"), variant: "danger" }, + important: { label: m("Важно"), variant: "warn" }, + minor: { label: m("Мелочь"), variant: "muted" }, +} as const; + +export async function ProposalList({ items, back }: { items: ProposalItem[]; back: string }) { + const t = await getT(); + const open = items.filter((i) => i.open); + return ( +
+ {items.map((i) => ( +
+
+ {i.key} + {i.title} + {i.severity && ( + + {t(SEVERITY[i.severity].label)} + + )} +
+ {i.open ? ( +
+ + + + +
+ ) : ( + {i.decision === "rejected" ? t("Отклонено") : i.severity === "breakage" ? t("Уже в бэклоге") : t("Взято в бэклог")} + )} +
+ ))} + {open.length > 0 && ( +
+ i.id).join(",")} /> + + + +
+ )} +
+ ); +} diff --git a/docs/glossary.md b/docs/glossary.md index fa1c5158..e25bec44 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -42,3 +42,4 @@ | Список задач | доска, бэклог | канбан-борд, backlog | «Бэклог» допустим как название колонки | | Ошибки продукта | баги | инциденты, Bugsink, Sentry | Вкладка «Баги» | | Сообщение о проблеме в Peppa FACTORY | обращение, сообщить о проблеме | фидбэк, баг-репорт, репорт, жалоба | Кнопка «Сообщить о проблеме», раздел «Обращения»; статусы: получено, разбираем, исправлено, отклонено. «Команда» в «передали команде» — люди, которые делают Peppa FACTORY | +| Задача, которую фабрика придумала сама | предложено, «Делать» / «Не надо» | автозадача, auto-task, авто-стори | Блок «Предложено» на доске: агенты за такие задачи не берутся, пока владелец не нажмёт «Делать»; «Поломка» идёт в работу сразу | diff --git a/openspec/changes/pep-197-no-task-loop/design.md b/openspec/changes/pep-197-no-task-loop/design.md new file mode 100644 index 00000000..6b16ee4e --- /dev/null +++ b/openspec/changes/pep-197-no-task-loop/design.md @@ -0,0 +1,10 @@ +## Решения +- **Не новый статус, а флаг.** «Предложено» = `status=backlog` + `proposed=1`: все читатели статусов (доска, MCP, бот) не ломаются; `readyBacklog` и пуш простоя пропускают `proposed`. `moveTask` снимает флаг (человек решил). +- **Происхождение** — колонка `origin` (`human|acceptance|incident|analyst`), `severity` (`breakage|important|minor`) — для задач агента приёмки; `breakage` — «Поломка». Миграция проставляет старым по признакам (подпись «Заведено продакт-агентом на приёмке», `incidents.task_id`, «[Дубль …]» / заметка аналитика). +- **Агентские задачи** = origin ≠ human. Предел «в работе» (3) считается по ним в диспетчере; ручное перетаскивание его обходит. +- **Приёмка (autonomy.acceptOwn)**: `mine` / `mine_breakage` (по умолчанию) / `all`. Задача человека принимается автомержем всегда (как раньше, при `merge=auto`); задача агента — по настройке. Не разрешено → автомерж и автозакрытие её пропускают, хук шлёт обычное «готово к ревью». +- **Дубли** — `runner/task-dedup.ts`: сначала точное совпадение нормализованного названия, потом короткий запрос `claudePrint` («повтор ли?») по открытым и сделанным за 60 дней; сбой модели = «не повтор». Решение пишется событием `task_dedup`. +- **Одно сообщение** — сообщение «Продакта» в обсуждении проекта + `settings chat.offer:` вида `proposals` (кнопки в вебе), в Telegram — сообщение владельцу с кнопками `p::do|no`, `p::important|none`. +- **Версия** — `settings product.version:` `{ids, doneAt}`: задачи человека, открытые на момент начала; финиш — все `done` и проход без поломок. Эпик как версия не делаем (в документе — вне объёма). +- Пределы проекта — `settings project.agent-limits:` `{inWork, perPass}`, меняет суперадмин (`peppa project agent-limits`). +- Уборка и сводка — `peppa agent-tasks tidy|report` (по живой базе). diff --git a/openspec/changes/pep-197-no-task-loop/live-table.md b/openspec/changes/pep-197-no-task-loop/live-table.md new file mode 100644 index 00000000..bad3293f --- /dev/null +++ b/openspec/changes/pep-197-no-task-loop/live-table.md @@ -0,0 +1,28 @@ +# Таблица по живой базе (копия на 2026-11-17, миграция 0023 применена к копии) + +``` +проект | человек | агенты | предложено | агенты за 7 дн. | траты агентов за 7 дн., $ | агентов больше +TR | 6 | 76 | 0 | 76 | 69.62 | да +BRM | 35 | 53 | 0 | 53 | 38.52 | да +WTC | 4 | 46 | 0 | 46 | 18.14 | да +TPTIP | 8 | 70 | 0 | 70 | 16.66 | да +DIK | 9 | 63 | 0 | 63 | 15.07 | да +FRTVL | 4 | 25 | 0 | 25 | 9.73 | да +QLFW | 12 | 27 | 0 | 27 | 5.50 | да +EA | 2 | 14 | 0 | 14 | 4.12 | да +PEP | 196 | 2 | 0 | 2 | 4.03 | нет +SBX | 5 | 0 | 0 | 0 | 0.00 | нет +PCHK | 3 | 0 | 0 | 0 | 0.00 | нет +HWT | 5 | 0 | 0 | 0 | 0.00 | нет +TZK | 4 | 0 | 0 | 0 | 0.00 | нет +YFYEHBSBSB | 1 | 0 | 0 | 0 | 0.00 | нет +RCT | 2 | 0 | 0 | 0 | 0.00 | нет +CLT | 11 | 0 | 0 | 0 | 0.00 | нет +SP | 5 | 0 | 0 | 0 | 0.00 | нет +IA | 2 | 0 | 0 | 0 | 0.00 | нет +INA | 2 | 0 | 0 | 0 | 0.00 | нет +TSA | 1 | 0 | 0 | 0 | 0.00 | нет +HELLO | 1 | 0 | 0 | 0 | 0.00 | нет +``` + +Траты — по сессиям задач агентов с активностью за 7 дней. «Человек» — задачи без признаков агента. diff --git a/openspec/changes/pep-197-no-task-loop/proposal.md b/openspec/changes/pep-197-no-task-loop/proposal.md new file mode 100644 index 00000000..ad207ff9 --- /dev/null +++ b/openspec/changes/pep-197-no-task-loop/proposal.md @@ -0,0 +1,15 @@ +## Why +Агент приёмки (PEP-112) заводит задачи на улучшения, диспетчер сам берёт их, автомерж принимает, агент приёмки снова смотрит продукт — круг без человека тратит подписки, проект не заканчивается (WTC — 50 задач, повторы по 4–5 раз). + +## What Changes +- У задачи есть происхождение (`tasks.origin`): человек, агент приёмки, разбор ошибок, аналитик; старым проставляется по признакам. +- Задачи агента приёмки попадают в «Предложено» (`tasks.proposed`), диспетчер их не берёт; поломка — сразу в бэклог с пометкой. +- Проверка на повторы перед созданием; замечание к открытой задаче вместо дубля. +- Одно сообщение владельцу после прохода приёмки, кнопки «Делать» / «Не надо» (+ «Делать важные», «Отклонить всё»). +- Версия проекта с финишем («Версия готова»), после неё — только поломки и недельная сводка. +- Пределы: ≤3 задач агентов в работе, ≤5 предложений за проход (суперадмин меняет). +- Автомерж принимает только задачи человека (и поломки) — настройка «Принимать сами». +- Разовая уборка и сводка суперадмину (CLI). + +## Impact +core (tasks, autonomy), runner (product-review, autonomy, hook), db (миграция 0023), web (доска, «Ваш продукт», автономность), bot, i18n. diff --git a/openspec/changes/pep-197-no-task-loop/specs/agent-task-origin/spec.md b/openspec/changes/pep-197-no-task-loop/specs/agent-task-origin/spec.md new file mode 100644 index 00000000..44d32fe3 --- /dev/null +++ b/openspec/changes/pep-197-no-task-loop/specs/agent-task-origin/spec.md @@ -0,0 +1,49 @@ +## ADDED Requirements + +### Requirement: Задачи агентов не берутся в работу сами +Задача, заведённая агентом приёмки, SHALL создаваться в «Предложено» и не браться диспетчером, пока владелец не нажал «Делать». Поломка SHALL идти в бэклог сразу с пометкой «Поломка». + +#### Scenario: Улучшение от агента приёмки +- **GIVEN** проект с режимом «Сам берёт» и пустым бэклогом +- **WHEN** агент приёмки находит улучшение +- **THEN** задача появляется в «Предложено» +- **AND** диспетчер её не берёт + +#### Scenario: Поломка критерия задачи человека +- **GIVEN** задача человека с критерием приёмки +- **WHEN** агент приёмки находит, что критерий не выполнен +- **THEN** задача создаётся в бэклоге с пометкой «Поломка» + +### Requirement: Без дублей +Перед созданием задачи агентом SHALL выполняться проверка повтора по открытым задачам и сделанным за 60 дней. + +#### Scenario: Повтор открытой задачи +- **GIVEN** открытая задача «Подписать кнопки» +- **WHEN** агент приёмки предлагает «Подписать кнопки на экране» +- **THEN** новая задача не создаётся, к открытой дописано замечание + +### Requirement: Одно сообщение и версия с финишем +После прохода приёмки владелец SHALL получать одно сообщение со списком и кнопками; когда задачи человека приняты и поломок нет — «Версия готова». + +#### Scenario: Решение владельца +- **GIVEN** сообщение «Нашёл 3 улучшения» +- **WHEN** владелец нажимает «Не надо» у пункта +- **THEN** задача архивируется и больше не предлагается + +#### Scenario: Версия готова +- **GIVEN** все открытые задачи человека приняты +- **WHEN** проход приёмки не находит поломок +- **THEN** владелец получает «Версия готова», дальше агент заводит только поломки + +### Requirement: Пределы и приёмка +В работе SHALL быть не больше 3 задач агентов на проект; автомерж SHALL принимать задачи агентов только по настройке «Принимать сами». + +#### Scenario: Четвёртая не стартует +- **GIVEN** 3 задачи агентов в работе +- **WHEN** диспетчер выбирает следующую +- **THEN** четвёртая задача агента не стартует + +#### Scenario: Автомерж по умолчанию +- **GIVEN** настройка по умолчанию «мои и поломки» +- **WHEN** задача из «Предложено» (после «Делать») прошла проверки +- **THEN** автомерж её не принимает, ждёт владельца diff --git a/openspec/changes/pep-197-no-task-loop/tasks.md b/openspec/changes/pep-197-no-task-loop/tasks.md new file mode 100644 index 00000000..31a3aecc --- /dev/null +++ b/openspec/changes/pep-197-no-task-loop/tasks.md @@ -0,0 +1,16 @@ +## 1. Данные +- [x] 1.1 Миграция 0023: origin, proposed, severity; backfill по признакам +- [x] 1.2 core/task-origin.ts: origin, proposed, лимиты, принять/отклонить, версия, сводка +## 2. Приёмка и диспетчер +- [x] 2.1 product-review: «Предложено», поломка, лимит 5, дубли, одно сообщение +- [x] 2.2 Диспетчер: пропуск proposed, предел 3 +- [x] 2.3 acceptOwn: автомерж / автозакрытие / хук +- [x] 2.4 Версия и «Версия готова», недельная сводка +## 3. Интерфейс +- [x] 3.1 Доска «Предложено», кнопки, «Ваш продукт» «Готово», автономность +- [x] 3.2 Telegram кнопки +- [x] 3.3 Переводы ru/kk/en, словарь +## 4. Уборка и сводка +- [x] 4.1 CLI tidy / report / agent-limits +## 5. Тесты +- [x] 5.1 Тесты по критериям diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index df4c1e9a..bd4487a9 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -75,7 +75,8 @@ import { checkPlatformChannel, describeChannel, getPlatformChannel, parseChatId, import { setSharedPool, sharedPool, createHost, deleteHost, findHost, HOST_STATUS_RU, listHosts, setHostDisabled, updateHost } from "@peppa/core"; import { getProjectRunnerSettings, getSystemRunnerSettings, getTaskRunnerSettings, resolveRunnerSettings, runnerStories, setProjectRunnerSettings, setSystemRunnerSettings, setTaskRunnerSettings, type RunnerSettingsPatch } from "@peppa/core"; import { branchProtectionState, connectErrorTrackingFromEnv, ensureBranchProtection, pauseProject, resumeProject } from "@peppa/runner"; -import { logoutAllUsers, showWelcomeToEveryone } from "@peppa/core"; +import { logoutAllUsers, showWelcomeToEveryone, agentTaskSummary, agentTaskTable, getAgentLimits, setAgentLimits, type AgentLimits } from "@peppa/core"; +import { tidyAgentTasks } from "@peppa/runner"; import { installCrashReporting } from "@peppa/core"; import { answerAndDeliver, connectCi, importIssues, deployProd, listReleases, platformReleaseOffers, setPlatformReleaseOffers, recordRelease, type ReleaseStatus, provisionProject, setProjectVisibility, transferProject, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner"; import { spawnSync } from "node:child_process"; @@ -91,6 +92,8 @@ const USAGE = `peppa — Peppa software factory CLI peppa project autonomy [manual|assisted|auto] [key=value…] (PEP-23: who takes stories, merge, closing, idle pushes) peppa project agent [key=value…] (PEP-41: provider model effort escalateModel escalateEffort escalateAfter fallbackProvider fallbackModel; value - = inherit) peppa project visibility public|private (repo visibility in Gitea: owner's client, then peppa-bot) + peppa project agent-limits [inWork=N perPass=N|reset] (PEP-197: limits for stories made by agents) + peppa agent-tasks report | tidy [KEY] [--dry-run] (PEP-197: people vs agents per project; one-off tidy) peppa project pause|resume (PEP-174: agents stop, nothing is sent; resume continues them) peppa project transfer (PEP-4: move the repo to another Gitea namespace as peppa-bot; fixes origin, CI runner, secret, webhook) peppa project protect (PEP-191: default branch protected, only peppa-bot writes) @@ -174,6 +177,7 @@ const { values: opts, positionals } = parseArgs({ goal: { type: "string", short: "g" }, status: { type: "string", short: "s" }, help: { type: "boolean", short: "h" }, + "dry-run": { type: "boolean" }, prompt: { type: "string", short: "p" }, mode: { type: "string" }, provider: { type: "string" }, @@ -382,7 +386,7 @@ async function main(): Promise { case "project autonomy": { // PEP-23: peppa project autonomy [manual|assisted|auto] [key=value…] const [key, ...rest] = args; - if (!key) throw new PeppaError("usage: peppa project autonomy [manual|assisted|auto] [pick=pm|auto wipLimit=N proposal=agent|pm merge=manual|auto close=pm|after_merge|after_hours closeAfterHours=N idlePush=on|off idlePushHours=N quiet=22-9|off]"); + if (!key) throw new PeppaError("usage: peppa project autonomy [manual|assisted|auto] [pick=pm|auto wipLimit=N proposal=agent|pm merge=manual|auto close=pm|after_merge|after_hours closeAfterHours=N acceptOwn=mine|mine_breakage|all idlePush=on|off idlePushHours=N quiet=22-9|off]"); const p = await getProject(db, key); if (rest.length) { const patch: AutonomyPatch = {}; @@ -398,7 +402,7 @@ async function main(): Promise { patch.quietTo = m ? Number(m[2]) : null; } else if (k === "idlePush") patch.idlePush = v === "on" || v === "true"; else if (k === "wipLimit" || k === "closeAfterHours" || k === "idlePushHours") patch[k] = Number(v); - else if (k === "pick" || k === "proposal" || k === "merge" || k === "close") (patch as Record)[k] = v; + else if (k === "pick" || k === "proposal" || k === "merge" || k === "close" || k === "acceptOwn") (patch as Record)[k] = v; else throw new PeppaError(`unknown setting: ${k}`); } await setAutonomy(db, p.id, patch); @@ -425,6 +429,31 @@ async function main(): Promise { } break; } + case "project agent-limits": { + if (!args[0]) throw new PeppaError("usage: peppa project agent-limits [inWork=N perPass=N|reset]"); + const p = await getProject(db, args[0]); + const patch: Partial = {}; + let reset = false; + for (const arg of args.slice(1)) { + if (arg === "reset") reset = true; + else { + const [k, v = ""] = arg.split("="); + if (k !== "inWork" && k !== "perPass") throw new PeppaError(`unknown limit: ${k}`); + patch[k] = Number(v); + } + } + const limits = reset ? await setAgentLimits(db, p.id, "reset") : Object.keys(patch).length ? await setAgentLimits(db, p.id, patch) : await getAgentLimits(db, p.id); + console.log(`${p.key}: stories of agents in work at once ≤ ${limits.inWork}, proposals per pass ≤ ${limits.perPass}`); + break; + } + case "agent-tasks report": + console.log(agentTaskTable(await agentTaskSummary(db))); + break; + case "agent-tasks tidy": { + const rows = await tidyAgentTasks(db, { dryRun: opts["dry-run"], only: args[0], log: (m) => console.log(m) }); + console.log(`${opts["dry-run"] ? "(dry run) " : ""}projects touched: ${rows.length}, moved to «Предложено»: ${rows.reduce((n, r) => n + r.moved, 0)}`); + break; + } case "project list": for (const p of await listProjects(db)) console.log(`${p.key.padEnd(8)} ${p.slug.padEnd(20)} ${p.name} ${p.workspacePath}${p.ownerId ? ` owner #${p.ownerId}` : ""}`); break; diff --git a/packages/core/src/autonomy.ts b/packages/core/src/autonomy.ts index 06a7738d..abecd2c6 100644 --- a/packages/core/src/autonomy.ts +++ b/packages/core/src/autonomy.ts @@ -11,6 +11,9 @@ export type PickMode = "pm" | "auto"; export type ProposalMode = "agent" | "pm"; export type MergeMode = "manual" | "auto"; export type CloseMode = "pm" | "after_merge" | "after_hours"; +/** PEP-197: whose stories Peppa accepts herself: only the person's / and breakages / all. */ +export type AcceptOwnMode = "mine" | "mine_breakage" | "all"; +export const ACCEPT_OWN_MODES: readonly AcceptOwnMode[] = ["mine", "mine_breakage", "all"]; export interface AutonomySettings { /** Who takes stories from the backlog: the PM (board) or the dispatcher (watchdog). */ @@ -24,6 +27,8 @@ export interface AutonomySettings { /** When a story in review becomes Done. */ close: CloseMode; closeAfterHours: number; + /** PEP-197: «Принимать сами» — which stories (by who made them) merge and close without the owner. */ + acceptOwn: AcceptOwnMode; /** Push to the PM when no agent works and the backlog is not empty (PM picks). */ idlePush: boolean; /** Not more often than this per project; also the "not now" snooze. */ @@ -42,6 +47,7 @@ const BASE: AutonomySettings = { merge: "manual", close: "pm", closeAfterHours: 24, + acceptOwn: "mine_breakage", idlePush: false, idlePushHours: 4, quietFrom: 22, @@ -120,6 +126,7 @@ function normalize(s: AutonomySettings): AutonomySettings { merge: oneOf(s.merge, ["manual", "auto"], "merge"), close: oneOf(s.close, ["pm", "after_merge", "after_hours"], "close"), closeAfterHours: intIn(s.closeAfterHours, 1, 24 * 14, "closeAfterHours"), + acceptOwn: oneOf(s.acceptOwn ?? "mine_breakage", ACCEPT_OWN_MODES, "acceptOwn"), idlePush: Boolean(s.idlePush), idlePushHours: intIn(s.idlePushHours, 1, 24 * 7, "idlePushHours"), // Both or none: half a range means nothing. @@ -135,7 +142,9 @@ function normalize(s: AutonomySettings): AutonomySettings { export async function setAutonomy(db: Db, projectId: number, patch: AutonomyPatch): Promise { const { level, ...fields } = patch; if (level && !(level in AUTONOMY_LEVELS)) throw new PeppaError(tr("Уровень: одно из {list}", { list: Object.keys(AUTONOMY_LEVELS).join(", ") })); - const base = level ? AUTONOMY_LEVELS[level] : await getAutonomy(db, projectId); + const current = await getAutonomy(db, projectId); + // PEP-197: a level changes how work goes, not whose stories are accepted without the owner. + const base = level ? { ...AUTONOMY_LEVELS[level], acceptOwn: current.acceptOwn } : current; const defined = Object.fromEntries(Object.entries(fields).filter(([, v]) => v !== undefined)); const next = normalize({ ...base, ...defined }); if (JSON.stringify(next) === JSON.stringify(BASE)) await deleteSetting(db, key(projectId)); @@ -164,6 +173,7 @@ export function describeAutonomy(s: AutonomySettings): string { // glossary-ignore: подробное описание автономности — для MCP и командной строки, на экране «Продакта» его нет v: s.close === "pm" ? tr("PM принимает") : s.close === "after_merge" ? tr("сразу после мержа") : tr("само через {n} ч без замечаний", { n: s.closeAfterHours }), }), + tr("Принимать сами: {v}", { v: s.acceptOwn === "mine" ? tr("только мои задачи") : s.acceptOwn === "all" ? tr("всё") : tr("мои и поломки") }), tr("Пуш при простое: {v}", { v: !s.idlePush ? tr("нет") diff --git a/packages/core/src/incidents.ts b/packages/core/src/incidents.ts index 6c8f7243..c0540f3b 100644 --- a/packages/core/src/incidents.ts +++ b/packages/core/src/incidents.ts @@ -268,6 +268,9 @@ export async function createBugTask(db: Db, i: Incident, by: NonNullable(); if (!messageIds.length) return out; for (const r of await db.select().from(settings).where(inArray(settings.key, messageIds.map(offerKey)))) out.set(Number(r.key.slice(OFFER_PREFIX.length)), r.value as ChatOffer); + // PEP-197: the list of suggested stories shows what became of each (the buttons live while undecided). + for (const offer of out.values()) { + if (offer.kind !== "proposals" || !offer.items?.length) continue; + const rows = await db.select({ id: tasks.id, proposed: tasks.proposed, archivedAt: tasks.archivedAt }).from(tasks).where(inArray(tasks.id, offer.items.map((i) => i.id))); + const byId = new Map(rows.map((x) => [x.id, x])); + offer.items = offer.items.map((i) => { + const t = byId.get(i.id); + return { ...i, open: !!t?.proposed && !t.archivedAt, decision: !t || t.proposed ? null : t.archivedAt ? "rejected" : "approved" }; + }); + } return out; } diff --git a/packages/core/src/product-review.ts b/packages/core/src/product-review.ts index 98f5c1b4..c5da0cf9 100644 --- a/packages/core/src/product-review.ts +++ b/packages/core/src/product-review.ts @@ -12,7 +12,7 @@ import { m as tr } from "@peppa/shared/i18n"; /** The product agent's name on its messages (an AI agent, shown with the robot badge). */ export const PRODUCT_AGENT_NAME = "Продакт"; -export const PRODUCT_REVIEW_MAX_STORIES = 3; +export const PRODUCT_REVIEW_MAX_STORIES = 5; export const PRODUCT_REVIEW_MAX_PAGES = 4; export const PRODUCT_PAGE_MAX_CHARS = 6000; @@ -119,6 +119,8 @@ export interface ProductReviewInput { secretNames: string[]; /** Titles of the project's open stories — not to file the same thing twice. */ openStories: string[]; + /** Titles the owner has already declined — not to suggest again. */ + rejected?: string[]; } const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}\n…(обрезано)` : s); @@ -130,7 +132,7 @@ export function productReviewPrompt(i: ProductReviewInput): string { "2. howto — как этим пользоваться в жизни, по шагам (3–7 шагов): открыть адрес, что нажать, что получится. Только то, что реально есть на экране.", "3. not_real — что пока не настоящее: демо-режим, вымышленные примеры, заглушки, «скоро», данные-образцы. Каждое — одной фразой простыми словами. Пусто, если всё настоящее.", "4. needs — что нужно от владельца, чтобы заработало по-настоящему (ключ сервиса, аккаунт, реквизиты): title — что дать, why — что без этого не работает, how — где это взять, по шагам для непрограммиста. Не повторяй пункты из раздела «Уже объявлено». Пусто, если ничего не нужно.", - `5. stories — доработки (не больше ${PRODUCT_REVIEW_MAX_STORIES}): всё, что пользователь не поймёт или не должен видеть. Служебные поля на экране («токен», «ключ API», «ID», технические коды), жаргон, непонятные ошибки, пустые экраны без подсказки, обещанное в стори, но отсутствующее. title — что исправить; description — что должен увидеть пользователь и критерии приёмки списком. Не заводи то, что уже есть в «Открытых стори». Пусто, если придраться не к чему.`, + `5. stories — доработки (не больше ${PRODUCT_REVIEW_MAX_STORIES}): всё, что пользователь не поймёт или не должен видеть. Служебные поля на экране («токен», «ключ API», «ID», технические коды), жаргон, непонятные ошибки, пустые экраны без подсказки, обещанное в стори, но отсутствующее. title — что исправить; description — что должен увидеть пользователь и критерии приёмки списком. Не заводи то, что уже есть в «Открытых стори». Пусто, если придраться не к чему. severity у каждой: breakage — только поломка (продукт не открывается или не работает главное, не выполнен критерий приёмки задачи, которую поставил человек); important — пользователь без этого не справится или не поймёт; minor — мелочь, шлифовка.`, "Тон: коллега, а не помощник. Простые слова, без жаргона (PR, CI, API, деплой, env, токен — нельзя; «ключ сервиса», «версия для проверки» — можно). Не хвали, без восклицаний. Не выдумывай: чего нет в тексте страниц и на скриншотах — того нет.", "", `Продукт: ${i.projectName} — ${i.envLabel}, адрес ${i.url}`, @@ -149,8 +151,9 @@ export function productReviewPrompt(i: ProductReviewInput): string { "", "## Открытые стори проекта", i.openStories.length ? i.openStories.map((t) => `- ${t}`).join("\n") : "(нет)", + ...(i.rejected?.length ? ["", "## Владелец уже отклонил (не предлагай снова)", ...i.rejected.map((t) => `- ${t}`)] : []), "", - 'Ответь ОДНОЙ строкой JSON без пояснений: {"summary":"…","howto":["…"],"not_real":["…"],"needs":[{"title":"…","why":"…","how":"…"}],"stories":[{"title":"…","description":"…"}]}', + 'Ответь ОДНОЙ строкой JSON без пояснений: {"summary":"…","howto":["…"],"not_real":["…"],"needs":[{"title":"…","why":"…","how":"…"}],"stories":[{"title":"…","description":"…","severity":"breakage|important|minor"}]}', ].join("\n"); } @@ -159,7 +162,7 @@ export interface ProductReviewReply { howto: string[]; notReal: string[]; needs: Array<{ title: string; why: string; how: string }>; - stories: Array<{ title: string; description: string }>; + stories: Array<{ title: string; description: string; severity: "breakage" | "important" | "minor" }>; } const str = (v: unknown, max: number) => (typeof v === "string" ? v.trim().slice(0, max) : ""); @@ -183,7 +186,7 @@ export function parseProductReview(text: string): ProductReviewReply | null { .filter((n) => n.title) .slice(0, 6), stories: objs(o.stories) - .map((s) => ({ title: str(s.title, 120), description: str(s.description, 6000) })) + .map((s) => ({ title: str(s.title, 120), description: str(s.description, 6000), severity: (s.severity === "breakage" || s.severity === "minor" ? s.severity : "important") as "breakage" | "important" | "minor" })) .filter((s) => s.title.length >= 3) .slice(0, PRODUCT_REVIEW_MAX_STORIES), }; @@ -193,7 +196,7 @@ export function parseProductReview(text: string): ProductReviewReply | null { } /** The product agent's message to the owner in the project's discussion. */ -export function productReviewMessage(r: ProductReviewReply, o: { env: "prod" | "staging"; url: string; openNeeds: ProductNeedView[]; filed: string[]; webUrl: string; projectKey: string }): string { +export function productReviewMessage(r: ProductReviewReply, o: { env: "prod" | "staging"; url: string; openNeeds: ProductNeedView[]; filed: string[]; webUrl: string; projectKey: string; found?: { n: number; important: number } }): string { const steps = (items: string[]) => items.map((x, i) => `${i + 1}. ${x}`).join("\n"); const bullets = (items: string[]) => items.map((x) => `• ${x}`).join("\n"); return [ @@ -206,6 +209,7 @@ export function productReviewMessage(r: ProductReviewReply, o: { env: "prod" | " `${tr("Чтобы заработало по-настоящему, нужно от вас:")}\n${bullets(o.openNeeds.map((n) => `${n.title}${n.why ? ` — ${n.why}` : ""}${n.how ? `\n ${tr("Где взять: {how}", { how: n.how })}` : ""}`))}\n${tr("Вставить или отметить «Сделано» — в карточке «Ваш продукт»: {url}", { url: `${o.webUrl}/p/${o.projectKey}` })}`, ] : []), - ...(o.filed.length ? [`${tr("Завёл доработки в бэклог:")}\n${bullets(o.filed)}`] : []), + // PEP-197: one message instead of a stream — the owner picks what to do with each item. + ...(o.found && o.filed.length ? [`${tr("Проверил продукт. Нашёл улучшений: {n} (важных: {k}).", { n: o.found.n, k: o.found.important })}\n${bullets(o.filed)}`] : o.filed.length ? [`${tr("Завёл доработки в бэклог:")}\n${bullets(o.filed)}`] : []), ].join("\n\n"); } diff --git a/packages/core/src/product.ts b/packages/core/src/product.ts index f2ee6573..ed103021 100644 --- a/packages/core/src/product.ts +++ b/packages/core/src/product.ts @@ -1,6 +1,7 @@ // 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 { getVersion, proposedCount } from "./task-origin.ts"; import { m as tr } from "@peppa/shared/i18n"; import { formatTaskKey } from "@peppa/shared"; import { projects, releases, tasks, type Db } from "@peppa/db"; @@ -29,6 +30,10 @@ export interface ProjectProduct { 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; + /** PEP-197: everything a person asked for in this version is accepted and nothing is broken. */ + versionDone: boolean; + /** PEP-197: stories the factory suggested that wait for the owner. */ + proposed: number; } /** An update that reported «начато» and nothing since is not «идёт» for ever. */ @@ -61,6 +66,8 @@ export async function projectProduct(db: Db, projectId: number): Promise s.path === "/")) } : null, }; } diff --git a/packages/core/src/task-dedup.ts b/packages/core/src/task-dedup.ts new file mode 100644 index 00000000..4b8677a2 --- /dev/null +++ b/packages/core/src/task-dedup.ts @@ -0,0 +1,51 @@ +// PEP-197: «это повтор задачи X?» — the question for the model before an agent files a story. +import { m as tr } from "@peppa/shared/i18n"; + +export const DEDUP_WINDOW_DAYS = 60; +export const DEDUP_MAX_CANDIDATES = 80; + +export interface DedupCandidate { + key: string; + title: string; + state: "open" | "done"; + /** ISO date of the day it was finished (state done). */ + doneAt?: string; +} + +export function dedupPrompt(task: { title: string; description: string }, candidates: DedupCandidate[]): string { + return [ + "Ты — проверка на повтор задач в софтвер-фабрике. Агент хочет завести новую задачу. Скажи, не повторяет ли она по смыслу одну из задач проекта: та же тема, тот же экран, то же исправление — даже если слова другие.", + "Повтор — это когда выполнение существующей задачи закрывает и новую. Соседняя тема — не повтор.", + "", + "## Новая задача", + `Название: ${task.title}`, + task.description.trim().slice(0, 1500), + "", + "## Задачи проекта (открытые и сделанные за последние 60 дней)", + candidates.map((c) => `- ${c.key} «${c.title}» [${c.state === "open" ? "открыта" : `сделана ${c.doneAt ?? ""}`}]`).join("\n"), + "", + 'Ответь ОДНОЙ строкой JSON без пояснений: {"duplicate_of":"KEY-N или null","reason":"одной фразой, почему"}', + ].join("\n"); +} + +export interface DedupAnswer { + duplicateOf: string | null; + reason: string; +} + +export function parseDedup(text: string): DedupAnswer | null { + const m = /\{[\s\S]*\}/.exec(text); + if (!m) return null; + try { + const o = JSON.parse(m[0]) as Record; + const key = typeof o.duplicate_of === "string" && /^[A-Za-z0-9]+-\d+$/.test(o.duplicate_of.trim()) ? o.duplicate_of.trim().toUpperCase() : null; + return { duplicateOf: key, reason: typeof o.reason === "string" ? o.reason.trim().slice(0, 300) : "" }; + } catch { + return null; + } +} + +/** Remark added to an open story when the acceptance agent noticed the same thing again. */ +export const dedupRemark = (title: string, description: string) => tr("Приёмка снова заметила то же самое: «{title}».\n{description}", { title, description: description.trim().slice(0, 800) }); +/** Mark on a story that looks like one already done. */ +export const dedupSimilarNote = (key: string, date: string) => tr("Похоже на {key}, сделано {date}.", { key, date }); diff --git a/packages/core/src/task-origin.ts b/packages/core/src/task-origin.ts new file mode 100644 index 00000000..48b63b1e --- /dev/null +++ b/packages/core/src/task-origin.ts @@ -0,0 +1,272 @@ +// PEP-197: who made a story, «Предложено», limits for stories of agents, the product's version +// with a finish line, and what the acceptance agent may not do alone. State lives in `tasks` +// (origin, proposed, severity) and `settings` (`project.agent-limits:`, `product.version:`, +// `product.rejected:`, `product.digest:`). +import { m as tr } from "@peppa/shared/i18n"; +import { projects, sessions, tasks, type Db } from "@peppa/db"; +import { and, eq, gte, inArray, isNull, ne, sql } from "drizzle-orm"; +import { getAutonomy, type AcceptOwnMode } from "./autonomy.ts"; +import { logEvent } from "./audit.ts"; +import { PeppaError } from "./errors.ts"; +import { notify } from "./notify.ts"; +import { usageTotals } from "./usage.ts"; +import { deleteSetting, getSetting, setSetting } from "./settings.ts"; + +export const TASK_ORIGINS = ["human", "acceptance", "incident", "analyst"] as const; +export type TaskOrigin = (typeof TASK_ORIGINS)[number]; +export const TASK_SEVERITIES = ["breakage", "important", "minor"] as const; +export type TaskSeverity = (typeof TASK_SEVERITIES)[number]; + +export const isAgentOrigin = (origin: string): boolean => origin !== "human"; + +export const SEVERITY_LABEL: Record = { + breakage: tr("Поломка"), + important: tr("Важно"), + minor: tr("Мелочь"), +}; + +export const ORIGIN_LABEL: Record = { + human: tr("человек"), + acceptance: tr("агент приёмки"), + incident: tr("разбор ошибок"), + analyst: tr("аналитик"), +}; + +// ── limits ───────────────────────────────────────────────────────────────────── + +export interface AgentLimits { + /** Stories made by agents that may be in work at once, per project. */ + inWork: number; + /** Proposals the acceptance agent may make in one pass. */ + perPass: number; +} +export const DEFAULT_AGENT_LIMITS: AgentLimits = { inWork: 3, perPass: 5 }; +const limitsKey = (projectId: number) => `project.agent-limits:${projectId}`; + +export async function getAgentLimits(db: Db, projectId: number): Promise { + const s = await getSetting>(db, limitsKey(projectId)); + return { ...DEFAULT_AGENT_LIMITS, ...(s ?? {}) }; +} + +export async function setAgentLimits(db: Db, projectId: number, patch: Partial | "reset"): Promise { + if (patch === "reset") { + await deleteSetting(db, limitsKey(projectId)); + return DEFAULT_AGENT_LIMITS; + } + const next = { ...(await getAgentLimits(db, projectId)), ...patch }; + for (const [k, max] of [["inWork", 20], ["perPass", 20]] as const) { + if (!Number.isInteger(next[k]) || next[k] < 0 || next[k] > max) throw new PeppaError(tr("{name}: целое от 0 до {max}", { name: k, max })); + } + await setSetting(db, limitsKey(projectId), next); + return next; +} + +/** Stories of agents in work (not in review), of one project. */ +export async function agentTasksInWork(db: Db, projectId: number): Promise { + const [r] = await db + .select({ n: sql`count(*)` }) + .from(tasks) + .where(and(eq(tasks.projectId, projectId), eq(tasks.status, "in_progress"), ne(tasks.origin, "human"), isNull(tasks.archivedAt))); + return Number(r?.n ?? 0); +} + +// ── «Предложено» ─────────────────────────────────────────────────────────────── + +export async function proposedTasks(db: Db, projectId: number) { + return db.select().from(tasks).where(and(eq(tasks.projectId, projectId), eq(tasks.proposed, true), isNull(tasks.archivedAt))); +} + +export async function proposedCount(db: Db, projectId: number): Promise { + return (await proposedTasks(db, projectId)).length; +} + +const rejectedKey = (projectId: number) => `product.rejected:${projectId}`; +export const normTitle = (s: string) => s.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, " ").trim(); + +export async function rejectedTitles(db: Db, projectId: number): Promise { + return (await getSetting(db, rejectedKey(projectId))) ?? []; +} + +/** «Делать»: the story goes to the backlog (the dispatcher may take it). */ +export async function approveProposal(db: Db, taskId: number, by?: string): Promise { + const [t] = await db.update(tasks).set({ proposed: false }).where(and(eq(tasks.id, taskId), eq(tasks.proposed, true))).returning(); + if (!t) return; + await logEvent(db, { projectId: t.projectId, taskId: t.id, type: "proposal_approved", payload: { by: by ?? null } }); + await notify(db, { type: "task_updated", taskId: t.id }); +} + +/** «Не надо»: archived with a mark; the acceptance agent will not suggest it again. */ +export async function rejectProposal(db: Db, taskId: number, by?: string): Promise { + const [t] = await db.update(tasks).set({ proposed: false, archivedAt: new Date() }).where(and(eq(tasks.id, taskId), eq(tasks.proposed, true))).returning(); + if (!t) return; + const list = await rejectedTitles(db, t.projectId); + const n = normTitle(t.title); + if (!list.includes(n)) await setSetting(db, rejectedKey(t.projectId), [...list, n].slice(-200)); + await logEvent(db, { projectId: t.projectId, taskId: t.id, type: "proposal_rejected", payload: { by: by ?? null } }); + await notify(db, { type: "task_updated", taskId: t.id }); +} + +/** Bulk: `important` — «Делать важные» (breakage and important), `none` — «Отклонить всё». */ +export async function resolveProposals(db: Db, ids: number[], mode: "important" | "none", by?: string): Promise { + if (!ids.length) return; + const rows = await db.select().from(tasks).where(and(inArray(tasks.id, ids), eq(tasks.proposed, true))); + for (const t of rows) { + if (mode === "none") await rejectProposal(db, t.id, by); + else if (t.severity === "breakage" || t.severity === "important") await approveProposal(db, t.id, by); + } +} + +// ── who may be accepted automatically ────────────────────────────────────────── + +/** May Peppa merge and close this story without the owner (autonomy «Принимать сами», PEP-197)? */ +export function mayAutoAccept(task: { origin: string; severity: string | null }, mode: AcceptOwnMode): boolean { + if (!isAgentOrigin(task.origin)) return true; + if (mode === "all") return true; + if (mode === "mine_breakage") return task.severity === "breakage"; + return false; +} + +export async function mayAutoAcceptTask(db: Db, task: { projectId: number; origin: string; severity: string | null }): Promise { + if (!isAgentOrigin(task.origin)) return true; + return mayAutoAccept(task, (await getAutonomy(db, task.projectId)).acceptOwn); +} + +// ── version with a finish line ───────────────────────────────────────────────── + +export interface VersionState { + /** Stories of the human that make this version. */ + ids: number[]; + startedAt: string; + /** Set when the owner was told «Версия готова» (or the project had nothing open). */ + doneAt: string | null; +} +const versionKey = (projectId: number) => `product.version:${projectId}`; +export const getVersion = (db: Db, projectId: number) => getSetting(db, versionKey(projectId)); + +/** A person made a story: it joins the open version, or starts a new one after a finished one. */ +export async function touchVersion(db: Db, projectId: number, taskId: number): Promise { + const v = await getVersion(db, projectId); + if (!v || v.doneAt) await setSetting(db, versionKey(projectId), { ids: [taskId], startedAt: new Date().toISOString(), doneAt: null } satisfies VersionState); + else if (!v.ids.includes(taskId)) await setSetting(db, versionKey(projectId), { ...v, ids: [...v.ids, taskId] }); +} + +/** The project's version is finished: nothing a person asked for is open. */ +export async function versionFinished(db: Db, projectId: number): Promise { + const v = await getVersion(db, projectId); + if (v) return v.doneAt != null; + // Never tracked (an old project): finished when no story of a person is open. + const open = await openHumanTasks(db, projectId); + if (open.length === 0) { + await setSetting(db, versionKey(projectId), { ids: [], startedAt: new Date().toISOString(), doneAt: new Date().toISOString() } satisfies VersionState); + return true; + } + await setSetting(db, versionKey(projectId), { ids: open, startedAt: new Date().toISOString(), doneAt: null } satisfies VersionState); + return false; +} + +async function openHumanTasks(db: Db, projectId: number): Promise { + const rows = await db + .select({ id: tasks.id }) + .from(tasks) + .where(and(eq(tasks.projectId, projectId), eq(tasks.origin, "human"), ne(tasks.status, "done"), isNull(tasks.archivedAt))); + return rows.map((r) => r.id); +} + +/** + * After a pass of the acceptance agent: every story of the version is done (or archived) and + * no breakage was found → the version is finished. True once, when it just finished. + */ +export async function finishVersionIfReady(db: Db, projectId: number, foundBreakage: boolean): Promise { + if (foundBreakage) return false; + if (!(await getVersion(db, projectId))) await versionFinished(db, projectId); // starts tracking + const v = await getVersion(db, projectId); + if (!v || v.doneAt) return false; + const rows = await db.select({ status: tasks.status, archivedAt: tasks.archivedAt }).from(tasks).where(inArray(tasks.id, v.ids)); + if (rows.some((r) => r.status !== "done" && !r.archivedAt)) return false; + await setSetting(db, versionKey(projectId), { ...v, doneAt: new Date().toISOString() }); + await logEvent(db, { projectId, type: "version_done", payload: { stories: v.ids.length } }); + return true; +} + +// ── improvements saved for the weekly message after the finish ───────────────── + +export interface DigestItem { + title: string; + description: string; + severity: TaskSeverity; +} +export interface DigestState { + items: DigestItem[]; + sentAt: string | null; +} +const digestKey = (projectId: number) => `product.digest:${projectId}`; +export const getDigest = async (db: Db, projectId: number): Promise => (await getSetting(db, digestKey(projectId))) ?? { items: [], sentAt: null }; +export const setDigest = (db: Db, projectId: number, d: DigestState) => setSetting(db, digestKey(projectId), d); + +// ── summary for the superadmin (and the table of the review) ─────────────────── + +export interface AgentTaskRow { + projectId: number; + key: string; + name: string; + human: number; + agents: number; + proposed: number; + agentsLastWeek: number; + /** Money spent on sessions of stories made by agents over 7 days, USD. */ + agentCostWeek: number; + agentsMoreThanHuman: boolean; +} + +export async function agentTaskSummary(db: Db, now = new Date()): Promise { + const since = new Date(now.getTime() - 7 * 86_400_000); + const rows = await db + .select({ + projectId: projects.id, + key: projects.key, + name: projects.name, + human: sql`sum(case when ${tasks.origin} = 'human' then 1 else 0 end)`, + agents: sql`sum(case when ${tasks.origin} <> 'human' then 1 else 0 end)`, + proposed: sql`sum(case when ${tasks.proposed} = 1 and ${tasks.archivedAt} is null then 1 else 0 end)`, + }) + .from(projects) + .innerJoin(tasks, eq(tasks.projectId, projects.id)) + .where(isNull(projects.deletedAt)) + .groupBy(projects.id); + const out: AgentTaskRow[] = []; + for (const r of rows) { + const [last] = await db + .select({ n: sql`count(*)` }) + .from(tasks) + .where(and(eq(tasks.projectId, r.projectId), ne(tasks.origin, "human"), gte(tasks.createdAt, since))); + out.push({ + projectId: r.projectId, + key: r.key, + name: r.name, + human: Number(r.human), + agents: Number(r.agents), + proposed: Number(r.proposed), + agentsLastWeek: Number(last?.n ?? 0), + agentCostWeek: await agentCostWeek(db, r.projectId, since), + agentsMoreThanHuman: Number(r.agents) > Number(r.human), + }); + } + return out.sort((a, b) => b.agentCostWeek - a.agentCostWeek || b.agents - a.agents); +} + +/** Sum of the cost of sessions of agent-made stories (sessions.usage keeps cost by generation). */ +async function agentCostWeek(db: Db, projectId: number, since: Date): Promise { + const rows = await db + .select({ usage: sessions.usage }) + .from(sessions) + .innerJoin(tasks, eq(tasks.id, sessions.taskId)) + .where(and(eq(sessions.projectId, projectId), ne(tasks.origin, "human"), gte(sessions.lastActivityAt, since))); + const total = rows.reduce((sum, r) => sum + (usageTotals(r.usage).costUsd ?? 0), 0); + return Math.round(total * 100) / 100; +} + +export function agentTaskTable(rows: AgentTaskRow[]): string { + const head = "проект | человек | агенты | предложено | агенты за 7 дн. | траты агентов за 7 дн., $ | агентов больше"; + return [head, ...rows.map((r) => `${r.key} | ${r.human} | ${r.agents} | ${r.proposed} | ${r.agentsLastWeek} | ${r.agentCostWeek.toFixed(2)} | ${r.agentsMoreThanHuman ? "да" : "нет"}`)].join("\n"); +} + diff --git a/packages/core/src/tasks.ts b/packages/core/src/tasks.ts index e439465a..66911fc0 100644 --- a/packages/core/src/tasks.ts +++ b/packages/core/src/tasks.ts @@ -20,6 +20,7 @@ import { keepQuestionDetails, messageText, stripServiceBlocks } from "./user-tex import { defaultMessageType, type MessageType } from "./questions.ts"; import { renderMain, type AgentMessage } from "./agent-message.ts"; import { setMessageDetails } from "./message-details.ts"; +import { touchVersion } from "./task-origin.ts"; export type Task = typeof tasks.$inferSelect; export type TaskStatus = (typeof taskStatus.enumValues)[number]; @@ -57,13 +58,17 @@ export interface NewTask { goalId?: number; title: string; description?: string; + /** PEP-197: who made it (default: a person); agents' stories are «Предложено» unless a breakage. */ + origin?: "human" | "acceptance" | "incident" | "analyst"; + proposed?: boolean; + severity?: "breakage" | "important" | "minor" | null; } export async function createTask(db: Db, t: NewTask): Promise { if (t.goalId != null) await getGoal(db, t.projectId, t.goalId); // Hand out the per-project number atomically. SQLite transactions are synchronous: no // await inside (the driver refuses an async callback). - return db.transaction( + const made = db.transaction( (tx) => { const [project] = tx .update(projects) @@ -87,6 +92,9 @@ export async function createTask(db: Db, t: NewTask): Promise { }, { behavior: "immediate" }, ); + // PEP-197: a story of a person belongs to the project's current version. + if ((t.origin ?? "human") === "human") await touchVersion(db, t.projectId, made.task.id); + return made; } export interface TaskFilter { diff --git a/packages/db/migrations/0023_curious_steel_serpent.sql b/packages/db/migrations/0023_curious_steel_serpent.sql new file mode 100644 index 00000000..462c2c51 --- /dev/null +++ b/packages/db/migrations/0023_curious_steel_serpent.sql @@ -0,0 +1,6 @@ +ALTER TABLE `tasks` ADD `origin` text DEFAULT 'human' NOT NULL;--> statement-breakpoint +ALTER TABLE `tasks` ADD `proposed` integer DEFAULT false NOT NULL;--> statement-breakpoint +ALTER TABLE `tasks` ADD `severity` text;--> statement-breakpoint +UPDATE `tasks` SET `origin` = 'acceptance' WHERE `description` LIKE '%Заведено продакт-агентом на приёмке%';--> statement-breakpoint +UPDATE `tasks` SET `origin` = 'incident' WHERE `origin` = 'human' AND `id` IN (SELECT `task_id` FROM `incidents` WHERE `task_id` IS NOT NULL);--> statement-breakpoint +UPDATE `tasks` SET `origin` = 'analyst' WHERE `origin` = 'human' AND (`title` LIKE '[Дубль%' OR `title` LIKE '%[Дубль %' OR `description` LIKE '%[Дубль %'); diff --git a/packages/db/migrations/meta/0023_snapshot.json b/packages/db/migrations/meta/0023_snapshot.json new file mode 100644 index 00000000..e61ff71b --- /dev/null +++ b/packages/db/migrations/meta/0023_snapshot.json @@ -0,0 +1,4605 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "a486ab9d-bc50-4491-8d4a-494d63f57378", + "prevId": "f4ed2cdf-e00b-4b7a-850f-88e5147baa6f", + "tables": { + "agents": { + "name": "agents", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "character": { + "name": "character", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "disabled_at": { + "name": "disabled_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "agents_name_unique": { + "name": "agents_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "attachments": { + "name": "attachments", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "chat_message_id": { + "name": "chat_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "event_id": { + "name": "event_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "file": { + "name": "file", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "mime": { + "name": "mime", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "attachments_task": { + "name": "attachments_task", + "columns": [ + "task_id" + ], + "isUnique": false + }, + "attachments_message": { + "name": "attachments_message", + "columns": [ + "chat_message_id" + ], + "isUnique": false + }, + "attachments_event": { + "name": "attachments_event", + "columns": [ + "event_id" + ], + "isUnique": false + }, + "attachments_project": { + "name": "attachments_project", + "columns": [ + "project_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "attachments_project_id_projects_id_fk": { + "name": "attachments_project_id_projects_id_fk", + "tableFrom": "attachments", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "attachments_user_id_users_id_fk": { + "name": "attachments_user_id_users_id_fk", + "tableFrom": "attachments", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "attachments_task_id_tasks_id_fk": { + "name": "attachments_task_id_tasks_id_fk", + "tableFrom": "attachments", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "attachments_chat_message_id_chat_messages_id_fk": { + "name": "attachments_chat_message_id_chat_messages_id_fk", + "tableFrom": "attachments", + "tableTo": "chat_messages", + "columnsFrom": [ + "chat_message_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "attachments_event_id_events_id_fk": { + "name": "attachments_event_id_events_id_fk", + "tableFrom": "attachments", + "tableTo": "events", + "columnsFrom": [ + "event_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "chat_messages": { + "name": "chat_messages", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "chat_id": { + "name": "chat_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "thread_key": { + "name": "thread_key", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "thread_title": { + "name": "thread_title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "important": { + "name": "important", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "author_kind": { + "name": "author_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'system'" + }, + "author_user_id": { + "name": "author_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "author_login": { + "name": "author_login", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "via": { + "name": "via", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "question_id": { + "name": "question_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_chat_id": { + "name": "tg_chat_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_message_id": { + "name": "tg_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "chat_messages_dedupe_key_unique": { + "name": "chat_messages_dedupe_key_unique", + "columns": [ + "dedupe_key" + ], + "isUnique": true + }, + "chat_messages_chat": { + "name": "chat_messages_chat", + "columns": [ + "chat_id", + "id" + ], + "isUnique": false + }, + "chat_messages_created_at": { + "name": "chat_messages_created_at", + "columns": [ + "created_at" + ], + "isUnique": false + }, + "chat_messages_tg": { + "name": "chat_messages_tg", + "columns": [ + "tg_chat_id", + "tg_message_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "chat_messages_chat_id_chats_id_fk": { + "name": "chat_messages_chat_id_chats_id_fk", + "tableFrom": "chat_messages", + "tableTo": "chats", + "columnsFrom": [ + "chat_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "chat_messages_author_user_id_users_id_fk": { + "name": "chat_messages_author_user_id_users_id_fk", + "tableFrom": "chat_messages", + "tableTo": "users", + "columnsFrom": [ + "author_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "chat_messages_question_id_questions_id_fk": { + "name": "chat_messages_question_id_questions_id_fk", + "tableFrom": "chat_messages", + "tableTo": "questions", + "columnsFrom": [ + "question_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "chat_messages_task_id_tasks_id_fk": { + "name": "chat_messages_task_id_tasks_id_fk", + "tableFrom": "chat_messages", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "chats": { + "name": "chats", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_chat_id": { + "name": "tg_chat_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_title": { + "name": "tg_title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_linked_at": { + "name": "tg_linked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_linked_by": { + "name": "tg_linked_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tg_bot_user_id": { + "name": "tg_bot_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "chats_user_id_unique": { + "name": "chats_user_id_unique", + "columns": [ + "user_id" + ], + "isUnique": true + }, + "chats_project_id_unique": { + "name": "chats_project_id_unique", + "columns": [ + "project_id" + ], + "isUnique": true + }, + "chats_tg_chat_id_unique": { + "name": "chats_tg_chat_id_unique", + "columns": [ + "tg_chat_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "chats_user_id_users_id_fk": { + "name": "chats_user_id_users_id_fk", + "tableFrom": "chats", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "chats_project_id_projects_id_fk": { + "name": "chats_project_id_projects_id_fk", + "tableFrom": "chats", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "chats_tg_linked_by_users_id_fk": { + "name": "chats_tg_linked_by_users_id_fk", + "tableFrom": "chats", + "tableTo": "users", + "columnsFrom": [ + "tg_linked_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "chats_tg_bot_user_id_users_id_fk": { + "name": "chats_tg_bot_user_id_users_id_fk", + "tableFrom": "chats", + "tableTo": "users", + "columnsFrom": [ + "tg_bot_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "check_runs": { + "name": "check_runs", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "check": { + "name": "check", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "run_url": { + "name": "run_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "log_tail": { + "name": "log_tail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "duration_sec": { + "name": "duration_sec", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'report'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "check_runs_project_sha_check": { + "name": "check_runs_project_sha_check", + "columns": [ + "project_id", + "sha", + "check" + ], + "isUnique": true + } + }, + "foreignKeys": { + "check_runs_project_id_projects_id_fk": { + "name": "check_runs_project_id_projects_id_fk", + "tableFrom": "check_runs", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "check_runs_task_id_tasks_id_fk": { + "name": "check_runs_task_id_tasks_id_fk", + "tableFrom": "check_runs", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "code_reviews": { + "name": "code_reviews", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "verdict": { + "name": "verdict", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "findings": { + "name": "findings", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "code_reviews_project_id_projects_id_fk": { + "name": "code_reviews_project_id_projects_id_fk", + "tableFrom": "code_reviews", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "code_reviews_task_id_tasks_id_fk": { + "name": "code_reviews_task_id_tasks_id_fk", + "tableFrom": "code_reviews", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "error_sources": { + "name": "error_sources", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bugsink_project_id": { + "name": "bugsink_project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "dsn": { + "name": "dsn", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "error_sources_bugsink_project_id_unique": { + "name": "error_sources_bugsink_project_id_unique", + "columns": [ + "bugsink_project_id" + ], + "isUnique": true + }, + "error_sources_project_kind": { + "name": "error_sources_project_kind", + "columns": [ + "project_id", + "kind" + ], + "isUnique": true + } + }, + "foreignKeys": { + "error_sources_project_id_projects_id_fk": { + "name": "error_sources_project_id_projects_id_fk", + "tableFrom": "error_sources", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "events": { + "name": "events", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_kind": { + "name": "actor_kind", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_user_id": { + "name": "actor_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_channel": { + "name": "actor_channel", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_client_id": { + "name": "actor_client_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "events_created_at": { + "name": "events_created_at", + "columns": [ + "created_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "events_project_id_projects_id_fk": { + "name": "events_project_id_projects_id_fk", + "tableFrom": "events", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_task_id_tasks_id_fk": { + "name": "events_task_id_tasks_id_fk", + "tableFrom": "events", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_session_id_sessions_id_fk": { + "name": "events_session_id_sessions_id_fk", + "tableFrom": "events", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "events_actor_user_id_users_id_fk": { + "name": "events_actor_user_id_users_id_fk", + "tableFrom": "events", + "tableTo": "users", + "columnsFrom": [ + "actor_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "feedback": { + "name": "feedback", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "via": { + "name": "via", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "context": { + "name": "context", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'{}'" + }, + "screenshots": { + "name": "screenshots", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'received'" + }, + "analysis": { + "name": "analysis", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "analysis_error": { + "name": "analysis_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "analysis_started_at": { + "name": "analysis_started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "option_index": { + "name": "option_index", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reject_reason": { + "name": "reject_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decided_by": { + "name": "decided_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decided_at": { + "name": "decided_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "feedback_user": { + "name": "feedback_user", + "columns": [ + "user_id", + "created_at" + ], + "isUnique": false + }, + "feedback_status": { + "name": "feedback_status", + "columns": [ + "status" + ], + "isUnique": false + } + }, + "foreignKeys": { + "feedback_user_id_users_id_fk": { + "name": "feedback_user_id_users_id_fk", + "tableFrom": "feedback", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "feedback_task_id_tasks_id_fk": { + "name": "feedback_task_id_tasks_id_fk", + "tableFrom": "feedback", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "feedback_decided_by_users_id_fk": { + "name": "feedback_decided_by_users_id_fk", + "tableFrom": "feedback", + "tableTo": "users", + "columnsFrom": [ + "decided_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "goals": { + "name": "goals", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'open'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "goals_project_id_projects_id_fk": { + "name": "goals_project_id_projects_id_fk", + "tableFrom": "goals", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "incident_settings": { + "name": "incident_settings", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "hook_secret": { + "name": "hook_secret", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "policy": { + "name": "policy", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'backlog'" + }, + "triage_prompt": { + "name": "triage_prompt", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "environments": { + "name": "environments", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[\"prod\",\"production\"]'" + }, + "daily_limit": { + "name": "daily_limit", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 5 + }, + "ignore_pattern": { + "name": "ignore_pattern", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "webhook_auto": { + "name": "webhook_auto", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "incident_settings_hook_secret_unique": { + "name": "incident_settings_hook_secret_unique", + "columns": [ + "hook_secret" + ], + "isUnique": true + } + }, + "foreignKeys": { + "incident_settings_project_id_projects_id_fk": { + "name": "incident_settings_project_id_projects_id_fk", + "tableFrom": "incident_settings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "incident_settings_goal_id_goals_id_fk": { + "name": "incident_settings_goal_id_goals_id_fk", + "tableFrom": "incident_settings", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "incidents": { + "name": "incidents", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bugsink_issue_id": { + "name": "bugsink_issue_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "friendly_id": { + "name": "friendly_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "culprit": { + "name": "culprit", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "level": { + "name": "level", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "environment": { + "name": "environment", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "first_release": { + "name": "first_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_release": { + "name": "last_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "events": { + "name": "events", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "first_seen": { + "name": "first_seen", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_seen": { + "name": "last_seen", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stack": { + "name": "stack", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'new'" + }, + "decision": { + "name": "decision", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decided_by": { + "name": "decided_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decision_reason": { + "name": "decision_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_created_at": { + "name": "task_created_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resolved_release": { + "name": "resolved_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resolved_at": { + "name": "resolved_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "regressions": { + "name": "regressions", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "incidents_bugsink_issue_id_unique": { + "name": "incidents_bugsink_issue_id_unique", + "columns": [ + "bugsink_issue_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "incidents_project_id_projects_id_fk": { + "name": "incidents_project_id_projects_id_fk", + "tableFrom": "incidents", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "incidents_task_id_tasks_id_fk": { + "name": "incidents_task_id_tasks_id_fk", + "tableFrom": "incidents", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_clients": { + "name": "oauth_clients", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_codes": { + "name": "oauth_codes", + "columns": { + "code_hash": { + "name": "code_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "code_challenge": { + "name": "code_challenge", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "used_at": { + "name": "used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_codes_client_id_oauth_clients_id_fk": { + "name": "oauth_codes_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_codes_user_id_users_id_fk": { + "name": "oauth_codes_user_id_users_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_tokens": { + "name": "oauth_tokens", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_tokens_client_id_oauth_clients_id_fk": { + "name": "oauth_tokens_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_tokens_user_id_users_id_fk": { + "name": "oauth_tokens_user_id_users_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_invites": { + "name": "project_invites", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "invited_by": { + "name": "invited_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "project_invites_project_id_projects_id_fk": { + "name": "project_invites_project_id_projects_id_fk", + "tableFrom": "project_invites", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_invites_invited_by_users_id_fk": { + "name": "project_invites_invited_by_users_id_fk", + "tableFrom": "project_invites", + "tableTo": "users", + "columnsFrom": [ + "invited_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_invites_project_id_login_pk": { + "columns": [ + "project_id", + "login" + ], + "name": "project_invites_project_id_login_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_members": { + "name": "project_members", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "added_by": { + "name": "added_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "project_members_project_id_projects_id_fk": { + "name": "project_members_project_id_projects_id_fk", + "tableFrom": "project_members", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_user_id_users_id_fk": { + "name": "project_members_user_id_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_added_by_users_id_fk": { + "name": "project_members_added_by_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "added_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_members_project_id_user_id_pk": { + "columns": [ + "project_id", + "user_id" + ], + "name": "project_members_project_id_user_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_secrets": { + "name": "project_secrets", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "value_enc": { + "name": "value_enc", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_by": { + "name": "updated_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "project_secrets_project_name": { + "name": "project_secrets_project_name", + "columns": [ + "project_id", + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "project_secrets_project_id_projects_id_fk": { + "name": "project_secrets_project_id_projects_id_fk", + "tableFrom": "project_secrets", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_secrets_created_by_users_id_fk": { + "name": "project_secrets_created_by_users_id_fk", + "tableFrom": "project_secrets", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "project_secrets_updated_by_users_id_fk": { + "name": "project_secrets_updated_by_users_id_fk", + "tableFrom": "project_secrets", + "tableTo": "users", + "columnsFrom": [ + "updated_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "projects": { + "name": "projects", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "gitea_owner": { + "name": "gitea_owner", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "gitea_repo": { + "name": "gitea_repo", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "default_branch": { + "name": "default_branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'main'" + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "owner_id": { + "name": "owner_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "next_task_number": { + "name": "next_task_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "subscription_pool_id": { + "name": "subscription_pool_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "deleted_by": { + "name": "deleted_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "projects_slug_unique": { + "name": "projects_slug_unique", + "columns": [ + "slug" + ], + "isUnique": true + }, + "projects_key_unique": { + "name": "projects_key_unique", + "columns": [ + "key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "projects_owner_id_users_id_fk": { + "name": "projects_owner_id_users_id_fk", + "tableFrom": "projects", + "tableTo": "users", + "columnsFrom": [ + "owner_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "projects_subscription_pool_id_subscription_pools_id_fk": { + "name": "projects_subscription_pool_id_subscription_pools_id_fk", + "tableFrom": "projects", + "tableTo": "subscription_pools", + "columnsFrom": [ + "subscription_pool_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "projects_deleted_by_users_id_fk": { + "name": "projects_deleted_by_users_id_fk", + "tableFrom": "projects", + "tableTo": "users", + "columnsFrom": [ + "deleted_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "push_outbox": { + "name": "push_outbox", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "urgency": { + "name": "urgency", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'normal'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "sent_at": { + "name": "sent_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "push_outbox_dedupe_key_unique": { + "name": "push_outbox_dedupe_key_unique", + "columns": [ + "dedupe_key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "push_outbox_subscription_id_push_subscriptions_id_fk": { + "name": "push_outbox_subscription_id_push_subscriptions_id_fk", + "tableFrom": "push_outbox", + "tableTo": "push_subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "push_subscriptions": { + "name": "push_subscriptions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "endpoint": { + "name": "endpoint", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "p256dh": { + "name": "p256dh", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "auth": { + "name": "auth", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_ok_at": { + "name": "last_ok_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "push_subscriptions_endpoint_unique": { + "name": "push_subscriptions_endpoint_unique", + "columns": [ + "endpoint" + ], + "isUnique": true + } + }, + "foreignKeys": { + "push_subscriptions_user_id_users_id_fk": { + "name": "push_subscriptions_user_id_users_id_fk", + "tableFrom": "push_subscriptions", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "questions": { + "name": "questions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "options": { + "name": "options", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "msg_type": { + "name": "msg_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "default_option": { + "name": "default_option", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "answer": { + "name": "answer", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "answered_via": { + "name": "answered_via", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "awaiting_hook": { + "name": "awaiting_hook", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "reminders": { + "name": "reminders", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "answered_at": { + "name": "answered_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "questions_project_id_projects_id_fk": { + "name": "questions_project_id_projects_id_fk", + "tableFrom": "questions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_task_id_tasks_id_fk": { + "name": "questions_task_id_tasks_id_fk", + "tableFrom": "questions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_session_id_sessions_id_fk": { + "name": "questions_session_id_sessions_id_fk", + "tableFrom": "questions", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "releases": { + "name": "releases", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "env": { + "name": "env", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "previous_sha": { + "name": "previous_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host": { + "name": "host", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tasks": { + "name": "tasks", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'deploying'" + }, + "deployed_by": { + "name": "deployed_by", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'ci'" + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "run_url": { + "name": "run_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "log_tail": { + "name": "log_tail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "screenshots": { + "name": "screenshots", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "releases_project_id_projects_id_fk": { + "name": "releases_project_id_projects_id_fk", + "tableFrom": "releases", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "review_settings": { + "name": "review_settings", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "max_iterations": { + "name": "max_iterations", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 2 + }, + "rules": { + "name": "rules", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "review_settings_project_id_projects_id_fk": { + "name": "review_settings_project_id_projects_id_fk", + "tableFrom": "review_settings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "runner_commands": { + "name": "runner_commands", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "result": { + "name": "result", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error_kind": { + "name": "error_kind", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor": { + "name": "actor", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host": { + "name": "host", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "finished_at": { + "name": "finished_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "runner_commands_status_idx": { + "name": "runner_commands_status_idx", + "columns": [ + "status", + "id" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "runner_hosts": { + "name": "runner_hosts", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ssh_target": { + "name": "ssh_target", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ssh_port": { + "name": "ssh_port", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 22 + }, + "workdir": { + "name": "workdir", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'peppa'" + }, + "peppa_url": { + "name": "peppa_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'unknown'" + }, + "info": { + "name": "info", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "disabled_at": { + "name": "disabled_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "runner_hosts_name_unique": { + "name": "runner_hosts_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "runner_tasks": { + "name": "runner_tasks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "prompt": { + "name": "prompt", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "front": { + "name": "front", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ended_at": { + "name": "ended_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "runner_tasks_session_idx": { + "name": "runner_tasks_session_idx", + "columns": [ + "session_id", + "status" + ], + "isUnique": false + } + }, + "foreignKeys": { + "runner_tasks_session_id_sessions_id_fk": { + "name": "runner_tasks_session_id_sessions_id_fk", + "tableFrom": "runner_tasks", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "runner_tasks_task_id_tasks_id_fk": { + "name": "runner_tasks_task_id_tasks_id_fk", + "tableFrom": "runner_tasks", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "sessions": { + "name": "sessions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tmux_name": { + "name": "tmux_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'claude'" + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_session_id": { + "name": "claude_session_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "auto_nudges": { + "name": "auto_nudges", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "resume_at": { + "name": "resume_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_probe_min": { + "name": "limit_probe_min", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_resumes": { + "name": "limit_resumes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "limit_resumes_day": { + "name": "limit_resumes_day", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_resumed_at": { + "name": "limit_resumed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rotate_reason": { + "name": "rotate_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host_id": { + "name": "host_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "container": { + "name": "container", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "agent_id": { + "name": "agent_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "usage": { + "name": "usage", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "watch_state": { + "name": "watch_state", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'starting'" + }, + "last_activity_at": { + "name": "last_activity_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "ended_at": { + "name": "ended_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "sessions_tmux_name_unique": { + "name": "sessions_tmux_name_unique", + "columns": [ + "tmux_name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "sessions_project_id_projects_id_fk": { + "name": "sessions_project_id_projects_id_fk", + "tableFrom": "sessions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sessions_task_id_tasks_id_fk": { + "name": "sessions_task_id_tasks_id_fk", + "tableFrom": "sessions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "sessions_subscription_id_subscriptions_id_fk": { + "name": "sessions_subscription_id_subscriptions_id_fk", + "tableFrom": "sessions", + "tableTo": "subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "sessions_host_id_runner_hosts_id_fk": { + "name": "sessions_host_id_runner_hosts_id_fk", + "tableFrom": "sessions", + "tableTo": "runner_hosts", + "columnsFrom": [ + "host_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "sessions_agent_id_agents_id_fk": { + "name": "sessions_agent_id_agents_id_fk", + "tableFrom": "sessions", + "tableTo": "agents", + "columnsFrom": [ + "agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "settings": { + "name": "settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscription_pool_members": { + "name": "subscription_pool_members", + "columns": { + "pool_id": { + "name": "pool_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "subscription_pool_members_pool_id_subscription_pools_id_fk": { + "name": "subscription_pool_members_pool_id_subscription_pools_id_fk", + "tableFrom": "subscription_pool_members", + "tableTo": "subscription_pools", + "columnsFrom": [ + "pool_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "subscription_pool_members_subscription_id_subscriptions_id_fk": { + "name": "subscription_pool_members_subscription_id_subscriptions_id_fk", + "tableFrom": "subscription_pool_members", + "tableTo": "subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "subscription_pool_members_pool_id_subscription_id_pk": { + "columns": [ + "pool_id", + "subscription_id" + ], + "name": "subscription_pool_members_pool_id_subscription_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscription_pools": { + "name": "subscription_pools", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "subscription_pools_name_unique": { + "name": "subscription_pools_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "subscription_pools_created_by_users_id_fk": { + "name": "subscription_pools_created_by_users_id_fk", + "tableFrom": "subscription_pools", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscriptions": { + "name": "subscriptions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "auth_kind": { + "name": "auth_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "secret_enc": { + "name": "secret_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "key_provider": { + "name": "key_provider", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "limited_until": { + "name": "limited_until", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "checked_at": { + "name": "checked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "activated_at": { + "name": "activated_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "subscriptions_created_by_users_id_fk": { + "name": "subscriptions_created_by_users_id_fk", + "tableFrom": "subscriptions", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "task_deps": { + "name": "task_deps", + "columns": { + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "blocked_by_id": { + "name": "blocked_by_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "task_deps_blocked_by": { + "name": "task_deps_blocked_by", + "columns": [ + "blocked_by_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "task_deps_task_id_tasks_id_fk": { + "name": "task_deps_task_id_tasks_id_fk", + "tableFrom": "task_deps", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "task_deps_blocked_by_id_tasks_id_fk": { + "name": "task_deps_blocked_by_id_tasks_id_fk", + "tableFrom": "task_deps", + "tableTo": "tasks", + "columnsFrom": [ + "blocked_by_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "task_deps_task_id_blocked_by_id_pk": { + "columns": [ + "task_id", + "blocked_by_id" + ], + "name": "task_deps_task_id_blocked_by_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tasks": { + "name": "tasks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "number": { + "name": "number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'backlog'" + }, + "openspec_change": { + "name": "openspec_change", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ci_attempts": { + "name": "ci_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "ci_failed_sha": { + "name": "ci_failed_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "gitea_issue": { + "name": "gitea_issue", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "position": { + "name": "position", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "archived_at": { + "name": "archived_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "origin": { + "name": "origin", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'human'" + }, + "proposed": { + "name": "proposed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "severity": { + "name": "severity", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "tasks_project_number": { + "name": "tasks_project_number", + "columns": [ + "project_id", + "number" + ], + "isUnique": true + }, + "tasks_project_issue": { + "name": "tasks_project_issue", + "columns": [ + "project_id", + "gitea_issue" + ], + "isUnique": true + } + }, + "foreignKeys": { + "tasks_project_id_projects_id_fk": { + "name": "tasks_project_id_projects_id_fk", + "tableFrom": "tasks", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tasks_goal_id_goals_id_fk": { + "name": "tasks_goal_id_goals_id_fk", + "tableFrom": "tasks", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "telegram_outbox": { + "name": "telegram_outbox", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "params": { + "name": "params", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "question_id": { + "name": "question_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "chat_message_id": { + "name": "chat_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "sent_at": { + "name": "sent_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "telegram_outbox_dedupe_key_unique": { + "name": "telegram_outbox_dedupe_key_unique", + "columns": [ + "dedupe_key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "telegram_outbox_question_id_questions_id_fk": { + "name": "telegram_outbox_question_id_questions_id_fk", + "tableFrom": "telegram_outbox", + "tableTo": "questions", + "columnsFrom": [ + "question_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "telegram_outbox_chat_message_id_chat_messages_id_fk": { + "name": "telegram_outbox_chat_message_id_chat_messages_id_fk", + "tableFrom": "telegram_outbox", + "tableTo": "chat_messages", + "columnsFrom": [ + "chat_message_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "telegram_updates": { + "name": "telegram_updates", + "columns": { + "update_id": { + "name": "update_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "users": { + "name": "users", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "gitea_id": { + "name": "gitea_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "access_token_enc": { + "name": "access_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "refresh_token_enc": { + "name": "refresh_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "token_expires_at": { + "name": "token_expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_token_enc": { + "name": "claude_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_token_set_at": { + "name": "claude_token_set_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_chat_id": { + "name": "telegram_chat_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_user_id": { + "name": "telegram_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_username": { + "name": "telegram_username", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_paired_at": { + "name": "telegram_paired_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_bot_token_enc": { + "name": "telegram_bot_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_bot_username": { + "name": "telegram_bot_username", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "egov_iin": { + "name": "egov_iin", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "egov_linked_at": { + "name": "egov_linked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "google_sub": { + "name": "google_sub", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "google_email": { + "name": "google_email", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "google_linked_at": { + "name": "google_linked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password_set_at": { + "name": "password_set_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "disabled_at": { + "name": "disabled_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_login_at": { + "name": "last_login_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "users_gitea_id_unique": { + "name": "users_gitea_id_unique", + "columns": [ + "gitea_id" + ], + "isUnique": true + }, + "users_login_unique": { + "name": "users_login_unique", + "columns": [ + "login" + ], + "isUnique": true + }, + "users_telegram_chat_id_unique": { + "name": "users_telegram_chat_id_unique", + "columns": [ + "telegram_chat_id" + ], + "isUnique": true + }, + "users_egov_iin_unique": { + "name": "users_egov_iin_unique", + "columns": [ + "egov_iin" + ], + "isUnique": true + }, + "users_google_sub_unique": { + "name": "users_google_sub_unique", + "columns": [ + "google_sub" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index 27e298a8..a95b8840 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -162,6 +162,13 @@ "when": 1794841100041, "tag": "0022_loving_mordo", "breakpoints": true + }, + { + "idx": 23, + "version": "6", + "when": 1794919319811, + "tag": "0023_curious_steel_serpent", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index 4aba7cac..6f6a5303 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -144,6 +144,12 @@ export const tasks = sqliteTable( position: real("position").notNull().default(0), // PEP-34: archived stories are hidden from the board, the dispatcher and epic progress. archivedAt: integer("archived_at", { mode: "timestamp_ms" }), + // PEP-197: who made the story — human | acceptance | incident | analyst (agents ≠ human). + origin: text("origin").notNull().default("human"), + // PEP-197: «Предложено» — a story of an agent the owner has not decided on (status stays backlog). + proposed: integer("proposed", { mode: "boolean" }).notNull().default(false), + // PEP-197: breakage | important | minor — set on stories of the acceptance agent. + severity: text("severity"), createdAt: createdAt(), updatedAt: updatedAt(), }, diff --git a/packages/mcp/src/manager.ts b/packages/mcp/src/manager.ts index b98bf18a..c7c20e72 100644 --- a/packages/mcp/src/manager.ts +++ b/packages/mcp/src/manager.ts @@ -289,6 +289,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ merge: z.enum(["manual", "auto"]).optional().describe("auto = merge green PRs without conflicts (pipeline changes always need the user)"), close: z.enum(["pm", "after_merge", "after_hours"]).optional(), close_after_hours: z.number().int().min(1).max(336).optional(), + accept_own: z.enum(["mine", "mine_breakage", "all"]).optional().describe("Which stories Peppa accepts herself when merge=auto: only the user's own / own and breakages (default) / all"), idle_push: z.boolean().optional().describe("Push the user when no agent works and the backlog is not empty"), idle_push_hours: z.number().int().min(1).max(168).optional(), quiet_from: z.number().int().min(0).max(23).nullable().optional(), @@ -307,6 +308,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ merge: a.merge, close: a.close, closeAfterHours: a.close_after_hours, + acceptOwn: a.accept_own, idlePush: a.idle_push, idlePushHours: a.idle_push_hours, quietFrom: a.quiet_from, diff --git a/packages/runner/src/analyst-chat.ts b/packages/runner/src/analyst-chat.ts index 690a409b..33894469 100644 --- a/packages/runner/src/analyst-chat.ts +++ b/packages/runner/src/analyst-chat.ts @@ -27,7 +27,7 @@ import { } from "@peppa/core"; import { chatMessages, chats, projects, type Db } from "@peppa/db"; import { and, desc, eq, gt, isNull, lte } from "drizzle-orm"; -import { localizeRoleMessage, m as tr, t } from "@peppa/shared/i18n"; +import { localizeRoleMessage, m as tr, t, type Locale } from "@peppa/shared/i18n"; import { claudePrint } from "./claude-print.ts"; const inFlight = new Set(); @@ -93,7 +93,7 @@ export async function analystChatTick(db: Db, opts: AnalystChatOptions = {}): Pr * agent's name) or, without an author, a system note. An agent's message also reaches the * project's people in their own Telegram bot / browser. */ -export async function sayInDiscussion(db: Db, project: Project, chatId: number, text: string, author: string | null = ANALYST_NAME) { +export async function sayInDiscussion(db: Db, project: Project, chatId: number, text: string, author: string | null = ANALYST_NAME, extra: { buttons?: (locale: Locale) => Array> } = {}) { const m = await addChatMessage(db, author ? { chatId, kind: "user", authorKind: "agent", authorLogin: author, text } : { chatId, kind: "user", authorKind: "system", text }); await notify(db, { type: "chat_message", messageId: m?.id ?? 0 }); if (author && m) { @@ -110,7 +110,7 @@ export async function sayInDiscussion(db: Db, project: Project, chatId: number, projectId: project.id, dedupeKey: `chat:m${m.id}:${u.telegramChatId}`, pushKey: `chat:m${m.id}:u${u.id}`, - telegram: { params: { text: `💬 ${esc(project.name)} · ${esc(who)}:\n${esc(short)}\n\n${t(locale, "Ответить: {url}", { url: `${process.env.PEPPA_WEB_URL ?? ""}/chats/${project.key}` })}`, parse_mode: "HTML", link_preview_options: { is_disabled: true } } }, + telegram: { params: { text: `💬 ${esc(project.name)} · ${esc(who)}:\n${esc(short)}\n\n${t(locale, "Ответить: {url}", { url: `${process.env.PEPPA_WEB_URL ?? ""}/chats/${project.key}` })}`, parse_mode: "HTML", link_preview_options: { is_disabled: true }, ...(extra.buttons ? { reply_markup: { inline_keyboard: extra.buttons(locale) } } : {}) } }, push: { title: `${project.name}: ${who}`, body: short.slice(0, 200), url: `/chats/${project.key}`, tag: `chat:${project.id}` }, }).catch(() => null); } diff --git a/packages/runner/src/autonomy.ts b/packages/runner/src/autonomy.ts index 18a23231..8dcf444b 100644 --- a/packages/runner/src/autonomy.ts +++ b/packages/runner/src/autonomy.ts @@ -47,6 +47,10 @@ import { pendingRefinements, pausedProjectIds, isProjectPaused, + agentTasksInWork, + getAgentLimits, + isAgentOrigin, + mayAutoAcceptTask, } from "@peppa/core"; import { goals, incidents, questions, tasks, type Db } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; @@ -129,6 +133,8 @@ async function autoMergeReviews(db: Db, project: Project, a: AutonomySettings, c const ref = refOf(project, task); // PEP-127: the PM accepted this story already — `pendingAcceptTick` merges and closes it. if (await getPendingAccept(db, task.id)) continue; + // PEP-197: a story the factory made itself waits for the owner unless «Принимать сами» says otherwise. + if (!(await mayAutoAcceptTask(db, task))) continue; const state = (await getSetting(db, mergeKey(task.id))) ?? {}; if (!taskPrNumber(project, task.prUrl)) { await afterMerge(db, ref, a, state, log); @@ -203,6 +209,8 @@ async function autoCloseReviews(db: Db, project: Project, a: AutonomySettings, n .from(questions) .where(and(eq(questions.taskId, task.id), eq(questions.kind, "attention"), isNull(questions.answeredAt))); if (!q || q.createdAt.getTime() > cutoff) continue; + // PEP-197: not closed by the clock for stories the owner has to accept. + if (!(await mayAutoAcceptTask(db, task))) continue; const ref = refOf(project, task); // A pipeline change is never accepted without the PM, however long it waits. const state = (await getSetting(db, mergeKey(task.id))) ?? {}; @@ -262,7 +270,8 @@ export async function autoPickSlots(db: Db, project: Project, a: AutonomySetting async function dispatch(db: Db, project: Project, a: AutonomySettings, now: Date, log: (m: string) => void) { const sessions = (await listSessions(db, { active: true })).filter((s) => s.projectId === project.id); const working = await workingSessions(db, sessions); - const backlog = await listTasks(db, { projectId: project.id, statuses: ["backlog"] }); + // PEP-197: «Предложено» is not the backlog: nothing there waits for an agent. + const backlog = (await listTasks(db, { projectId: project.id, statuses: ["backlog"] })).filter((t) => !t.proposed); // PEP-42: only stories whose predecessors are in review/done; PEP-34: in board order. const ready = await readyBacklog(db, project.id, backlog); const state = await getIdle(db, project.id); @@ -289,8 +298,12 @@ async function dispatch(db: Db, project: Project, a: AutonomySettings, now: Date if (ready.length && !(await poolHasRoom(db, project.id, now))) return; // PEP-10: stories waiting in runner queues count as taken; PEP-182: so do the ones waiting for room. let slots = a.wipLimit - working.length - (await queuedItems(db, { sessionIds: sessions.map((s) => s.id) })).length - (await capacityQueue(db, { projectIds: [project.id] })).length; + // PEP-197: not more than N stories made by agents in work at once; a person's go first anyway. + const agentLimit = (await getAgentLimits(db, project.id)).inWork; + let agentWork = await agentTasksInWork(db, project.id); for (const task of ready) { if (slots <= 0) break; + if (isAgentOrigin(task.origin) && agentWork >= agentLimit) continue; const ref = refOf(project, task); // PEP-150: a story whose start attempts ran out waits for the superadmin; the next one goes. if ((await getPlatformDelay(db, { projectId: project.id, taskId: task.id }, "start"))?.exhausted) continue; @@ -301,6 +314,7 @@ async function dispatch(db: Db, project: Project, a: AutonomySettings, now: Date if (r.waiting) break; await clearPlatformDelay(db, { projectId: project.id, taskId: task.id }, "start"); slots--; + if (isAgentOrigin(task.origin)) agentWork++; } catch (e) { // Back to the backlog: the card must not hang in "in progress" without an agent. const fresh = await resolveTaskById(db, task.id).catch(() => null); @@ -349,7 +363,8 @@ export async function readyBacklog(db: const refining = await intakePendingTasks(db, projectId); // PEP-115: nor does a story whose fresh comment the analyst is still working into the description. const commented = await pendingRefinements(db, { projectId }); - const ready = list.filter((t) => !blocked.has(t.id) && !refining.has(t.id) && !commented.has(t.id)); + // PEP-197: «Предложено» — stories of agents the owner has not decided on — are not taken. + const ready = list.filter((t) => !blocked.has(t.id) && !refining.has(t.id) && !commented.has(t.id) && !t.proposed); // PEP-103: fixing errors comes first — bug stories, then the rest, each in board order. const bugs = await bugTaskIds(db, projectId); // PEP-145: before everything — the system story that makes the product open by a link. diff --git a/packages/runner/src/flow.ts b/packages/runner/src/flow.ts index c29083e5..db03572f 100644 --- a/packages/runner/src/flow.ts +++ b/packages/runner/src/flow.ts @@ -1,7 +1,7 @@ // PM-side moves on the task board and review acceptance (web and Telegram use these). import { m } from "@peppa/shared/i18n"; import { releaseIntake } from "./intake.ts"; -import { addStoryComment, answerQuestion, assertProjectActive, STORY_PRODUCT_TEXT, giteaForBot, GATE_UNKNOWN_REASON, clearPendingAccept, PENDING_ACCEPT_ANSWER, setPendingAccept, dropQueuedTask, clearCapacityWait, isWaitingForCapacity, getQuestion, listSessions, PeppaError, pendingQuestions, prGate, queuedItems, reorderTask, resolveTask, setTaskArchived, updateTask, type Question, type ReorderTo, type TaskRef } from "@peppa/core"; +import { addStoryComment, approveProposal, answerQuestion, assertProjectActive, STORY_PRODUCT_TEXT, giteaForBot, GATE_UNKNOWN_REASON, clearPendingAccept, PENDING_ACCEPT_ANSWER, setPendingAccept, dropQueuedTask, clearCapacityWait, isWaitingForCapacity, getQuestion, listSessions, PeppaError, pendingQuestions, prGate, queuedItems, reorderTask, resolveTask, setTaskArchived, updateTask, type Question, type ReorderTo, type TaskRef } from "@peppa/core"; import { tasks, projects, type Db } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; import { eq } from "drizzle-orm"; @@ -50,6 +50,11 @@ export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: Sta if (isRunnerClient()) return runnerCall(db, "move", { task: ref.key, to, start }, { key: `task:${ref.task.id}` }); const from = columnOf(ref.task.status); let stopped = 0; + // PEP-197: a person moved the card — that is the decision on a «Предложено» story. + if (ref.task.proposed) { + await approveProposal(db, ref.task.id); + ref.task = { ...ref.task, proposed: false }; + } if (to === "in_progress") { // PEP-84: the PM took the story before the roles finished — they let it go. await releaseIntake(db, ref.task.id); diff --git a/packages/runner/src/hook.ts b/packages/runner/src/hook.ts index 09133b6d..c8102175 100644 --- a/packages/runner/src/hook.ts +++ b/packages/runner/src/hook.ts @@ -13,6 +13,7 @@ import { recordStep, describeUsage, getAutonomy, + mayAutoAcceptTask, getBudgetState, parseStatusLine, recordStatusLine, @@ -244,7 +245,7 @@ async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue: await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() }); return null; } - if (task?.status === "review" && (await getAutonomy(db, task.projectId)).merge === "auto") { + if (task?.status === "review" && (await getAutonomy(db, task.projectId)).merge === "auto" && (await mayAutoAcceptTask(db, task))) { // PEP-25: Peppa merges this PR itself (watchdog); the PM hears only if it can't. await logSessionEvent(db, s, "awaiting_automerge", { pr: task.prUrl }); await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() }); diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts index b5cd3f43..a12f586c 100644 --- a/packages/runner/src/index.ts +++ b/packages/runner/src/index.ts @@ -17,6 +17,9 @@ export * from "./incidents.ts"; export * from "./analyst-chat.ts"; export * from "./message-intent.ts"; export * from "./product-review.ts"; +export * from "./proposals.ts"; +export * from "./task-dedup.ts"; +export * from "./task-tidy.ts"; export * from "./feedback.ts"; export * from "./triage.ts"; export * from "./ci-feedback.ts"; diff --git a/packages/runner/src/intake.ts b/packages/runner/src/intake.ts index edf658e1..3f2600c0 100644 --- a/packages/runner/src/intake.ts +++ b/packages/runner/src/intake.ts @@ -73,7 +73,7 @@ async function step(db: Db, ref: TaskRef, state: IntakeState, now: Date): Promis if (!note) throw new Error(m("продакт ответил не по формату")); const splitKeys: string[] = []; for (const s of note.split) { - const extra = await createTask(db, { projectId: project.id, goalId: task.goalId ?? undefined, title: s.title, description: s.description }); + const extra = await createTask(db, { projectId: project.id, goalId: task.goalId ?? undefined, title: s.title, description: s.description, origin: "analyst" }); // A split story is already cut by the product manager: the analyst takes it from here. await setIntakeState(db, extra.task.id, { stage: "analyst", original: { title: s.title, description: s.description }, product: { ...note, title: s.title, split: [] }, attempts: 0 }); splitKeys.push(extra.key); diff --git a/packages/runner/src/message-intent.ts b/packages/runner/src/message-intent.ts index eb1499db..4fa60256 100644 --- a/packages/runner/src/message-intent.ts +++ b/packages/runner/src/message-intent.ts @@ -102,7 +102,7 @@ export async function resolveChatOffer(db: Db, user: User, messageId: number, ch const offer = await getChatOffer(db, messageId); if (!offer || chat.kind !== "project" || !chat.projectId) throw new PeppaError(m("Эта кнопка уже не работает. Напишите сообщение ещё раз.")); const project = await projectForUser(db, user.id, chat.projectId); - const allowed: Record = { task: ["task"], choice: ["answer", "task"], draft: ["create", "cancel"] }; + const allowed: Record = { task: ["task"], choice: ["answer", "task"], draft: ["create", "cancel"], proposals: [] }; if (!allowed[offer.kind].includes(choice)) throw new PeppaError(m("Эта кнопка уже не работает. Напишите сообщение ещё раз.")); // One press — one outcome: the buttons go away first. await dropChatOffer(db, messageId); diff --git a/packages/runner/src/product-link.ts b/packages/runner/src/product-link.ts index c7fdb72d..b31a47fc 100644 --- a/packages/runner/src/product-link.ts +++ b/packages/runner/src/product-link.ts @@ -81,7 +81,7 @@ export async function ensureProductLinkTask(db: Db, project: Project, o: Product 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 }); + const ref = await createTask(db, { projectId: project.id, title: PRODUCT_LINK_TITLE, description, origin: "acceptance", severity: "breakage" }); // 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" }); diff --git a/packages/runner/src/product-review.ts b/packages/runner/src/product-review.ts index 2497c09d..28be7797 100644 --- a/packages/runner/src/product-review.ts +++ b/packages/runner/src/product-review.ts @@ -6,7 +6,20 @@ // What the owner must give goes to the «чтобы заработало по-настоящему» list; what a user would // not understand becomes backlog stories. import { + addIntakeNote, createTask, + dedupRemark, + dedupSimilarNote, + finishVersionIfReady, + getAgentLimits, + getDigest, + normTitle, + rejectedTitles, + setChatOffer, + setDigest, + SEVERITY_LABEL, + versionFinished, + type ProductReviewReply, guardUntrusted, declareNeeds, ensureProjectChat, @@ -33,19 +46,21 @@ import { } from "@peppa/core"; import { projects, releases, settings, tasks, type Db } from "@peppa/db"; import { and, desc, eq, isNull, ne, sql } from "drizzle-orm"; +import { m as tr, t, type Locale } from "@peppa/shared/i18n"; import { sayInDiscussion } from "./analyst-chat.ts"; +import { checkDuplicate } from "./task-dedup.ts"; import { claudePrint } from "./claude-print.ts"; import { releaseScreenshotFiles, type Release } from "./deploy.ts"; const inFlight = new Set(); const MAX_ATTEMPTS = 2; const MAX_SHOTS = 3; -const norm = (s: string) => s.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, " ").trim(); export interface ProductReviewOptions { log?: (m: string) => void; /** Wait for the model calls (tests); the watchdog lets them run in the background. */ wait?: boolean; + now?: Date; } /** Deploys the product agent has not looked at yet. */ @@ -53,6 +68,7 @@ export async function productReviewTick(db: Db, opts: ProductReviewOptions = {}) if (process.env.PEPPA_PRODUCT_REVIEW === "off") return; const log = opts.log ?? (() => {}); const jobs: Promise[] = []; + await productDigestTick(db, opts.now ?? new Date(), log).catch((e) => log(`product digest: ${(e as Error).message}`)); const rows = await db.select().from(settings).where(sql`${settings.key} like ${`${PRODUCT_REVIEW_PENDING_PREFIX}%`}`); for (const row of rows) { const projectId = Number(row.key.slice(PRODUCT_REVIEW_PENDING_PREFIX.length)); @@ -146,6 +162,7 @@ async function review(db: Db, project: Project, rel: Release, pending: PendingPr needs: await productNeeds(db, project.id), secretNames: (await listProjectSecrets(db, project.id)).map((s) => s.name), openStories: all.map((t) => t.title), + rejected: (await rejectedTitles(db, project.id)).slice(-30), }), }); if (!out.ok) return retry(out.error); @@ -155,21 +172,108 @@ async function review(db: Db, project: Project, rel: Release, pending: PendingPr // Dealt with from here on: whatever fails below is not retried into a second message. await setPendingProductReview(db, project.id, null); await declareNeeds(db, project.id, reply.needs, { source: "product", replaceSource: true }); - const known = new Set((await db.select({ title: tasks.title }).from(tasks).where(and(eq(tasks.projectId, project.id), isNull(tasks.archivedAt)))).map((t) => norm(t.title))); - const filed: string[] = []; - for (const s of reply.stories) { - if (known.has(norm(s.title))) continue; - known.add(norm(s.title)); + // PEP-197: what the agent found is checked for repeats and goes to «Предложено» (a breakage — to the backlog). + const filed = await fileStories(db, project, reply.stories, { envLabel, url, log }); + const stillOpen = await openNeeds(db, project.id); + await saveProductReview(db, project.id, { at: new Date().toISOString(), env: rel.env as "staging" | "prod", sha: rel.sha, url, summary: reply.summary, howto: reply.howto, notReal: reply.notReal, filed: filed.created.map((f) => f.key) }); + const chat = await ensureProjectChat(db, project.id); + // PEP-197: the version is finished when everything a person asked for is accepted and nothing is broken. + const versionDone = await finishVersionIfReady(db, project.id, filed.breakage); + const found = { n: filed.created.length, important: filed.created.filter((f) => f.severity !== "minor").length }; + let text = productReviewMessage(reply, { env: rel.env === "prod" ? "prod" : "staging", url, openNeeds: stillOpen, filed: filed.created.map((f) => `${f.key} «${f.title}» — ${tr(SEVERITY_LABEL[f.severity])}`), webUrl: process.env.PEPPA_WEB_URL ?? "", projectKey: project.key, found }); + if (versionDone) text += `\n\n${tr("Версия готова. Продукт: {url}", { url })}\n${tr("Что умеет: {summary}", { summary: reply.summary })}`; + // One message, buttons under it: «Делать» / «Не надо» per item, «Делать важные» / «Отклонить всё». + const said = await sayInDiscussion(db, project, chat.id, text, PRODUCT_AGENT_NAME, { buttons: (locale) => proposalButtons(filed.created, locale) }); + if (said && filed.created.length) await setChatOffer(db, said.id, { kind: "proposals", text: "", items: filed.created.map((f) => ({ id: f.id, key: f.key, title: f.title, severity: f.severity })) }); + log(`product review ${project.key}: ${rel.env} ${rel.sha.slice(0, 7)} — needs ${stillOpen.length}, stories ${filed.created.length}`); +} + +const SEVERITY_ORDER = { breakage: 0, important: 1, minor: 2 } as const; +type Severity = "breakage" | "important" | "minor"; +interface Filed { + id: number; + key: string; + title: string; + severity: Severity; +} + +/** + * Files the stories the acceptance agent found: not more than the project's limit per pass, + * never what the owner declined, never a repeat (a remark goes to the open story instead). + * An improvement waits in «Предложено»; a breakage goes to the backlog at once, marked. + * After the version's finish only breakages are filed; the rest is kept for the weekly message. + */ +export async function fileStories(db: Db, project: Project, stories: ProductReviewReply["stories"], o: { envLabel: string; url: string; log?: (m: string) => void; ignoreFinish?: boolean }): Promise<{ created: Filed[]; breakage: boolean; kept: number }> { + const limits = await getAgentLimits(db, project.id); + const finished = o.ignoreFinish ? false : await versionFinished(db, project.id); + const rejected = new Set(await rejectedTitles(db, project.id)); + const created: Filed[] = []; + let breakage = false; + let kept = 0; + const ordered = [...stories].sort((a, b) => SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity]).slice(0, Math.max(0, limits.perPass)); + for (const s of ordered) { + if (rejected.has(normTitle(s.title))) continue; + if (s.severity === "breakage") breakage = true; + const dup = await checkDuplicate(db, project, s, { log: o.log }); + if (dup.kind === "open") { + await addIntakeNote(db, dup.task, "product", dedupRemark(s.title, s.description)); + o.log?.(`product review ${project.key}: «${s.title}» — повтор ${dup.key}, замечание дописано`); + continue; + } + if (finished && s.severity !== "breakage") { + const d = await getDigest(db, project.id); + if (!d.items.some((i) => normTitle(i.title) === normTitle(s.title))) await setDigest(db, project.id, { items: [...d.items, { title: s.title, description: s.description, severity: s.severity }].slice(-20), sentAt: d.sentAt ?? new Date().toISOString() }); + kept++; + continue; + } // glossary-user: описание задачи, которое читает владелец - const description = `${s.description}\n\n_Заведено продакт-агентом на приёмке: ${envLabel}, ${url}._`; - const ref = await createTask(db, { projectId: project.id, title: s.title, description }); + let description = `${s.description}\n\n_Заведено продакт-агентом на приёмке${o.url ? `: ${o.envLabel}, ${o.url}` : ""}._`; + if (dup.kind === "done") description += `\n\n_${dedupSimilarNote(dup.key, dup.doneAt.toISOString().slice(0, 10))}_`; + const isBreakage = s.severity === "breakage"; + const ref = await createTask(db, { projectId: project.id, title: s.title, description, origin: "acceptance", severity: s.severity, proposed: !isBreakage }); // Already formulated: «продакт» and «аналитик» of the intake skip it. await setIntakeState(db, ref.task.id, { stage: "done", original: { title: s.title, description }, attempts: 0, note: "заведена продакт-агентом на приёмке" }); - filed.push(`${ref.key} «${s.title}»`); + created.push({ id: ref.task.id, key: ref.key, title: s.title, severity: s.severity }); + } + return { created, breakage, kept }; +} + +/** Telegram buttons under the message: per item «Делать» / «Не надо» (`p::do|no`), then for all. */ +export function proposalButtons(items: Array<{ id: number; key: string; severity: string }>, locale: Locale): Array> { + const open = items.filter((i) => i.severity !== "breakage"); + if (!open.length) return []; + const rows = open.map((i) => [ + { text: `✅ ${t(locale, "Делать")} ${i.key}`, callback_data: `p:${i.id}:do` }, + { text: `✖️ ${t(locale, "Не надо")} ${i.key}`, callback_data: `p:${i.id}:no` }, + ]); + const ids = open.map((i) => i.id).join(","); + rows.push([{ text: `✅ ${t(locale, "Делать важные")}`, callback_data: `p:${ids}:important` }, { text: `✖️ ${t(locale, "Отклонить всё")}`, callback_data: `p:${ids}:none` }]); + return rows; +} + +const DIGEST_EVERY_MS = 7 * 86_400_000; + +/** + * After the version's finish the improvements were only kept; once a week they go to the owner in + * one message (to «Предложено», with the same buttons). + */ +export async function productDigestTick(db: Db, now: Date, log: (m: string) => void = () => {}): Promise { + const rows = await db.select().from(settings).where(sql`${settings.key} like ${"product.digest:%"}`); + for (const row of rows) { + const projectId = Number(row.key.slice("product.digest:".length)); + const d = await getDigest(db, projectId); + if (!d.items.length || (d.sentAt && now.getTime() - Date.parse(d.sentAt) < DIGEST_EVERY_MS)) continue; + if (await isProjectPaused(db, projectId)) continue; + const [project] = await db.select().from(projects).where(eq(projects.id, projectId)); + if (!project) continue; + await setDigest(db, projectId, { items: [], sentAt: now.toISOString() }); + const filed = await fileStories(db, project, d.items.map((i) => ({ title: i.title, description: i.description, severity: i.severity })), { envLabel: "", url: "", log, ignoreFinish: true }); + if (!filed.created.length) continue; + const chat = await ensureProjectChat(db, project.id); + const found = { n: filed.created.length, important: filed.created.filter((f) => f.severity !== "minor").length }; + const lines = filed.created.map((f) => `• ${f.key} «${f.title}» — ${tr(SEVERITY_LABEL[f.severity])}`).join("\n"); + const said = await sayInDiscussion(db, project, chat.id, `${tr("Раз в неделю: нашёл улучшений: {n} (важных: {k}).", { n: found.n, k: found.important })}\n${lines}`, PRODUCT_AGENT_NAME, { buttons: (locale) => proposalButtons(filed.created, locale) }); + if (said) await setChatOffer(db, said.id, { kind: "proposals", text: "", items: filed.created.map((f) => ({ id: f.id, key: f.key, title: f.title, severity: f.severity })) }); + log(`product digest ${project.key}: ${filed.created.length}`); } - const stillOpen = await openNeeds(db, project.id); - await saveProductReview(db, project.id, { at: new Date().toISOString(), env: rel.env as "staging" | "prod", sha: rel.sha, url, summary: reply.summary, howto: reply.howto, notReal: reply.notReal, filed: filed.map((f) => f.split(" ")[0]!) }); - const chat = await ensureProjectChat(db, project.id); - await sayInDiscussion(db, project, chat.id, productReviewMessage(reply, { env: rel.env === "prod" ? "prod" : "staging", url, openNeeds: stillOpen, filed, webUrl: process.env.PEPPA_WEB_URL ?? "", projectKey: project.key }), PRODUCT_AGENT_NAME); - log(`product review ${project.key}: ${rel.env} ${rel.sha.slice(0, 7)} — needs ${stillOpen.length}, stories ${filed.length}`); } diff --git a/packages/runner/src/proposals.ts b/packages/runner/src/proposals.ts new file mode 100644 index 00000000..a9be583d --- /dev/null +++ b/packages/runner/src/proposals.ts @@ -0,0 +1,21 @@ +// PEP-197: the owner decides on stories the factory suggests: «Делать» / «Не надо», and for the +// whole list «Делать важные» / «Отклонить всё». The same for the web (chat, board) and Telegram. +import { approveProposal, PeppaError, projectForUser, rejectProposal, resolveProposals, type User } from "@peppa/core"; +import { tasks, type Db } from "@peppa/db"; +import { inArray } from "drizzle-orm"; +import { m } from "@peppa/shared/i18n"; + +export type ProposalChoice = "do" | "no" | "important" | "none"; + +export async function decideProposals(db: Db, user: Pick, taskIds: number[], choice: ProposalChoice): Promise { + if (!taskIds.length) throw new PeppaError(m("Эта кнопка уже не работает.")); + const rows = await db.select({ id: tasks.id, projectId: tasks.projectId, proposed: tasks.proposed }).from(tasks).where(inArray(tasks.id, taskIds)); + // Only stories of the owner's own projects (or ones they take part in). + for (const projectId of new Set(rows.map((r) => r.projectId))) await projectForUser(db, user.id, projectId); + const open = rows.filter((r) => r.proposed).map((r) => r.id); + if (!open.length) throw new PeppaError(m("По этим задачам решение уже принято.")); + if (choice === "do") for (const id of open) await approveProposal(db, id, user.login); + else if (choice === "no") for (const id of open) await rejectProposal(db, id, user.login); + else await resolveProposals(db, open, choice, user.login); + return open.length; +} diff --git a/packages/runner/src/task-dedup.ts b/packages/runner/src/task-dedup.ts new file mode 100644 index 00000000..43bccbcd --- /dev/null +++ b/packages/runner/src/task-dedup.ts @@ -0,0 +1,50 @@ +// PEP-197: before an agent files a story — is it a repeat? Exact title first (no model), then a +// short question to the model on the project's subscription. A failing model means «not a repeat». +import { dedupPrompt, DEDUP_MAX_CANDIDATES, DEDUP_WINDOW_DAYS, logEvent, normTitle, parseDedup, type DedupCandidate, type Project, type Task } from "@peppa/core"; +import { tasks, type Db } from "@peppa/db"; +import { formatTaskKey } from "@peppa/shared"; +import { and, desc, eq, gte, isNull, ne, or } from "drizzle-orm"; +import { claudePrint } from "./claude-print.ts"; + +export type DupVerdict = + | { kind: "none" } + | { kind: "open"; task: Task; key: string; reason: string } + | { kind: "done"; task: Task; key: string; reason: string; doneAt: Date }; + +export async function checkDuplicate(db: Db, project: Project, story: { title: string; description: string }, opts: { log?: (m: string) => void; origin?: string } = {}): Promise { + const since = new Date(Date.now() - DEDUP_WINDOW_DAYS * 86_400_000); + const rows = await db + .select() + .from(tasks) + .where(and(eq(tasks.projectId, project.id), isNull(tasks.archivedAt), or(ne(tasks.status, "done"), gte(tasks.updatedAt, since)))) + .orderBy(desc(tasks.id)) + .limit(DEDUP_MAX_CANDIDATES); + const verdictFor = (t: Task, reason: string): DupVerdict => { + const key = formatTaskKey(project.key, t.number); + return t.status === "done" ? { kind: "done", task: t, key, reason, doneAt: t.updatedAt } : { kind: "open", task: t, key, reason }; + }; + const decided = async (v: DupVerdict, how: string) => { + if (v.kind !== "none") await logEvent(db, { projectId: project.id, taskId: v.task.id, type: "task_dedup", payload: { decision: v.kind === "open" ? "remark" : "similar_done", of: v.key, how, reason: v.reason, title: story.title } }); + return v; + }; + const same = rows.find((t) => normTitle(t.title) === normTitle(story.title)); + if (same) return decided(verdictFor(same, "то же название"), "title"); + if (!rows.length) return { kind: "none" }; + + const candidates: DedupCandidate[] = rows.map((t) => ({ key: formatTaskKey(project.key, t.number), title: t.title, state: t.status === "done" ? "done" : "open", doneAt: t.status === "done" ? t.updatedAt.toISOString().slice(0, 10) : undefined })); + const out = await claudePrint(db, project, { + bin: process.env.PEPPA_INTAKE_BIN ?? "claude", + model: process.env.PEPPA_DEDUP_MODEL ?? process.env.PEPPA_INTENT_MODEL ?? "haiku", + timeoutMs: Number(process.env.PEPPA_INTENT_TIMEOUT_MS ?? 30_000), + who: "проверка повторов", + prompt: dedupPrompt(story, candidates), + }); + if (!out.ok) { + opts.log?.(`dedup ${project.key}: ${out.error} — считаю не повтором`); + return { kind: "none" }; + } + const answer = parseDedup(out.text); + const hit = answer?.duplicateOf ? rows.find((t) => formatTaskKey(project.key, t.number).toUpperCase() === answer.duplicateOf) : undefined; + if (!answer || !hit) return { kind: "none" }; + return decided(verdictFor(hit, answer.reason), "model"); +} diff --git a/packages/runner/src/task-tidy.ts b/packages/runner/src/task-tidy.ts new file mode 100644 index 00000000..bbce9077 --- /dev/null +++ b/packages/runner/src/task-tidy.ts @@ -0,0 +1,67 @@ +// PEP-197: one-off tidy of a live system. Per project: stories of agents that are not started yet +// move to «Предложено»; started ones are left to finish; repeats among the open ones are marked. +// The owner gets one message. Nothing is deleted or archived. +import { ensureProjectChat, logEvent, normTitle, listProjects, setSetting, getSetting, type Project } from "@peppa/core"; +import { sessions, tasks, type Db } from "@peppa/db"; +import { m as tr } from "@peppa/shared/i18n"; +import { formatTaskKey } from "@peppa/shared"; +import { and, eq, isNull, ne } from "drizzle-orm"; +import { PRODUCT_AGENT_NAME } from "@peppa/core"; +import { sayInDiscussion } from "./analyst-chat.ts"; + +export interface TidyRow { + key: string; + moved: number; + started: number; + duplicates: number; +} + +export async function tidyAgentTasks(db: Db, opts: { dryRun?: boolean; only?: string; log?: (m: string) => void } = {}): Promise { + const out: TidyRow[] = []; + for (const project of await listProjects(db)) { + if (opts.only && project.key !== opts.only) continue; + const row = await tidyProject(db, project, !!opts.dryRun); + if (row) out.push(row); + opts.log?.(`${project.key}: ${row ? `${row.moved} → «Предложено», ${row.started} начато, дублей ${row.duplicates}` : "нечего убирать"}`); + } + return out; +} + +async function tidyProject(db: Db, project: Project, dryRun: boolean): Promise { + const open = await db + .select() + .from(tasks) + .where(and(eq(tasks.projectId, project.id), ne(tasks.origin, "human"), ne(tasks.status, "done"), isNull(tasks.archivedAt))); + if (!open.length) return null; + let moved = 0; + let started = 0; + let duplicates = 0; + const seen = new Map(); + const doneKey = `task.tidy:${project.id}`; + for (const t of open.sort((a, b) => a.number - b.number)) { + const key = formatTaskKey(project.key, t.number); + const norm = normTitle(t.title); + const first = seen.get(norm); + if (first) { + duplicates++; + if (!dryRun) await logEvent(db, { projectId: project.id, taskId: t.id, type: "task_dedup", payload: { decision: "duplicate", of: first, how: "tidy", title: t.title } }); + } else seen.set(norm, key); + const [s] = await db.select({ id: sessions.id }).from(sessions).where(eq(sessions.taskId, t.id)).limit(1); + if (t.status !== "backlog" || s || t.proposed) { + if (t.status !== "backlog" || s) started++; + continue; + } + moved++; + if (!dryRun) { + await db.update(tasks).set({ proposed: true }).where(eq(tasks.id, t.id)); + await logEvent(db, { projectId: project.id, taskId: t.id, type: "task_tidied", payload: { to: "proposed" } }); + } + } + if (!dryRun && moved > 0 && !(await getSetting(db, doneKey))) { + await setSetting(db, doneKey, { at: new Date().toISOString(), moved }); + const chat = await ensureProjectChat(db, project.id); + // glossary-user: сообщение владельцу проекта + await sayInDiscussion(db, project, chat.id, tr("Навели порядок: задач, которые фабрика завела сама, и которые ждут вашего решения: {n}. Они в «Предложено» на доске. Ничего не удалено.", { n: moved }), PRODUCT_AGENT_NAME); + } + return { key: project.key, moved, started, duplicates }; +} diff --git a/packages/shared/src/i18n/en/index.ts b/packages/shared/src/i18n/en/index.ts index 98edbbc8..1a0da0a2 100644 --- a/packages/shared/src/i18n/en/index.ts +++ b/packages/shared/src/i18n/en/index.ts @@ -22,5 +22,6 @@ import { untrusted } from "./untrusted.ts"; import { mcpGuide } from "./mcp-guide.ts"; import { subscriptionRequest } from "./subscription-request.ts"; import { domainGuard } from "./domain-guard.ts"; +import { proposals } from "./proposals.ts"; -export const en: Dict = { ...common, ...story, ...project, ...admin, ...settings, ...help, ...runner, ...bot, ...merge, ...merge_a, ...merge_b, ...merge_c, ...merge_d, ...feedback, ...attachments, ...capacity, ...untrusted, ...mcpGuide, ...subscriptionRequest, ...domainGuard, ...intent }; +export const en: Dict = { ...common, ...story, ...project, ...admin, ...settings, ...help, ...runner, ...bot, ...merge, ...merge_a, ...merge_b, ...merge_c, ...merge_d, ...feedback, ...attachments, ...capacity, ...untrusted, ...mcpGuide, ...subscriptionRequest, ...domainGuard, ...intent, ...proposals }; diff --git a/packages/shared/src/i18n/en/proposals.ts b/packages/shared/src/i18n/en/proposals.ts new file mode 100644 index 00000000..2c3f62ee --- /dev/null +++ b/packages/shared/src/i18n/en/proposals.ts @@ -0,0 +1,43 @@ +// PEP-197: «Предложено», limits for factory-made tasks, who is accepted automatically. +export const proposals: Record = { + "Эта кнопка уже не работает.": "This button no longer works.", + "Задачи, которые фабрика завела сама": "Tasks the factory made on its own", + "Люди": "People", + "Фабрика": "Factory", + "Ждут решения": "Waiting for a decision", + "За неделю, $": "Per week, $", + "фабрика завела больше": "the factory made more", + "Принимать сами": "Accept on its own", + "Только мои задачи": "Only my tasks", + "Мои задачи и поломки": "My tasks and breakages", + "Всё, что завела фабрика": "Everything the factory made", + "Поломка": "Breakage", + "Важно": "Important", + "Мелочь": "Minor", + "Предложено": "Suggested", + "Это придумала сама фабрика. Пока вы не нажмёте «Делать», агенты за эти задачи не возьмутся.": "The factory came up with these itself. Agents will not start them until you press «Do it».", + "Делать важные": "Do the important ones", + "Отклонить всё": "Decline all", + "Делать": "Do it", + "Не надо": "Not needed", + "Отклонено": "Declined", + "Уже в бэклоге": "Already in the backlog", + "Взято в бэклог": "Added to the backlog", + "Принято, задач: {n}": "Accepted, tasks: {n}", + "Отклонено: {n}": "Declined: {n}", + "Принимать сами: {v}": "Accept on its own: {v}", + "только мои задачи": "only my tasks", + "всё": "everything", + "мои и поломки": "mine and breakages", + "Проверил продукт. Нашёл улучшений: {n} (важных: {k}).": "I checked the product. Improvements found: {n} (important: {k}).", + "Приёмка снова заметила то же самое: «{title}».\n{description}": "Acceptance noticed the same thing again: «{title}».\n{description}", + "Похоже на {key}, сделано {date}.": "Similar to {key}, done {date}.", + "агент приёмки": "acceptance agent", + "разбор ошибок": "error triage", + "{name}: целое от 0 до {max}": "{name}: a whole number from 0 to {max}", + "Версия готова. Продукт: {url}": "The version is ready. Product: {url}", + "Что умеет: {summary}": "What it can do: {summary}", + "Раз в неделю: нашёл улучшений: {n} (важных: {k}).": "Once a week: improvements found: {n} (important: {k}).", + "По этим задачам решение уже принято.": "A decision on these tasks has already been made.", + "Навели порядок: задач, которые фабрика завела сама, и которые ждут вашего решения: {n}. Они в «Предложено» на доске. Ничего не удалено.": "We tidied up: tasks the factory made itself that wait for your decision: {n}. They are in «Suggested» on the board. Nothing was deleted.", +}; diff --git a/packages/shared/src/i18n/kk/index.ts b/packages/shared/src/i18n/kk/index.ts index 90102005..8ec7fc68 100644 --- a/packages/shared/src/i18n/kk/index.ts +++ b/packages/shared/src/i18n/kk/index.ts @@ -22,5 +22,6 @@ import { untrusted } from "./untrusted.ts"; import { mcpGuide } from "./mcp-guide.ts"; import { subscriptionRequest } from "./subscription-request.ts"; import { domainGuard } from "./domain-guard.ts"; +import { proposals } from "./proposals.ts"; -export const kk: Dict = { ...admin, ...bot, ...common, ...help, ...mergeA, ...mergeB, ...mergeC, ...mergeD, ...merge, ...project, ...runner, ...settings, ...story, ...feedback, ...attachments, ...capacity, ...untrusted, ...mcpGuide, ...subscriptionRequest, ...domainGuard, ...intent }; +export const kk: Dict = { ...admin, ...bot, ...common, ...help, ...mergeA, ...mergeB, ...mergeC, ...mergeD, ...merge, ...project, ...runner, ...settings, ...story, ...feedback, ...attachments, ...capacity, ...untrusted, ...mcpGuide, ...subscriptionRequest, ...domainGuard, ...intent, ...proposals }; diff --git a/packages/shared/src/i18n/kk/proposals.ts b/packages/shared/src/i18n/kk/proposals.ts new file mode 100644 index 00000000..d526e9a9 --- /dev/null +++ b/packages/shared/src/i18n/kk/proposals.ts @@ -0,0 +1,43 @@ +// PEP-197: «Предложено», limits for factory-made tasks, who is accepted automatically. +export const proposals: Record = { + "Эта кнопка уже не работает.": "Бұл түйме енді жұмыс істемейді.", + "Задачи, которые фабрика завела сама": "Фабрика өзі қосқан тапсырмалар", + "Люди": "Адамдар", + "Фабрика": "Фабрика", + "Ждут решения": "Шешімді күтуде", + "За неделю, $": "Аптасына, $", + "фабрика завела больше": "фабрика көбірек қосты", + "Принимать сами": "Өзі қабылдау", + "Только мои задачи": "Тек менің тапсырмаларым", + "Мои задачи и поломки": "Менің тапсырмаларым және ақаулар", + "Всё, что завела фабрика": "Фабрика қосқанның бәрі", + "Поломка": "Ақау", + "Важно": "Маңызды", + "Мелочь": "Ұсақ-түйек", + "Предложено": "Ұсынылған", + "Это придумала сама фабрика. Пока вы не нажмёте «Делать», агенты за эти задачи не возьмутся.": "Мұны фабрика өзі ойлап тапты. «Орындау» түймесін баспайынша, агенттер бұл тапсырмаларға кіріспейді.", + "Делать важные": "Маңыздыларын орындау", + "Отклонить всё": "Бәрінен бас тарту", + "Делать": "Орындау", + "Не надо": "Қажет емес", + "Отклонено": "Бас тартылды", + "Уже в бэклоге": "Бэклогта бар", + "Взято в бэклог": "Бэклогқа алынды", + "Принято, задач: {n}": "Қабылданды, тапсырмалар: {n}", + "Отклонено: {n}": "Бас тартылды: {n}", + "Принимать сами: {v}": "Өзі қабылдау: {v}", + "только мои задачи": "тек менің тапсырмаларым", + "всё": "бәрі", + "мои и поломки": "менікі және ақаулар", + "Проверил продукт. Нашёл улучшений: {n} (важных: {k}).": "Өнімді тексердім. Табылған жақсартулар: {n} (маңыздысы: {k}).", + "Приёмка снова заметила то же самое: «{title}».\n{description}": "Қабылдау тағы да сол нәрсені байқады: «{title}».\n{description}", + "Похоже на {key}, сделано {date}.": "{key} тапсырмасына ұқсас, {date} орындалған.", + "агент приёмки": "қабылдау агенті", + "разбор ошибок": "қателерді талдау", + "{name}: целое от 0 до {max}": "{name}: 0-ден {max}-ге дейінгі бүтін сан", + "Версия готова. Продукт: {url}": "Нұсқа дайын. Өнім: {url}", + "Что умеет: {summary}": "Не істей алады: {summary}", + "Раз в неделю: нашёл улучшений: {n} (важных: {k}).": "Аптасына бір рет: табылған жақсартулар: {n} (маңыздысы: {k}).", + "По этим задачам решение уже принято.": "Бұл тапсырмалар бойынша шешім қабылданған.", + "Навели порядок: задач, которые фабрика завела сама, и которые ждут вашего решения: {n}. Они в «Предложено» на доске. Ничего не удалено.": "Тәртіпке келтірдік: фабрика өзі қосқан және сіздің шешіміңізді күтетін тапсырмалар: {n}. Олар тақтадағы «Ұсынылған» бөлімінде. Ештеңе жойылған жоқ.", +}; diff --git a/packages/testkit/src/mock-intake.ts b/packages/testkit/src/mock-intake.ts index dd63e814..21ef0098 100644 --- a/packages/testkit/src/mock-intake.ts +++ b/packages/testkit/src/mock-intake.ts @@ -10,6 +10,8 @@ import { appendFileSync, existsSync, readdirSync, readFileSync } from "node:fs"; interface Scenario { /** PEP-112: the product agent on acceptance: {summary, howto[], not_real[], needs[], stories[]}. */ accept?: object; + /** PEP-197: the repeat check: {duplicate_of: KEY|null, reason}; default — the candidate sharing half the words. */ + dedup?: object; /** PEP-143: the feedback agent: {summary, kind, cause, confident, options[], recommended, duplicate_of}. */ feedback?: object; /** PEP-153: the message classifier: {kind: question|task|unsure, answer}. */ @@ -29,10 +31,10 @@ interface Scenario { const file = process.env.MOCK_INTAKE_SCENARIO; const sc: Scenario = file && existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {}; const prompt = readFileSync(0, "utf8"); -const role = prompt.startsWith("Ты — диспетчер сообщений") ? "intent" : prompt.startsWith("Ты — агент обратной связи") ? "feedback" : prompt.startsWith("Ты — продакт-менеджер софтвер-фабрики на приёмке") ? "accept" : prompt.startsWith("Ты — продакт-менеджер") ? "product" : prompt.startsWith("Ты — аналитик проекта в чате") ? "chat" : prompt.includes("## Новые комментарии продакта") ? "refine" : "analyst"; +const role = prompt.startsWith("Ты — проверка на повтор") ? "dedup" : prompt.startsWith("Ты — диспетчер сообщений") ? "intent" : prompt.startsWith("Ты — агент обратной связи") ? "feedback" : prompt.startsWith("Ты — продакт-менеджер софтвер-фабрики на приёмке") ? "accept" : prompt.startsWith("Ты — продакт-менеджер") ? "product" : prompt.startsWith("Ты — аналитик проекта в чате") ? "chat" : prompt.includes("## Новые комментарии продакта") ? "refine" : "analyst"; const answered = /Ответ продакта:\n/.test(prompt); const title = /^Название: (.*)$/m.exec(prompt)?.[1] ?? ""; -if (file) appendFileSync(`${file}.log.jsonl`, JSON.stringify({ role, title, answered, answer: /Ответ продакта:\n([\s\S]*?)\n\n/.exec(prompt)?.[1] ?? null, hasContext: prompt.includes("## Стандарты проекта"), prompt, argv: process.argv.slice(2), files: role === "accept" || role === "feedback" || role === "chat" || role === "refine" ? readdirSync(process.cwd()) : undefined, token: process.env.CLAUDE_CODE_OAUTH_TOKEN ? "set" : null }) + "\n"); +if (file) appendFileSync(`${file}.log.jsonl`, JSON.stringify({ role, title, answered, answer: /Ответ продакта:\n([\s\S]*?)\n\n/.exec(prompt)?.[1] ?? null, hasContext: prompt.includes("## Стандарты проекта"), prompt, argv: process.argv.slice(2), files: role === "accept" || role === "dedup" || role === "feedback" || role === "chat" || role === "refine" ? readdirSync(process.cwd()) : undefined, token: process.env.CLAUDE_CODE_OAUTH_TOKEN ? "set" : null }) + "\n"); if (!process.argv.includes("-p")) { console.error("mock-intake: expected -p (non-interactive print mode)"); process.exit(2); @@ -97,6 +99,11 @@ const feedback = sc.feedback ?? { recommended: 2, duplicate_of: null, }; +// PEP-197, repeat check: without a scenario a candidate sharing at least half of the words is a repeat. +const words = (x: string) => new Set(x.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter((w) => w.length > 2)); +const newWords = words(/Название: (.*)/.exec(prompt)?.[1] ?? ""); +const similar = [...prompt.matchAll(/^- (\S+) «(.*)» \[/gm)].find((c) => { const w = words(c[2]!); const common = [...newWords].filter((x) => w.has(x)).length; return newWords.size > 0 && common / Math.min(newWords.size, w.size || 1) >= 0.5; }); +const dedup = sc.dedup ?? { duplicate_of: similar?.[1] ?? null, reason: similar ? "та же тема" : "" }; if (sc.slowMs) await new Promise((r) => setTimeout(r, sc.slowMs)); -const result = sc.garbage ? "Не могу помочь с этим." : JSON.stringify(role === "intent" ? intent : role === "feedback" ? feedback : role === "accept" ? accept : role === "product" ? product : role === "chat" ? chat : role === "refine" ? refine : analyst); +const result = sc.garbage ? "Не могу помочь с этим." : JSON.stringify(role === "dedup" ? dedup : role === "intent" ? intent : role === "feedback" ? feedback : role === "accept" ? accept : role === "product" ? product : role === "chat" ? chat : role === "refine" ? refine : analyst); process.stdout.write(JSON.stringify({ type: "result", subtype: "success", is_error: false, num_turns: 1, result, session_id: "mock-intake" }) + "\n"); diff --git a/packages/testkit/test/agent-task-tidy.test.ts b/packages/testkit/test/agent-task-tidy.test.ts new file mode 100644 index 00000000..9e8ff67e --- /dev/null +++ b/packages/testkit/test/agent-task-tidy.test.ts @@ -0,0 +1,48 @@ +// PEP-197: the one-off tidy and the summary for the superadmin. +import assert from "node:assert/strict"; +import { after, describe, test } from "node:test"; +import { core, db, project, runner, teardown } from "./helpers.ts"; +import { tasks } from "@peppa/db"; +import { eq } from "drizzle-orm"; + +after(teardown); + +describe("PEP-197: уборка и сводка", () => { + test("not started stories of agents go to «Предложено»; started ones stay; repeats are marked; one message; nothing deleted", async () => { + const tp = await project({ turns: [] }); + const p = await core.getProject(db, tp.key); + const idle = await core.createTask(db, { projectId: p.id, title: "Подписать кнопки", origin: "acceptance", severity: "important" }); + const repeat = await core.createTask(db, { projectId: p.id, title: "Подписать кнопки!", origin: "acceptance", severity: "important" }); + const going = await core.createTask(db, { projectId: p.id, title: "Другая тема", origin: "acceptance" }); + await core.updateTask(db, going, { status: "in_progress" }); + const mine = await core.createTask(db, { projectId: p.id, title: "Просьба человека" }); + + const dry = await runner.tidyAgentTasks(db, { dryRun: true, only: p.key }); + assert.deepEqual(dry.map((r) => [r.moved, r.started, r.duplicates]), [[2, 1, 1]]); + assert.equal((await core.proposedTasks(db, p.id)).length, 0, "a dry run changes nothing"); + + await runner.tidyAgentTasks(db, { only: p.key }); + assert.deepEqual((await core.proposedTasks(db, p.id)).map((t) => t.id).sort(), [idle.task.id, repeat.task.id].sort()); + const [still] = await db.select().from(tasks).where(eq(tasks.id, going.task.id)); + assert.equal(still!.proposed, false); + assert.equal(still!.status, "in_progress", "a started story is finished as it is"); + assert.equal((await core.resolveTask(db, mine.key)).task.proposed, false, "a story of a person is not touched"); + const talk = (await core.discussionMessages(db, (await core.ensureProjectChat(db, p.id)).id)).map((m) => m.text); + assert.equal(talk.filter((t) => /Навели порядок/.test(t)).length, 1); + + await runner.tidyAgentTasks(db, { only: p.key }); + const again = (await core.discussionMessages(db, (await core.ensureProjectChat(db, p.id)).id)).filter((m) => /Навели порядок/.test(m.text)); + assert.equal(again.length, 1, "the owner is told once"); + assert.equal((await core.listTasks(db, { projectId: p.id, includeArchived: true })).length, 5, "nothing is deleted or archived"); + }); + + test("summary: people and agents per project, projects where agents made more", async () => { + const tp = await project({ turns: [] }); + const p = await core.getProject(db, tp.key); + await core.createTask(db, { projectId: p.id, title: "Первая от агента", origin: "acceptance", proposed: true }); + await core.createTask(db, { projectId: p.id, title: "Вторая от агента", origin: "incident" }); + const row = (await core.agentTaskSummary(db)).find((r) => r.key === p.key)!; + assert.deepEqual([row.human, row.agents, row.proposed, row.agentsMoreThanHuman], [1, 2, 1, true]); + assert.match(core.agentTaskTable([row]), new RegExp(`${p.key} \\| 1 \\| 2 \\| 1 \\|`)); + }); +}); diff --git a/packages/testkit/test/autonomy-levels.test.ts b/packages/testkit/test/autonomy-levels.test.ts index 77dbe1ae..267dc0d4 100644 --- a/packages/testkit/test/autonomy-levels.test.ts +++ b/packages/testkit/test/autonomy-levels.test.ts @@ -8,7 +8,7 @@ import { join } from "node:path"; import { after, before, describe, test } from "node:test"; import { core, db, project, runner, superadmin, teardown, waitFor, type TestProject } from "./helpers.ts"; import { MockGitea } from "../src/mock-gitea.ts"; -import { projects } from "@peppa/db"; +import { projects, tasks } from "@peppa/db"; import { eq } from "drizzle-orm"; process.env.PEPPA_SECRET = "mock-secret-for-tests"; @@ -257,6 +257,45 @@ async function prTask(level: Parameters[2], turns: Para const pull = (t: PrTask) => gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo).pulls[t.pr.number - 1]!; +describe("PEP-197: stories of agents in work", () => { + test("three stories of agents in work: the fourth does not start; a story of a person does", async () => { + const tp = await project({ turns: [] }); + const p = await projectOf(tp); + await core.setAutonomy(db, p.id, { level: "auto", wipLimit: 5, ...NO_QUIET }); + const make = async (title: string, status: "backlog" | "in_progress") => { + const ref = await core.createTask(db, { projectId: p.id, title, origin: "acceptance", severity: "breakage" }); + if (status === "in_progress") await core.updateTask(db, ref, { status }); + return ref; + }; + await make("поломка 1", "in_progress"); + await make("поломка 2", "in_progress"); + await make("поломка 3", "in_progress"); + const fourth = await make("поломка 4", "backlog"); + assert.equal(await core.agentTasksInWork(db, p.id), 3); + await autonomy(); + assert.equal((await taskOf(fourth.key)).status, "backlog", "the fourth story of an agent waits"); + assert.equal((await taskOf(tp.taskKey)).status, "in_progress", "a story of a person is not held by the limit"); + + await core.setAgentLimits(db, p.id, { inWork: 4 }); + await autonomy(); + assert.equal((await taskOf(fourth.key)).status, "in_progress", "the superadmin raised the limit"); + }); + + test("«Предложено»: the dispatcher takes nothing from there until «Делать»", async () => { + const tp = await project({ turns: [] }); + const p = await projectOf(tp); + await core.updateTask(db, await core.resolveTask(db, tp.taskKey), { status: "done" }); + await core.setAutonomy(db, p.id, { level: "auto", ...NO_QUIET }); + const idea = await core.createTask(db, { projectId: p.id, title: "идея агента", origin: "acceptance", severity: "important", proposed: true }); + assert.deepEqual((await runner.readyBacklog(db, p.id)).map((t) => t.id), []); + await autonomy(); + assert.equal((await taskOf(idea.key)).status, "backlog"); + assert.equal((await activeOf(p.id)).length, 0); + await core.approveProposal(db, idea.task.id); + assert.deepEqual((await runner.readyBacklog(db, p.id)).map((t) => t.id), [idea.task.id]); + }); +}); + describe("auto-merge and closing", () => { test("merge=auto, close=after_merge: a green PR is merged and the story closed", async () => { const t = await prTask({ merge: "auto", close: "after_merge" }); @@ -279,6 +318,35 @@ describe("auto-merge and closing", () => { assert.equal((await taskOf(t.tp.taskKey)).status, "done"); }); + test("PEP-197: a story of an agent (after «Делать») is not merged by default; a breakage and «всё» are", async () => { + const mark = (t: PrTask, set: { origin: string; severity: string | null }) => Promise.resolve().then(async () => { + const ref = await core.resolveTask(db, t.tp.taskKey); + await db.update(tasks).set(set).where(eq(tasks.id, ref.task.id)); + }); + const important = await prTask({ merge: "auto", close: "after_merge" }); + await mark(important, { origin: "acceptance", severity: "important" }); + await autonomy(); + assert.equal(pull(important).merged, false, "default «мои и поломки»: the owner accepts what the factory thought of"); + assert.equal((await taskOf(important.tp.taskKey)).status, "review"); + const [q] = await openQuestions(important.proj.id); + assert.equal(q, undefined, "nothing is asked of the owner before the agent says it is ready"); + + const breakage = await prTask({ merge: "auto", close: "after_merge" }); + await mark(breakage, { origin: "acceptance", severity: "breakage" }); + await autonomy(); + assert.equal(pull(breakage).merged, true, "a breakage is accepted automatically by default"); + + const mineOnly = await prTask({ merge: "auto", close: "after_merge", acceptOwn: "mine" }); + await mark(mineOnly, { origin: "acceptance", severity: "breakage" }); + await autonomy(); + assert.equal(pull(mineOnly).merged, false, "«только мои задачи»: not even a breakage"); + + const all = await prTask({ merge: "auto", close: "after_merge", acceptOwn: "all" }); + await mark(all, { origin: "acceptance", severity: "minor" }); + await autonomy(); + assert.equal(pull(all).merged, true, "«всё»"); + }); + test("pending checks: nothing merged yet", async () => { const t = await prTask({ merge: "auto", close: "after_merge" }); t.push(); // new head without statuses diff --git a/packages/testkit/test/product-acceptance.test.ts b/packages/testkit/test/product-acceptance.test.ts index 88854a66..722e5bad 100644 --- a/packages/testkit/test/product-acceptance.test.ts +++ b/packages/testkit/test/product-acceptance.test.ts @@ -263,12 +263,14 @@ describe("PEP-112: продакт-агент принимает выкаченн assert.match(talk[0]!.text, /Как пользоваться:\n1\. Откройте адрес продукта/); assert.match(talk[0]!.text, /Пока не настоящее:\n• Демо-режим: показаны вымышленные примеры/); assert.match(talk[0]!.text, /Чтобы заработало по-настоящему, нужно от вас:\n• Ключ сервиса — без него показаны примеры/); - assert.match(talk[0]!.text, /Завёл доработки в бэклог:\n• MAC\w-2 «Убрать служебное поле «Токен запуска» с экрана»/); + assert.match(talk[0]!.text, /Нашёл улучшений: 1 \(важных: 1\)\.\n• MAC\w-2 «Убрать служебное поле «Токен запуска» с экрана» — Важно/); assert.deepEqual((await core.openNeeds(db, p.id)).map((x) => [x.title, x.source]), [["Ключ сервиса", "product"]]); const stories = await core.listTasks(db, { projectId: p.id }); const filed = stories.find((t) => /Токен запуска/.test(t.title))!; assert.equal(filed.status, "backlog"); + assert.equal(filed.proposed, true, "PEP-197: a story of the acceptance agent waits in «Предложено»"); + assert.equal(filed.origin, "acceptance"); assert.match(filed.description ?? "", /Заведено продакт-агентом на приёмке/); assert.equal((await core.getIntakeState(db, filed.id))?.stage, "done", "already formulated: the intake roles skip it"); const review = (await core.lastProductReview(db, p.id))!; @@ -381,10 +383,163 @@ describe("PEP-112: страница глазами пользователя", () }); test("parseProductReview: missing parts are empty, too many stories are cut, no summary — no review", () => { - const r = core.parseProductReview('Вот: {"summary":"Работает","stories":[{"title":"А1"},{"title":"Б22"},{"title":"В33"},{"title":"Г44"},{"title":"Д55"}]}')!; + const r = core.parseProductReview('Вот: {"summary":"Работает","stories":[{"title":"А111"},{"title":"Б222"},{"title":"В333"},{"title":"Г444"},{"title":"Д555"},{"title":"Е666"},{"title":"Ж777"}]}')!; assert.deepEqual([r.howto, r.notReal, r.needs], [[], [], []]); assert.equal(r.stories.length, core.PRODUCT_REVIEW_MAX_STORIES); assert.equal(core.parseProductReview('{"howto":["x"]}'), null); assert.equal(core.parseProductReview("Не могу помочь"), null); }); }); + +// ── PEP-197: the factory does not set tasks for itself in a circle ─────────────────────────── + +const found = (...stories: Array<{ title: string; description?: string; severity?: string }>) => + setScenario({ accept: { summary: "Продукт открывается.", howto: [], not_real: [], needs: [], stories: stories.map((x) => ({ description: "Что должен увидеть пользователь.", ...x })) } }); +let sha = 0; +const pass = async (p: { id: number; key: string }) => { + await healthy(p, "staging", `sha${++sha}00000`); + await tick(); +}; +/** The owner has asked for something that is still open: the version is not finished. */ +const asked = (projectId: number) => core.createTask(db, { projectId, title: "Просьба владельца" }); +const byTitle = async (projectId: number, title: string) => (await core.listTasks(db, { projectId, includeArchived: true })).find((t) => t.title === title); + +describe("PEP-197: приёмка предлагает, а не запускает", () => { + test("Scenario: Агент приёмки находит улучшение — задача в «Предложено», диспетчер её не берёт; поломка — в бэклоге с пометкой", async () => { + page = REAL_PAGE; + const p = await proj(); + await asked(p.id); + found({ title: "Подписать кнопку «Подобрать»", severity: "important" }, { title: "Страница не открывается без токена", severity: "breakage" }); + await pass(p); + const idea = (await byTitle(p.id, "Подписать кнопку «Подобрать»"))!; + assert.deepEqual([idea.origin, idea.proposed, idea.severity, idea.status], ["acceptance", true, "important", "backlog"]); + const broken = (await byTitle(p.id, "Страница не открывается без токена"))!; + assert.deepEqual([broken.origin, broken.proposed, broken.severity, broken.status], ["acceptance", false, "breakage", "backlog"], "a breakage goes to the backlog at once, marked"); + assert.deepEqual((await runner.readyBacklog(db, p.id)).map((t) => t.id), [broken.id], "the dispatcher sees the breakage only"); + }); + + test("Scenario: Повтор открытой задачи не создаётся — к ней дописано замечание; похожая сделанная — в «Предложено» с пометкой", async () => { + page = REAL_PAGE; + const p = await proj(); + await asked(p.id); + const open = await core.createTask(db, { projectId: p.id, title: "Подписать кнопки на главном экране" }); + const done = await core.createTask(db, { projectId: p.id, title: "Добавить кнопку назад на рецепт" }); + await core.updateTask(db, done, { status: "done" }); + found({ title: "Подписать кнопки на экране", severity: "important" }, { title: "Кнопка назад на рецепт", severity: "minor" }); + const before = (await core.listTasks(db, { projectId: p.id })).length; + await pass(p); + assert.equal(await byTitle(p.id, "Подписать кнопки на экране"), undefined, "a repeat of an open story is not created"); + assert.match((await core.storyComments(db, open.task.id)).map((c) => c.text).join("\n"), /Приёмка снова заметила то же самое: «Подписать кнопки на экране»/); + const similar = (await byTitle(p.id, "Кнопка назад на рецепт"))!; + assert.equal(similar.proposed, true); + assert.match(similar.description ?? "", new RegExp(`Похоже на ${done.key}, сделано \\d{4}-\\d{2}-\\d{2}`)); + assert.equal((await core.listTasks(db, { projectId: p.id })).length, before + 1); + const log = await db.select().from((await import("@peppa/db")).events).where((await import("drizzle-orm")).eq((await import("@peppa/db")).events.type, "task_dedup")); + assert.ok(log.some((e) => (e.payload as { decision?: string }).decision === "remark" && e.projectId === p.id), "the decision is in the journal"); + assert.ok(log.some((e) => (e.payload as { decision?: string }).decision === "similar_done" && e.projectId === p.id)); + }); + + test("Scenario: После прохода — одно сообщение; «Делать» и «Не надо» работают; отклонённое больше не предлагается", async () => { + page = REAL_PAGE; + const p = await proj(); + await asked(p.id); + found({ title: "Убрать слово «ID» с экрана", severity: "important" }, { title: "Выровнять отступы в шапке", severity: "minor" }, { title: "Починить вход", severity: "breakage" }); + await pass(p); + const talk = await chatOf(p.id); + assert.equal(talk.length, 1, "one message instead of a stream"); + assert.match(talk[0]!.text, /Нашёл улучшений: 3 \(важных: 2\)\./); + assert.match(talk[0]!.text, /«Починить вход» — Поломка/); + const msg = (await core.discussionMessages(db, (await core.ensureProjectChat(db, p.id)).id))[0]!; + const offer = (await core.chatOffers(db, [msg.id])).get(msg.id)!; + assert.equal(offer.kind, "proposals"); + assert.deepEqual(offer.items!.map((i) => [i.title, i.open]), [["Починить вход", false], ["Убрать слово «ID» с экрана", true], ["Выровнять отступы в шапке", true]]); + + const idea = (await byTitle(p.id, "Убрать слово «ID» с экрана"))!; + const minor = (await byTitle(p.id, "Выровнять отступы в шапке"))!; + await runner.decideProposals(db, pm, [idea.id], "do"); + assert.equal((await byTitle(p.id, idea.title))!.proposed, false, "«Делать» moves it to the backlog"); + await runner.decideProposals(db, pm, [minor.id], "no"); + const rejected = (await byTitle(p.id, minor.title))!; + assert.ok(rejected.archivedAt, "«Не надо» archives it"); + await assert.rejects(runner.decideProposals(db, pm, [minor.id], "do"), /уже принято/); + const after = (await core.chatOffers(db, [msg.id])).get(msg.id)!; + assert.deepEqual(after.items!.map((i) => i.decision), ["approved", "approved", "rejected"]); + + found({ title: "Выровнять отступы в шапке", severity: "minor" }); + const count = (await core.listTasks(db, { projectId: p.id, includeArchived: true })).length; + await pass(p); + assert.equal((await core.listTasks(db, { projectId: p.id, includeArchived: true })).length, count, "declined — not suggested again"); + }); + + test("«Делать важные» и «Отклонить всё»; предел предложений за проход", async () => { + page = REAL_PAGE; + const p = await proj(); + await asked(p.id); + await core.setAgentLimits(db, p.id, { perPass: 2 }); + found({ title: "Первое замечание по экрану", severity: "minor" }, { title: "Второе замечание по входу", severity: "important" }, { title: "Третье замечание по оплате", severity: "important" }); + await pass(p); + const made = (await core.listTasks(db, { projectId: p.id })).filter((t) => t.origin === "acceptance"); + assert.equal(made.length, 2, "not more than the limit per pass (the most important first)"); + assert.deepEqual(made.map((t) => t.severity).sort(), ["important", "important"]); + await core.setAgentLimits(db, p.id, "reset"); + assert.equal((await core.getAgentLimits(db, p.id)).perPass, 5); + await runner.decideProposals(db, pm, made.map((t) => t.id), "none"); + assert.equal((await core.proposedTasks(db, p.id)).length, 0); + }); +}); + +describe("PEP-197: версия с финишем", () => { + test("Scenario: Задачи человека приняты, поломок нет — «Версия готова»; дальше только поломки, улучшения копятся на неделю", async () => { + page = REAL_PAGE; + const p = await proj(); + const mine = await core.createTask(db, { projectId: p.id, title: "Подбор стажировок" }); + found(); + await pass(p); + assert.ok(!(await chatOf(p.id)).some((m) => /Версия готова/.test(m.text)), "a story of a person is still open"); + assert.equal((await core.getVersion(db, p.id))?.doneAt, null); + + await core.updateTask(db, mine, { status: "done" }); + found({ title: "Шапка плохо выглядит на телефоне", severity: "important" }); + await pass(p); + const talk = await chatOf(p.id); + assert.ok(talk.some((m) => /Версия готова\. Продукт: https:\/\/staging\.mock\.test/.test(m.text) && /Что умеет: Продукт открывается\./.test(m.text)), "«Версия готова» with the link and what it can do"); + assert.equal((await core.projectProduct(db, p.id)).versionDone, true, "the card «Ваш продукт» says «Готово»"); + assert.equal((await byTitle(p.id, "Шапка плохо выглядит на телефоне"))!.title.length > 0, true); + }); + + test("после финиша агент приёмки заводит только поломки; улучшения — одним сообщением раз в неделю", async () => { + page = REAL_PAGE; + const p = await proj(); + found(); + await pass(p); // nothing open from a person: the version is finished at once + assert.ok((await core.getVersion(db, p.id))?.doneAt); + found({ title: "Подсказка под полем поиска", severity: "important" }, { title: "Сайт упал после входа", severity: "breakage" }); + await pass(p); + assert.equal(await byTitle(p.id, "Подсказка под полем поиска"), undefined, "an improvement is only kept"); + assert.equal((await byTitle(p.id, "Сайт упал после входа"))!.severity, "breakage"); + assert.equal((await core.getDigest(db, p.id)).items.length, 1); + + const week = new Date(Date.now() + 8 * 86_400_000); + await runner.productDigestTick(db, new Date()); + assert.equal(await byTitle(p.id, "Подсказка под полем поиска"), undefined, "not before the week is out"); + await runner.productDigestTick(db, week); + const idea = (await byTitle(p.id, "Подсказка под полем поиска"))!; + assert.equal(idea.proposed, true); + assert.ok((await chatOf(p.id)).some((m) => /Раз в неделю: нашёл улучшений: 1/.test(m.text))); + await runner.productDigestTick(db, week); + assert.equal((await core.listTasks(db, { projectId: p.id })).filter((t) => t.title === idea.title).length, 1); + + // A new story of a person starts the next version. + await core.createTask(db, { projectId: p.id, title: "Ещё одна просьба владельца" }); + assert.equal((await core.getVersion(db, p.id))?.doneAt, null); + }); + + test("mayAutoAccept: whose stories are accepted by Peppa", () => { + const human = { origin: "human", severity: null }; + const idea = { origin: "acceptance", severity: "important" }; + const broken = { origin: "incident", severity: "breakage" }; + assert.deepEqual([human, idea, broken].map((t) => core.mayAutoAccept(t, "mine")), [true, false, false]); + assert.deepEqual([human, idea, broken].map((t) => core.mayAutoAccept(t, "mine_breakage")), [true, false, true]); + assert.deepEqual([human, idea, broken].map((t) => core.mayAutoAccept(t, "all")), [true, true, true]); + }); +}); -- 2.45.2 From e29e95e13f1161fd29d5e1392c0992266db93db2 Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Tue, 17 Nov 2026 17:58:31 +0500 Subject: [PATCH 02/73] =?UTF-8?q?PEP-197:=20=D1=82=D0=B5=D1=81=D1=82=20pro?= =?UTF-8?q?duct=20=D0=BF=D0=BE=D0=B4=20=D0=BD=D0=BE=D0=B2=D1=8B=D0=B5=20?= =?UTF-8?q?=D0=BF=D0=BE=D0=BB=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/testkit/test/product.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/testkit/test/product.test.ts b/packages/testkit/test/product.test.ts index e898ba1d..a0d3c5cb 100644 --- a/packages/testkit/test/product.test.ts +++ b/packages/testkit/test/product.test.ts @@ -17,7 +17,7 @@ describe("PEP-111: the project's product", () => { test("nothing deployed: no versions, only the count of accepted stories", async () => { const p = await proj(); const t = await core.createTask(db, { projectId: p.id, title: "Первая" }); - assert.deepEqual(await core.projectProduct(db, p.id), { live: null, check: null, doneStories: 0, fix: null, broken: false, preparing: false, shot: null }); + assert.deepEqual(await core.projectProduct(db, p.id), { live: null, check: null, doneStories: 0, fix: null, broken: false, preparing: false, shot: null, versionDone: false, proposed: 0 }); await core.updateTask(db, t, { status: "done" }); assert.equal((await core.projectProduct(db, p.id)).doneStories, 1); assert.equal((await core.productUrls(db, [p.id])).size, 0); -- 2.45.2 From 156f1fbaaf4c1399fc77d1639e88afcfde3e636d Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Tue, 17 Nov 2026 17:59:38 +0500 Subject: [PATCH 03/73] =?UTF-8?q?PEP-197:=20=D0=B0=D1=80=D1=85=D0=B8=D0=B2?= =?UTF-8?q?=20change?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../design.md | 0 .../live-table.md | 0 .../proposal.md | 0 .../specs/agent-task-origin/spec.md | 0 .../2026-11-17-pep-197-no-task-loop}/tasks.md | 0 openspec/specs/agent-task-origin/spec.md | 54 +++++++++++++++++++ 6 files changed, 54 insertions(+) rename openspec/changes/{pep-197-no-task-loop => archive/2026-11-17-pep-197-no-task-loop}/design.md (100%) rename openspec/changes/{pep-197-no-task-loop => archive/2026-11-17-pep-197-no-task-loop}/live-table.md (100%) rename openspec/changes/{pep-197-no-task-loop => archive/2026-11-17-pep-197-no-task-loop}/proposal.md (100%) rename openspec/changes/{pep-197-no-task-loop => archive/2026-11-17-pep-197-no-task-loop}/specs/agent-task-origin/spec.md (100%) rename openspec/changes/{pep-197-no-task-loop => archive/2026-11-17-pep-197-no-task-loop}/tasks.md (100%) create mode 100644 openspec/specs/agent-task-origin/spec.md diff --git a/openspec/changes/pep-197-no-task-loop/design.md b/openspec/changes/archive/2026-11-17-pep-197-no-task-loop/design.md similarity index 100% rename from openspec/changes/pep-197-no-task-loop/design.md rename to openspec/changes/archive/2026-11-17-pep-197-no-task-loop/design.md diff --git a/openspec/changes/pep-197-no-task-loop/live-table.md b/openspec/changes/archive/2026-11-17-pep-197-no-task-loop/live-table.md similarity index 100% rename from openspec/changes/pep-197-no-task-loop/live-table.md rename to openspec/changes/archive/2026-11-17-pep-197-no-task-loop/live-table.md diff --git a/openspec/changes/pep-197-no-task-loop/proposal.md b/openspec/changes/archive/2026-11-17-pep-197-no-task-loop/proposal.md similarity index 100% rename from openspec/changes/pep-197-no-task-loop/proposal.md rename to openspec/changes/archive/2026-11-17-pep-197-no-task-loop/proposal.md diff --git a/openspec/changes/pep-197-no-task-loop/specs/agent-task-origin/spec.md b/openspec/changes/archive/2026-11-17-pep-197-no-task-loop/specs/agent-task-origin/spec.md similarity index 100% rename from openspec/changes/pep-197-no-task-loop/specs/agent-task-origin/spec.md rename to openspec/changes/archive/2026-11-17-pep-197-no-task-loop/specs/agent-task-origin/spec.md diff --git a/openspec/changes/pep-197-no-task-loop/tasks.md b/openspec/changes/archive/2026-11-17-pep-197-no-task-loop/tasks.md similarity index 100% rename from openspec/changes/pep-197-no-task-loop/tasks.md rename to openspec/changes/archive/2026-11-17-pep-197-no-task-loop/tasks.md diff --git a/openspec/specs/agent-task-origin/spec.md b/openspec/specs/agent-task-origin/spec.md new file mode 100644 index 00000000..b6f39d74 --- /dev/null +++ b/openspec/specs/agent-task-origin/spec.md @@ -0,0 +1,54 @@ +# agent-task-origin Specification + +## Purpose +TBD - created by archiving change pep-197-no-task-loop. Update Purpose after archive. + +## Requirements + +### Requirement: Задачи агентов не берутся в работу сами +Задача, заведённая агентом приёмки, SHALL создаваться в «Предложено» и не браться диспетчером, пока владелец не нажал «Делать». Поломка SHALL идти в бэклог сразу с пометкой «Поломка». + +#### Scenario: Улучшение от агента приёмки +- **GIVEN** проект с режимом «Сам берёт» и пустым бэклогом +- **WHEN** агент приёмки находит улучшение +- **THEN** задача появляется в «Предложено» +- **AND** диспетчер её не берёт + +#### Scenario: Поломка критерия задачи человека +- **GIVEN** задача человека с критерием приёмки +- **WHEN** агент приёмки находит, что критерий не выполнен +- **THEN** задача создаётся в бэклоге с пометкой «Поломка» + +### Requirement: Без дублей +Перед созданием задачи агентом SHALL выполняться проверка повтора по открытым задачам и сделанным за 60 дней. + +#### Scenario: Повтор открытой задачи +- **GIVEN** открытая задача «Подписать кнопки» +- **WHEN** агент приёмки предлагает «Подписать кнопки на экране» +- **THEN** новая задача не создаётся, к открытой дописано замечание + +### Requirement: Одно сообщение и версия с финишем +После прохода приёмки владелец SHALL получать одно сообщение со списком и кнопками; когда задачи человека приняты и поломок нет — «Версия готова». + +#### Scenario: Решение владельца +- **GIVEN** сообщение «Нашёл 3 улучшения» +- **WHEN** владелец нажимает «Не надо» у пункта +- **THEN** задача архивируется и больше не предлагается + +#### Scenario: Версия готова +- **GIVEN** все открытые задачи человека приняты +- **WHEN** проход приёмки не находит поломок +- **THEN** владелец получает «Версия готова», дальше агент заводит только поломки + +### Requirement: Пределы и приёмка +В работе SHALL быть не больше 3 задач агентов на проект; автомерж SHALL принимать задачи агентов только по настройке «Принимать сами». + +#### Scenario: Четвёртая не стартует +- **GIVEN** 3 задачи агентов в работе +- **WHEN** диспетчер выбирает следующую +- **THEN** четвёртая задача агента не стартует + +#### Scenario: Автомерж по умолчанию +- **GIVEN** настройка по умолчанию «мои и поломки» +- **WHEN** задача из «Предложено» (после «Делать») прошла проверки +- **THEN** автомерж её не принимает, ждёт владельца -- 2.45.2 From 05a4dab2f40a129e02ae4535c51447ddb8134695 Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Tue, 17 Nov 2026 17:59:46 +0500 Subject: [PATCH 04/73] =?UTF-8?q?PEP-197:=20=D0=BF=D0=B0=D0=BC=D1=8F=D1=82?= =?UTF-8?q?=D1=8C=20=D0=BF=D1=80=D0=BE=D0=B5=D0=BA=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .peppa/memory.md | 1 + 1 file changed, 1 insertion(+) diff --git a/.peppa/memory.md b/.peppa/memory.md index 5b607682..5538a57d 100644 --- a/.peppa/memory.md +++ b/.peppa/memory.md @@ -46,6 +46,7 @@ - Узкие места: запуск/перенос раннера — `pickSubscription`/`rotationCandidate`; агент, модель, сообщение человеку — `startRunner`/`resumeSession`, `claudePrint`, `deliverToUser` или с `isProjectPaused`; список проектов — `listProjects(db)`/`userProjectIds`, прямой `from(projects)` — с `isNull(projects.deletedAt)`; действие веба, которое запускает/убивает агентов, — через runnerCall. - Сообщения человеку: вопрос — `askPm`/`raiseSessionQuestion` с `msgType` и вариантами; «готово» — только `sendReviewCard`; ход работы/блокер — события; сбой платформы — `platformDelay`/`sessionDelay`, исключение — `platformFailure`; тип читать `questionType`/`needsPerson`, не `kind`. Текст агента — `admitAgentMessage` + `renderMain`, техника в `details`. - Вопрос ≠ задача (PEP-153): текст человека, который может стать задачей, — через `classifyMessage` (runner/message-intent.ts; в тестах mock-intake роль `intent`); молча задачу не заводить — кнопки (`chat.offer:`, `INTENT_TEXT`). +- Задачу агента заводи через createTask с origin (acceptance|incident|analyst) и fileStories/checkDuplicate (PEP-197); «Предложено» = backlog + tasks.proposed, readyBacklog их не отдаёт; автомерж задач агента — по autonomy.acceptOwn (mayAutoAcceptTask). ## Решения - После правок `template/` — `scripts/push-template.sh` и `peppa ci connect ` старым проектам. -- 2.45.2 From 2f6ee065cfac127312c8594b5fd3e4f2db4944a4 Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Tue, 17 Nov 2026 19:35:16 +0500 Subject: [PATCH 05/73] =?UTF-8?q?PEP-200:=20=D0=B2=D1=85=D0=BE=D0=B4=20?= =?UTF-8?q?=D1=87=D0=B5=D1=80=D0=B5=D0=B7=20eGov=20=E2=80=94=20=D0=BF?= =?UTF-8?q?=D0=BE=D0=B2=D1=82=D0=BE=D1=80=20=D0=B7=D0=B0=D0=BF=D1=80=D0=BE?= =?UTF-8?q?=D1=81=D0=B0=20=D0=BA=20relay=20=D1=87=D0=B5=D1=80=D0=B5=D0=B7?= =?UTF-8?q?=20=D0=B0=D0=B4=D1=80=D0=B5=D1=81=D0=B0=20=D0=B7=D0=B0=D0=BF?= =?UTF-8?q?=D0=B0=D1=81=D0=BD=D0=BE=D0=B3=D0=BE=20DNS?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Системный DNS Mac Studio отдаёт для sign.aitu.uz недоступные адреса Cloudflare; если relay не ответил, запрос повторяется через адреса от PEPPA_FALLBACK_DNS (по умолчанию 1.1.1.1) с тем же именем хоста. Co-Authored-By: Claude Opus 5.5 --- packages/core/src/egov.ts | 11 +++- packages/core/src/fallback-fetch.ts | 83 +++++++++++++++++++++++++++++ packages/core/src/index.ts | 1 + packages/testkit/test/egov.test.ts | 20 +++++++ 4 files changed, 114 insertions(+), 1 deletion(-) create mode 100644 packages/core/src/fallback-fetch.ts diff --git a/packages/core/src/egov.ts b/packages/core/src/egov.ts index 4ff7bb7a..94ee65b1 100644 --- a/packages/core/src/egov.ts +++ b/packages/core/src/egov.ts @@ -12,6 +12,7 @@ import { PeppaError } from "./errors.ts"; import { deleteSetting, getSetting, setSetting } from "./settings.ts"; import { getUser, type User } from "./users.ts"; import { announceNewUser } from "./new-users.ts"; +import { fetchViaFallbackDns, type FallbackResponse } from "./fallback-fetch.ts"; export const EGOV_FLOW_TTL_MS = 5 * 60_000; export type EgovPurpose = "login" | "link"; @@ -38,13 +39,21 @@ const flowKey = (handle: string) => `egov.flow:${hashToken(handle)}`; async function relay(path: string, init?: RequestInit): Promise { const base = loadEnv().KAZEDS_RELAY_BASE.replace(/\/$/, ""); // The relay sometimes hangs on one of its addresses: one quick retry (PEP-194). - let res: Response | null = null; + let res: Response | FallbackResponse | null = null; for (let attempt = 0; attempt < 2 && (!res || res.status >= 500); attempt++) { try { res = await fetch(base + path, { ...init, headers: { "Content-Type": "application/json" }, signal: AbortSignal.timeout(8_000) }); } catch { /* network error or timeout: retry once */ } + // No answer at all: the system resolver may point at an unreachable address (PEP-200). + if (!res) { + res = await fetchViaFallbackDns(base + path, { + method: init?.method, + body: typeof init?.body === "string" ? init.body : undefined, + headers: { "Content-Type": "application/json" }, + }); + } } if (!res) throw new PeppaError(tr("eGov сейчас не отвечает — попробуйте ещё раз через минуту")); const body = (await res.json().catch(() => ({}))) as T & { message?: string; error?: string }; diff --git a/packages/core/src/fallback-fetch.ts b/packages/core/src/fallback-fetch.ts new file mode 100644 index 00000000..a376b488 --- /dev/null +++ b/packages/core/src/fallback-fetch.ts @@ -0,0 +1,83 @@ +// Some Cloudflare addresses are unreachable from the Peppa host, while the system resolver keeps +// handing them out (sign.aitu.uz → 188.114.96.3/97.3, PEP-200). When a request gets no response at +// all, it is repeated through the addresses another resolver gives (PEPPA_FALLBACK_DNS, default +// 1.1.1.1), keeping the host name for TLS (SNI) and the Host header. No system settings are touched. +import { Resolver } from "node:dns/promises"; +import { lookup as systemLookup } from "node:dns/promises"; +import http from "node:http"; +import https from "node:https"; + +export interface FallbackResponse { + status: number; + ok: boolean; + json(): Promise; +} + +type Resolve = (host: string) => Promise; + +let mockResolve: Resolve | null = null; +/** Tests: replace the fallback resolver (null restores the real one). */ +export function mockFallbackResolver(fn: Resolve | null): void { + mockResolve = fn; +} + +async function fallbackAddresses(host: string): Promise { + if (mockResolve) return mockResolve(host); + const servers = (process.env.PEPPA_FALLBACK_DNS ?? "1.1.1.1").split(",").map((s) => s.trim()).filter(Boolean); + if (!servers.length || servers[0] === "off") return []; + const r = new Resolver({ timeout: 3_000, tries: 1 }); + r.setServers(servers); + const ips = await r.resolve4(host).catch(() => [] as string[]); + const system = new Set((await systemLookup(host, { all: true, family: 4 }).catch(() => [])).map((a) => a.address)); + // Addresses the system already gave were just tried; put them last. + return [...ips.filter((ip) => !system.has(ip)), ...ips.filter((ip) => system.has(ip))]; +} + +function requestVia(url: URL, ip: string, init: { method?: string; body?: string; headers?: Record }, timeoutMs: number): Promise { + const mod = url.protocol === "http:" ? http : https; + return new Promise((resolve, reject) => { + const req = mod.request( + url, + { + method: init.method ?? "GET", + headers: init.headers, + timeout: timeoutMs, + lookup: (_h, opts, cb) => { + if ((opts as { all?: boolean }).all) (cb as (e: null, a: { address: string; family: number }[]) => void)(null, [{ address: ip, family: 4 }]); + else cb(null, ip, 4); + }, + }, + (res) => { + const chunks: Buffer[] = []; + res.on("data", (c: Buffer) => chunks.push(c)); + res.on("end", () => { + const text = Buffer.concat(chunks).toString("utf8"); + const status = res.statusCode ?? 0; + resolve({ status, ok: status >= 200 && status < 300, json: async () => JSON.parse(text) }); + }); + res.on("error", reject); + }, + ); + req.on("timeout", () => req.destroy(new Error("timeout"))); + req.on("error", reject); + if (init.body) req.write(init.body); + req.end(); + }); +} + +/** The same request through the fallback resolver's addresses; null when none answered. */ +export async function fetchViaFallbackDns( + target: string, + init: { method?: string; body?: string; headers?: Record } = {}, + timeoutMs = 8_000, +): Promise { + const url = new URL(target); + for (const ip of await fallbackAddresses(url.hostname)) { + try { + return await requestVia(url, ip, init, timeoutMs); + } catch { + /* next address */ + } + } + return null; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 91e5a8d2..5c85f2d2 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -90,3 +90,4 @@ export * from "./feedback.ts"; export * from "./bench.ts"; export * from "./untrusted.ts"; export * from "./egress.ts"; +export * from "./fallback-fetch.ts"; diff --git a/packages/testkit/test/egov.test.ts b/packages/testkit/test/egov.test.ts index 47c6be6e..143e7128 100644 --- a/packages/testkit/test/egov.test.ts +++ b/packages/testkit/test/egov.test.ts @@ -44,6 +44,26 @@ describe("eGov QR", () => { relay.failNext = 0; }); + test("the system resolver gives an unreachable address: the fallback resolver's address works (PEP-200)", async () => { + const real = process.env.KAZEDS_RELAY_BASE!; + const u = new URL(real); + u.hostname = "mock-relay.invalid"; + process.env.KAZEDS_RELAY_BASE = u.toString(); + const asked: string[] = []; + core.mockFallbackResolver(async (host) => (asked.push(host), ["127.0.0.1"])); + try { + const f = await core.startEgovFlow(db, "login"); + assert.match(f.qrContent, /^mobileSign:/); + assert.ok(asked.includes("mock-relay.invalid")); + // No fallback address either: the clear message stays. + core.mockFallbackResolver(async () => []); + await assert.rejects(core.startEgovFlow(db, "login"), (e: Error) => e instanceof core.PeppaError && /не отвечает/.test(e.message)); + } finally { + core.mockFallbackResolver(null); + process.env.KAZEDS_RELAY_BASE = real; + } + }); + test("unknown IIN: the first login registers the account, the next one finds it (PEP-71)", async () => { relay.signer = { iin: "850505400008", name: "ИВАНОВА ӘЙГЕРІМ ҚАЙРАТҚЫЗЫ" }; const f = await core.startEgovFlow(db, "login"); -- 2.45.2 From 67bf91e9df30ff423b1d679fba7f7c07253caa85 Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Tue, 17 Nov 2026 20:02:02 +0500 Subject: [PATCH 06/73] =?UTF-8?q?PEP-202:=20OpenSpec=20change=20=E2=80=94?= =?UTF-8?q?=20=D1=81=D0=B5=D1=80=D0=B2=D0=B8=D1=81=20=D0=BC=D0=BE=D0=BD?= =?UTF-8?q?=D0=B8=D1=82=D0=BE=D1=80=D0=B8=D0=BD=D0=B3=D0=BE=D0=B2=20Observ?= =?UTF-8?q?ability?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../changes/pep-202-observability/design.md | 75 ++++++++++++++++ .../changes/pep-202-observability/proposal.md | 25 ++++++ .../specs/observability/spec.md | 88 +++++++++++++++++++ .../specs/service-monitoring/spec.md | 9 ++ .../changes/pep-202-observability/tasks.md | 26 ++++++ 5 files changed, 223 insertions(+) create mode 100644 openspec/changes/pep-202-observability/design.md create mode 100644 openspec/changes/pep-202-observability/proposal.md create mode 100644 openspec/changes/pep-202-observability/specs/observability/spec.md create mode 100644 openspec/changes/pep-202-observability/specs/service-monitoring/spec.md create mode 100644 openspec/changes/pep-202-observability/tasks.md diff --git a/openspec/changes/pep-202-observability/design.md b/openspec/changes/pep-202-observability/design.md new file mode 100644 index 00000000..8ceb0051 --- /dev/null +++ b/openspec/changes/pep-202-observability/design.md @@ -0,0 +1,75 @@ +## Context +Peppa работает на одном Mac Studio: веб, бот, вачдог — процессы launchd из рабочей копии, общая база SQLite `~/.peppa/peppa.db`, Telegram — через durable outbox, который разбирает бот (а при его падении служебные сообщения `mon:` доставляет вачдог). PEP-201 добавил в вачдог временную проверку сети. Нужен постоянный инструмент: мониторинги, которые создают суперадмин и агенты платформы. + +## Goals / Non-Goals +**Goals:** отдельный процесс проверок, не мешающий вачдогу и вебу; мониторинги создаются без правки конфигов и перезапуска (веб и MCP); одно сообщение на смену состояния; журнал за неделю. +**Non-Goals:** метрики и трассировки (это не Prometheus), мониторинги владельцев проектов, публичная страница статуса, хранение дольше 7 дней. + +## Decisions + +### Свой сервис, а не готовое решение +- Uptime Kuma: нет публичного API создания мониторингов (только socket.io своего интерфейса), свои пользователи и интерфейс вне Peppa. +- Gatus: мониторинги в YAML-файле, добавление — правка файла и перечитывание; плохо с «создать через MCP». +- Prometheus + blackbox + Alertmanager: тяжело для аптайма. +- Bun/Go: ещё одна среда исполнения и сборки; нагрузка — десятки запросов в минуту, Node 26 справляется. +Берём идеи: условия проверки (Gatus), heartbeat (Healthchecks.io), полоска последних проверок (Uptime Kuma). + +### Процесс и база +- `peppa-observer` — отдельный процесс (`apps/observer/src/index.ts`, bin `peppa-observer`, launchd `quest.telecom.peppa.observer`), heartbeat `heartbeat:observer` в основной базе (PEP-20), `installCrashReporting`. +- База мониторингов — отдельный файл `PEPPA_OBSERVE_DB` (по умолчанию `~/.peppa/observe.db`), WAL, `busy_timeout`: частые записи проверок не конкурируют с основной базой. Схема Drizzle в том же пакете `@peppa/db` отдельным модулем `observe-schema.ts`, миграции `packages/db/observe-migrations`, применение — `peppa db migrate` применяет обе. +- Таблицы: `monitors` (id, name, kind, target JSON, interval_sec, timeout_ms, fail_threshold, recover_threshold, paused_at, created_by_kind/id, created_at, updated_at, state, state_since, last_check_at), `monitor_checks` (monitor_id, at, ok, latency_ms, detail JSON — код, адреса, ошибка; индекс (monitor_id, at)), `monitor_incidents` (monitor_id, started_at, ended_at, reason). +- Хранение: раз в час `DELETE FROM monitor_checks WHERE at < now-7d` (и закрытые сбои старше 7 дней); `PEPPA_OBSERVE_RETENTION_DAYS`, по умолчанию 7. + +### Планировщик +- Цикл раз в секунду: мониторинги, у которых `last_check_at + interval <= now`, не на паузе; не больше `PEPPA_OBSERVE_CONCURRENCY` (16) проверок одновременно; у каждой свой таймаут. +- Изменения мониторингов (веб, MCP) — строки в базе; сервис перечитывает список каждый цикл (`PRAGMA data_version`), без перезапуска. +- Интервал не меньше 30 с; не больше 200 мониторингов. + +### Виды проверок +- `http`: `{url, method?, expectStatus? (по умолчанию 200–399), contains?, maxLatencyMs?, certDays? (по умолчанию 14)}`; ответ без тела больше 64 КБ; при отсутствии ответа — повтор через адреса запасного DNS (как PEP-200), результат в `detail.via`. +- `tcp`: `{host, port}`. +- `dns`: `{host}` — системный резолвер и запасной (`PEPPA_FALLBACK_DNS`, 1.1.1.1,1.0.0.1), TCP 443 к адресам; `detail.state` ok / dns / blocked / down (логика PEP-201 `probeHost`). +- `internet`: `{hosts[]}` — не работает, только если не открывается ни один. +- `heartbeat`: `{graceSec}` — у мониторинга секретный токен; `POST|GET /api/observe/hb/` (веб, без входа) пишет отметку; нет отметки дольше `interval+grace` — неудача. + +### Состояния и уведомления +- `up` / `down` / `degraded` (http: ответ есть, но превышено `maxLatencyMs` или сертификат истекает; dns: `blocked`). +- Смена `up→down` — после `fail_threshold` (3) неудач подряд; `down→up` — после `recover_threshold` (2) удач подряд. Открывается/закрывается `monitor_incidents`. +- Сообщение — через `postToChannel(db, "services", "mon:ch:obs:::", …)` основной базы, без канала — `alertAdmins` (`mon:obs:…`): «🔴 {name} не работает: {reason}», «🟡 {name} нестабилен: {reason}», «✅ {name} снова работает — простой {n} мин». Ключ от сбоя — одно сообщение даже при повторе. +- «Интернет» лежит → остальные мониторинги, упавшие в этот же момент, не пишут по отдельности (сводка в сообщении про интернет). +- Мониторинг на паузе не проверяется и не пишет. + +### Доступ +- Веб `/observability` и пункт меню — только `isSuperadmin`; иначе 404 (как `/subscriptions`). +- Удалённый MCP: инструменты видны и работают только для суперадмина. +- MCP агента: только сессии платформенного проекта (`PEPPA_PLATFORM_KEY`); автор — `agent` + id сессии, событие журнала `monitor_created`/`monitor_updated`/`monitor_deleted` (core/audit.ts). +- Внутренние адреса (localhost, 127.0.0.1, частные сети) разрешены — мониторинги создаёт только платформа. + +### MCP +`list_monitors`, `get_monitor` (состояние, аптайм 24 ч/7 д, последние 50 проверок, сбои), `create_monitor`, `update_monitor`, `pause_monitor` (`paused: bool`), `delete_monitor`. Проверка входа — `zod`-схемы по виду. Добавить в список `oauth.test.ts` и в справочник `/help` «Инженер». + +### Веб +- Пункт меню «Observability» (иконка `Activity`), только суперадмину. +- `/observability`: строка мониторинга — значок состояния, имя, вид и цель, аптайм 24 ч и 7 д, полоска последних 30 проверок, время последней проверки; кнопка «Новый мониторинг». +- `/observability/`: состояние, сбои за неделю, журнал проверок (постранично), правка, пауза, удаление с подтверждением; для heartbeat — ссылка отметки. +- Живые обновления — область `observability` в `LiveRefresh` (отпечаток по `observe.db`). + +### Встроенные мониторинги +При первом запуске (пустая таблица) сервис создаёт: «eGov relay» — `http https://sign.aitu.uz/` и `dns sign.aitu.uz`; «Интернет» — `internet` (api.telegram.org, chatgpt.com, api.anthropic.com, registry.npmjs.org, git.telecom.quest). Удалённые не создаются повторно (`settings` `observe.seeded`). + +### Перенос PEP-201 +После выкатки сервиса `runner/net-watch.ts` и вызов из вачдога удаляются; состояние `net.watch` стирается. + +## Risks / Trade-offs +- Ещё один процесс launchd → за ним следит вачдог (heartbeat), падение — сообщение админам. +- Сеть Mac Studio сама бывает недоступна — сообщения копятся в outbox и уходят, когда Telegram снова открывается; «Интернет» — сообщение о восстановлении со временем простоя. +- Ложные срабатывания — пороги 3/2 и не меньше 30 с. + +## Migration Plan +1. Схема и миграции `observe.db`; `peppa db migrate` на живой — до кода. +2. Сервис, веб, MCP; `scripts/install-launchd.sh observer` на живой (согласовать с PM: новый launchd-агент). +3. Удалить PEP-201 проверку из вачдога. +Откат: `launchctl bootout` агента observer; основная база не затронута. + +## Open Questions +- Нет. diff --git a/openspec/changes/pep-202-observability/proposal.md b/openspec/changes/pep-202-observability/proposal.md new file mode 100644 index 00000000..73ed0288 --- /dev/null +++ b/openspec/changes/pep-202-observability/proposal.md @@ -0,0 +1,25 @@ +## Why +Сегодня вход через eGov и агенты на ChatGPT падали, потому что с Mac Studio перестали открываться адреса, которые отдаёт DNS. Узнали мы об этом от пользователей. У Peppa нет места, где видно, работают ли внешние сервисы, от которых она зависит, и интернет на сервере, и нет способа быстро добавить такую проверку — руками или агентом. + +## What Changes +- Новый сервис `peppa-observer` (launchd, Node/TypeScript в репозитории Peppa, своя база `~/.peppa/observe.db`): по расписанию выполняет мониторинги и пишет журнал проверок, журнал хранится 7 дней. +- Виды мониторингов: HTTP(S) (код, время ответа, текст в ответе, срок сертификата), TCP, DNS (системный DNS против запасного 1.1.1.1), «Интернет» (группа адресов), heartbeat (сервис сам отмечается по ссылке). +- Состояния «работает / не работает / нестабилен»; смена — после N неудачных проверок подряд; одно сообщение «не работает» и одно «снова работает — простой N мин» в Telegram-канал платформы (без канала — суперадминам). +- Раздел «Observability» в левом меню — только суперадмину: список с аптаймом за 24 ч и 7 дней, страница мониторинга с журналом и сбоями, создание, правка, пауза, удаление. +- MCP-инструменты мониторингов: в удалённом MCP — только суперадмину; в MCP агента — только сессиям платформенного проекта (`PEPPA_PLATFORM_KEY`). +- Встроенные мониторинги при первом запуске: `sign.aitu.uz` (HTTP + DNS) и «Интернет». +- Проверка сети из вачдога (PEP-201) переезжает в сервис и удаляется из вачдога. + +## Capabilities +### New Capabilities +- `observability`: сервис мониторингов, виды проверок, состояния и уведомления, журнал с хранением 7 дней, раздел в вебе для суперадмина, MCP-инструменты. + +### Modified Capabilities +- `service-monitoring`: вачдог следит за живостью `peppa-observer` (heartbeat), как за ботом и вебом. + +## Impact +- Новый пакет `apps/observer` (или `packages/observer`), launchd-агент `quest.telecom.peppa.observer`, `scripts/install-launchd.sh observer`. +- `packages/core` — модель и доступ к базе мониторингов (отдельный файл SQLite, своя схема и миграции). +- `packages/mcp` — инструменты `*_monitor(s)`; `apps/web` — раздел `/observability`, пункт меню суперадмина. +- `runner/net-watch.ts` (PEP-201) удаляется после переноса. +- Не входит: мониторинги для владельцев проектов, автоматические мониторинги staging/prod проектов, публичная страница статуса, хранение агрегатов дольше 7 дней. diff --git a/openspec/changes/pep-202-observability/specs/observability/spec.md b/openspec/changes/pep-202-observability/specs/observability/spec.md new file mode 100644 index 00000000..74a7fa33 --- /dev/null +++ b/openspec/changes/pep-202-observability/specs/observability/spec.md @@ -0,0 +1,88 @@ +## ADDED Requirements + +### Requirement: Сервис мониторингов +Peppa SHALL выполнять мониторинги в отдельном процессе `peppa-observer` со своей базой и SHALL хранить журнал проверок не дольше 7 дней. Изменение мониторинга SHALL применяться без перезапуска сервиса. + +#### Scenario: Новый мониторинг без перезапуска +- **GIVEN** сервис работает +- **WHEN** суперадмин создаёт HTTP-мониторинг с интервалом 30 с +- **THEN** первая проверка выполняется в течение 30 с, результат в журнале + +#### Scenario: Хранение 7 дней +- **GIVEN** в журнале есть проверки старше 7 дней +- **WHEN** проходит ежечасная уборка +- **THEN** проверки старше 7 дней удалены, более новые остались + +### Requirement: Виды проверок +Мониторинг SHALL быть одного из видов: HTTP(S), TCP, DNS, «Интернет», heartbeat. DNS-проверка SHALL отличать «системный DNS отдаёт недоступные адреса» от полной недоступности, сравнивая с запасным DNS. + +#### Scenario: DNS отдаёт недоступные адреса +- **GIVEN** системный DNS отдаёт для sign.aitu.uz недоступные адреса, а запасной — рабочие +- **WHEN** выполняется DNS-проверка +- **THEN** результат «нестабилен» с плохими и рабочими адресами в журнале + +#### Scenario: Heartbeat молчит +- **GIVEN** heartbeat-мониторинг с интервалом 5 мин и запасом 1 мин +- **WHEN** отметки нет 7 минут +- **THEN** проверка неудачна + +#### Scenario: Интернет +- **GIVEN** мониторинг «Интернет» с пятью адресами +- **WHEN** не открывается ни один +- **THEN** проверка неудачна; если открывается хоть один — удачна + +### Requirement: Состояния и уведомления +Состояние SHALL меняться на «не работает» после заданного числа неудач подряд (по умолчанию 3) и на «работает» после заданного числа удач подряд (по умолчанию 2). На каждую смену SHALL уходить одно сообщение в Telegram-канал платформы (без канала — суперадминам), сообщение о восстановлении SHALL содержать длительность простоя. Пока нет интернета, мониторинги, упавшие вместе с ним, SHALL не писать по отдельности. + +#### Scenario: Сбой и восстановление +- **GIVEN** мониторинг «eGov relay» работает +- **WHEN** три проверки подряд неудачны, потом две удачны через 12 минут +- **THEN** в канал ушло «🔴 eGov relay не работает» и «✅ eGov relay снова работает — простой 12 мин», каждое один раз + +#### Scenario: Одиночный сбой +- **WHEN** одна проверка неудачна, следующая удачна +- **THEN** сообщений нет, состояние «работает» + +#### Scenario: Нет интернета +- **GIVEN** мониторинги «Интернет» и «eGov relay» +- **WHEN** пропадает интернет +- **THEN** приходит одно сообщение о мониторинге «Интернет», про «eGov relay» отдельного нет + +### Requirement: Раздел Observability только суперадмину +Раздел «Observability» в левом меню, его страницы и действия SHALL быть доступны только суперадмину; остальным пункта меню нет, адрес отвечает 404. + +#### Scenario: Обычный пользователь +- **WHEN** пользователь без прав суперадмина открывает `/observability` +- **THEN** 404, пункта в меню нет + +#### Scenario: Суперадмин +- **WHEN** суперадмин открывает раздел +- **THEN** видит мониторинги с состоянием, аптаймом за 24 ч и 7 дней и последними проверками, может создать, изменить, приостановить и удалить + +### Requirement: Мониторинги через MCP +Инструменты мониторингов SHALL быть в удалённом MCP только для суперадмина и в MCP агента только для сессий платформенного проекта. Изменение мониторинга SHALL записываться в журнал с автором. + +#### Scenario: Агент платформы добавляет мониторинг +- **GIVEN** сессия агента проекта PEP +- **WHEN** агент вызывает `create_monitor` +- **THEN** мониторинг создан, в журнале событие с автором-агентом + +#### Scenario: Агент другого проекта +- **WHEN** агент проекта не платформы вызывает `create_monitor` +- **THEN** отказ, мониторинг не создан + +#### Scenario: Не суперадмин в удалённом MCP +- **WHEN** пользователь без прав суперадмина вызывает `list_monitors` +- **THEN** отказ + +### Requirement: Встроенные мониторинги +При первом запуске сервис SHALL создать мониторинги «eGov relay» (HTTP и DNS для sign.aitu.uz) и «Интернет»; удалённые суперадмином SHALL не создаваться снова. + +#### Scenario: Первый запуск +- **WHEN** сервис запускается с пустой базой +- **THEN** есть мониторинги «eGov relay» и «Интернет» + +#### Scenario: Удалённый не возвращается +- **GIVEN** суперадмин удалил «eGov relay» +- **WHEN** сервис перезапускается +- **THEN** «eGov relay» не создан снова diff --git a/openspec/changes/pep-202-observability/specs/service-monitoring/spec.md b/openspec/changes/pep-202-observability/specs/service-monitoring/spec.md new file mode 100644 index 00000000..08b8aa23 --- /dev/null +++ b/openspec/changes/pep-202-observability/specs/service-monitoring/spec.md @@ -0,0 +1,9 @@ +## ADDED Requirements + +### Requirement: Вачдог следит за сервисом мониторингов +Вачдог SHALL проверять heartbeat `peppa-observer` так же, как бота и веб, и SHALL сообщать админам, если сервис молчит дольше порога. + +#### Scenario: Сервис мониторингов упал +- **GIVEN** `peppa-observer` не пишет heartbeat дольше 5 минут +- **WHEN** вачдог проверяет сервисы +- **THEN** админы получают одно сообщение «не отвечает», после восстановления — «снова работает» diff --git a/openspec/changes/pep-202-observability/tasks.md b/openspec/changes/pep-202-observability/tasks.md new file mode 100644 index 00000000..f1196897 --- /dev/null +++ b/openspec/changes/pep-202-observability/tasks.md @@ -0,0 +1,26 @@ +## 1. База мониторингов +- [ ] 1.1 Схема `observe-schema.ts` (monitors, monitor_checks, monitor_incidents), отдельный файл `PEPPA_OBSERVE_DB`, миграции `observe-migrations`, `peppa db migrate` применяет обе +- [ ] 1.2 `core/observe.ts`: CRUD мониторингов с проверкой входа по виду, аптайм 24 ч/7 д, журнал, уборка старше 7 дней + +## 2. Сервис peppa-observer +- [ ] 2.1 Процесс, bin, heartbeat `observer`, `installCrashReporting`, launchd `quest.telecom.peppa.observer` в `install-launchd.sh` +- [ ] 2.2 Планировщик: интервал, параллельность, таймауты, перечитывание при изменениях +- [ ] 2.3 Проверки http, tcp, dns (перенос `probeHost` из PEP-201), internet, heartbeat (`/api/observe/hb/`) +- [ ] 2.4 Состояния, пороги, сбои, сообщения в канал / суперадминам, подавление при отсутствии интернета +- [ ] 2.5 Встроенные мониторинги при первом запуске (`observe.seeded`) + +## 3. Доступ и MCP +- [ ] 3.1 Инструменты в удалённом MCP (только суперадмин) и в MCP агента (только платформенный проект), события журнала +- [ ] 3.2 `oauth.test.ts`, справочник `/help` «Инженер» + +## 4. Веб +- [ ] 4.1 Пункт меню «Observability» суперадмину, `/observability` список, `/observability/` журнал и сбои, формы создания и правки, пауза, удаление +- [ ] 4.2 Живая область `observability`; тексты ru/kk/en, словарь + +## 5. Вачдог +- [ ] 5.1 `checkServices` следит за `observer` +- [ ] 5.2 Удалить `runner/net-watch.ts` и вызов из вачдога (PEP-201) + +## 6. Тесты и выкатка +- [ ] 6.1 `observability.test.ts` на моках сети: пороги, одно сообщение, восстановление с простоем, интернет, heartbeat, хранение, доступ, встроенные +- [ ] 6.2 AGENTS.md; выкатка: миграция, сборка, установка launchd-агента (с согласия PM), проверка в браузере -- 2.45.2 From c3c26d35af0af047fd847eae80ced37fb379c2f9 Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Tue, 17 Nov 2026 20:11:26 +0500 Subject: [PATCH 07/73] =?UTF-8?q?PEP-197:=20=D0=BF=D0=B5=D1=80=D0=B5=D0=B7?= =?UTF-8?q?=D0=B0=D0=BF=D1=83=D1=81=D0=BA=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5?= =?UTF-8?q?=D1=80=D0=BE=D0=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 -- 2.45.2 From 49a8a4976e6a2a6a0939bce01e478f1f8d5b8662 Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Tue, 17 Nov 2026 20:33:47 +0500 Subject: [PATCH 08/73] =?UTF-8?q?PEP-197:=20=D0=BF=D0=B0=D0=BC=D1=8F=D1=82?= =?UTF-8?q?=D1=8C=20=E2=80=94=20=D1=83=D0=B1=D1=80=D0=B0=D1=82=D1=8C=20?= =?UTF-8?q?=D0=B4=D1=83=D0=B1=D0=BB=D1=8C=20=D0=BF=D1=83=D0=BD=D0=BA=D1=82?= =?UTF-8?q?=D0=B0=20=D0=BE=20=D1=81=D0=BE=D0=BE=D0=B1=D1=89=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D1=8F=D1=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- .peppa/memory.md | 1 - 1 file changed, 1 deletion(-) diff --git a/.peppa/memory.md b/.peppa/memory.md index 9a43cb2a..a166e356 100644 --- a/.peppa/memory.md +++ b/.peppa/memory.md @@ -44,7 +44,6 @@ - Переписка проекта (PEP-155): `projectThreadList`/`threadGroup`/`plainLine` (core/chat-threads.ts); поиск кириллицы — в JS. - Тесты: места подписки занимай `core.createSession` с `subscriptionId`; задачу из очереди ёмкости убирай `moveTask(backlog)`, иначе её подхватит тик соседнего теста. Конец хода агента вопроса не создаёт — жди статус сессии `idle`. Сообщения суперадмина — `superadmin()` из helpers.ts. Текст из `chat_messages` сравнивай через `stripAsIs`. - Узкие места: запуск/перенос раннера — `pickSubscription`/`rotationCandidate`; агент, модель, сообщение человеку — `startRunner`/`resumeSession`, `claudePrint`, `deliverToUser` или с `isProjectPaused`; список проектов — `listProjects(db)`/`userProjectIds`, прямой `from(projects)` — с `isNull(projects.deletedAt)`; действие веба, которое запускает/убивает агентов, — через runnerCall. -- Сообщения человеку: вопрос — `askPm`/`raiseSessionQuestion` с `msgType` и вариантами; «готово» — только `sendReviewCard`; ход работы/блокер — события; сбой платформы — `platformDelay`/`sessionDelay`, исключение — `platformFailure`; тип читать `questionType`/`needsPerson`, не `kind`. Текст агента — `admitAgentMessage` + `renderMain`, техника в `details`. - Вопрос ≠ задача (PEP-153): текст человека, который может стать задачей, — через `classifyMessage` (runner/message-intent.ts; в тестах mock-intake роль `intent`); молча задачу не заводить — кнопки (`chat.offer:`, `INTENT_TEXT`). - Задачу агента заводи через createTask с origin (acceptance|incident|analyst) и fileStories/checkDuplicate (PEP-197); «Предложено» = backlog + tasks.proposed, readyBacklog их не отдаёт; автомерж задач агента — по autonomy.acceptOwn (mayAutoAcceptTask). - Неудачная версия (PEP-158): `rolled_back`/`failed` → агенту задачи, `returnFailedRelease` (runner/deploy-feedback.ts); счётчик — `attempts` задержки `deploy` (3 — суперадмину, 6 — стоп). -- 2.45.2 From c2b5a46ee66d4192bf16f4c470daffb0e214395c Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Tue, 17 Nov 2026 20:38:45 +0500 Subject: [PATCH 09/73] =?UTF-8?q?PEP-203:=20=D0=BF=D0=BE=D0=B4=D0=B1=D0=BE?= =?UTF-8?q?=D1=80=20=D1=81=D0=BF=D0=B5=D1=86=D0=B8=D0=B0=D0=BB=D0=B8=D1=81?= =?UTF-8?q?=D1=82=D0=B0=20=D0=BD=D0=B5=20=D0=B4=D0=B5=D1=80=D0=B6=D0=B8?= =?UTF-8?q?=D1=82=20=D1=82=D0=B8=D0=BA=20=D0=B2=D0=B0=D1=87=D0=B4=D0=BE?= =?UTF-8?q?=D0=B3=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit specialistHold звал модель по очереди для каждой готовой задачи бэклога прямо в тике: на живой 125 задач — вачдог не писал heartbeat, выкатка откатывалась. Теперь тик читает только готовые подборы, недостающие считаются в фоне по одному и только для первых трёх задач очереди; пока подбор считается, такая задача ждёт. Co-Authored-By: Claude Opus 5.5 --- packages/runner/src/team-match.ts | 37 ++++++++++++++++++++++-- packages/testkit/src/mock-team.ts | 5 +++- packages/testkit/test/team-match.test.ts | 26 +++++++++++++++++ 3 files changed, 64 insertions(+), 4 deletions(-) diff --git a/packages/runner/src/team-match.ts b/packages/runner/src/team-match.ts index dfe9266d..d9688daf 100644 --- a/packages/runner/src/team-match.ts +++ b/packages/runner/src/team-match.ts @@ -43,17 +43,48 @@ export async function ensureTaskMatch(db: Db, taskId: number): Promise>(); + +function matchInBackground(db: Db, taskId: number): void { + if (inflight.has(taskId) || inflight.size >= 1) return; + const p = ensureTaskMatch(db, taskId) + .catch(() => null) + .finally(() => inflight.delete(taskId)); + inflight.set(taskId, p); +} + +/** Tests: wait for the background matches started so far. */ +export async function teamMatchesSettled(): Promise { + while (inflight.size) await Promise.all([...inflight.values()]); +} + /** * Stories the dispatcher must hold back: they fit a specialist who is busy right now and have - * not waited longer than the platform's threshold. Not a failure — nobody is told. + * not waited longer than the platform's threshold, or their match is still being computed + * (head of the queue only). Not a failure — nobody is told. */ export async function specialistHold(db: Db, list: T[], now = new Date()): Promise> { const held = new Set(); if (!list.length || !(await listSpecialists(db)).length) return held; const { waitMin } = await getTeamSettings(db); + let unknown = 0; for (const t of list) { - const match = await ensureTaskMatch(db, t.id); - if (!match?.agentId) continue; + const match = await getTeamMatch(db, t.id); + if (!match) { + if (unknown >= HOLD_SCAN) continue; + // The story already had an agent: the same one goes on, nothing to decide. + const [prior] = await db.select({ id: sessions.id }).from(sessions).where(and(eq(sessions.taskId, t.id), isNotNull(sessions.agentId))).limit(1); + if (prior) continue; + unknown++; + matchInBackground(db, t.id); + held.add(t.id); + continue; + } + if (!match.agentId) continue; const [a] = await db.select().from(agents).where(eq(agents.id, match.agentId)); if (!a || !isSpecialist(a) || !(await agentIsBusy(db, a.id))) continue; const since = match.waitSince ?? now.getTime(); diff --git a/packages/testkit/src/mock-team.ts b/packages/testkit/src/mock-team.ts index f2fb4ec5..a102ebe5 100644 --- a/packages/testkit/src/mock-team.ts +++ b/packages/testkit/src/mock-team.ts @@ -1,5 +1,5 @@ // mock-team (PEP-183): stands in for `claude -p` as the specialist matcher. The scenario file -// (MOCK_TEAM_SCENARIO, JSON): { "rules": [{ "match": "безопасн", "agent": "Страж ИБ", "reason": "…" }], "fail": false }. +// (MOCK_TEAM_SCENARIO, JSON): { "rules": [{ "match": "безопасн", "agent": "Страж ИБ", "reason": "…" }], "fail": false, "slowMs": 0 }. // The first rule whose regexp matches the story's title ("Задача: …") wins; none → agent null. // Every call is appended to .log.jsonl. import { appendFileSync, existsSync, readFileSync } from "node:fs"; @@ -7,6 +7,8 @@ import { appendFileSync, existsSync, readFileSync } from "node:fs"; interface Scenario { rules?: Array<{ match: string; agent: string | null; reason?: string }>; fail?: boolean; + /** Answer after this many ms (a slow model). */ + slowMs?: number; } const file = process.env.MOCK_TEAM_SCENARIO; const sc: Scenario = file && existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {}; @@ -17,6 +19,7 @@ if (!process.argv.includes("-p")) { console.error("mock-team: expected -p (non-interactive print mode)"); process.exit(2); } +if (sc.slowMs) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, sc.slowMs); if (sc.fail) { console.error("mock-team: API Error: 529 overloaded"); process.exit(1); diff --git a/packages/testkit/test/team-match.test.ts b/packages/testkit/test/team-match.test.ts index eec5b45d..de4357f2 100644 --- a/packages/testkit/test/team-match.test.ts +++ b/packages/testkit/test/team-match.test.ts @@ -53,6 +53,9 @@ describe("Специалисты и задачи по профилю", () => { const t = await next.task(); const [proj] = await core.listProjects(db).then((l) => l.filter((x) => x.key === next.key)); const now = new Date(); + // PEP-203: the match is computed in the background; until then the head of the queue waits. + assert.deepEqual([...(await runner.specialistHold(db, [t], now))], [t.id], "the match is being computed"); + await runner.teamMatchesSettled(); assert.deepEqual([...(await runner.specialistHold(db, [t], now))], [t.id], "waits for the busy specialist"); assert.deepEqual([...(await runner.specialistHold(db, [t], new Date(now.getTime() + 20 * 60_000)))], [t.id], "still within 30 min"); assert.deepEqual([...(await runner.specialistHold(db, [t], new Date(now.getTime() + 31 * 60_000)))], [], "after the threshold it is free to go"); @@ -66,6 +69,29 @@ describe("Специалисты и задачи по профилю", () => { await core.setTeamSettings(db, { waitMin: 30 }); }); + test("Scenario: длинный бэклог — тик не ждёт модель, подбор только для головы очереди (PEP-203)", async () => { + scenario({ rules: [{ match: "безопасн", agent: "Страж ИБ", reason: "про безопасность" }], slowMs: 400 }); + const list = []; + for (let i = 0; i < 6; i++) { + const p = await project({ turns: [[{ say: "ok" }]] }); + await retitle(p, `Задача ${i}`); + list.push(await p.task()); + } + const t0 = Date.now(); + const held = await runner.specialistHold(db, list); + assert.ok(Date.now() - t0 < 300, "the tick does not wait for the model"); + assert.deepEqual([...held], list.slice(0, 3).map((t) => t.id), "only the head of the queue waits"); + await runner.teamMatchesSettled(); + for (let i = 0; i < 3 && !(await core.getTeamMatch(db, list[2]!.id)); i++) { + await runner.specialistHold(db, list); + await runner.teamMatchesSettled(); + } + for (const t of list.slice(0, 3)) assert.ok(await core.getTeamMatch(db, t.id), "head matched"); + for (const t of list.slice(3)) assert.equal(await core.getTeamMatch(db, t.id), null, "the rest is not matched yet"); + assert.deepEqual([...(await runner.specialistHold(db, list))], list.slice(3, 6).map((t) => t.id), "the next three are now the unknown head"); + await runner.teamMatchesSettled(); + }); + test("Scenario: стёрли специализацию — следующая задача идёт как универсалу", async () => { await core.updateAgent(db, guard.id, { character: "" }); await core.updateAgent(db, plain.id, { disabled: true }); -- 2.45.2 From 7ffef5718f4b5f0b71e95670e0117225c9156029 Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Tue, 17 Nov 2026 21:12:27 +0500 Subject: [PATCH 10/73] =?UTF-8?q?PEP-198:=20=D0=BF=D0=BB=D0=B0=D0=BD=20?= =?UTF-8?q?=D0=B8=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5=D0=BD=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../changes/pep-198-one-analyst/design.md | 46 ++++++++ .../changes/pep-198-one-analyst/proposal.md | 16 +++ .../specs/analyst-voice/spec.md | 100 ++++++++++++++++++ openspec/changes/pep-198-one-analyst/tasks.md | 21 ++++ 4 files changed, 183 insertions(+) create mode 100644 openspec/changes/pep-198-one-analyst/design.md create mode 100644 openspec/changes/pep-198-one-analyst/proposal.md create mode 100644 openspec/changes/pep-198-one-analyst/specs/analyst-voice/spec.md create mode 100644 openspec/changes/pep-198-one-analyst/tasks.md diff --git a/openspec/changes/pep-198-one-analyst/design.md b/openspec/changes/pep-198-one-analyst/design.md new file mode 100644 index 00000000..89d68bb2 --- /dev/null +++ b/openspec/changes/pep-198-one-analyst/design.md @@ -0,0 +1,46 @@ +## Контекст +Опирается на PEP-197 (происхождение задач `tasks.origin`, «Предложено», проверка повторов `checkDuplicate`, одно сообщение приёмки). Ветка стоит поверх PEP-197. + +## Решения + +### Вход задачи — один вызов +- `intakePrompt` заменяет `productPrompt` + `analystPrompt`; ответ `IntakeNote` = `{goal, title, deferred[], split[], description, criteria[], out_of_scope[], decisions[], comment}`. Первая строка промпта «Ты — аналитик софтвер-фабрики на входе задачи» — по ней mock-intake узнаёт роль `intake`. +- Стадии: новая `analyst` (одна); старые `product`, `finalize` выполняются тем же шагом (контекст старого `product`-заметки, если есть, идёт в промпт); `waiting` — сразу решается вариантами по умолчанию (как раньше, по дедлайну) — данные (`original`, `product`, `analyst`) сохраняются в состоянии. +- Две неудачи: `stage: done`, заметка Аналитика с причиной и одно сообщение владельцу (`sayInDiscussion` от Аналитика; без Telegram-повторов — ключ `intake.fail:`). +- Модель/таймаут: `PEPPA_INTAKE_MODEL`/`PEPPA_INTAKE_TIMEOUT_MS`, как было. + +### Решения задачи +- `settings task.decisions:` = `Decision[]` `{id, text, status: default|confirmed|changed, kind: plain|split, by?, at?, was?}` (без миграции). `core/task-decisions.ts`: `getDecisions`, `setDecisions`, `confirmDecision`, `changeDecision` (возвращает, что делать), `decisionsAssumptions` — раздел «Допущения» собирается из списка. +- «Нужно иначе» (`runner/decisions.ts` `changeTaskDecision`): бэклог/`proposing` без живого агента → `addStoryComment` («было — …, нужно — …»): его подхватывает существующий `storyRefineTick` (PEP-115) — Аналитик пересобирает постановку; в работе → комментарий + `sendToSession` живому агенту (или в `get_task` при следующем запуске); на ревью → `fixStory`. Статус решения — `changed`, `was` хранит прежний текст. +- «Подходит» — только статус `confirmed`, ничего не запускает. +- Веб: `components/TaskDecisions.tsx` под заголовком задачи (и в «Продакте», и в «Инженере»), кнопки `min-h-11`, поле «Как нужно?» через `
`. + +### Разбивка +- Части: `createTask(origin: "analyst")` с описанием `… _Из разбивки KEY._`, intake сразу `done` (часть уже сформулирована Аналитиком), `addDependency(часть → первая)`, `settings task.split-of:` = parentId. `readyBacklog` не берёт часть, пока первая не `done` (зависимость открывается уже на `review` — этого мало). +- Решение kind `split`: «Разделила на N задач: KEY-2, KEY-3». «Не делить» (`undoSplit`) архивирует части и дописывает их названия и отложенное в описание первой («## Отложено при разбивке» → «## Тоже входит»). +- Перед созданием части — `checkDuplicate` (PEP-197); повтор — часть не создаётся, в решении «уже есть KEY». + +### Один собеседник +- `runner/agent-relay.ts` `relayAgentQuestion(db, ref, q)`: правило без модели (технические слова — стек, база, библиотека, тест, ветка, сборка…) → technical; иначе модель (роль `relay`, haiku, `PEPPA_RELAY_MODEL`) с последними сообщениями задачи владельцу: `{verdict: product|technical|repeat, text, options[], default}`. Сбой модели → передаём как есть (лучше дойти, чем потеряться). + - technical → вопрос не создаётся, агенту ответ «Это технический вопрос — решите сами и запишите в design.md», событие `relay_held`. + - repeat → не создаётся, агенту «владельцу уже задан такой вопрос #N». + - product → `askPm` с текстом Аналитика и вариантами; `settings question.voice:` = `analyst`. + - MCP `ask_pm` и `report_blocker(product)` идут через него; `PEPPA_AGENT_RELAY=off` — прежнее поведение. +- Telegram: вторая строка `renderQuestion` — «🔎 Аналитик · вопрос / готово / сообщение» вместо «Сообщение от фабрики». Находки агента приёмки — автор `ANALYST_NAME`, первая строка «Агент приёмки проверил продукт». +- Агент обратной связи пишет суперадмину (это не владелец продукта) — не меняется. + +### Готовые задачи сводкой +- `sendReviewCard`: задача с `origin ≠ human` → `settings question.digest:` (`holdForDigest`). Бот (`reconcile`) не шлёт такой вопрос в Telegram/push; на Главной («Ждут „Принять“») он есть. +- `readyDigestTick` (вачдог): после `workTo` (порог вачдога, часовой пояс `PEPPA_TZ`) — по проекту одно сообщение Аналитика «За день готовы N задач: …», отметка `ready.digest:` = дата. + +### Застрявшая задача +- `stuckTaskTick` (вачдог, раз в 10 мин): задача `in_progress`, у сессии статус `idle`/`waiting_input` и `last_activity_at` старше часа, `prGate` зелёный → `platformDelay(reason: "stuck")` (суперадмину) и одна строка владельцу от Аналитика «Задача KEY задерживается на нашей стороне», `settings stuck.task:` (раз на эпизод; снимается, когда задача ушла из «в работе»). + +### Чат: только кнопкой +- `create` модели больше не создаёт задачи: предложения сохраняются в оффер `stories` (`items: [{title, description}]`), под сообщением карточки и одна кнопка «Завести задачи» (`choice: stories`); создание — `resolveChatOffer` человеком, с проверкой повторов, intake `done`, ≤4. +- Промпт чата: ≤4 части, ≤2 вопроса только о продукте, технический выбор (сервис, ключ) — решает сам и пишет по шагам. +- Контекст (`analystChatContext`): описания открытых и сделанных за 30 дней (сжато, лимит 12 000 символов), решения, итог приёмки (`product.review`), ссылка на продукт; при вопросе «как выглядит» — до 2 последних скриншотов как файлы. + +### Словарь и тексты +- `docs/glossary.md`: строка «ИИ-роли | Аналитик, агент приёмки | продакт-агент, продакт-менеджер фабрики, ИИ-продакт». Тест: имена ИИ-ролей (`ANALYST_NAME`, `ACCEPTANCE_AGENT_NAME`, подписи intake) не содержат «продакт». +- «Помощь»: `PRODUCT_HELP` и справочник «Инженера». diff --git a/openspec/changes/pep-198-one-analyst/proposal.md b/openspec/changes/pep-198-one-analyst/proposal.md new file mode 100644 index 00000000..7d0dbb6b --- /dev/null +++ b/openspec/changes/pep-198-one-analyst/proposal.md @@ -0,0 +1,16 @@ +## Why +Пользователю (~16 человек, в основном не программисты) пишут семь «голосов»: аналитик в чате, роли «Продакт» и «Аналитик» на входе задачи, бот, агент-разработчик, агент приёмки, агент обратной связи, сама фабрика. Манера разная, сообщения повторяются, слово «продакт» значит три вещи. Роли на входе пересекаются и делают два запроса к модели. Решения аналитика спрятаны в описании задачи. Задачи из чата заводятся по решению модели, что человек «сказал да». + +## What Changes +- **Роли и названия**: «Продакт» — только человек; ИИ-роли «Продакт» нет, агент на приёмке — «Агент приёмки». Словарь запрещает «продакт-агент» и родственные имена ИИ-ролей. +- **Один собеседник**: вопрос разработчика владельцу проходит через Аналитика (`relayAgentQuestion`): технический — не доходит (агенту «решите сами»), повтор по смыслу — не доходит, о продукте — один раз, словами Аналитика, с вариантами. Telegram подписывает сообщения фабрики «Аналитик». Находки агента приёмки — от Аналитика. +- **Готовые задачи сводкой**: «готово» по задаче, которую человек не ждёт (заведена агентом), не шлётся в Telegram сразу, а уходит одной сводкой в конце рабочего дня. +- **Один Аналитик на входе**: один промпт, один ответ JSON (цель, урезание, разбивка ≤4, описание, критерии, вне задачи, решения, комментарий). Старые стадии `product`/`waiting`/`finalize` доводятся тем же шагом. Две неудачи — задача идёт как написана, владельцу одно сообщение. Задача из чата с критериями вход не проходит. Перед созданием частей — проверка повторов. +- **Разбивка**: части в бэклоге с пометкой «Из разбивки KEY» и зависимостью от первой (диспетчер ждёт, пока первая принята); решение «Разделила на N задач» с «Подходит» / «Не делить». +- **Решения на виду**: список решений задачи (`task.decisions:`) — блок «Фабрика решила за вас» на странице задачи (оба режима) с «Подходит» / «Нужно иначе»; «Нужно иначе» в бэклоге — пересборка постановки, в работе — агенту «было — …, нужно — …», на ревью — как «Поправить». +- **Аналитик знает проект**: контекст — описания открытых и недавно сделанных задач, решения, итог агента приёмки, ссылка на продукт; на «как выглядит» — последние скриншоты. Застрявшая задача (в работе, агент свободен > 1 ч, проверки зелёные) — суперадмину и одна строка владельцу. +- **Задачи из чата только кнопкой**: предложения Аналитика — карточки с кнопкой «Завести задачи»; модель сама задач не создаёт; не больше 4. +- **«Помощь»**: абзац о ролях переписан; «до трёх вопросов» и «30 минут» убраны. + +## Impact +core (intake, analyst-chat, task-decisions, agent-relay, ready-digest, help-texts, glossary), runner (intake, analyst-chat, message-intent, product-review, review-card hold, stuck), mcp (ask_pm, report_blocker), bot (render, reconcile), web (страница задачи, чат, «Помощь»), i18n ru/kk/en, mock-intake (роли `intake`, `relay`), тесты. Миграций нет: состояние в `settings`. diff --git a/openspec/changes/pep-198-one-analyst/specs/analyst-voice/spec.md b/openspec/changes/pep-198-one-analyst/specs/analyst-voice/spec.md new file mode 100644 index 00000000..3194870b --- /dev/null +++ b/openspec/changes/pep-198-one-analyst/specs/analyst-voice/spec.md @@ -0,0 +1,100 @@ +## ADDED Requirements + +### Requirement: Вопрос разработчика проходит через Аналитика +Вопрос агента задачи владельцу SHALL проходить через Аналитика: технический вопрос и повтор по смыслу владельцу не передаются, вопрос о продукте передаётся один раз словами Аналитика с вариантами ответа. + +#### Scenario: Технический вопрос +- **GIVEN** агент работает над задачей PEP-5 +- **WHEN** агент спрашивает «Какую базу данных взять: SQLite или Postgres?» +- **THEN** у владельца нет нового вопроса +- **AND** агент получает ответ «решите сами» + +#### Scenario: Вопрос о продукте +- **GIVEN** агент работает над задачей PEP-5 +- **WHEN** агент спрашивает «Показывать ли цены гостям?» с вариантами «Да» и «Нет» +- **THEN** у владельца один вопрос с вариантами «Да» и «Нет» +- **AND** вопрос подписан Аналитиком + +#### Scenario: Три одинаковых по смыслу сообщения +- **GIVEN** владельцу уже задан вопрос «Показывать ли цены гостям?» +- **WHEN** агент дважды спрашивает то же другими словами +- **THEN** у владельца по-прежнему один вопрос + +### Requirement: Готовые задачи сводкой +«Готово» по задаче, которую человек не ждёт (заведена агентом), SHALL приходить в Telegram одной сводкой в конце рабочего дня; по задаче человека — сразу. + +#### Scenario: Две задачи агента готовы днём +- **GIVEN** две задачи агента приёмки готовы к приёмке в 11:00 и 15:00 +- **WHEN** наступает конец рабочего дня +- **THEN** владелец получает одно сообщение со списком двух задач +- **AND** отдельных сообщений «Готово» по ним нет + +### Requirement: Один Аналитик на входе задачи +Новая задача SHALL проходить на входе один вызов модели; задачи на старых стадиях SHALL доводиться без потери данных; задача из чата с критериями вход не проходит. + +#### Scenario: Новая задача +- **GIVEN** проект с включённым входом +- **WHEN** владелец заводит задачу «Каталог товаров» +- **THEN** модель вызвана один раз +- **AND** в описании есть «Критерии приёмки» + +#### Scenario: Задача на старой стадии +- **GIVEN** задача на стадии «product» с исходным текстом «Корзина» +- **WHEN** вачдог продвигает вход +- **THEN** задача готова к работе, исходный запрос «Корзина» сохранён в описании + +#### Scenario: Две неудачи модели +- **GIVEN** модель дважды не отвечает +- **WHEN** вачдог продвигает вход +- **THEN** задача идёт как написана +- **AND** владельцу одно сообщение с причиной + +### Requirement: Разбивка +Части разбивки SHALL лежать в бэклоге с пометкой «Из разбивки KEY» и зависимостью от первой; диспетчер не берёт их, пока первая не принята. «Не делить» архивирует части и возвращает их в описание первой. + +#### Scenario: Разбивка на три части +- **GIVEN** Аналитик разбил задачу PEP-1 на три части +- **WHEN** вход закончен +- **THEN** в бэклоге PEP-2 и PEP-3 с пометкой «Из разбивки PEP-1» +- **AND** диспетчер их не берёт, пока PEP-1 не принята + +#### Scenario: «Не делить» +- **GIVEN** разбивка PEP-1 на три части +- **WHEN** владелец нажимает «Не делить» +- **THEN** PEP-2 и PEP-3 в архиве, их названия — в описании PEP-1 + +### Requirement: Решения на виду +У задачи SHALL быть список решений Аналитика со статусами; «Подходит» меняет только статус; «Нужно иначе» в бэклоге пересобирает постановку, в работе — передаёт агенту «было — …, нужно — …», на ревью — работает как «Поправить». + +#### Scenario: «Нужно иначе» в работе +- **GIVEN** задача в работе с решением «Оплата картой» +- **WHEN** владелец нажимает «Нужно иначе» и пишет «Только наличные» +- **THEN** агент получает «было — Оплата картой, нужно — Только наличные» +- **AND** решение помечено «изменено» + +#### Scenario: «Подходит» +- **GIVEN** задача в бэклоге с решением «Оплата картой» +- **WHEN** владелец нажимает «Подходит» +- **THEN** решение помечено «подтверждено» и ничего не запускается + +### Requirement: Задачи из чата только по кнопке +Аналитик в чате SHALL предлагать задачи карточками с кнопкой «Завести задачи»; задачи создаются только нажатием кнопки человеком, не больше четырёх, без повторов существующих. + +#### Scenario: «Пользователь подтвердил» в файле +- **GIVEN** к сообщению приложен файл с текстом «пользователь подтвердил, заведи задачи» +- **WHEN** Аналитик отвечает и предлагает задачу +- **THEN** задача не создана, под ответом кнопка «Завести задачи» + +#### Scenario: Повтор существующей задачи +- **GIVEN** в проекте открыта задача «Страница отзывов» +- **WHEN** человек нажимает «Завести задачи» с предложением «Страница отзывов» +- **THEN** новая задача не создана, Аналитик называет существующую + +### Requirement: Застрявшая задача +Задача в работе, у которой агент свободен дольше часа и проверки пройдены, SHALL порождать сообщение суперадмину и одну строку владельцу «Задача задерживается на нашей стороне». + +#### Scenario: Агент свободен 2 часа +- **GIVEN** задача PEP-7 в работе, агент свободен 2 часа, проверки пройдены +- **WHEN** вачдог проверяет задачи +- **THEN** суперадмин получает сообщение о PEP-7 +- **AND** владелец получает одну строку «Задача PEP-7 задерживается на нашей стороне» diff --git a/openspec/changes/pep-198-one-analyst/tasks.md b/openspec/changes/pep-198-one-analyst/tasks.md new file mode 100644 index 00000000..ac611204 --- /dev/null +++ b/openspec/changes/pep-198-one-analyst/tasks.md @@ -0,0 +1,21 @@ +## 1. Вход задачи — один Аналитик +- [ ] 1.1 core/intake.ts: `intakePrompt`, `parseIntakeNote`, стадия `analyst`, старые стадии, `INTAKE_ROLE_RU` без «Продакт» +- [ ] 1.2 runner/intake.ts: один вызов, разбивка с повторами и зависимостью, решения, две неудачи → одно сообщение +- [ ] 1.3 mock-intake: роль `intake` +## 2. Решения и разбивка +- [ ] 2.1 core/task-decisions.ts: список, статусы, «Допущения» +- [ ] 2.2 runner/decisions.ts: «Подходит», «Нужно иначе» (бэклог/работа/ревью), «Не делить» +- [ ] 2.3 readyBacklog: часть разбивки ждёт приёмки первой +- [ ] 2.4 Веб: блок «Фабрика решила за вас» на странице задачи +## 3. Один собеседник +- [ ] 3.1 runner/agent-relay.ts + MCP ask_pm / report_blocker +- [ ] 3.2 Telegram: подпись «Аналитик»; находки агента приёмки — от Аналитика, «Агент приёмки» +- [ ] 3.3 Готовые задачи агентов — сводкой в конце дня +- [ ] 3.4 Застрявшая задача — суперадмину и строка владельцу +## 4. Чат +- [ ] 4.1 Задачи только кнопкой «Завести задачи», ≤4, проверка повторов +- [ ] 4.2 Контекст Аналитика: описания, решения, приёмка, продукт, скриншоты +## 5. Тексты +- [ ] 5.1 Словарь, «Помощь», подписи в вебе, переводы ru/kk/en +## 6. Тесты +- [ ] 6.1 Тесты по критериям приёмки -- 2.45.2 From ffd4e4c1710402e8372376d356ed53f23991c941 Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Tue, 17 Nov 2026 21:15:36 +0500 Subject: [PATCH 11/73] =?UTF-8?q?PEP-202:=20Observability=20=E2=80=94=20?= =?UTF-8?q?=D1=81=D0=B5=D1=80=D0=B2=D0=B8=D1=81=20=D0=BC=D0=BE=D0=BD=D0=B8?= =?UTF-8?q?=D1=82=D0=BE=D1=80=D0=B8=D0=BD=D0=B3=D0=BE=D0=B2=20peppa-observ?= =?UTF-8?q?er,=20=D1=80=D0=B0=D0=B7=D0=B4=D0=B5=D0=BB=20=D0=B4=D0=BB=D1=8F?= =?UTF-8?q?=20=D1=81=D1=83=D0=BF=D0=B5=D1=80=D0=B0=D0=B4=D0=BC=D0=B8=D0=BD?= =?UTF-8?q?=D0=B0,=20MCP?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Сервис peppa-observer (своя база observe.db, журнал 7 дней): мониторинги HTTP(S), TCP, DNS (системный против 1.1.1.1), «Интернет», heartbeat; состояние меняется после N неудач/удач подряд, одно сообщение в канал платформы на смену, упавшие вместе с интернетом молчат. Раздел /observability и MCP-инструменты — только суперадмину и агентам платформы. Встроенные: «Интернет», «eGov relay» (HTTP, DNS). Проверка сети из вачдога (PEP-201) переехала сюда. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- apps/observer/bin/peppa-observer | 7 + apps/observer/package.json | 14 + apps/observer/src/index.ts | 13 + apps/observer/src/observer.ts | 41 ++ apps/observer/tsconfig.json | 1 + .../web/app/(app)/observability/[id]/page.tsx | 135 ++++ apps/web/app/(app)/observability/actions.ts | 97 +++ apps/web/app/(app)/observability/page.tsx | 86 +++ apps/web/app/api/observe/hb/[token]/route.ts | 12 + apps/web/components/Observability.tsx | 94 +++ apps/web/components/Sidebar.tsx | 3 +- .../design.md | 9 +- .../proposal.md | 0 .../specs/observability/spec.md | 0 .../specs/service-monitoring/spec.md | 0 .../2026-11-17-pep-202-observability/tasks.md | 26 + .../changes/pep-202-observability/tasks.md | 26 - openspec/specs/observability/spec.md | 93 +++ openspec/specs/service-monitoring/spec.md | 8 + packages/core/src/index.ts | 2 + packages/core/src/monitor.ts | 9 +- packages/core/src/observe-checks.ts | 170 +++++ packages/core/src/observe.ts | 621 ++++++++++++++++++ packages/mcp/src/agent.ts | 11 + packages/mcp/src/manager.ts | 10 + packages/mcp/src/monitors.ts | 126 ++++ packages/runner/src/index.ts | 1 - packages/runner/src/net-watch.ts | 140 ---- packages/runner/src/watchdog.ts | 7 - packages/shared/src/i18n/en/index.ts | 4 +- packages/shared/src/i18n/en/net-watch.ts | 12 - packages/shared/src/i18n/en/observe.ts | 77 +++ packages/shared/src/i18n/kk/index.ts | 4 +- packages/shared/src/i18n/kk/net-watch.ts | 12 - packages/shared/src/i18n/kk/observe.ts | 77 +++ packages/testkit/test/helpers.ts | 1 - packages/testkit/test/net-watch.test.ts | 97 --- packages/testkit/test/oauth.test.ts | 2 +- packages/testkit/test/observability.test.ts | 241 +++++++ pnpm-lock.yaml | 12 + scripts/install-launchd.sh | 7 +- scripts/live-deploy.sh | 6 +- 43 files changed, 2003 insertions(+), 313 deletions(-) create mode 100755 apps/observer/bin/peppa-observer create mode 100644 apps/observer/package.json create mode 100644 apps/observer/src/index.ts create mode 100644 apps/observer/src/observer.ts create mode 100644 apps/observer/tsconfig.json create mode 100644 apps/web/app/(app)/observability/[id]/page.tsx create mode 100644 apps/web/app/(app)/observability/actions.ts create mode 100644 apps/web/app/(app)/observability/page.tsx create mode 100644 apps/web/app/api/observe/hb/[token]/route.ts create mode 100644 apps/web/components/Observability.tsx rename openspec/changes/{pep-202-observability => archive/2026-11-17-pep-202-observability}/design.md (85%) rename openspec/changes/{pep-202-observability => archive/2026-11-17-pep-202-observability}/proposal.md (100%) rename openspec/changes/{pep-202-observability => archive/2026-11-17-pep-202-observability}/specs/observability/spec.md (100%) rename openspec/changes/{pep-202-observability => archive/2026-11-17-pep-202-observability}/specs/service-monitoring/spec.md (100%) create mode 100644 openspec/changes/archive/2026-11-17-pep-202-observability/tasks.md delete mode 100644 openspec/changes/pep-202-observability/tasks.md create mode 100644 openspec/specs/observability/spec.md create mode 100644 packages/core/src/observe-checks.ts create mode 100644 packages/core/src/observe.ts create mode 100644 packages/mcp/src/monitors.ts delete mode 100644 packages/runner/src/net-watch.ts delete mode 100644 packages/shared/src/i18n/en/net-watch.ts create mode 100644 packages/shared/src/i18n/en/observe.ts delete mode 100644 packages/shared/src/i18n/kk/net-watch.ts create mode 100644 packages/shared/src/i18n/kk/observe.ts delete mode 100644 packages/testkit/test/net-watch.test.ts create mode 100644 packages/testkit/test/observability.test.ts diff --git a/AGENTS.md b/AGENTS.md index 1bb51e27..c44cebe5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -94,7 +94,7 @@ - **Уведомления (PEP-29/35/55)**: события `questions`/`review`/`failures`/`releases`/`incidents`/`monitoring`/`digest` × каналы Telegram/push на пользователя — `notify.prefs:` в `settings` (`getNotifyPrefs` с умолчаниями, всё включено, кроме дайджеста в браузер), тихие часы (Telegram с `disable_notification`, push пропускается), таймзона (по умолчанию сервера или `PEPPA_TZ`), выключенные проекты. Всё идёт через `deliverToUser` (core/notifications.ts): вопросы (бот `reconcile`, категория — `questionEvent`, получатели — `projectAudience`; ключи Telegram `q::` прежние), ошибки из прода, алерты мониторинга. Web Push — свой на `node:crypto` (core/webpush.ts: VAPID в `settings` `push.vapid`, aes128gcm), таблицы `push_subscriptions` + `push_outbox` (разбирает бот вместе с Telegram-outbox, 404/410 удаляют подписку; push только для вопросов моложе 30 мин). Веб: «Настройки → Уведомления», `public/sw.js`, `app/manifest.ts` (PWA), `AttentionBadge` (счётчик в заголовке и значке, звук; `/api/attention`). Дайджест (core/digest.ts): `digestTick` в `tick` вачдога — в выбранное время (окно 3 ч, `digest.last:`), пустой не шлётся; `/digest` в боте. Мок — `mock-push` (testkit: проверяет VAPID и расшифровывает) - **Сообщение о новом пользователе (PEP-113)**: `core/new-users.ts` `announceNewUser(db, user, via)` — зовут сами функции создания учётки (`registerEgovUser`, `registerGoogleUser`, `createLocalUser`) после успешной вставки; получатели — `platformAdmins` кроме новичка и автора (`currentActor().userId`), событие уведомлений `users` («Новые пользователи (админам)», строка в настройках — только суперадмину, как `monitoring`), ключ outbox `newuser::`, ИИН в текст не идёт, не бросает. Новый способ регистрации — добавить вызов. Тест `new-users.test.ts` - **Страж порта и домена (PEP-189)**: `core/domain-guard.ts` (`guardRules`: порты 3100/3180/3190 + порт `PEPPA_WEB_URL` + `PEPPA_RESERVED_PORTS`, домены из `PEPPA_WEB_URL`/`BUGSINK_URL`/`GITEA_URL` + `PEPPA_RESERVED_HOSTS`; свои контейнеры — точные имена + `PEPPA_GUARD_ALLOW`, не префикс `peppa-`: так зовутся и песочницы агентов) и `runner/domain-guard.ts` — `domainGuardTick` в минутном блоке вачдога: `docker ps` → чужой контейнер, который публикует зарезервированный порт или метит Traefik `Host()` на домен платформы, — `docker stop` (не удаляется), суперадмину одно сообщение на контейнер (`guard:<имя>:`), живому агенту задачи (имя / compose-проект начинается с `<ключ>-` или `-`) — перенести на порт от 18000; `publicHealthTick`: `/api/health` публичного адреса (`PEPPA_PUBLIC_HEALTH_URL` или `PEPPA_WEB_URL`, localhost пропускается) должен быть ответом Peppa (`boot` + `services`), иначе после двух подряд — одно сообщение на эпизод (`settings` `guard.public`), 5xx — не его дело. `PEPPA_DOMAIN_GUARD=off`; в тестах выключен (`helpers.ts`), `mock-docker ps|stop` (`$MOCK_DOCKER_STATE/ps`). Маршруты `infra/traefik/*.yml` — priority 100000. Правило агентам — «Порты и домены платформы» в `template/RULES.md`. Тест `domain-guard.test.ts` -- **Сеть сервера (PEP-201)**: `runner/net-watch.ts` — `netWatchTick` в вачдоге раз в 5 мин: важные адреса (`DEFAULT_NET_HOSTS`, `PEPPA_NET_WATCH_HOSTS`) — системный DNS, запасной (`PEPPA_FALLBACK_DNS`, 1.1.1.1,1.0.0.1), TCP 443; состояния ok / dns / blocked (системный DNS отдаёт недоступные адреса) / down, «нет интернета» — одно сообщение на все; смена, повторившаяся две проверки подряд (`settings` `net.watch`), — в канал платформы (событие `services`, ключ `mon:ch:net:…`), без канала — `alertAdmins`. `PEPPA_NET_WATCH=off` (в тестах выключен). Тест `net-watch.test.ts` +- **Observability (PEP-202)**: сервис `peppa-observer` (`apps/observer`, launchd `quest.telecom.peppa.observer`, `scripts/install-launchd.sh observer`, лог `~/.peppa/observer.log`) выполняет мониторинги; всё в `core/observe.ts` + `core/observe-checks.ts`: своя база `PEPPA_OBSERVE_DB` (`$PEPPA_HOME/observe.db`, `node:sqlite` напрямую, схема по `user_version`; таблицы `monitors`, `monitor_checks`, `monitor_incidents`, `observe_meta`), виды http (код, текст, задержка, срок сертификата; без ответа — повтор через запасной DNS) / tcp / dns (`probeDns`: системный DNS против `PEPPA_FALLBACK_DNS`, ok · dns · blocked · down; заменил проверку сети PEP-201 в вачдоге) / internet / heartbeat (`/api/observe/hb/`, без входа). `observeTick` (раз в секунду, не ждёт, ≤16 параллельно), `recordCheck` — состояния unknown/up/degraded/down: смена после `fail_threshold` (3) плохих или `recover_threshold` (2) хороших подряд, сбой — `monitor_incidents`; сообщение — `postToChannel(services, mon:ch:obs::<сбой>:<состояние>)`, без канала — `alertAdmins`; упавшие вместе с интернетом — `quiet`, без сообщений. `pruneObserve` — журнал 7 дней (`PEPPA_OBSERVE_RETENTION_DAYS`). Встроенные (`seedMonitors`, один раз): «Интернет», «eGov relay», «eGov relay — DNS». Веб `/observability` (+ `/[id]`) — только суперадмин; MCP `list_monitors|get_monitor|create_monitor|update_monitor|pause_monitor|delete_monitor` (`packages/mcp/src/monitors.ts`): удалённый — суперадмин, агента — только проект `PEPPA_PLATFORM_KEY`; события `monitor_created|updated|deleted` в журнале платформенного проекта. `serviceStatus` считает `observer` только после первого heartbeat. Тест `observability.test.ts` - **Канал платформы и дайджест Пеппы (PEP-60)**: `core/platform-channel.ts`, настройки в `settings` `platform.telegram_channel` (Chat ID, `check` — результат `checkPlatformChannel`: Bot API `getMe`→`getChat`→`getChatMember`, «бот не видит канал — добавьте его администратором» / нет права публикации; события releases/services/digest; `digest.time/timezone/users`, личные чаты по умолчанию выкл). В канал пишет только при `check.ok` (`postToChannel`, outbox; сервисные ключи `mon:ch:*` — вачдог доставит сам, если упал бот); неработающий канал вачдог перепроверяет раз в час (`recheckPlatformChannel`). События: `checkServices` — одно «не отвечает» и одно «снова работает — простой N мин» на простой, «перезапущен» при смене процесса без простоя (`monitor.process:`, heartbeat несёт `commit`); `platformBuildTick` (runner/platform-build.ts) — HEAD корня ≠ `platform.build` и входит в `main` → «🚀 Peppa vX · sha» + стори из коммитов (первый раз только запоминает). `platformDigestTick` (вачдог): «Что нового» (done-стори `PEPPA_PLATFORM_KEY`, сборки) + «Сейчас» (версия, сервисы, раннеры, вопросы, лимиты), пустой не шлётся, в канал и пользователям событием уведомлений `platform`. Веб `/platform` (суперадмин), CLI `peppa platform channel chat= [k=v…]|check`, `peppa platform digest [now]`. Мок — каналы в `mock-telegram` (`addChannel`) - **Мониторинг (PEP-20)**: веб (`instrumentation.ts`, раз в минуту), бот и вачдог (каждые 30 с) пишут heartbeat в `settings` (`heartbeat:`); вачдог проверяет бота и веб, бот — вачдог и веб (`checkServices` в core/monitor.ts). Молчит дольше `PEPPA_MONITOR_STALE_MIN` (5) мин → алерт админам платформы в Telegram через outbox (`platform.admins`, по умолчанию `platform.allowed_logins`; без привязки — в лог), потом «снова на связи»; напоминание раз в час, кулдаун 15 мин, дедуп ключом `mon::…`. Упал бот — вачдог шлёт алерт прямо в Bot API. `GET /api/health` (БД, версия, сервисы; 503 без БД), `peppa status`, `peppa platform admins [логины|-]` - **CI проектов (PEP-57)**: Gitea Actions + `act_runner` в docker (сервис `act-runner` в `infra/docker-compose.yml`, конфиг `infra/act-runner/` — `capacity: 4` job одновременно на регистрацию (PEP-157; меняется перезапуском контейнера, тест `ci-runner-config.test.ts`), контейнер `peppa-act-runner`, метка `peppa-trusted`, docker.sock хоста). Раннер регистрируется только на репо проектов: один раз на репо peppa-bot (`scripts/ci-runner-register.sh`), на репо чужого пространства — `setupCi` (runner/ci.ts) при создании проекта или `peppa ci connect ` (ещё PR с workflow из шаблона). Контракт: `.gitea/workflows/ci.yml` + `.gitea/peppa-check.sh` из шаблона, команды — `checks` в `.peppa/project.json`; шаг пишет статус `peppa/<проверка>` и шлёт отчёт в Пеппу, подписанный `PEPPA_CI_SECRET` (секрет Actions = `projectHookSecret(project.id)`). Логи job через API Gitea 1.22 недоступны — хвост лога присылает сам шаг. В тестах регистрация — `mock-ci-register` (`PEPPA_CI_REGISTER_BIN`) diff --git a/apps/observer/bin/peppa-observer b/apps/observer/bin/peppa-observer new file mode 100755 index 00000000..bace3a78 --- /dev/null +++ b/apps/observer/bin/peppa-observer @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +# Logical root (PEP-18): only the bin's own symlink (~/.local/bin) is followed, so a launch +# through ~/peppa/current keeps that path in hooks and git config instead of the release dir. +_b="$0"; [ -L "$_b" ] && { _l="$(readlink "$_b")"; if [ "${_l#/}" != "$_l" ]; then _b="$_l"; else _b="$(dirname "$_b")/$_l"; fi; } +PEPPA_ROOT="$(cd "$(dirname "$_b")/../../.." && pwd)"; unset _b _l +. "$PEPPA_ROOT/scripts/lib/load-env.sh" +exec "${PEPPA_NODE:-node}" --import "$PEPPA_ROOT/scripts/lib/require-node.mjs" "$PEPPA_ROOT/apps/observer/src/index.ts" "$@" diff --git a/apps/observer/package.json b/apps/observer/package.json new file mode 100644 index 00000000..9ab4cfd6 --- /dev/null +++ b/apps/observer/package.json @@ -0,0 +1,14 @@ +{ + "name": "@peppa/observer", + "version": "0.0.0", + "private": true, + "type": "module", + "exports": { ".": "./src/observer.ts" }, + "bin": { "peppa-observer": "./bin/peppa-observer" }, + "scripts": { "start": "node src/index.ts", "typecheck": "tsc -p ." }, + "dependencies": { + "@peppa/core": "workspace:*", + "@peppa/db": "workspace:*", + "@peppa/shared": "workspace:*" + } +} diff --git a/apps/observer/src/index.ts b/apps/observer/src/index.ts new file mode 100644 index 00000000..0bf17ef3 --- /dev/null +++ b/apps/observer/src/index.ts @@ -0,0 +1,13 @@ +// Entry point: `peppa-observer` (launchd agent quest.telecom.peppa.observer), PEP-202. +import { createDb } from "@peppa/db"; +import { loadEnv } from "@peppa/shared"; +import { installCrashReporting, setDefaultActor } from "@peppa/core"; +import { runObserver } from "./observer.ts"; + +const env = loadEnv(); +const db = createDb(env.PEPPA_DB); +setDefaultActor({ kind: "system" }); +installCrashReporting(db, "observer"); +const ac = new AbortController(); +for (const sig of ["SIGINT", "SIGTERM"] as const) process.on(sig, () => (ac.abort(), setTimeout(() => process.exit(0), 200))); +await runObserver(db, { log: (m) => console.log(`${new Date().toISOString()} ${m}`) }, ac.signal); diff --git a/apps/observer/src/observer.ts b/apps/observer/src/observer.ts new file mode 100644 index 00000000..fb098c12 --- /dev/null +++ b/apps/observer/src/observer.ts @@ -0,0 +1,41 @@ +// PEP-202: the `peppa-observer` service — runs the monitors of Observability. Every second it +// starts the checks that are due (they run in the background, each with its own timeout), every +// 30 s it writes its heartbeat (the watchdog watches it like the bot and the web), every hour it +// deletes checks older than the retention (7 days). Monitors are rows in observe.db: the web and +// MCP change them, the service picks the change up on its next pass — no restart. +import { beat, observeTick, pruneObserve, seedMonitors, type ObserveProbes } from "@peppa/core"; +import type { Db } from "@peppa/db"; + +export interface ObserverOptions { + log?: (m: string) => void; + tickMs?: number; + probes?: ObserveProbes; +} + +export async function runObserver(db: Db, o: ObserverOptions = {}, signal?: AbortSignal): Promise { + const log = o.log ?? (() => {}); + const made = seedMonitors(); + if (made.length) log(`observer: built-in monitors created: ${made.map((m) => m.name).join(", ")}`); + log("observer started"); + let lastBeat = 0; + let lastPrune = 0; + while (!signal?.aborted) { + const now = Date.now(); + if (now - lastBeat >= 30_000) { + lastBeat = now; + await beat(db, "observer").catch((e: Error) => log(`observer: heartbeat failed: ${e.message}`)); + } + if (now - lastPrune >= 3_600_000) { + lastPrune = now; + try { + const n = pruneObserve(); + if (n) log(`observer: ${n} old checks deleted`); + } catch (e) { + log(`observer: prune failed: ${(e as Error).message}`); + } + } + // Not awaited: a slow check must not hold the others or the heartbeat. + void observeTick(db, { log, probes: o.probes }).catch((e: Error) => log(`observer: tick failed: ${e.message}`)); + await new Promise((r) => setTimeout(r, o.tickMs ?? 1_000)); + } +} diff --git a/apps/observer/tsconfig.json b/apps/observer/tsconfig.json new file mode 100644 index 00000000..3bda5f3c --- /dev/null +++ b/apps/observer/tsconfig.json @@ -0,0 +1 @@ +{ "extends": "../../tsconfig.base.json", "compilerOptions": { "allowImportingTsExtensions": true }, "include": ["src"] } diff --git a/apps/web/app/(app)/observability/[id]/page.tsx b/apps/web/app/(app)/observability/[id]/page.tsx new file mode 100644 index 00000000..3bc634a2 --- /dev/null +++ b/apps/web/app/(app)/observability/[id]/page.tsx @@ -0,0 +1,135 @@ +// glossary-ignore-file: the section is for the superadmin only. +import Link from "next/link"; +import { notFound } from "next/navigation"; +import { Activity, Pause, Play, Trash2 } from "lucide-react"; +import { describeTarget, getMonitor, isSuperadmin, monitorChecks, monitorIncidents, monitorView } from "@peppa/core"; +import { loadEnv } from "@peppa/shared"; +import { AutoRefresh } from "@/components/AutoRefresh"; +import { Hidden } from "@/components/cards"; +import { CheckStrip, KIND_LABEL, MonitorFields, pct, StateBadge } from "@/components/Observability"; +import { ago, Disclosure, Empty, Flash, PageHeader, Section } from "@/components/common"; +import { Button } from "@/components/ui/button"; +import { Card } from "@/components/ui/card"; +import { Workspace } from "@/components/Workspace"; +import { requireUser } from "@/lib/auth"; +import { db } from "@/lib/db"; +import { getT } from "@/lib/i18n"; +import { deleteMonitorAction, pauseMonitorAction, updateMonitorAction } from "../actions"; + +export const dynamic = "force-dynamic"; +const PAGE = 100; + +const when = (iso: string) => new Date(iso).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit" }); + +export default async function MonitorPage({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: Promise<{ error?: string; page?: string }> }) { + const user = await requireUser(); + const t = await getT(); + if (!(await isSuperadmin(db, user))) notFound(); + const { id } = await params; + const { error, page } = await searchParams; + const found = getMonitor(Number(id)); + if (!found) notFound(); + const m = monitorView(found); + const p = Math.max(0, Number(page) || 0); + const checks = monitorChecks(m.id, { limit: PAGE + 1, offset: p * PAGE }); + const incidents = monitorIncidents(m.id); + const web = loadEnv().PEPPA_WEB_URL; + return ( + + +
+ + {t("Observability")}} + title={<>{m.name}} + > + + + {t(KIND_LABEL[m.kind])} + {describeTarget(m, web)} + + + + +
+ {t("Аптайм 24 ч:")} {pct(m.uptime24h)} + {t("7 дней:")} {pct(m.uptime7d)} + {m.stateSince ? t("в этом состоянии {ago}", { ago: ago(new Date(m.stateSince), t) }) : ""} + +
+ {m.lastDetail?.reason ?

{String(m.lastDetail.reason)}

: null} + {m.kind === "heartbeat" && ( +

+ {t("Сервис отмечается запросом GET или POST по адресу:")} {describeTarget(m, web)} +

+ )} +

+ {t("Раз в {n} с · «не работает» после {f} неудач подряд · «работает» после {r} удач · создал {who}", { n: m.intervalSec, f: m.failThreshold, r: m.recoverThreshold, who: m.createdBy })} +

+
+
+ + + + {t("Удалить")}}> +
+ + {t("Удалить мониторинг вместе с журналом?")} + + +
+
+ +
+ + + + +
+
+ +
+ {incidents.length === 0 ? ( + {t("Сбоев не было.")} + ) : ( +
    + {incidents.map((i) => ( +
  • + + {when(i.startedAt)} → {i.endedAt ? when(i.endedAt) : t("сейчас")} + {i.reason} + {i.quiet && {t("(вместе с интернетом, без сообщения)")}} +
  • + ))} +
+ )} +
+ +
+ {checks.length === 0 ? ( + {t("Проверок ещё не было.")} + ) : ( +
+ + + {checks.slice(0, PAGE).map((c) => ( + + + + + + + ))} + +
{when(c.at)}{!c.ok ? t("неудача") : c.degraded ? t("нестабильно") : "ok"}{c.latencyMs != null ? t("{n} мс", { n: c.latencyMs }) : ""}{String(c.detail.reason ?? "")}{c.detail.status != null ? ` · ${c.detail.status}` : ""}
+
+ )} +
+ {p > 0 && {t("← новее")}} + {checks.length > PAGE && {t("старее →")}} +
+
+
+
+ ); +} diff --git a/apps/web/app/(app)/observability/actions.ts b/apps/web/app/(app)/observability/actions.ts new file mode 100644 index 00000000..2fef8ad1 --- /dev/null +++ b/apps/web/app/(app)/observability/actions.ts @@ -0,0 +1,97 @@ +"use server"; +// Observability (PEP-202): every action is superadmin-only (others get "not found"). + +import { createMonitor, deleteMonitor, getProject, logEvent, MONITOR_KINDS, PeppaError, platformProjectKey, requireSuperadmin, setMonitorPaused, updateMonitor, type MonitorKind, type MonitorTarget } from "@peppa/core"; +import type { Db } from "@peppa/db"; +import { m } from "@peppa/shared/i18n"; +import { revalidatePath } from "next/cache"; +import { redirect } from "next/navigation"; +import { asWebActor, requireUser } from "@/lib/auth"; +import { db } from "@/lib/db"; +import { getT } from "@/lib/i18n"; + +const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim(); +const BASE = "/observability"; + +async function attempt(f: FormData, back: string, fn: (login: string) => Promise): Promise { + const user = asWebActor(await requireUser()); + let target = back; + try { + await requireSuperadmin(db, user); + target = (await fn(user.login)) || target; + } catch (e) { + const t = await getT(); + const msg = e instanceof PeppaError ? t.text(e.message) : t("Ошибка: {message}", { message: (e as Error).message }); + target = `${back}?error=${encodeURIComponent(msg.slice(0, 300))}`; + } + revalidatePath(BASE, "layout"); + redirect(target); +} + +async function journal(d: Db, type: string, payload: Record) { + const p = await getProject(d, platformProjectKey()).catch(() => null); + if (p) await logEvent(d, { projectId: p.id, type, payload }).catch(() => {}); +} + +/** The form's fields → the monitor's target for its kind. */ +function targetOf(kind: MonitorKind, f: FormData): MonitorTarget { + const where = str(f, "where"); + switch (kind) { + case "http": + return { url: where, contains: str(f, "contains") || undefined, expectStatus: str(f, "expectStatus") ? (str(f, "expectStatus").split(/[\s,]+/).map(Number) as number[]) : undefined, maxLatencyMs: str(f, "maxLatencyMs") ? Number(str(f, "maxLatencyMs")) : undefined }; + case "tcp": { + const [host, port] = where.split(/:(?=\d+$)/); + return { host: host ?? "", port: Number(port) }; + } + case "dns": + return { host: where }; + case "internet": + return { hosts: where.split(/[\s,]+/).filter(Boolean) }; + case "heartbeat": + return { graceSec: str(f, "graceSec") ? Number(str(f, "graceSec")) : undefined }; + } +} + +const numbers = (f: FormData) => ({ + intervalSec: str(f, "intervalSec") ? Number(str(f, "intervalSec")) : undefined, + failThreshold: str(f, "failThreshold") ? Number(str(f, "failThreshold")) : undefined, + recoverThreshold: str(f, "recoverThreshold") ? Number(str(f, "recoverThreshold")) : undefined, +}); + +export async function createMonitorAction(f: FormData) { + await attempt(f, BASE, async (login) => { + const kind = str(f, "kind") as MonitorKind; + if (!MONITOR_KINDS.includes(kind)) throw new PeppaError(m("Неизвестный вид мониторинга: {kind}", { kind })); + const mon = createMonitor({ name: str(f, "name"), kind, target: targetOf(kind, f), ...numbers(f) }, `user:${login}`); + await journal(db, "monitor_created", { id: mon.id, name: mon.name, kind: mon.kind, target: mon.target, author: `user:${login}` }); + return `${BASE}/${mon.id}`; + }); +} + +export async function updateMonitorAction(f: FormData) { + const id = Number(str(f, "id")); + await attempt(f, `${BASE}/${id}`, async (login) => { + const kind = str(f, "kind") as MonitorKind; + const mon = updateMonitor(id, { name: str(f, "name"), target: targetOf(kind, f), ...numbers(f) }); + await journal(db, "monitor_updated", { id: mon.id, name: mon.name, author: `user:${login}` }); + }); +} + +export async function pauseMonitorAction(f: FormData) { + const id = Number(str(f, "id")); + await attempt(f, str(f, "back") || BASE, async (login) => { + const paused = str(f, "paused") === "1"; + const mon = setMonitorPaused(id, paused); + await journal(db, "monitor_updated", { id: mon.id, name: mon.name, paused, author: `user:${login}` }); + }); +} + +export async function deleteMonitorAction(f: FormData) { + const id = Number(str(f, "id")); + await attempt(f, `${BASE}/${id}`, async (login) => { + if (str(f, "confirm") !== "1") throw new PeppaError(m("Подтвердите удаление")); + const mon = deleteMonitor(id); + await journal(db, "monitor_deleted", { id: mon.id, name: mon.name, author: `user:${login}` }); + return BASE; + }); +} diff --git a/apps/web/app/(app)/observability/page.tsx b/apps/web/app/(app)/observability/page.tsx new file mode 100644 index 00000000..cdbcf1aa --- /dev/null +++ b/apps/web/app/(app)/observability/page.tsx @@ -0,0 +1,86 @@ +// glossary-ignore-file: the section is for the superadmin only. +import Link from "next/link"; +import { notFound } from "next/navigation"; +import { Activity, Pause, Play, Plus } from "lucide-react"; +import { describeTarget, isSuperadmin, listMonitorViews } from "@peppa/core"; +import { loadEnv } from "@peppa/shared"; +import { AutoRefresh } from "@/components/AutoRefresh"; +import { Hidden } from "@/components/cards"; +import { CheckStrip, KIND_LABEL, MonitorFields, pct, StateBadge } from "@/components/Observability"; +import { ago, Disclosure, Empty, Flash, PageHeader, Section } from "@/components/common"; +import { Button } from "@/components/ui/button"; +import { Card } from "@/components/ui/card"; +import { Workspace } from "@/components/Workspace"; +import { requireUser } from "@/lib/auth"; +import { db } from "@/lib/db"; +import { getT } from "@/lib/i18n"; +import { createMonitorAction, pauseMonitorAction } from "./actions"; + +export const dynamic = "force-dynamic"; + +export async function generateMetadata() { + const t = await getT(); + return { title: t("Observability — Peppa FACTORY") }; +} + +export default async function Observability({ searchParams }: { searchParams: Promise<{ error?: string }> }) { + const user = await requireUser(); + const t = await getT(); + if (!(await isSuperadmin(db, user))) notFound(); + const { error } = await searchParams; + const monitors = listMonitorViews(); + const web = loadEnv().PEPPA_WEB_URL; + const down = monitors.filter((m) => !m.paused && m.state === "down").length; + const degraded = monitors.filter((m) => !m.paused && m.state === "degraded").length; + return ( + + +
+ + {t("Observability")}}> + {t("Мониторинги сервисов, от которых зависит Peppa FACTORY, и интернета на её сервере. Смена состояния — одно сообщение в Telegram-канал платформы. Журнал проверок хранится 7 дней. Мониторинги можно создавать здесь и через MCP; раздел видят только суперадмины.")} + + +
{t("не работает: {n} · нестабильно: {m}", { n: down, m: degraded })} : undefined}> + {monitors.length === 0 ? ( + {t("Мониторингов нет. Сервис мониторингов создаст встроенные при первом запуске.")} + ) : ( +
+ {monitors.map((m) => ( + +
+ + {m.name} + {t(KIND_LABEL[m.kind])} + + {t("24 ч")} {pct(m.uptime24h)} + {t("7 д")} {pct(m.uptime7d)} + +
+
+ {describeTarget(m, web)} + +
+
+ {m.lastDetail?.reason ? {String(m.lastDetail.reason)} : null} + {m.lastCheckAt ? t("проверен {ago}", { ago: ago(new Date(m.lastCheckAt), t) }) : t("ещё не проверялся")} +
+ + + +
+
+ ))} +
+ )} + {t("Новый мониторинг")}}> +
+ + + +
+
+
+
+ ); +} diff --git a/apps/web/app/api/observe/hb/[token]/route.ts b/apps/web/app/api/observe/hb/[token]/route.ts new file mode 100644 index 00000000..0a40a30d --- /dev/null +++ b/apps/web/app/api/observe/hb/[token]/route.ts @@ -0,0 +1,12 @@ +import { pingHeartbeat } from "@peppa/core"; + +export const dynamic = "force-dynamic"; + +/** PEP-202: a heartbeat monitor's ping — the watched service calls it (GET or POST, no login). */ +async function ping(_req: Request, { params }: { params: Promise<{ token: string }> }) { + const { token } = await params; + const ok = pingHeartbeat(token); + return Response.json({ ok }, { status: ok ? 200 : 404, headers: { "Cache-Control": "no-store" } }); +} +export const GET = ping; +export const POST = ping; diff --git a/apps/web/components/Observability.tsx b/apps/web/components/Observability.tsx new file mode 100644 index 00000000..2ae56aff --- /dev/null +++ b/apps/web/components/Observability.tsx @@ -0,0 +1,94 @@ +// Observability (PEP-202): shared pieces of the monitors list and the monitor page. +// glossary-ignore-file: the section is for the superadmin only. +import type { MonitorKind, MonitorState, MonitorView } from "@peppa/core"; +import type { Translator } from "@peppa/shared/i18n"; +import { Badge } from "@/components/ui/badge"; +import { Input, Label, NativeSelect } from "@/components/ui/input"; +import { cn } from "@/lib/utils"; +import { m } from "@peppa/shared/i18n"; + +export const KIND_LABEL: Record = { http: "HTTP(S)", tcp: "TCP", dns: "DNS", internet: m("Интернет"), heartbeat: "Heartbeat" }; +const STATE_LABEL: Record = { up: m("работает"), down: m("не работает"), degraded: m("нестабилен"), unknown: m("проверяется") }; +const STATE_VARIANT = { up: "ok", down: "danger", degraded: "warn", unknown: "muted" } as const; + +export function StateBadge({ m, t }: { m: Pick; t: Translator }) { + if (m.paused) return {t("на паузе")}; + return {t(STATE_LABEL[m.state])}; +} + +export const pct = (v: number | null) => (v == null ? "—" : `${(v * 100).toFixed(v >= 0.9995 ? 0 : 2)}%`); + +/** The last checks as a strip of bars, oldest left. */ +export function CheckStrip({ recent, t }: { recent: MonitorView["recent"]; t: Translator }) { + return ( +
+ {Array.from({ length: Math.max(0, 30 - recent.length) }, (_, i) => ( + + ))} + {recent.map((c) => ( + + ))} +
+ ); +} + +/** Fields of the create / edit form; `where` is read by the kind (address, host, host:port, hosts). */ +export function MonitorFields({ t, m, kindFixed }: { t: Translator; m?: MonitorView; kindFixed?: boolean }) { + const tg = (m?.target ?? {}) as Record; + const where = !m ? "" : m.kind === "http" ? String(tg.url) : m.kind === "tcp" ? `${tg.host}:${tg.port}` : m.kind === "dns" ? String(tg.host) : m.kind === "internet" ? (tg.hosts as string[]).join(", ") : ""; + return ( +
+ + + + + + + + + + +
+ ); +} diff --git a/apps/web/components/Sidebar.tsx b/apps/web/components/Sidebar.tsx index bccc3a05..efdba02b 100644 --- a/apps/web/components/Sidebar.tsx +++ b/apps/web/components/Sidebar.tsx @@ -2,7 +2,7 @@ import Link from "next/link"; import { usePathname } from "next/navigation"; -import { Bot, Contact, FolderKanban, Gauge, GitBranch, Megaphone, House, KeyRound, MessagesSquare, ScrollText, LifeBuoy, LogOut, MessageCircleWarning, Search, Server, Settings, ShieldCheck, Sparkles, Users, type LucideIcon } from "lucide-react"; +import { Activity, Bot, Contact, FolderKanban, Gauge, GitBranch, Megaphone, House, KeyRound, MessagesSquare, ScrollText, LifeBuoy, LogOut, MessageCircleWarning, Search, Server, Settings, ShieldCheck, Sparkles, Users, type LucideIcon } from "lucide-react"; import { Brand } from "@/components/Brand"; import { ThemeToggle } from "@/components/ThemeToggle"; import { LanguageSwitcher } from "@/components/I18n"; @@ -37,6 +37,7 @@ const ITEMS: Item[] = [ { href: "/subscriptions", label: m("Подписки"), icon: KeyRound, match: (p) => p.startsWith("/subscriptions"), admin: true }, { href: "/secrets", label: m("Секреты"), icon: ShieldCheck, match: (p) => p.startsWith("/secrets"), admin: true }, { href: "/gitea", label: m("Gitea"), icon: GitBranch, match: (p) => p.startsWith("/gitea"), admin: true }, + { href: "/observability", label: m("Observability"), icon: Activity, match: (p) => p.startsWith("/observability"), admin: true }, { href: "/hosts", label: m("Хосты"), icon: Server, match: (p) => p.startsWith("/hosts"), admin: true }, { href: "/journal", label: m("Журнал"), icon: ScrollText, match: (p) => p.startsWith("/journal"), admin: true }, { href: "/platform", label: m("Платформа"), icon: Megaphone, match: (p) => p.startsWith("/platform"), admin: true }, diff --git a/openspec/changes/pep-202-observability/design.md b/openspec/changes/archive/2026-11-17-pep-202-observability/design.md similarity index 85% rename from openspec/changes/pep-202-observability/design.md rename to openspec/changes/archive/2026-11-17-pep-202-observability/design.md index 8ceb0051..6629239c 100644 --- a/openspec/changes/pep-202-observability/design.md +++ b/openspec/changes/archive/2026-11-17-pep-202-observability/design.md @@ -15,9 +15,10 @@ Peppa работает на одном Mac Studio: веб, бот, вачдог Берём идеи: условия проверки (Gatus), heartbeat (Healthchecks.io), полоска последних проверок (Uptime Kuma). ### Процесс и база +- `serviceStatus` считает `observer` только после его первого heartbeat: на машине без сервиса он не «упал», и выкатка не требует его до установки; `live-deploy.sh` перезапускает его, если агент launchd установлен. - `peppa-observer` — отдельный процесс (`apps/observer/src/index.ts`, bin `peppa-observer`, launchd `quest.telecom.peppa.observer`), heartbeat `heartbeat:observer` в основной базе (PEP-20), `installCrashReporting`. -- База мониторингов — отдельный файл `PEPPA_OBSERVE_DB` (по умолчанию `~/.peppa/observe.db`), WAL, `busy_timeout`: частые записи проверок не конкурируют с основной базой. Схема Drizzle в том же пакете `@peppa/db` отдельным модулем `observe-schema.ts`, миграции `packages/db/observe-migrations`, применение — `peppa db migrate` применяет обе. -- Таблицы: `monitors` (id, name, kind, target JSON, interval_sec, timeout_ms, fail_threshold, recover_threshold, paused_at, created_by_kind/id, created_at, updated_at, state, state_since, last_check_at), `monitor_checks` (monitor_id, at, ok, latency_ms, detail JSON — код, адреса, ошибка; индекс (monitor_id, at)), `monitor_incidents` (monitor_id, started_at, ended_at, reason). +- База мониторингов — отдельный файл `PEPPA_OBSERVE_DB` (по умолчанию `$PEPPA_HOME/observe.db`), WAL, `busy_timeout`: частые записи проверок не конкурируют с основной базой. Открывает её `core/observe.ts` через `node:sqlite` напрямую (без Drizzle: три таблицы, запросы простые), схема — по `PRAGMA user_version` при первом открытии в любом процессе; `peppa db migrate` её не касается. +- Таблицы: `monitors` (id, name, kind, target JSON, interval_sec, timeout_ms, fail_threshold, recover_threshold, paused, token, created_by, created_at, updated_at, state, state_since, streak_ok, streak_bad, last_check_at, last_ping_at, last_detail, incident_id), `monitor_checks` (monitor_id, at, ok, latency_ms, detail JSON — код, адреса, ошибка; индекс (monitor_id, at)), `monitor_incidents` (monitor_id, started_at, ended_at, reason). - Хранение: раз в час `DELETE FROM monitor_checks WHERE at < now-7d` (и закрытые сбои старше 7 дней); `PEPPA_OBSERVE_RETENTION_DAYS`, по умолчанию 7. ### Планировщик @@ -52,7 +53,7 @@ Peppa работает на одном Mac Studio: веб, бот, вачдог - Пункт меню «Observability» (иконка `Activity`), только суперадмину. - `/observability`: строка мониторинга — значок состояния, имя, вид и цель, аптайм 24 ч и 7 д, полоска последних 30 проверок, время последней проверки; кнопка «Новый мониторинг». - `/observability/`: состояние, сбои за неделю, журнал проверок (постранично), правка, пауза, удаление с подтверждением; для heartbeat — ссылка отметки. -- Живые обновления — область `observability` в `LiveRefresh` (отпечаток по `observe.db`). +- Обновление страниц — `AutoRefresh` раз в 15 с (раздел читает только суперадмин; отдельная область `LiveRefresh` не нужна). ### Встроенные мониторинги При первом запуске (пустая таблица) сервис создаёт: «eGov relay» — `http https://sign.aitu.uz/` и `dns sign.aitu.uz`; «Интернет» — `internet` (api.telegram.org, chatgpt.com, api.anthropic.com, registry.npmjs.org, git.telecom.quest). Удалённые не создаются повторно (`settings` `observe.seeded`). @@ -66,7 +67,7 @@ Peppa работает на одном Mac Studio: веб, бот, вачдог - Ложные срабатывания — пороги 3/2 и не меньше 30 с. ## Migration Plan -1. Схема и миграции `observe.db`; `peppa db migrate` на живой — до кода. +1. Схема `observe.db` создаётся сама при первом открытии. 2. Сервис, веб, MCP; `scripts/install-launchd.sh observer` на живой (согласовать с PM: новый launchd-агент). 3. Удалить PEP-201 проверку из вачдога. Откат: `launchctl bootout` агента observer; основная база не затронута. diff --git a/openspec/changes/pep-202-observability/proposal.md b/openspec/changes/archive/2026-11-17-pep-202-observability/proposal.md similarity index 100% rename from openspec/changes/pep-202-observability/proposal.md rename to openspec/changes/archive/2026-11-17-pep-202-observability/proposal.md diff --git a/openspec/changes/pep-202-observability/specs/observability/spec.md b/openspec/changes/archive/2026-11-17-pep-202-observability/specs/observability/spec.md similarity index 100% rename from openspec/changes/pep-202-observability/specs/observability/spec.md rename to openspec/changes/archive/2026-11-17-pep-202-observability/specs/observability/spec.md diff --git a/openspec/changes/pep-202-observability/specs/service-monitoring/spec.md b/openspec/changes/archive/2026-11-17-pep-202-observability/specs/service-monitoring/spec.md similarity index 100% rename from openspec/changes/pep-202-observability/specs/service-monitoring/spec.md rename to openspec/changes/archive/2026-11-17-pep-202-observability/specs/service-monitoring/spec.md diff --git a/openspec/changes/archive/2026-11-17-pep-202-observability/tasks.md b/openspec/changes/archive/2026-11-17-pep-202-observability/tasks.md new file mode 100644 index 00000000..df87d954 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-pep-202-observability/tasks.md @@ -0,0 +1,26 @@ +## 1. База мониторингов +- [x] 1.1 Схема (monitors, monitor_checks, monitor_incidents, observe_meta) в отдельном файле `PEPPA_OBSERVE_DB`, версия — `PRAGMA user_version` +- [x] 1.2 `core/observe.ts`: CRUD мониторингов с проверкой входа по виду, аптайм 24 ч/7 д, журнал, уборка старше 7 дней + +## 2. Сервис peppa-observer +- [x] 2.1 Процесс, bin, heartbeat `observer`, `installCrashReporting`, launchd `quest.telecom.peppa.observer` в `install-launchd.sh` +- [x] 2.2 Планировщик: интервал, параллельность, таймауты, перечитывание при изменениях +- [x] 2.3 Проверки http, tcp, dns (перенос `probeHost` из PEP-201), internet, heartbeat (`/api/observe/hb/`) +- [x] 2.4 Состояния, пороги, сбои, сообщения в канал / суперадминам, подавление при отсутствии интернета +- [x] 2.5 Встроенные мониторинги при первом запуске (`observe.seeded`) + +## 3. Доступ и MCP +- [x] 3.1 Инструменты в удалённом MCP (только суперадмин) и в MCP агента (только платформенный проект), события журнала +- [x] 3.2 `oauth.test.ts`, справочник `/help` «Инженер» + +## 4. Веб +- [x] 4.1 Пункт меню «Observability» суперадмину, `/observability` список, `/observability/` журнал и сбои, формы создания и правки, пауза, удаление +- [x] 4.2 Обновление раз в 15 с (`AutoRefresh`); тексты ru/kk/en, словарь + +## 5. Вачдог +- [x] 5.1 `checkServices` следит за `observer` +- [x] 5.2 Удалить `runner/net-watch.ts` и вызов из вачдога (PEP-201) + +## 6. Тесты и выкатка +- [x] 6.1 `observability.test.ts` на моках сети: пороги, одно сообщение, восстановление с простоем, интернет, heartbeat, хранение, доступ, встроенные +- [x] 6.2 AGENTS.md; `install-launchd.sh observer`, перезапуск в `live-deploy.sh` diff --git a/openspec/changes/pep-202-observability/tasks.md b/openspec/changes/pep-202-observability/tasks.md deleted file mode 100644 index f1196897..00000000 --- a/openspec/changes/pep-202-observability/tasks.md +++ /dev/null @@ -1,26 +0,0 @@ -## 1. База мониторингов -- [ ] 1.1 Схема `observe-schema.ts` (monitors, monitor_checks, monitor_incidents), отдельный файл `PEPPA_OBSERVE_DB`, миграции `observe-migrations`, `peppa db migrate` применяет обе -- [ ] 1.2 `core/observe.ts`: CRUD мониторингов с проверкой входа по виду, аптайм 24 ч/7 д, журнал, уборка старше 7 дней - -## 2. Сервис peppa-observer -- [ ] 2.1 Процесс, bin, heartbeat `observer`, `installCrashReporting`, launchd `quest.telecom.peppa.observer` в `install-launchd.sh` -- [ ] 2.2 Планировщик: интервал, параллельность, таймауты, перечитывание при изменениях -- [ ] 2.3 Проверки http, tcp, dns (перенос `probeHost` из PEP-201), internet, heartbeat (`/api/observe/hb/`) -- [ ] 2.4 Состояния, пороги, сбои, сообщения в канал / суперадминам, подавление при отсутствии интернета -- [ ] 2.5 Встроенные мониторинги при первом запуске (`observe.seeded`) - -## 3. Доступ и MCP -- [ ] 3.1 Инструменты в удалённом MCP (только суперадмин) и в MCP агента (только платформенный проект), события журнала -- [ ] 3.2 `oauth.test.ts`, справочник `/help` «Инженер» - -## 4. Веб -- [ ] 4.1 Пункт меню «Observability» суперадмину, `/observability` список, `/observability/` журнал и сбои, формы создания и правки, пауза, удаление -- [ ] 4.2 Живая область `observability`; тексты ru/kk/en, словарь - -## 5. Вачдог -- [ ] 5.1 `checkServices` следит за `observer` -- [ ] 5.2 Удалить `runner/net-watch.ts` и вызов из вачдога (PEP-201) - -## 6. Тесты и выкатка -- [ ] 6.1 `observability.test.ts` на моках сети: пороги, одно сообщение, восстановление с простоем, интернет, heartbeat, хранение, доступ, встроенные -- [ ] 6.2 AGENTS.md; выкатка: миграция, сборка, установка launchd-агента (с согласия PM), проверка в браузере diff --git a/openspec/specs/observability/spec.md b/openspec/specs/observability/spec.md new file mode 100644 index 00000000..8cae21be --- /dev/null +++ b/openspec/specs/observability/spec.md @@ -0,0 +1,93 @@ +# observability Specification + +## Purpose +TBD - created by archiving change pep-202-observability. Update Purpose after archive. + +## Requirements + +### Requirement: Сервис мониторингов +Peppa SHALL выполнять мониторинги в отдельном процессе `peppa-observer` со своей базой и SHALL хранить журнал проверок не дольше 7 дней. Изменение мониторинга SHALL применяться без перезапуска сервиса. + +#### Scenario: Новый мониторинг без перезапуска +- **GIVEN** сервис работает +- **WHEN** суперадмин создаёт HTTP-мониторинг с интервалом 30 с +- **THEN** первая проверка выполняется в течение 30 с, результат в журнале + +#### Scenario: Хранение 7 дней +- **GIVEN** в журнале есть проверки старше 7 дней +- **WHEN** проходит ежечасная уборка +- **THEN** проверки старше 7 дней удалены, более новые остались + +### Requirement: Виды проверок +Мониторинг SHALL быть одного из видов: HTTP(S), TCP, DNS, «Интернет», heartbeat. DNS-проверка SHALL отличать «системный DNS отдаёт недоступные адреса» от полной недоступности, сравнивая с запасным DNS. + +#### Scenario: DNS отдаёт недоступные адреса +- **GIVEN** системный DNS отдаёт для sign.aitu.uz недоступные адреса, а запасной — рабочие +- **WHEN** выполняется DNS-проверка +- **THEN** результат «нестабилен» с плохими и рабочими адресами в журнале + +#### Scenario: Heartbeat молчит +- **GIVEN** heartbeat-мониторинг с интервалом 5 мин и запасом 1 мин +- **WHEN** отметки нет 7 минут +- **THEN** проверка неудачна + +#### Scenario: Интернет +- **GIVEN** мониторинг «Интернет» с пятью адресами +- **WHEN** не открывается ни один +- **THEN** проверка неудачна; если открывается хоть один — удачна + +### Requirement: Состояния и уведомления +Состояние SHALL меняться на «не работает» после заданного числа неудач подряд (по умолчанию 3) и на «работает» после заданного числа удач подряд (по умолчанию 2). На каждую смену SHALL уходить одно сообщение в Telegram-канал платформы (без канала — суперадминам), сообщение о восстановлении SHALL содержать длительность простоя. Пока нет интернета, мониторинги, упавшие вместе с ним, SHALL не писать по отдельности. + +#### Scenario: Сбой и восстановление +- **GIVEN** мониторинг «eGov relay» работает +- **WHEN** три проверки подряд неудачны, потом две удачны через 12 минут +- **THEN** в канал ушло «🔴 eGov relay не работает» и «✅ eGov relay снова работает — простой 12 мин», каждое один раз + +#### Scenario: Одиночный сбой +- **WHEN** одна проверка неудачна, следующая удачна +- **THEN** сообщений нет, состояние «работает» + +#### Scenario: Нет интернета +- **GIVEN** мониторинги «Интернет» и «eGov relay» +- **WHEN** пропадает интернет +- **THEN** приходит одно сообщение о мониторинге «Интернет», про «eGov relay» отдельного нет + +### Requirement: Раздел Observability только суперадмину +Раздел «Observability» в левом меню, его страницы и действия SHALL быть доступны только суперадмину; остальным пункта меню нет, адрес отвечает 404. + +#### Scenario: Обычный пользователь +- **WHEN** пользователь без прав суперадмина открывает `/observability` +- **THEN** 404, пункта в меню нет + +#### Scenario: Суперадмин +- **WHEN** суперадмин открывает раздел +- **THEN** видит мониторинги с состоянием, аптаймом за 24 ч и 7 дней и последними проверками, может создать, изменить, приостановить и удалить + +### Requirement: Мониторинги через MCP +Инструменты мониторингов SHALL быть в удалённом MCP только для суперадмина и в MCP агента только для сессий платформенного проекта. Изменение мониторинга SHALL записываться в журнал с автором. + +#### Scenario: Агент платформы добавляет мониторинг +- **GIVEN** сессия агента проекта PEP +- **WHEN** агент вызывает `create_monitor` +- **THEN** мониторинг создан, в журнале событие с автором-агентом + +#### Scenario: Агент другого проекта +- **WHEN** агент проекта не платформы вызывает `create_monitor` +- **THEN** отказ, мониторинг не создан + +#### Scenario: Не суперадмин в удалённом MCP +- **WHEN** пользователь без прав суперадмина вызывает `list_monitors` +- **THEN** отказ + +### Requirement: Встроенные мониторинги +При первом запуске сервис SHALL создать мониторинги «eGov relay» (HTTP и DNS для sign.aitu.uz) и «Интернет»; удалённые суперадмином SHALL не создаваться снова. + +#### Scenario: Первый запуск +- **WHEN** сервис запускается с пустой базой +- **THEN** есть мониторинги «eGov relay» и «Интернет» + +#### Scenario: Удалённый не возвращается +- **GIVEN** суперадмин удалил «eGov relay» +- **WHEN** сервис перезапускается +- **THEN** «eGov relay» не создан снова diff --git a/openspec/specs/service-monitoring/spec.md b/openspec/specs/service-monitoring/spec.md index 87ce9f26..d662875b 100644 --- a/openspec/specs/service-monitoring/spec.md +++ b/openspec/specs/service-monitoring/spec.md @@ -127,3 +127,11 @@ - **GIVEN** проект PAY без выбранной подписки - **WHEN** диспетчер не может запустить агента - **THEN** владелец получает сообщение с причиной простыми словами + +### Requirement: Вачдог следит за сервисом мониторингов +Вачдог SHALL проверять heartbeat `peppa-observer` так же, как бота и веб, и SHALL сообщать админам, если сервис молчит дольше порога. + +#### Scenario: Сервис мониторингов упал +- **GIVEN** `peppa-observer` не пишет heartbeat дольше 5 минут +- **WHEN** вачдог проверяет сервисы +- **THEN** админы получают одно сообщение «не отвечает», после восстановления — «снова работает» diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 5c85f2d2..48493d3e 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -91,3 +91,5 @@ export * from "./bench.ts"; export * from "./untrusted.ts"; export * from "./egress.ts"; export * from "./fallback-fetch.ts"; +export * from "./observe.ts"; +export * from "./observe-checks.ts"; diff --git a/packages/core/src/monitor.ts b/packages/core/src/monitor.ts index e4e4654b..441fefb1 100644 --- a/packages/core/src/monitor.ts +++ b/packages/core/src/monitor.ts @@ -15,10 +15,12 @@ import { getPlatformChannel, postToChannel } from "./platform-channel.ts"; import { deleteSetting, getSetting, setSetting } from "./settings.ts"; import type { User } from "./users.ts"; -export const SERVICES = ["web", "bot", "watchdog"] as const; +export const SERVICES = ["web", "bot", "watchdog", "observer"] as const; +/** Counted only once they have reported: a service not installed on this host is not «down» (PEP-202). */ +const OPTIONAL_SERVICES: ReadonlySet = new Set(["observer"]); export type Service = (typeof SERVICES)[number]; -export const SERVICE_NAMES: Record = { web: tr("веб"), bot: tr("бот"), watchdog: tr("вачдог") }; +export const SERVICE_NAMES: Record = { web: tr("веб"), bot: tr("бот"), watchdog: tr("вачдог"), observer: tr("мониторинги") }; export interface Heartbeat { at: string; @@ -147,7 +149,7 @@ export async function beat(db: Db, service: Service, o: { now?: Date; version?: export async function serviceStatus(db: Db, o: { now?: Date; staleMs?: number; probe?: boolean | (() => Promise) } = {}): Promise { const now = (o.now ?? new Date()).getTime(); const stale = o.staleMs ?? defaultStaleMs(); - return Promise.all( + const states = await Promise.all( SERVICES.map(async (service) => { const heartbeat = await getSetting(db, hbKey(service)); const ageMs = heartbeat ? Math.max(0, now - Date.parse(heartbeat.at)) : null; @@ -158,6 +160,7 @@ export async function serviceStatus(db: Db, o: { now?: Date; staleMs?: number; p return { service, heartbeat, ageMs, ok: ok && !portDown, ...(portDown ? { portDown } : {}) }; }), ); + return states.filter((s) => s.heartbeat || !OPTIONAL_SERVICES.has(s.service)); } export const minutes = (ms: number) => Math.round(ms / MIN); diff --git a/packages/core/src/observe-checks.ts b/packages/core/src/observe-checks.ts new file mode 100644 index 00000000..71fd3f47 --- /dev/null +++ b/packages/core/src/observe-checks.ts @@ -0,0 +1,170 @@ +// PEP-202: what one check of a monitor does. Network access goes through `ObserveProbes`, so tests +// replace the network with a mock. The DNS check compares the system resolver with a fallback one +// (PEPPA_FALLBACK_DNS, 1.1.1.1): «the system DNS gives unreachable addresses» is not «the host is +// down» (sign.aitu.uz, 2026-11-17; moved here from the watchdog's PEP-201 check). +// glossary-ignore-file: check results are read by the superadmin only. +import { Resolver, lookup } from "node:dns/promises"; +import net from "node:net"; +import tls from "node:tls"; +import { m as tr } from "@peppa/shared/i18n"; +import { fetchViaFallbackDns } from "./fallback-fetch.ts"; +import type { DnsTarget, HeartbeatTarget, HttpTarget, InternetTarget, Monitor, TcpTarget } from "./observe.ts"; + +export interface CheckResult { + ok: boolean; + /** Works, but not well: slow, certificate expiring, the system DNS points at bad addresses. */ + degraded: boolean; + latencyMs?: number; + /** Short reason for a bad result (shown in the message and the journal). */ + reason: string; + detail: Record; +} + +export interface HttpAnswer { + status: number; + body: string; +} + +export interface ObserveProbes { + http(url: string, o: { method: string; timeoutMs: number }): Promise; + certDaysLeft(host: string, port: number, timeoutMs: number): Promise; + systemLookup(host: string): Promise; + fallbackLookup(host: string): Promise; + reachable(host: string, port: number, timeoutMs: number): Promise; +} + +const MAX_BODY = 64 * 1024; + +export const realObserveProbes: ObserveProbes = { + async http(url, o) { + const init = { method: o.method, redirect: "follow" as const, signal: AbortSignal.timeout(o.timeoutMs), headers: { "User-Agent": "peppa-observer" } }; + try { + const res = await fetch(url, init); + const body = o.method === "HEAD" ? "" : (await res.text()).slice(0, MAX_BODY); + return { status: res.status, body }; + } catch (e) { + // No answer at all: the system resolver may point at an unreachable address (PEP-200). + const r = await fetchViaFallbackDns(url, { method: o.method }, o.timeoutMs); + if (!r) throw e; + return { status: r.status, body: "", via: "fallback-dns" }; + } + }, + certDaysLeft(host, port, timeoutMs) { + return new Promise((resolve) => { + const s = tls.connect({ host, port, servername: host, timeout: timeoutMs, rejectUnauthorized: false }, () => { + const c = s.getPeerCertificate(); + s.destroy(); + resolve(c?.valid_to ? Math.floor((Date.parse(c.valid_to) - Date.now()) / 86_400_000) : null); + }); + s.once("timeout", () => (s.destroy(), resolve(null))); + s.once("error", () => resolve(null)); + }); + }, + async systemLookup(host) { + return (await lookup(host, { all: true, family: 4 }).catch(() => [])).map((a) => a.address); + }, + async fallbackLookup(host) { + const servers = (process.env.PEPPA_FALLBACK_DNS ?? "1.1.1.1,1.0.0.1").split(",").map((s) => s.trim()).filter((s) => s && s !== "off"); + if (!servers.length) return []; + const r = new Resolver({ timeout: 4_000, tries: 2 }); + r.setServers(servers); + return r.resolve4(host).catch(() => []); + }, + reachable(host, port, timeoutMs) { + return new Promise((resolve) => { + const s = net.connect({ host, port, timeout: timeoutMs }); + const done = (ok: boolean) => (s.destroy(), resolve(ok)); + s.once("connect", () => done(true)); + s.once("timeout", () => done(false)); + s.once("error", () => done(false)); + }); + }, +}; + +export type DnsState = "ok" | "dns" | "blocked" | "down"; + +export interface DnsProbe { + host: string; + state: DnsState; + /** System resolver's addresses. */ + system: string[]; + /** Fallback resolver's addresses that answered. */ + working: string[]; +} + +/** Resolves a host both ways and tries its addresses on port 443. */ +export async function probeDns(host: string, p: ObserveProbes, timeoutMs = 5_000): Promise { + const system = await p.systemLookup(host); + const sysOk = (await Promise.all(system.slice(0, 3).map((ip) => p.reachable(ip, 443, timeoutMs)))).some(Boolean); + if (sysOk) return { host, state: "ok", system, working: [] }; + const fallback = (await p.fallbackLookup(host)).filter((ip) => !system.includes(ip)).slice(0, 3); + const ok = await Promise.all(fallback.map((ip) => p.reachable(ip, 443, timeoutMs))); + const working = fallback.filter((_, i) => ok[i]); + if (working.length) return { host, state: system.length ? "blocked" : "dns", system, working }; + return { host, state: "down", system, working: [] }; +} + +async function httpCheck(t: HttpTarget, m: Monitor, p: ObserveProbes): Promise { + const t0 = Date.now(); + let a: HttpAnswer & { via?: string }; + try { + a = await p.http(t.url, { method: t.method ?? "GET", timeoutMs: m.timeoutMs }); + } catch (e) { + const msg = (e as Error).name === "TimeoutError" ? tr("нет ответа за {n} с", { n: Math.round(m.timeoutMs / 1000) }) : tr("нет ответа ({error})", { error: String((e as Error).cause ?? (e as Error).message).slice(0, 120) }); + return { ok: false, degraded: false, latencyMs: Date.now() - t0, reason: msg, detail: {} }; + } + const latencyMs = Date.now() - t0; + const detail: Record = { status: a.status, ...(a.via ? { via: a.via } : {}) }; + const okStatus = t.expectStatus?.length ? t.expectStatus.includes(a.status) : a.status >= 200 && a.status < 400; + if (!okStatus) return { ok: false, degraded: false, latencyMs, reason: tr("ответ {status}", { status: a.status }), detail }; + if (t.contains && !a.via && !a.body.includes(t.contains)) return { ok: false, degraded: false, latencyMs, reason: tr("в ответе нет «{text}»", { text: t.contains }), detail }; + const reasons: string[] = []; + if (a.via) reasons.push(tr("отвечает только через запасной DNS")); + if (t.maxLatencyMs && latencyMs > t.maxLatencyMs) reasons.push(tr("медленно: {n} мс", { n: latencyMs })); + const url = new URL(t.url); + if (url.protocol === "https:") { + const days = await p.certDaysLeft(url.hostname, Number(url.port) || 443, m.timeoutMs).catch(() => null); + if (days != null) { + detail.certDays = days; + if (days < (t.certDays ?? 14)) reasons.push(days < 0 ? tr("сертификат истёк") : tr("сертификат истекает через {n} дн.", { n: days })); + } + } + return { ok: true, degraded: reasons.length > 0, latencyMs, reason: reasons.join("; "), detail }; +} + +/** Runs one check of the monitor. */ +export async function runCheck(m: Monitor, p: ObserveProbes, now = new Date()): Promise { + switch (m.kind) { + case "http": + return httpCheck(m.target as HttpTarget, m, p); + case "tcp": { + const t = m.target as TcpTarget; + const t0 = Date.now(); + const ok = await p.reachable(t.host, t.port, m.timeoutMs); + return { ok, degraded: false, latencyMs: Date.now() - t0, reason: ok ? "" : tr("порт {port} не открывается", { port: t.port }), detail: {} }; + } + case "dns": { + const d = await probeDns((m.target as DnsTarget).host, p, Math.min(m.timeoutMs, 5_000)); + const detail = { dns: d.state, system: d.system, working: d.working }; + if (d.state === "ok") return { ok: true, degraded: false, reason: "", detail }; + if (d.state === "blocked") + return { ok: true, degraded: true, reason: tr("системный DNS отдаёт недоступные адреса {bad}, рабочие — {ips} (их даёт 1.1.1.1)", { bad: d.system.join(", "), ips: d.working.join(", ") }), detail }; + if (d.state === "dns") return { ok: true, degraded: true, reason: tr("системный DNS не отвечает, рабочие адреса {ips} даёт 1.1.1.1", { ips: d.working.join(", ") }), detail }; + return { ok: false, degraded: false, reason: tr("недоступен ни по одному адресу"), detail }; + } + case "internet": { + const hosts = (m.target as InternetTarget).hosts; + const probes = await Promise.all(hosts.map((h) => probeDns(h, p, Math.min(m.timeoutMs, 5_000)))); + const up = probes.filter((x) => x.state !== "down").map((x) => x.host); + const detail = { up, down: probes.filter((x) => x.state === "down").map((x) => x.host) }; + return up.length ? { ok: true, degraded: false, reason: "", detail } : { ok: false, degraded: false, reason: tr("не открывается ни один из адресов {hosts}", { hosts: hosts.join(", ") }), detail }; + } + case "heartbeat": { + const grace = ((m.target as HeartbeatTarget).graceSec ?? 60) * 1000; + const last = m.lastPingAt ? Date.parse(m.lastPingAt) : Date.parse(m.createdAt); + const silent = now.getTime() - last; + const ok = silent <= m.intervalSec * 1000 + grace; + return { ok, degraded: false, reason: ok ? "" : tr("нет отметки {n} мин", { n: Math.round(silent / 60_000) }), detail: { lastPingAt: m.lastPingAt } }; + } + } +} diff --git a/packages/core/src/observe.ts b/packages/core/src/observe.ts new file mode 100644 index 00000000..8358d0c9 --- /dev/null +++ b/packages/core/src/observe.ts @@ -0,0 +1,621 @@ +// PEP-202: Observability — monitors of the services Peppa depends on (and of the internet on the +// Peppa host). Monitors, their checks and incidents live in a separate SQLite file +// (PEPPA_OBSERVE_DB, default $PEPPA_HOME/observe.db): checks are frequent and must not compete with +// the main database. The `peppa-observer` process runs `observeTick`; the web and MCP read and +// change monitors through the functions here. Only the superadmin and the platform's agents get here. +// glossary-ignore-file: the section is for the superadmin only. +import { DatabaseSync } from "node:sqlite"; +import { mkdirSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { randomBytes } from "node:crypto"; +import { peppaHome } from "@peppa/shared"; +import { m as tr } from "@peppa/shared/i18n"; +import type { Db } from "@peppa/db"; +import { PeppaError } from "./errors.ts"; +import { alertAdmins } from "./monitor.ts"; +import { getPlatformChannel, postToChannel } from "./platform-channel.ts"; +import { realObserveProbes, runCheck, type CheckResult, type ObserveProbes } from "./observe-checks.ts"; + +export type MonitorKind = "http" | "tcp" | "dns" | "internet" | "heartbeat"; +export type MonitorState = "unknown" | "up" | "degraded" | "down"; +export const MONITOR_KINDS: MonitorKind[] = ["http", "tcp", "dns", "internet", "heartbeat"]; + +export interface HttpTarget { + url: string; + method?: "GET" | "HEAD"; + /** Accepted codes; default 200–399. */ + expectStatus?: number[]; + /** Text the body must contain. */ + contains?: string; + /** Slower than this = degraded. */ + maxLatencyMs?: number; + /** The certificate expires sooner than this = degraded (https only; default 14). */ + certDays?: number; +} +export interface TcpTarget { + host: string; + port: number; +} +export interface DnsTarget { + host: string; +} +export interface InternetTarget { + hosts: string[]; +} +export interface HeartbeatTarget { + /** Extra seconds after the interval before a missing ping counts. */ + graceSec?: number; +} +export type MonitorTarget = HttpTarget | TcpTarget | DnsTarget | InternetTarget | HeartbeatTarget; + +export interface Monitor { + id: number; + name: string; + kind: MonitorKind; + target: MonitorTarget; + intervalSec: number; + timeoutMs: number; + failThreshold: number; + recoverThreshold: number; + paused: boolean; + /** Heartbeat monitors: the secret part of the ping address. */ + token: string | null; + createdBy: string; + createdAt: string; + updatedAt: string; + state: MonitorState; + stateSince: string | null; + streakOk: number; + streakBad: number; + lastCheckAt: string | null; + lastPingAt: string | null; + lastDetail: Record | null; + incidentId: number | null; +} + +export interface MonitorCheck { + id: number; + monitorId: number; + at: string; + ok: boolean; + degraded: boolean; + latencyMs: number | null; + detail: Record; +} + +export interface MonitorIncident { + id: number; + monitorId: number; + state: MonitorState; + reason: string; + startedAt: string; + endedAt: string | null; + /** Fell together with the internet: no message about it. */ + quiet: boolean; +} + +export interface MonitorInput { + name: string; + kind: MonitorKind; + target: MonitorTarget; + intervalSec?: number; + timeoutMs?: number; + failThreshold?: number; + recoverThreshold?: number; +} + +export const MIN_INTERVAL_SEC = 30; +export const MAX_MONITORS = 200; +export const DEFAULT_INTERVAL_SEC = 60; +export const retentionDays = () => Number(process.env.PEPPA_OBSERVE_RETENTION_DAYS) || 7; + +// ── the database ─────────────────────────────────────────────────────────────────── + +const SCHEMA = [ + `CREATE TABLE monitors ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + kind TEXT NOT NULL, + target TEXT NOT NULL, + interval_sec INTEGER NOT NULL, + timeout_ms INTEGER NOT NULL, + fail_threshold INTEGER NOT NULL, + recover_threshold INTEGER NOT NULL, + paused INTEGER NOT NULL DEFAULT 0, + token TEXT UNIQUE, + created_by TEXT NOT NULL, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + state TEXT NOT NULL DEFAULT 'unknown', + state_since TEXT, + streak_ok INTEGER NOT NULL DEFAULT 0, + streak_bad INTEGER NOT NULL DEFAULT 0, + last_check_at TEXT, + last_ping_at TEXT, + last_detail TEXT, + incident_id INTEGER + )`, + `CREATE TABLE monitor_checks ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + monitor_id INTEGER NOT NULL REFERENCES monitors(id) ON DELETE CASCADE, + at TEXT NOT NULL, + ok INTEGER NOT NULL, + degraded INTEGER NOT NULL DEFAULT 0, + latency_ms INTEGER, + detail TEXT NOT NULL + )`, + `CREATE INDEX monitor_checks_monitor_at ON monitor_checks (monitor_id, at)`, + `CREATE TABLE monitor_incidents ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + monitor_id INTEGER NOT NULL REFERENCES monitors(id) ON DELETE CASCADE, + state TEXT NOT NULL, + reason TEXT NOT NULL, + started_at TEXT NOT NULL, + ended_at TEXT, + quiet INTEGER NOT NULL DEFAULT 0 + )`, + `CREATE INDEX monitor_incidents_monitor ON monitor_incidents (monitor_id, started_at)`, + `CREATE TABLE observe_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)`, +]; +/** Each entry upgrades the file by one version (PRAGMA user_version). */ +const MIGRATIONS: string[][] = [SCHEMA]; + +const opened = new Map(); + +export const observeDbPath = () => process.env.PEPPA_OBSERVE_DB ?? join(peppaHome(), "observe.db"); + +/** The observe database of this process (opened and migrated on first use). */ +export function observeDb(): DatabaseSync { + const path = observeDbPath(); + const known = opened.get(path); + if (known) return known; + mkdirSync(dirname(path), { recursive: true }); + const db = new DatabaseSync(path); + db.exec("PRAGMA busy_timeout = 5000"); + db.exec("PRAGMA journal_mode = WAL"); + db.exec("PRAGMA foreign_keys = ON"); + const version = Number((db.prepare("PRAGMA user_version").get() as { user_version: number }).user_version); + for (let v = version; v < MIGRATIONS.length; v++) { + db.exec("BEGIN IMMEDIATE"); + try { + for (const sql of MIGRATIONS[v]!) db.exec(sql); + db.exec(`PRAGMA user_version = ${v + 1}`); + db.exec("COMMIT"); + } catch (e) { + db.exec("ROLLBACK"); + throw e; + } + } + opened.set(path, db); + return db; +} + +/** Tests: forget opened files. */ +export function closeObserveDb(): void { + for (const db of opened.values()) db.close(); + opened.clear(); +} + +type Row = Record; +const json = (s: unknown, d: T): T => { + try { + return s == null ? d : (JSON.parse(String(s)) as T); + } catch { + return d; + } +}; + +function toMonitor(r: Row): Monitor { + return { + id: Number(r.id), + name: String(r.name), + kind: r.kind as MonitorKind, + target: json(r.target, {}) as MonitorTarget, + intervalSec: Number(r.interval_sec), + timeoutMs: Number(r.timeout_ms), + failThreshold: Number(r.fail_threshold), + recoverThreshold: Number(r.recover_threshold), + paused: Number(r.paused) === 1, + token: (r.token as string | null) ?? null, + createdBy: String(r.created_by), + createdAt: String(r.created_at), + updatedAt: String(r.updated_at), + state: r.state as MonitorState, + stateSince: (r.state_since as string | null) ?? null, + streakOk: Number(r.streak_ok), + streakBad: Number(r.streak_bad), + lastCheckAt: (r.last_check_at as string | null) ?? null, + lastPingAt: (r.last_ping_at as string | null) ?? null, + lastDetail: json(r.last_detail, null), + incidentId: r.incident_id == null ? null : Number(r.incident_id), + }; +} + +const toCheck = (r: Row): MonitorCheck => ({ + id: Number(r.id), + monitorId: Number(r.monitor_id), + at: String(r.at), + ok: Number(r.ok) === 1, + degraded: Number(r.degraded) === 1, + latencyMs: r.latency_ms == null ? null : Number(r.latency_ms), + detail: json(r.detail, {}), +}); + +const toIncident = (r: Row): MonitorIncident => ({ + id: Number(r.id), + monitorId: Number(r.monitor_id), + state: r.state as MonitorState, + reason: String(r.reason), + startedAt: String(r.started_at), + endedAt: (r.ended_at as string | null) ?? null, + quiet: Number(r.quiet) === 1, +}); + +// ── validation ───────────────────────────────────────────────────────────────────── + +const HOST_RE = /^(?=.{1,253}$)([a-z0-9-]{1,63}\.)*[a-z0-9-]{1,63}$/i; +const IP_RE = /^\d{1,3}(\.\d{1,3}){3}$/; +const bad = (msg: string, vars?: Record): never => { + throw new PeppaError(tr(msg, vars)); +}; +const int = (v: unknown, min: number, max: number, field: string): number => { + const n = Number(v); + if (!Number.isInteger(n) || n < min || n > max) bad("{field}: целое число от {min} до {max}", { field, min, max }); + return n; +}; +const host = (v: unknown): string => { + const h = String(v ?? "").trim().toLowerCase(); + if (!HOST_RE.test(h) && !IP_RE.test(h)) bad("Неверное имя хоста: {host}", { host: h || "—" }); + return h; +}; + +export function normalizeTarget(kind: MonitorKind, t: Record): MonitorTarget { + switch (kind) { + case "http": { + let url: URL; + try { + url = new URL(String(t.url ?? "")); + } catch { + return bad("Неверный адрес: нужен http:// или https://"); + } + if (url.protocol !== "http:" && url.protocol !== "https:") bad("Неверный адрес: нужен http:// или https://"); + const out: HttpTarget = { url: url.toString() }; + if (t.method === "HEAD") out.method = "HEAD"; + if (t.expectStatus != null && (!Array.isArray(t.expectStatus) || t.expectStatus.length)) { + const list = (Array.isArray(t.expectStatus) ? t.expectStatus : String(t.expectStatus).split(/[\s,]+/)).filter((x) => String(x).trim() !== ""); + if (list.length) out.expectStatus = list.map((c) => int(c, 100, 599, "expectStatus")); + } + if (t.contains != null && String(t.contains).trim()) out.contains = String(t.contains).slice(0, 200); + if (t.maxLatencyMs != null && String(t.maxLatencyMs) !== "") out.maxLatencyMs = int(t.maxLatencyMs, 1, 60_000, "maxLatencyMs"); + if (t.certDays != null && String(t.certDays) !== "") out.certDays = int(t.certDays, 0, 365, "certDays"); + return out; + } + case "tcp": + return { host: host(t.host), port: int(t.port, 1, 65535, "port") }; + case "dns": + return { host: host(t.host) }; + case "internet": { + const list = (Array.isArray(t.hosts) ? t.hosts : String(t.hosts ?? "").split(/[\s,]+/)).map(String).filter(Boolean); + if (!list.length || list.length > 10) bad("Интернет: от 1 до 10 адресов"); + return { hosts: [...new Set(list.map(host))] }; + } + case "heartbeat": + return t.graceSec != null && String(t.graceSec) !== "" ? { graceSec: int(t.graceSec, 0, 86_400, "graceSec") } : {}; + } +} + +function normalize(input: MonitorInput): Required> & { target: MonitorTarget } { + const name = String(input.name ?? "").trim(); + if (!name || name.length > 80) bad("Название: от 1 до 80 символов"); + if (!MONITOR_KINDS.includes(input.kind)) bad("Неизвестный вид мониторинга: {kind}", { kind: String(input.kind) }); + const intervalSec = int(input.intervalSec ?? DEFAULT_INTERVAL_SEC, MIN_INTERVAL_SEC, 86_400, "intervalSec"); + return { + name, + kind: input.kind, + target: normalizeTarget(input.kind, (input.target ?? {}) as Record), + intervalSec, + timeoutMs: int(input.timeoutMs ?? 10_000, 1_000, 30_000, "timeoutMs"), + failThreshold: int(input.failThreshold ?? 3, 1, 20, "failThreshold"), + recoverThreshold: int(input.recoverThreshold ?? 2, 1, 20, "recoverThreshold"), + }; +} + +// ── monitors ─────────────────────────────────────────────────────────────────────── + +export function getMonitor(id: number): Monitor | null { + const r = observeDb().prepare("SELECT * FROM monitors WHERE id = ?").get(id) as Row | undefined; + return r ? toMonitor(r) : null; +} + +export function listMonitors(): Monitor[] { + return (observeDb().prepare("SELECT * FROM monitors ORDER BY name COLLATE NOCASE, id").all() as Row[]).map(toMonitor); +} + +/** Creates a monitor; `author` is «user:», «agent:s» or «system». */ +export function createMonitor(input: MonitorInput, author: string, now = new Date()): Monitor { + const n = normalize(input); + const db = observeDb(); + const count = Number((db.prepare("SELECT count(*) AS n FROM monitors").get() as Row).n); + if (count >= MAX_MONITORS) bad("Мониторингов уже {n} — больше нельзя", { n: MAX_MONITORS }); + const iso = now.toISOString(); + const token = n.kind === "heartbeat" ? randomBytes(18).toString("base64url") : null; + const r = db + .prepare( + `INSERT INTO monitors (name, kind, target, interval_sec, timeout_ms, fail_threshold, recover_threshold, token, created_by, created_at, updated_at, state_since, last_ping_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`, + ) + .get(n.name, n.kind, JSON.stringify(n.target), n.intervalSec, n.timeoutMs, n.failThreshold, n.recoverThreshold, token, author, iso, iso, iso, n.kind === "heartbeat" ? iso : null) as Row; + return toMonitor(r); +} + +export function updateMonitor(id: number, patch: Partial, now = new Date()): Monitor { + const cur = getMonitor(id); + if (!cur) return bad("Мониторинг не найден"); + if (patch.kind && patch.kind !== cur.kind) bad("Вид мониторинга не меняется — создайте новый"); + const n = normalize({ + name: patch.name ?? cur.name, + kind: cur.kind, + target: (patch.target ?? cur.target) as MonitorTarget, + intervalSec: patch.intervalSec ?? cur.intervalSec, + timeoutMs: patch.timeoutMs ?? cur.timeoutMs, + failThreshold: patch.failThreshold ?? cur.failThreshold, + recoverThreshold: patch.recoverThreshold ?? cur.recoverThreshold, + }); + const r = observeDb() + .prepare(`UPDATE monitors SET name = ?, target = ?, interval_sec = ?, timeout_ms = ?, fail_threshold = ?, recover_threshold = ?, updated_at = ?, last_check_at = NULL WHERE id = ? RETURNING *`) + .get(n.name, JSON.stringify(n.target), n.intervalSec, n.timeoutMs, n.failThreshold, n.recoverThreshold, now.toISOString(), id) as Row; + return toMonitor(r); +} + +/** Pause or resume; a paused monitor is not checked and says nothing. Resuming starts fresh. */ +export function setMonitorPaused(id: number, paused: boolean, now = new Date()): Monitor { + const cur = getMonitor(id); + if (!cur) return bad("Мониторинг не найден"); + const db = observeDb(); + const iso = now.toISOString(); + if (paused && cur.incidentId) db.prepare("UPDATE monitor_incidents SET ended_at = ? WHERE id = ? AND ended_at IS NULL").run(iso, cur.incidentId); + const r = db + .prepare( + paused + ? `UPDATE monitors SET paused = 1, updated_at = ?, incident_id = NULL WHERE id = ? RETURNING *` + : `UPDATE monitors SET paused = 0, updated_at = ?, state = 'unknown', state_since = ?, streak_ok = 0, streak_bad = 0, last_check_at = NULL, last_ping_at = CASE WHEN kind = 'heartbeat' THEN ? ELSE last_ping_at END WHERE id = ? RETURNING *`, + ) + .get(...(paused ? [iso, id] : [iso, iso, iso, id])) as Row; + return toMonitor(r); +} + +export function deleteMonitor(id: number): Monitor { + const cur = getMonitor(id); + if (!cur) return bad("Мониторинг не найден"); + observeDb().prepare("DELETE FROM monitors WHERE id = ?").run(id); + return cur; +} + +/** A heartbeat monitor's ping (the web route `/api/observe/hb/`); false — unknown token. */ +export function pingHeartbeat(token: string, now = new Date()): boolean { + if (!/^[A-Za-z0-9_-]{10,64}$/.test(token)) return false; + const r = observeDb().prepare("UPDATE monitors SET last_ping_at = ? WHERE token = ? AND kind = 'heartbeat'").run(now.toISOString(), token); + return Number(r.changes) > 0; +} + +export function monitorChecks(id: number, o: { limit?: number; offset?: number } = {}): MonitorCheck[] { + return (observeDb().prepare("SELECT * FROM monitor_checks WHERE monitor_id = ? ORDER BY at DESC, id DESC LIMIT ? OFFSET ?").all(id, o.limit ?? 50, o.offset ?? 0) as Row[]).map(toCheck); +} + +export function monitorIncidents(id: number, limit = 50): MonitorIncident[] { + return (observeDb().prepare("SELECT * FROM monitor_incidents WHERE monitor_id = ? ORDER BY started_at DESC, id DESC LIMIT ?").all(id, limit) as Row[]).map(toIncident); +} + +/** Share of good checks (degraded counts as working) since `sinceMs` ago; null without checks. */ +export function monitorUptime(id: number, sinceMs: number, now = new Date()): number | null { + const r = observeDb() + .prepare("SELECT count(*) AS n, sum(ok) AS good FROM monitor_checks WHERE monitor_id = ? AND at >= ?") + .get(id, new Date(now.getTime() - sinceMs).toISOString()) as Row; + const n = Number(r.n); + return n ? Number(r.good ?? 0) / n : null; +} + +export interface MonitorView extends Monitor { + uptime24h: number | null; + uptime7d: number | null; + /** The last checks, oldest first. */ + recent: Array<{ at: string; ok: boolean; degraded: boolean }>; +} + +export function monitorView(m: Monitor, now = new Date()): MonitorView { + const recent = (observeDb().prepare("SELECT at, ok, degraded FROM monitor_checks WHERE monitor_id = ? ORDER BY at DESC, id DESC LIMIT 30").all(m.id) as Row[]) + .map((r) => ({ at: String(r.at), ok: Number(r.ok) === 1, degraded: Number(r.degraded) === 1 })) + .reverse(); + return { ...m, uptime24h: monitorUptime(m.id, 86_400_000, now), uptime7d: monitorUptime(m.id, 7 * 86_400_000, now), recent }; +} + +export const listMonitorViews = (now = new Date()) => listMonitors().map((m) => monitorView(m, now)); + +/** One line about where the monitor looks. */ +export function describeTarget(m: Pick, webUrl = ""): string { + const t = m.target as Record; + switch (m.kind) { + case "http": + return String(t.url); + case "tcp": + return `${t.host}:${t.port}`; + case "dns": + return String(t.host); + case "internet": + return (t.hosts as string[]).join(", "); + case "heartbeat": + return `${webUrl}/api/observe/hb/${m.token}`; + } +} + +// ── checks and states ────────────────────────────────────────────────────────────── + +export interface Transition { + from: MonitorState; + to: MonitorState; + incident: MonitorIncident | null; + /** The closed incident (recovery). */ + ended: MonitorIncident | null; +} + +/** Records one check and moves the state machine; returns the change, if any. */ +export function recordCheck(m: Monitor, r: CheckResult, o: { now?: Date; quiet?: boolean } = {}): Transition | null { + const now = o.now ?? new Date(); + const iso = now.toISOString(); + const db = observeDb(); + const good = r.ok && !r.degraded; + db.prepare("INSERT INTO monitor_checks (monitor_id, at, ok, degraded, latency_ms, detail) VALUES (?, ?, ?, ?, ?, ?)").run( + m.id, + iso, + r.ok ? 1 : 0, + r.degraded ? 1 : 0, + r.latencyMs ?? null, + JSON.stringify({ ...r.detail, reason: r.reason }), + ); + const streakOk = good ? m.streakOk + 1 : 0; + const streakBad = good ? 0 : m.streakBad + 1; + const target: MonitorState = good ? "up" : r.ok ? "degraded" : "down"; + let to = m.state; + if (target === "up" && m.state !== "up" && (m.state === "unknown" || streakOk >= m.recoverThreshold)) to = "up"; + if (target !== "up" && m.state !== target && streakBad >= m.failThreshold) to = target; + let transition: Transition | null = null; + let incidentId = m.incidentId; + if (to !== m.state) { + let incident: MonitorIncident | null = null; + let ended: MonitorIncident | null = null; + if (to === "up") { + if (incidentId) { + db.prepare("UPDATE monitor_incidents SET ended_at = ? WHERE id = ?").run(iso, incidentId); + ended = toIncident(db.prepare("SELECT * FROM monitor_incidents WHERE id = ?").get(incidentId) as Row); + } + incidentId = null; + } else if (incidentId) { + // down ↔ degraded: the same incident, a new state. + db.prepare("UPDATE monitor_incidents SET state = ?, reason = ? WHERE id = ?").run(to, r.reason, incidentId); + incident = toIncident(db.prepare("SELECT * FROM monitor_incidents WHERE id = ?").get(incidentId) as Row); + } else { + incident = toIncident( + db.prepare("INSERT INTO monitor_incidents (monitor_id, state, reason, started_at, quiet) VALUES (?, ?, ?, ?, ?) RETURNING *").get(m.id, to, r.reason, iso, o.quiet ? 1 : 0) as Row, + ); + incidentId = incident.id; + } + transition = { from: m.state, to, incident, ended }; + } + db.prepare(`UPDATE monitors SET state = ?, state_since = ?, streak_ok = ?, streak_bad = ?, last_check_at = ?, last_detail = ?, incident_id = ? WHERE id = ?`).run( + to, + to !== m.state ? iso : m.stateSince, + streakOk, + streakBad, + iso, + JSON.stringify({ ...r.detail, reason: r.reason, latencyMs: r.latencyMs ?? null }), + incidentId, + m.id, + ); + return transition; +} + +/** Text of the message about a change (null — nothing to say: the first «works», a quiet incident). */ +export function transitionText(m: Pick, t: Transition, now = new Date()): string | null { + if (t.to === "up") { + if (!t.ended || t.ended.quiet) return null; + const n = Math.max(1, Math.round((now.getTime() - Date.parse(t.ended.startedAt)) / 60_000)); + return tr("✅ {name} снова работает — простой {n} мин.", { name: m.name, n }); + } + if (t.incident?.quiet) return null; + return t.to === "down" ? tr("🔴 {name} не работает: {reason}", { name: m.name, reason: t.incident?.reason ?? "" }) : tr("🟡 {name} нестабилен: {reason}", { name: m.name, reason: t.incident?.reason ?? "" }); +} + +const esc = (s: string) => s.replace(/&/g, "&").replace(//g, ">"); + +async function announce(db: Db, m: Monitor, t: Transition, text: string, log: (s: string) => void): Promise { + const inc = t.ended?.id ?? t.incident?.id ?? 0; + const key = `obs:${m.id}:${inc}:${t.to}`; + const channel = await getPlatformChannel(db); + if (await postToChannel(db, "services", `mon:ch:${key}`, esc(text), channel)) { + log(`observe: ${text}`); + return; + } + await alertAdmins(db, `mon:${key}`, text, log); +} + +const inflight = new Set(); +const running: Promise[] = []; + +export interface ObserveTickOptions { + now?: Date; + probes?: ObserveProbes; + log?: (s: string) => void; + /** At most this many checks at once (default PEPPA_OBSERVE_CONCURRENCY or 16). */ + concurrency?: number; +} + +/** Is the internet down right now (an internet monitor not on pause is down)? */ +function internetDown(): boolean { + return listMonitors().some((m) => m.kind === "internet" && !m.paused && (m.state === "down" || (m.streakBad > 0 && m.state !== "degraded"))); +} + +async function checkOne(db: Db, m: Monitor, o: ObserveTickOptions): Promise { + const log = o.log ?? (() => {}); + const r = await runCheck(m, o.probes ?? realObserveProbes, o.now ?? new Date()).catch((e: Error): CheckResult => ({ ok: false, degraded: false, reason: e.message, detail: {} })); + const fresh = getMonitor(m.id); + if (!fresh || fresh.paused) return; // deleted or paused while checking + const quiet = m.kind !== "internet" && !r.ok && internetDown(); + const t = recordCheck(fresh, r, { now: o.now, quiet }); + if (!t) return; + const text = transitionText(fresh, t, o.now); + if (text) await announce(db, fresh, t, text, log).catch((e: Error) => log(`observe: announce failed: ${e.message}`)); +} + +/** + * Starts the checks that are due (not on pause, interval passed, not already running). Resolves + * when the started checks are done; the service does not wait for it, tests do. + */ +export async function observeTick(db: Db, o: ObserveTickOptions = {}): Promise { + const now = (o.now ?? new Date()).getTime(); + const limit = o.concurrency ?? (Number(process.env.PEPPA_OBSERVE_CONCURRENCY) || 16); + const due = listMonitors().filter((m) => !m.paused && !inflight.has(m.id) && (!m.lastCheckAt || Date.parse(m.lastCheckAt) + m.intervalSec * 1000 <= now)); + // The internet first: whether others are quiet depends on it. + due.sort((a, b) => Number(b.kind === "internet") - Number(a.kind === "internet")); + const started: Promise[] = []; + for (const m of due) { + if (inflight.size >= limit) break; + inflight.add(m.id); + const p = checkOne(db, m, o).finally(() => inflight.delete(m.id)); + started.push(p); + running.push(p); + } + await Promise.all(started); + return started.length; +} + +/** Tests: wait for every check started so far. */ +export async function observeSettled(): Promise { + while (running.length) await Promise.all(running.splice(0)); +} + +/** Deletes checks and closed incidents older than the retention (default 7 days). */ +export function pruneObserve(now = new Date(), days = retentionDays()): number { + const cut = new Date(now.getTime() - days * 86_400_000).toISOString(); + const db = observeDb(); + const r = db.prepare("DELETE FROM monitor_checks WHERE at < ?").run(cut); + db.prepare("DELETE FROM monitor_incidents WHERE ended_at IS NOT NULL AND ended_at < ?").run(cut); + return Number(r.changes); +} + +// ── built-in monitors ────────────────────────────────────────────────────────────── + +export const DEFAULT_INTERNET_HOSTS = ["api.telegram.org", "chatgpt.com", "api.anthropic.com", "registry.npmjs.org", "git.telecom.quest"]; + +/** On the first start: «eGov relay» (HTTP and DNS for sign.aitu.uz) and «Интернет». Never again. */ +export function seedMonitors(now = new Date()): Monitor[] { + const db = observeDb(); + if (db.prepare("SELECT 1 FROM observe_meta WHERE key = 'seeded'").get()) return []; + const made = [ + createMonitor({ name: "Интернет", kind: "internet", target: { hosts: DEFAULT_INTERNET_HOSTS }, intervalSec: 60 }, "system", now), + createMonitor({ name: "eGov relay", kind: "http", target: { url: "https://sign.aitu.uz/" }, intervalSec: 60 }, "system", now), + createMonitor({ name: "eGov relay — DNS", kind: "dns", target: { host: "sign.aitu.uz" }, intervalSec: 300 }, "system", now), + ]; + db.prepare("INSERT INTO observe_meta (key, value) VALUES ('seeded', ?)").run(now.toISOString()); + return made; +} + diff --git a/packages/mcp/src/agent.ts b/packages/mcp/src/agent.ts index fd2675f0..ed7718d3 100644 --- a/packages/mcp/src/agent.ts +++ b/packages/mcp/src/agent.ts @@ -54,6 +54,8 @@ import { requestReview, reviewGate, sayInDiscussion, storyBranch } from "@peppa/ import { z } from "zod"; import { asIs, m } from "@peppa/shared/i18n"; import { formatIncident, formatTask } from "./format.ts"; +import { registerMonitorTools } from "./monitors.ts"; +import { platformProjectKey } from "@peppa/core"; export interface AgentServerOptions { /** The project of the agent's repo (.peppa/project.json) — default for bare story numbers. */ @@ -107,6 +109,15 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer return project; } + // PEP-202: Observability — only agents of the platform project itself. + registerMonitorTools(db, (name, description, schema, _readOnly, run) => tool(name, description, schema, run), { + async check() { + const key = sessionId ? (await getSession(db, sessionId)).projectKey : defaultKey; + if (!key || key !== platformProjectKey()) throw new PeppaError(`Access denied: monitors are managed only by agents of the platform project ${platformProjectKey()}`); + return { author: sessionId ? `agent:s${sessionId}` : "agent", sessionId: sessionId ?? null }; + }, + }); + /** A story of this project (PEP-17: an agent behind the relay can't reach other projects). */ async function resolve(task: string) { const ref = await resolveTask(db, task, defaultKey); diff --git a/packages/mcp/src/manager.ts b/packages/mcp/src/manager.ts index b98bf18a..7ca3162e 100644 --- a/packages/mcp/src/manager.ts +++ b/packages/mcp/src/manager.ts @@ -58,6 +58,8 @@ import { applyPlan, archiveTask, planEpic, reorderBoardTask, type PlannedStory, import { and, asc, eq, inArray, isNull } from "drizzle-orm"; import { z } from "zod"; import { formatIncident, formatMetrics, formatTask } from "./format.ts"; +import { registerMonitorTools } from "./monitors.ts"; +import { isSuperadmin as isPlatformSuperadmin } from "@peppa/core"; type Result = { content: Array<{ type: "text"; text: string }>; isError?: boolean }; const COLUMNS = ["backlog", "in_progress", "review", "done"] as const; @@ -146,6 +148,14 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ tool("get_started", GET_STARTED_DESCRIPTION, {}, true, async () => MCP_GUIDE); + // PEP-202: Observability — superadmin only. + registerMonitorTools(db, tool, { + async check() { + if (!(await isPlatformSuperadmin(db, user))) throw new PeppaError("Observability is available to the platform superadmin only"); + return { author: `user:${user.login}` }; + }, + }); + tool("list_projects", "List the user's Peppa projects (key, name, Gitea repo URL, story counts by board column).", {}, true, async () => { const ps = await listUserProjects(db, user.id); if (!ps.length) return `${GET_STARTED_HINT}\n\nNo projects yet. Create one at ${webUrl}/projects/new`; diff --git a/packages/mcp/src/monitors.ts b/packages/mcp/src/monitors.ts new file mode 100644 index 00000000..00215d34 --- /dev/null +++ b/packages/mcp/src/monitors.ts @@ -0,0 +1,126 @@ +// PEP-202: Observability tools — the same set in the remote MCP (superadmin only) and in the agent +// MCP (sessions of the platform project only). Every change goes to the journal with its author. +import { z } from "zod"; +import type { Db } from "@peppa/db"; +import { + createMonitor, + deleteMonitor, + describeTarget, + getMonitor, + getProject, + logEvent, + monitorChecks, + monitorIncidents, + monitorView, + listMonitorViews, + PeppaError, + platformProjectKey, + setMonitorPaused, + updateMonitor, + type MonitorKind, + type MonitorView, +} from "@peppa/core"; +import { loadEnv } from "@peppa/shared"; + +type Define = (name: string, description: string, schema: S, readOnly: boolean, run: (a: z.infer>) => Promise) => void; + +export interface MonitorAccess { + /** Throws when the caller may not use monitors; returns the author («user:», «agent:s»). */ + check(): Promise<{ author: string; sessionId?: number | null }>; +} + +export const MONITOR_TOOLS = ["list_monitors", "get_monitor", "create_monitor", "update_monitor", "pause_monitor", "delete_monitor"]; + +const kind = z.enum(["http", "tcp", "dns", "internet", "heartbeat"]); +const target = z + .object({ + url: z.string().optional().describe("http: the address, http:// or https://"), + method: z.enum(["GET", "HEAD"]).optional(), + expectStatus: z.array(z.number().int()).optional().describe("http: accepted codes (default 200–399)"), + contains: z.string().optional().describe("http: text the body must contain"), + maxLatencyMs: z.number().int().optional().describe("http: slower = degraded"), + certDays: z.number().int().optional().describe("http: certificate expiring sooner = degraded (default 14)"), + host: z.string().optional().describe("tcp / dns: host name or IPv4"), + port: z.number().int().optional().describe("tcp: port"), + hosts: z.array(z.string()).optional().describe("internet: up to 10 hosts; down only when none opens"), + graceSec: z.number().int().optional().describe("heartbeat: extra seconds after the interval (default 60)"), + }) + .describe("Where to look; fields by kind"); +const common = { + interval_sec: z.number().int().min(30).optional().describe("Seconds between checks (≥30, default 60)"), + timeout_ms: z.number().int().optional().describe("Per check, 1000–30000 (default 10000)"), + fail_threshold: z.number().int().optional().describe("Bad checks in a row before «down» (default 3)"), + recover_threshold: z.number().int().optional().describe("Good checks in a row before «up» again (default 2)"), +}; + +const pct = (v: number | null) => (v == null ? "—" : `${(v * 100).toFixed(v >= 0.9995 ? 0 : 2)}%`); +const line = (m: MonitorView) => + `- #${m.id} ${m.name} [${m.kind}] ${describeTarget(m, loadEnv().PEPPA_WEB_URL)} — ${m.paused ? "paused" : m.state}${m.lastDetail?.reason ? ` (${m.lastDetail.reason})` : ""} · uptime 24h ${pct(m.uptime24h)}, 7d ${pct(m.uptime7d)}`; + +async function journal(db: Db, type: string, sessionId: number | null | undefined, payload: Record) { + const p = await getProject(db, platformProjectKey()).catch(() => null); + if (p) await logEvent(db, { projectId: p.id, sessionId: sessionId ?? null, type, payload }).catch(() => {}); +} + +export function registerMonitorTools(db: Db, define: Define, access: MonitorAccess): void { + const found = (id: number) => getMonitor(id) ?? (() => { throw new PeppaError("Monitor not found"); })(); + + define("list_monitors", "Observability (PEP-202): every monitor of the Peppa platform with its state, last reason and uptime for 24 h and 7 days.", {}, true, async () => { + await access.check(); + const list = listMonitorViews(); + return list.length ? list.map(line).join("\n") : "No monitors."; + }); + + define("get_monitor", "Observability: one monitor — state, uptime, incidents of the week and the last checks.", { id: z.number().int(), checks: z.number().int().min(1).max(500).optional().describe("How many last checks (default 50)") }, true, async ({ id, checks }) => { + await access.check(); + const m = monitorView(found(id)); + const inc = monitorIncidents(id, 20); + const cs = monitorChecks(id, { limit: checks ?? 50 }); + return [ + line(m), + `interval ${m.intervalSec}s, timeout ${m.timeoutMs}ms, down after ${m.failThreshold} bad, up after ${m.recoverThreshold} good; created by ${m.createdBy}`, + "", + "Incidents:", + ...(inc.length ? inc.map((i) => `- ${i.startedAt} → ${i.endedAt ?? "now"}: ${i.state} — ${i.reason}${i.quiet ? " (with the internet, no message)" : ""}`) : ["- none"]), + "", + "Last checks:", + ...cs.map((c) => `- ${c.at} ${c.ok ? (c.degraded ? "degraded" : "ok") : "FAIL"}${c.latencyMs != null ? ` ${c.latencyMs}ms` : ""}${c.detail.reason ? ` — ${c.detail.reason}` : ""}`), + ].join("\n"); + }); + + define( + "create_monitor", + "Observability: add a monitor. Kinds: http (url, expectStatus, contains, maxLatencyMs, certDays), tcp (host, port), dns (host — system DNS vs 1.1.1.1), internet (hosts), heartbeat (graceSec; returns the ping address the service must call). State changes go to the platform's Telegram channel.", + { name: z.string().min(1).max(80), kind, target, ...common }, + false, + async (a) => { + const who = await access.check(); + const m = createMonitor({ name: a.name, kind: a.kind as MonitorKind, target: a.target, intervalSec: a.interval_sec, timeoutMs: a.timeout_ms, failThreshold: a.fail_threshold, recoverThreshold: a.recover_threshold }, who.author); + await journal(db, "monitor_created", who.sessionId, { id: m.id, name: m.name, kind: m.kind, target: m.target, author: who.author }); + return `Created #${m.id} ${m.name} [${m.kind}] ${describeTarget(m, loadEnv().PEPPA_WEB_URL)}; first check within a few seconds.`; + }, + ); + + define("update_monitor", "Observability: change a monitor (the kind stays). Fields left out stay.", { id: z.number().int(), name: z.string().min(1).max(80).optional(), target: target.optional(), ...common }, false, async (a) => { + const who = await access.check(); + found(a.id); + const m = updateMonitor(a.id, { name: a.name, target: a.target, intervalSec: a.interval_sec, timeoutMs: a.timeout_ms, failThreshold: a.fail_threshold, recoverThreshold: a.recover_threshold }); + await journal(db, "monitor_updated", who.sessionId, { id: m.id, name: m.name, author: who.author }); + return `Updated #${m.id} ${m.name}.`; + }); + + define("pause_monitor", "Observability: pause (no checks, no messages) or resume a monitor.", { id: z.number().int(), paused: z.boolean() }, false, async ({ id, paused }) => { + const who = await access.check(); + found(id); + const m = setMonitorPaused(id, paused); + await journal(db, "monitor_updated", who.sessionId, { id: m.id, name: m.name, paused, author: who.author }); + return `#${m.id} ${m.name}: ${paused ? "paused" : "resumed"}.`; + }); + + define("delete_monitor", "Observability: delete a monitor with its checks and incidents.", { id: z.number().int() }, false, async ({ id }) => { + const who = await access.check(); + const m = deleteMonitor(found(id).id); + await journal(db, "monitor_deleted", who.sessionId, { id: m.id, name: m.name, author: who.author }); + return `Deleted #${m.id} ${m.name}.`; + }); +} diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts index bf1ef238..027714bd 100644 --- a/packages/runner/src/index.ts +++ b/packages/runner/src/index.ts @@ -64,4 +64,3 @@ export * from "./domain-guard.ts"; export * from "./pipeline-guard.ts"; export * from "./pause.ts"; export * from "./pick-question.ts"; -export * from "./net-watch.ts"; diff --git a/packages/runner/src/net-watch.ts b/packages/runner/src/net-watch.ts deleted file mode 100644 index 96835610..00000000 --- a/packages/runner/src/net-watch.ts +++ /dev/null @@ -1,140 +0,0 @@ -// PEP-201: the watchdog watches DNS and the internet from the Peppa host. Every few minutes each -// important host is resolved by the system resolver and by a fallback one (1.1.1.1), and its -// addresses are tried on port 443. A state that holds for two checks in a row and differs from the -// last announced one goes to the platform's Telegram channel (no channel — to the superadmins). -// glossary-ignore-file: messages here are for the superadmin. -import { Resolver, lookup } from "node:dns/promises"; -import net from "node:net"; -import { alertAdmins, getPlatformChannel, getSetting, postToChannel, setSetting } from "@peppa/core"; -import { m } from "@peppa/shared/i18n"; -import type { Db } from "@peppa/db"; - -export type HostState = "ok" | "dns" | "blocked" | "down"; - -export interface HostProbe { - host: string; - state: HostState; - /** System resolver's addresses. */ - system: string[]; - /** Fallback resolver's addresses that answered. */ - working: string[]; -} - -export interface NetProbes { - systemLookup(host: string): Promise; - fallbackLookup(host: string): Promise; - reachable(ip: string, port: number): Promise; -} - -export const DEFAULT_NET_HOSTS = ["sign.aitu.uz", "chatgpt.com", "api.anthropic.com", "api.telegram.org", "git.telecom.quest", "registry.npmjs.org"]; -export const NET_WATCH_EVERY_MS = 5 * 60_000; -const STATE = "net.watch"; - -interface WatchState { - /** Announced state per host, and since when. */ - hosts: Record; - internet?: { down: boolean; since: string; pending?: boolean }; -} - -export const netWatchHosts = () => - (process.env.PEPPA_NET_WATCH_HOSTS ?? "").split(",").map((s) => s.trim()).filter(Boolean).concat(process.env.PEPPA_NET_WATCH_HOSTS ? [] : DEFAULT_NET_HOSTS); - -export const realNetProbes: NetProbes = { - async systemLookup(host) { - return (await lookup(host, { all: true, family: 4 }).catch(() => [])).map((a) => a.address); - }, - async fallbackLookup(host) { - const servers = (process.env.PEPPA_FALLBACK_DNS ?? "1.1.1.1,1.0.0.1").split(",").map((s) => s.trim()).filter((s) => s && s !== "off"); - if (!servers.length) return []; - const r = new Resolver({ timeout: 4_000, tries: 2 }); - r.setServers(servers); - return r.resolve4(host).catch(() => []); - }, - reachable(ip, port) { - return new Promise((resolve) => { - const s = net.connect({ host: ip, port, timeout: 5_000 }); - const done = (ok: boolean) => (s.destroy(), resolve(ok)); - s.once("connect", () => done(true)); - s.once("timeout", () => done(false)); - s.once("error", () => done(false)); - }); - }, -}; - -export async function probeHost(host: string, p: NetProbes): Promise { - const system = await p.systemLookup(host); - const sysOk = (await Promise.all(system.slice(0, 3).map((ip) => p.reachable(ip, 443)))).some(Boolean); - if (sysOk) return { host, state: "ok", system, working: [] }; - const fallback = (await p.fallbackLookup(host)).filter((ip) => !system.includes(ip)).slice(0, 3); - const ok = await Promise.all(fallback.map((ip) => p.reachable(ip, 443))); - const answered = fallback.filter((_, i) => ok[i]); - if (answered.length) return { host, state: system.length ? "blocked" : "dns", system, working: answered }; - return { host, state: "down", system, working: [] }; -} - -const ago = (since: string, now: Date) => Math.max(1, Math.round((now.getTime() - Date.parse(since)) / 60_000)); - -export function describeProbe(p: HostProbe): string { - switch (p.state) { - case "ok": - return m("✅ {host} снова открывается.", { host: p.host }); - case "dns": - return m("🌐 {host}: системный DNS не отвечает, запасной DNS (1.1.1.1) даёт рабочие адреса {ips}. Смените DNS на 1.1.1.1 в настройках сети.", { host: p.host, ips: p.working.join(", ") }); - case "blocked": - return m("🌐 {host}: системный DNS отдаёт недоступные адреса {bad}, рабочие — {ips} (их даёт 1.1.1.1). Смените DNS на 1.1.1.1 в настройках сети или напишите провайдеру.", { host: p.host, bad: p.system.join(", "), ips: p.working.join(", ") }); - case "down": - return m("🌐 {host} недоступен ни по одному адресу.", { host: p.host }); - } -} - -async function announce(db: Db, key: string, text: string, log: (m: string) => void): Promise { - const channel = await getPlatformChannel(db); - if (await postToChannel(db, "services", `mon:ch:${key}`, text, channel)) { - log(`net watch: ${text}`); - return; - } - await alertAdmins(db, `mon:${key}`, text, log); -} - -/** One check of every host; announces states that held for two checks. */ -export async function netWatchTick(db: Db, o: { now?: Date; probes?: NetProbes; hosts?: string[]; log?: (m: string) => void } = {}): Promise { - if (process.env.PEPPA_NET_WATCH === "off") return []; - const now = o.now ?? new Date(); - const log = o.log ?? (() => {}); - const probes = o.probes ?? realNetProbes; - const results = await Promise.all((o.hosts ?? netWatchHosts()).map((h) => probeHost(h, probes))); - const st = (await getSetting(db, STATE)) ?? { hosts: {} }; - const iso = now.toISOString(); - const stamp = now.getTime(); - - // No host answers at all: one "no internet" message instead of one per host. - const allDown = results.length > 0 && results.every((r) => r.state === "down"); - const inet = st.internet ?? { down: false, since: iso }; - if (allDown !== inet.down) { - if (inet.pending === allDown) { - await announce(db, `net:inet:${allDown ? "down" : "up"}:${stamp}`, allDown ? m("🌐 С сервера Peppa FACTORY нет интернета: не открывается ни один из адресов {hosts}.", { hosts: results.map((r) => r.host).join(", ") }) : m("✅ Интернет на сервере Peppa FACTORY снова есть — не было {n} мин.", { n: ago(inet.since, now) }), log); - st.internet = { down: allDown, since: iso }; - } else st.internet = { ...inet, pending: allDown }; - } else st.internet = { down: inet.down, since: inet.since }; - - for (const r of results) { - const prev = st.hosts[r.host] ?? { state: "ok" as HostState, since: iso }; - if (r.state === prev.state) { - st.hosts[r.host] = { state: prev.state, since: prev.since }; - continue; - } - if (prev.pending !== r.state) { - st.hosts[r.host] = { ...prev, pending: r.state }; - continue; - } - // Hosts that are down while the whole internet is down are covered by the message above. - const quiet = allDown || (r.state === "ok" && prev.state === "down" && inet.down); - if (!quiet) { - const text = r.state === "ok" ? `${describeProbe(r)} ${m("Не открывался {n} мин.", { n: ago(prev.since, now) })}` : describeProbe(r); - await announce(db, `net:${r.host}:${r.state}:${stamp}`, text, log); - } - st.hosts[r.host] = { state: r.state, since: iso }; - } - await setSetting(db, STATE, st); - return results; -} diff --git a/packages/runner/src/watchdog.ts b/packages/runner/src/watchdog.ts index 9867ede6..756124da 100644 --- a/packages/runner/src/watchdog.ts +++ b/packages/runner/src/watchdog.ts @@ -33,7 +33,6 @@ import { ADD_SUBSCRIPTION_HINT, freshLimitLine, limitLines, recordLimit } from " import { limitDelay, limitOver } from "./limit-delay.ts"; import { checksQueueTick, platformDelayTick } from "./platform-delays.ts"; import { domainGuardTick } from "./domain-guard.ts"; -import { NET_WATCH_EVERY_MS, netWatchTick } from "./net-watch.ts"; import { killRunner, resumeSession, stopSession } from "./sessions.ts"; import { hostTick } from "./hosts.ts"; import { getProjectPause, injectionDigestTick, getSubscription, isUsable, pausedProjectIds, reportPlatformError, setProjectPause } from "@peppa/core"; @@ -314,7 +313,6 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg: } let lastCiPoll = 0; -let lastNetWatch = 0; export async function runWatchdog(db: Db, opts: WatchdogOptions, signal?: AbortSignal): Promise { const log = opts.log ?? (() => {}); @@ -345,11 +343,6 @@ export async function runWatchdog(db: Db, opts: WatchdogOptions, signal?: AbortS // PEP-189: no container takes the platform's port or domain; the public address answers Peppa. await domainGuardTick(db, { log }).catch(failed(db, log, "domain guard failed")); } - // PEP-201: DNS and the internet from the Peppa host — changes go to the platform channel. - if (Date.now() - lastNetWatch >= NET_WATCH_EVERY_MS) { - lastNetWatch = Date.now(); - await netWatchTick(db, { log }).catch(failed(db, log, "net watch failed")); - } // Daily copy of the SQLite database (PEP-36); a no-op until a day has passed. await backupDb(db, { log }).catch(failed(db, log, "backup failed")); await new Promise((r) => setTimeout(r, opts.intervalMs)); diff --git a/packages/shared/src/i18n/en/index.ts b/packages/shared/src/i18n/en/index.ts index 9e8f8361..09c3d8dc 100644 --- a/packages/shared/src/i18n/en/index.ts +++ b/packages/shared/src/i18n/en/index.ts @@ -22,6 +22,6 @@ import { untrusted } from "./untrusted.ts"; import { mcpGuide } from "./mcp-guide.ts"; import { subscriptionRequest } from "./subscription-request.ts"; import { domainGuard } from "./domain-guard.ts"; -import { netWatch } from "./net-watch.ts"; +import { observe } from "./observe.ts"; -export const en: Dict = { ...common, ...story, ...project, ...admin, ...settings, ...help, ...runner, ...bot, ...merge, ...merge_a, ...merge_b, ...merge_c, ...merge_d, ...feedback, ...attachments, ...capacity, ...untrusted, ...mcpGuide, ...subscriptionRequest, ...domainGuard, ...netWatch, ...intent }; +export const en: Dict = { ...common, ...story, ...project, ...admin, ...settings, ...help, ...runner, ...bot, ...merge, ...merge_a, ...merge_b, ...merge_c, ...merge_d, ...feedback, ...attachments, ...capacity, ...untrusted, ...mcpGuide, ...subscriptionRequest, ...domainGuard, ...observe, ...intent }; diff --git a/packages/shared/src/i18n/en/net-watch.ts b/packages/shared/src/i18n/en/net-watch.ts deleted file mode 100644 index bf4d0b0b..00000000 --- a/packages/shared/src/i18n/en/net-watch.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type { Dict } from "../index.ts"; - -// PEP-201: the watchdog watches DNS and the internet from the Peppa host. -export const netWatch: Dict = { - "✅ {host} снова открывается.": "✅ {host} opens again.", - "🌐 {host}: системный DNS не отвечает, запасной DNS (1.1.1.1) даёт рабочие адреса {ips}. Смените DNS на 1.1.1.1 в настройках сети.": "🌐 {host}: the system DNS does not answer, the fallback DNS (1.1.1.1) gives working addresses {ips}. Switch DNS to 1.1.1.1 in the network settings.", - "🌐 {host}: системный DNS отдаёт недоступные адреса {bad}, рабочие — {ips} (их даёт 1.1.1.1). Смените DNS на 1.1.1.1 в настройках сети или напишите провайдеру.": "🌐 {host}: the system DNS gives unreachable addresses {bad}, working ones are {ips} (from 1.1.1.1). Switch DNS to 1.1.1.1 in the network settings or contact the provider.", - "🌐 {host} недоступен ни по одному адресу.": "🌐 {host} is unreachable at every address.", - "🌐 С сервера Peppa FACTORY нет интернета: не открывается ни один из адресов {hosts}.": "🌐 The Peppa FACTORY server has no internet: none of {hosts} opens.", - "✅ Интернет на сервере Peppa FACTORY снова есть — не было {n} мин.": "✅ The Peppa FACTORY server has internet again — it was gone for {n} min.", - "Не открывался {n} мин.": "It did not open for {n} min.", -}; diff --git a/packages/shared/src/i18n/en/observe.ts b/packages/shared/src/i18n/en/observe.ts new file mode 100644 index 00000000..668a16fd --- /dev/null +++ b/packages/shared/src/i18n/en/observe.ts @@ -0,0 +1,77 @@ +import type { Dict } from "../index.ts"; + +// PEP-202: Observability (superadmin). +export const observe: Dict = { + "Аптайм 24 ч:": "Uptime 24 h:", + "7 дней:": "7 days:", + "в этом состоянии {ago}": "in this state {ago}", + "Сервис отмечается запросом GET или POST по адресу:": "The service checks in with a GET or POST request to:", + "Раз в {n} с · «не работает» после {f} неудач подряд · «работает» после {r} удач · создал {who}": "Every {n} s · «down» after {f} failures in a row · «up» after {r} successes · created by {who}", + "Удалить мониторинг вместе с журналом?": "Delete the monitor together with its log?", + "Сбои за неделю": "Incidents this week", + "Сбоев не было.": "No incidents.", + "сейчас": "now", + "(вместе с интернетом, без сообщения)": "(with the internet, no message)", + "Журнал проверок": "Check log", + "Проверок ещё не было.": "No checks yet.", + "неудача": "failure", + "нестабильно": "unstable", + "← новее": "← newer", + "старее →": "older →", + "Мониторинги сервисов, от которых зависит Peppa FACTORY, и интернета на её сервере. Смена состояния — одно сообщение в Telegram-канал платформы. Журнал проверок хранится 7 дней. Мониторинги можно создавать здесь и через MCP; раздел видят только суперадмины.": "Monitors of the services Peppa FACTORY depends on and of the internet on its server. A change of state is one message to the platform's Telegram channel. The check log is kept for 7 days. Monitors can be created here and via MCP; only superadmins see this section.", + "Мониторинги": "Monitors", + "не работает: {n} · нестабильно: {m}": "down: {n} · unstable: {m}", + "Мониторингов нет. Сервис мониторингов создаст встроенные при первом запуске.": "No monitors. The monitoring service creates the built-in ones on its first start.", + "Аптайм за 24 часа": "Uptime for 24 hours", + "Аптайм за 7 дней": "Uptime for 7 days", + "ещё не проверялся": "not checked yet", + "Новый мониторинг": "New monitor", + "на паузе": "paused", + "Последние проверки": "Last checks", + "https://… · хост · хост:порт · адреса через запятую (у heartbeat пусто)": "https://… · host · host:port · hosts separated by commas (empty for heartbeat)", + "Проверять раз в, с": "Check every, s", + "Текст в ответе (HTTP)": "Text in the response (HTTP)", + "Коды ответа (HTTP), через запятую": "Response codes (HTTP), comma-separated", + "Медленнее, мс — нестабилен (HTTP)": "Slower than, ms — unstable (HTTP)", + "Неудач подряд до «не работает»": "Failures in a row before «down»", + "Удач подряд до «работает»": "Successes in a row before «up»", + "Запас heartbeat, с": "Heartbeat grace, s", + "мониторинги": "monitors", + "нет ответа за {n} с": "no answer in {n} s", + "нет ответа ({error})": "no answer ({error})", + "ответ {status}": "response {status}", + "в ответе нет «{text}»": "the response has no «{text}»", + "отвечает только через запасной DNS": "answers only via the fallback DNS", + "медленно: {n} мс": "slow: {n} ms", + "сертификат истёк": "the certificate has expired", + "сертификат истекает через {n} дн.": "the certificate expires in {n} days", + "порт {port} не открывается": "port {port} does not open", + "системный DNS отдаёт недоступные адреса {bad}, рабочие — {ips} (их даёт 1.1.1.1)": "the system DNS gives unreachable addresses {bad}, working ones are {ips} (from 1.1.1.1)", + "системный DNS не отвечает, рабочие адреса {ips} даёт 1.1.1.1": "the system DNS does not answer, 1.1.1.1 gives working addresses {ips}", + "недоступен ни по одному адресу": "unreachable at every address", + "не открывается ни один из адресов {hosts}": "none of {hosts} opens", + "нет отметки {n} мин": "no check-in for {n} min", + "✅ {name} снова работает — простой {n} мин.": "✅ {name} is up again — downtime {n} min.", + "🔴 {name} не работает: {reason}": "🔴 {name} is down: {reason}", + "🟡 {name} нестабилен: {reason}": "🟡 {name} is unstable: {reason}", + "Неизвестный вид мониторинга: {kind}": "Unknown monitor kind: {kind}", + "Подтвердите удаление": "Confirm the deletion", + "24 ч": "24 h", + "7 д": "7 d", + "{n} мс": "{n} ms", + "Интернет": "Internet", + "работает": "up", + "не работает": "down", + "нестабилен": "unstable", + "проверяется": "checking", + "Observability": "Observability", + "Observability — Peppa FACTORY": "Observability — Peppa FACTORY", + "{field}: целое число от {min} до {max}": "{field}: a whole number from {min} to {max}", + "Неверное имя хоста: {host}": "Invalid host name: {host}", + "Неверный адрес: нужен http:// или https://": "Invalid address: http:// or https:// is needed", + "Интернет: от 1 до 10 адресов": "Internet: 1 to 10 hosts", + "Название: от 1 до 80 символов": "Name: 1 to 80 characters", + "Мониторингов уже {n} — больше нельзя": "There are already {n} monitors — no more allowed", + "Мониторинг не найден": "Monitor not found", + "Вид мониторинга не меняется — создайте новый": "The monitor kind cannot change — create a new one", +}; diff --git a/packages/shared/src/i18n/kk/index.ts b/packages/shared/src/i18n/kk/index.ts index e831877c..defffd65 100644 --- a/packages/shared/src/i18n/kk/index.ts +++ b/packages/shared/src/i18n/kk/index.ts @@ -22,6 +22,6 @@ import { untrusted } from "./untrusted.ts"; import { mcpGuide } from "./mcp-guide.ts"; import { subscriptionRequest } from "./subscription-request.ts"; import { domainGuard } from "./domain-guard.ts"; -import { netWatch } from "./net-watch.ts"; +import { observe } from "./observe.ts"; -export const kk: Dict = { ...admin, ...bot, ...common, ...help, ...mergeA, ...mergeB, ...mergeC, ...mergeD, ...merge, ...project, ...runner, ...settings, ...story, ...feedback, ...attachments, ...capacity, ...untrusted, ...mcpGuide, ...subscriptionRequest, ...domainGuard, ...netWatch, ...intent }; +export const kk: Dict = { ...admin, ...bot, ...common, ...help, ...mergeA, ...mergeB, ...mergeC, ...mergeD, ...merge, ...project, ...runner, ...settings, ...story, ...feedback, ...attachments, ...capacity, ...untrusted, ...mcpGuide, ...subscriptionRequest, ...domainGuard, ...observe, ...intent }; diff --git a/packages/shared/src/i18n/kk/net-watch.ts b/packages/shared/src/i18n/kk/net-watch.ts deleted file mode 100644 index 298f7f7a..00000000 --- a/packages/shared/src/i18n/kk/net-watch.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type { Dict } from "../index.ts"; - -// PEP-201: the watchdog watches DNS and the internet from the Peppa host. -export const netWatch: Dict = { - "✅ {host} снова открывается.": "✅ {host} қайта ашылады.", - "🌐 {host}: системный DNS не отвечает, запасной DNS (1.1.1.1) даёт рабочие адреса {ips}. Смените DNS на 1.1.1.1 в настройках сети.": "🌐 {host}: жүйелік DNS жауап бермейді, қосалқы DNS (1.1.1.1) жұмыс істейтін мекенжайлар береді: {ips}. Желі баптауларында DNS-ті 1.1.1.1-ге ауыстырыңыз.", - "🌐 {host}: системный DNS отдаёт недоступные адреса {bad}, рабочие — {ips} (их даёт 1.1.1.1). Смените DNS на 1.1.1.1 в настройках сети или напишите провайдеру.": "🌐 {host}: жүйелік DNS қолжетімсіз мекенжайлар береді: {bad}, жұмыс істейтіндері — {ips} (1.1.1.1 береді). Желі баптауларында DNS-ті 1.1.1.1-ге ауыстырыңыз немесе провайдерге жазыңыз.", - "🌐 {host} недоступен ни по одному адресу.": "🌐 {host} ешбір мекенжай бойынша қолжетімсіз.", - "🌐 С сервера Peppa FACTORY нет интернета: не открывается ни один из адресов {hosts}.": "🌐 Peppa FACTORY серверінде интернет жоқ: {hosts} мекенжайларының ешқайсысы ашылмайды.", - "✅ Интернет на сервере Peppa FACTORY снова есть — не было {n} мин.": "✅ Peppa FACTORY серверінде интернет қайта бар — {n} мин болмады.", - "Не открывался {n} мин.": "{n} мин ашылмады.", -}; diff --git a/packages/shared/src/i18n/kk/observe.ts b/packages/shared/src/i18n/kk/observe.ts new file mode 100644 index 00000000..89ef100a --- /dev/null +++ b/packages/shared/src/i18n/kk/observe.ts @@ -0,0 +1,77 @@ +import type { Dict } from "../index.ts"; + +// PEP-202: Observability (superadmin). +export const observe: Dict = { + "Аптайм 24 ч:": "Аптайм 24 сағ:", + "7 дней:": "7 күн:", + "в этом состоянии {ago}": "бұл күйде {ago}", + "Сервис отмечается запросом GET или POST по адресу:": "Сервис мына мекенжайға GET немесе POST сұрауымен белгі береді:", + "Раз в {n} с · «не работает» после {f} неудач подряд · «работает» после {r} удач · создал {who}": "Әр {n} с · қатарынан {f} сәтсіздіктен кейін «жұмыс істемейді» · {r} сәттіліктен кейін «жұмыс істейді» · жасаған {who}", + "Удалить мониторинг вместе с журналом?": "Мониторингті журналымен бірге жою керек пе?", + "Сбои за неделю": "Апта ішіндегі іркілістер", + "Сбоев не было.": "Іркіліс болған жоқ.", + "сейчас": "қазір", + "(вместе с интернетом, без сообщения)": "(интернетпен бірге, хабарламасыз)", + "Журнал проверок": "Тексерулер журналы", + "Проверок ещё не было.": "Әзірге тексеру болған жоқ.", + "неудача": "сәтсіз", + "нестабильно": "тұрақсыз", + "← новее": "← жаңарақ", + "старее →": "ескірек →", + "Мониторинги сервисов, от которых зависит Peppa FACTORY, и интернета на её сервере. Смена состояния — одно сообщение в Telegram-канал платформы. Журнал проверок хранится 7 дней. Мониторинги можно создавать здесь и через MCP; раздел видят только суперадмины.": "Peppa FACTORY тәуелді сервистердің және оның серверіндегі интернеттің мониторингтері. Күйдің өзгеруі — платформаның Telegram-арнасына бір хабарлама. Тексерулер журналы 7 күн сақталады. Мониторингтерді осында және MCP арқылы жасауға болады; бөлімді тек суперәкімшілер көреді.", + "Мониторинги": "Мониторингтер", + "не работает: {n} · нестабильно: {m}": "жұмыс істемейді: {n} · тұрақсыз: {m}", + "Мониторингов нет. Сервис мониторингов создаст встроенные при первом запуске.": "Мониторинг жоқ. Мониторинг сервисі алғаш іске қосылғанда кірістірілгендерін жасайды.", + "Аптайм за 24 часа": "24 сағаттағы аптайм", + "Аптайм за 7 дней": "7 күндегі аптайм", + "ещё не проверялся": "әлі тексерілмеген", + "Новый мониторинг": "Жаңа мониторинг", + "на паузе": "кідірісте", + "Последние проверки": "Соңғы тексерулер", + "https://… · хост · хост:порт · адреса через запятую (у heartbeat пусто)": "https://… · хост · хост:порт · үтір арқылы мекенжайлар (heartbeat үшін бос)", + "Проверять раз в, с": "Тексеру жиілігі, с", + "Текст в ответе (HTTP)": "Жауаптағы мәтін (HTTP)", + "Коды ответа (HTTP), через запятую": "Жауап кодтары (HTTP), үтір арқылы", + "Медленнее, мс — нестабилен (HTTP)": "Баяуырақ, мс — тұрақсыз (HTTP)", + "Неудач подряд до «не работает»": "«Жұмыс істемейді» дейін қатарынан сәтсіздік", + "Удач подряд до «работает»": "«Жұмыс істейді» дейін қатарынан сәттілік", + "Запас heartbeat, с": "Heartbeat қоры, с", + "мониторинги": "мониторингтер", + "нет ответа за {n} с": "{n} с ішінде жауап жоқ", + "нет ответа ({error})": "жауап жоқ ({error})", + "ответ {status}": "жауап {status}", + "в ответе нет «{text}»": "жауапта «{text}» жоқ", + "отвечает только через запасной DNS": "тек қосалқы DNS арқылы жауап береді", + "медленно: {n} мс": "баяу: {n} мс", + "сертификат истёк": "сертификаттың мерзімі өтті", + "сертификат истекает через {n} дн.": "сертификаттың мерзімі {n} күннен кейін бітеді", + "порт {port} не открывается": "{port} порты ашылмайды", + "системный DNS отдаёт недоступные адреса {bad}, рабочие — {ips} (их даёт 1.1.1.1)": "жүйелік DNS қолжетімсіз мекенжайлар береді: {bad}, жұмыс істейтіндері — {ips} (1.1.1.1 береді)", + "системный DNS не отвечает, рабочие адреса {ips} даёт 1.1.1.1": "жүйелік DNS жауап бермейді, 1.1.1.1 жұмыс істейтін мекенжайлар береді: {ips}", + "недоступен ни по одному адресу": "ешбір мекенжай бойынша қолжетімсіз", + "не открывается ни один из адресов {hosts}": "{hosts} мекенжайларының ешқайсысы ашылмайды", + "нет отметки {n} мин": "{n} мин белгі жоқ", + "✅ {name} снова работает — простой {n} мин.": "✅ {name} қайта жұмыс істейді — тоқтап тұрғаны {n} мин.", + "🔴 {name} не работает: {reason}": "🔴 {name} жұмыс істемейді: {reason}", + "🟡 {name} нестабилен: {reason}": "🟡 {name} тұрақсыз: {reason}", + "Неизвестный вид мониторинга: {kind}": "Мониторингтің белгісіз түрі: {kind}", + "Подтвердите удаление": "Жоюды растаңыз", + "24 ч": "24 сағ", + "7 д": "7 к", + "{n} мс": "{n} мс", + "Интернет": "Интернет", + "работает": "жұмыс істейді", + "не работает": "жұмыс істемейді", + "нестабилен": "тұрақсыз", + "проверяется": "тексерілуде", + "Observability": "Observability", + "Observability — Peppa FACTORY": "Observability — Peppa FACTORY", + "{field}: целое число от {min} до {max}": "{field}: {min}-ден {max}-ге дейінгі бүтін сан", + "Неверное имя хоста: {host}": "Хост атауы қате: {host}", + "Неверный адрес: нужен http:// или https://": "Мекенжай қате: http:// немесе https:// керек", + "Интернет: от 1 до 10 адресов": "Интернет: 1-ден 10-ға дейін мекенжай", + "Название: от 1 до 80 символов": "Атауы: 1-ден 80-ге дейін таңба", + "Мониторингов уже {n} — больше нельзя": "Мониторинг саны {n} — бұдан артық болмайды", + "Мониторинг не найден": "Мониторинг табылмады", + "Вид мониторинга не меняется — создайте новый": "Мониторинг түрі өзгермейді — жаңасын жасаңыз", +}; diff --git a/packages/testkit/test/helpers.ts b/packages/testkit/test/helpers.ts index eada46ce..6c572c21 100644 --- a/packages/testkit/test/helpers.ts +++ b/packages/testkit/test/helpers.ts @@ -39,7 +39,6 @@ Object.assign(process.env, { // PEP-189: the guard runs `docker stop` — never against the real docker of the machine running tests; // domain-guard.test.ts turns it on with mock-docker. PEPPA_DOMAIN_GUARD: "off", - PEPPA_NET_WATCH: "off", // PEP-153: the message classifier never reaches a real CLI from a test. PEPPA_INTENT_BIN: join(ROOT, "packages/testkit/bin/mock-intake"), }); diff --git a/packages/testkit/test/net-watch.test.ts b/packages/testkit/test/net-watch.test.ts deleted file mode 100644 index dcca573e..00000000 --- a/packages/testkit/test/net-watch.test.ts +++ /dev/null @@ -1,97 +0,0 @@ -// PEP-201: the watchdog watches DNS and the internet from the Peppa host and tells the platform -// channel (no channel — the superadmins) about changes that held for two checks. -import assert from "node:assert/strict"; -import { after, describe, test } from "node:test"; -import { core, db, runner, teardown } from "./helpers.ts"; -import { telegramOutbox } from "@peppa/db"; -import { like } from "drizzle-orm"; -import { stripAsIs } from "@peppa/shared/i18n"; -import type { NetProbes } from "@peppa/runner"; - -process.env.PEPPA_SECRET = "mock-secret-for-tests"; -delete process.env.PEPPA_NET_WATCH; -after(teardown); - -/** Mock network: what the system and fallback resolvers give, which addresses answer. */ -function mockNet() { - const system = new Map(); - const fallback = new Map(); - const up = new Set(); - const probes: NetProbes = { - systemLookup: async (h) => system.get(h) ?? [], - fallbackLookup: async (h) => fallback.get(h) ?? [], - reachable: async (ip) => up.has(ip), - }; - return { system, fallback, up, probes }; -} - -const texts = async (prefix: string) => - (await db.select().from(telegramOutbox).where(like(telegramOutbox.dedupeKey, `${prefix}%`))).map((r) => ({ chat: r.params.chat_id, text: stripAsIs(String(r.params.text)) })); - -describe("net watch", () => { - const hosts = ["mock-relay.example", "mock-ai.example"]; - const net = mockNet(); - net.system.set("mock-relay.example", ["10.0.0.1"]).set("mock-ai.example", ["10.0.1.1"]); - net.fallback.set("mock-relay.example", ["10.0.0.9"]).set("mock-ai.example", ["10.0.1.1"]); - net.up.add("10.0.0.1").add("10.0.1.1").add("10.0.0.9"); - let t = Date.parse("2026-11-17T10:00:00Z"); - const tick = () => runner.netWatchTick(db, { probes: net.probes, hosts, now: new Date((t += 5 * 60_000)) }); - - test("probe: ok, bad addresses from the system DNS, no DNS, down", async () => { - assert.equal((await runner.probeHost("mock-relay.example", net.probes)).state, "ok"); - net.up.delete("10.0.0.1"); - const p = await runner.probeHost("mock-relay.example", net.probes); - assert.equal(p.state, "blocked"); - assert.deepEqual(p.working, ["10.0.0.9"]); - assert.match(stripAsIs(runner.describeProbe(p)), /10\.0\.0\.1.*10\.0\.0\.9.*1\.1\.1\.1/); - net.system.set("mock-relay.example", []); - assert.equal((await runner.probeHost("mock-relay.example", net.probes)).state, "dns"); - net.up.delete("10.0.0.9"); - assert.equal((await runner.probeHost("mock-relay.example", net.probes)).state, "down"); - net.system.set("mock-relay.example", ["10.0.0.1"]); - net.up.add("10.0.0.1").add("10.0.0.9"); - }); - - test("no channel: the superadmins hear a change once it held for two checks, and the recovery", async () => { - const chat = 880_001; - const u = await core.upsertUserFromGitea(db, { id: chat, login: "mock-net-admin" }, { access_token: "x" }); - const { users } = await import("@peppa/db"); - const { eq } = await import("drizzle-orm"); - await db.update(users).set({ telegramChatId: chat, telegramUserId: chat }).where(eq(users.id, u.id)); - await core.setPlatformAdmins(db, ["mock-net-admin"]); - - await tick(); - net.up.delete("10.0.0.1"); // the system DNS points at an unreachable address - await tick(); - assert.equal((await texts("mon:net:")).length, 0, "one bad check is not enough"); - await tick(); - let msgs = await texts("mon:net:"); - assert.equal(msgs.length, 1); - assert.match(msgs[0]!.text, /mock-relay\.example.*недоступные адреса 10\.0\.0\.1.*10\.0\.0\.9/); - await tick(); - assert.equal((await texts("mon:net:")).length, 1, "the same state is not repeated"); - net.up.add("10.0.0.1"); - await tick(); - await tick(); - msgs = await texts("mon:net:"); - assert.equal(msgs.length, 2); - assert.match(msgs[1]!.text, /mock-relay\.example снова открывается\. Не открывался 15 мин/); - }); - - test("the channel is connected: messages go there; no internet is one message, not one per host", async () => { - await core.setSetting(db, "platform.telegram_channel", { chatId: -100777, title: "mock", check: { ok: true, error: null, at: new Date().toISOString() }, events: { releases: true, services: true, digest: true }, digest: { time: "09:00", timezone: "UTC", users: false } }); - net.up.clear(); - await tick(); - await tick(); - let msgs = await texts("mon:ch:net:"); - assert.equal(msgs.length, 1); - assert.equal(msgs[0]!.chat, -100777); - assert.match(msgs[0]!.text, /нет интернета.*mock-relay\.example, mock-ai\.example/); - net.up.add("10.0.0.1").add("10.0.1.1").add("10.0.0.9"); - await tick(); - await tick(); - msgs = await texts("mon:ch:net:"); - assert.equal(msgs.length, 2); - assert.match(msgs[1]!.text, /Интернет .* снова есть — не было 10 мин/); - }); -}); diff --git a/packages/testkit/test/oauth.test.ts b/packages/testkit/test/oauth.test.ts index 6c191a3f..6869c1f8 100644 --- a/packages/testkit/test/oauth.test.ts +++ b/packages/testkit/test/oauth.test.ts @@ -99,7 +99,7 @@ describe("PM tools over MCP", () => { await core.setProjectOwner(db, proj.id, owner.id); const { client, call } = await mcpAs(owner); const tools = (await client.listTools()).tools; - assert.deepEqual(tools.map((t) => t.name).sort(), ["add_member", "answer_question", "apply_plan", "archive_task", "create_epic", "create_goal", "create_project", "create_task", "decide_incident", "deploy", "get_incident", "get_incident_policy", "get_metrics", "get_project_settings", "get_started", "get_task", "get_usage", "list_epics", "list_goals", "list_inbox", "list_incidents", "list_members", "list_projects", "list_releases", "list_secrets", "list_tasks", "move_task", "plan_epic", "remove_member", "reorder_task", "resolve_incident", "set_dependencies", "set_incident_policy", "set_project_visibility", "update_epic", "update_goal", "update_project_settings", "update_task"]); + assert.deepEqual(tools.map((t) => t.name).sort(), ["add_member", "answer_question", "apply_plan", "archive_task", "create_epic", "create_goal", "create_monitor", "create_project", "create_task", "decide_incident", "delete_monitor", "deploy", "get_incident", "get_incident_policy", "get_metrics", "get_monitor", "get_project_settings", "get_started", "get_task", "get_usage", "list_epics", "list_goals", "list_inbox", "list_incidents", "list_members", "list_monitors", "list_projects", "list_releases", "list_secrets", "list_tasks", "move_task", "pause_monitor", "plan_epic", "remove_member", "reorder_task", "resolve_incident", "set_dependencies", "set_incident_policy", "set_project_visibility", "update_epic", "update_goal", "update_monitor", "update_project_settings", "update_task"]); assert.equal(tools.find((t) => t.name === "list_tasks")?.annotations?.readOnlyHint, true); assert.equal(tools.find((t) => t.name === "move_task")?.annotations?.readOnlyHint, false); diff --git a/packages/testkit/test/observability.test.ts b/packages/testkit/test/observability.test.ts new file mode 100644 index 00000000..d8aaae2c --- /dev/null +++ b/packages/testkit/test/observability.test.ts @@ -0,0 +1,241 @@ +// PEP-202, spec observability: monitors of the platform — checks on a mock network, states after +// N bad/good checks in a row, one message per change (the platform channel or the superadmins), +// quiet while the internet is down, heartbeat, 7-day retention, built-in monitors, access via MCP. +import assert from "node:assert/strict"; +import { after, describe, test } from "node:test"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { events, telegramOutbox, users } from "@peppa/db"; +import { and, eq, like } from "drizzle-orm"; +import { stripAsIs } from "@peppa/shared/i18n"; +import type { ObserveProbes } from "@peppa/core"; +import { core, db, project, teardown } from "./helpers.ts"; + +process.env.PEPPA_SECRET = "mock-secret-for-tests"; +process.env.PEPPA_WEB_URL = "http://peppa.test"; +const { createAgentServer } = await import("@peppa/mcp/agent"); +const { createManagerServer } = await import("@peppa/mcp/manager"); +after(async () => { + core.closeObserveDb(); + await teardown(); +}); + +/** Mock network: per host the system / fallback addresses, which addresses answer, HTTP answers. */ +function mockNet() { + const system = new Map(); + const fallback = new Map(); + const up = new Set(); + const http = new Map(); + const probes: ObserveProbes = { + async http(url) { + const a = http.get(url) ?? { status: 200, body: "ok" }; + if (a === "timeout") throw Object.assign(new Error("timeout"), { name: "TimeoutError" }); + return a; + }, + certDaysLeft: async () => 90, + systemLookup: async (h) => system.get(h) ?? [], + fallbackLookup: async (h) => fallback.get(h) ?? [], + reachable: async (ip) => up.has(ip), + }; + return { system, fallback, up, http, probes }; +} + +const sent = async (prefix: string) => + (await db.select().from(telegramOutbox).where(like(telegramOutbox.dedupeKey, `${prefix}%`))).map((r) => ({ chat: r.params.chat_id, text: stripAsIs(String(r.params.text)) })); + +let clock = Date.parse("2026-11-17T10:00:00Z"); +const net = mockNet(); +/** One pass of the service a minute later (every monitor here checks once a minute). */ +async function pass(minutes = 1) { + clock += minutes * 60_000; + await core.observeTick(db, { probes: net.probes, now: new Date(clock) }); +} + +async function mcp(server: { connect: (t: never) => Promise }) { + const [a, b] = InMemoryTransport.createLinkedPair(); + await server.connect(a as never); + const client = new Client({ name: "mock", version: "0" }); + await client.connect(b); + return async (name: string, args: Record = {}) => { + const r = await client.callTool({ name, arguments: args }); + return { text: (r.content as Array<{ text: string }>)[0]!.text, isError: !!r.isError }; + }; +} + +describe("Observability", () => { + test("Scenario: built-in monitors on the first start; a deleted one does not come back", () => { + const made = core.seedMonitors(new Date(clock)); + assert.deepEqual(made.map((m) => m.name), ["Интернет", "eGov relay", "eGov relay — DNS"]); + for (const m of made) core.deleteMonitor(m.id); + assert.deepEqual(core.seedMonitors(new Date(clock)), [], "seeded once"); + assert.equal(core.listMonitors().length, 0); + }); + + test("Scenario: validation — a bad address, a short interval, an unknown kind", () => { + assert.throws(() => core.createMonitor({ name: "x", kind: "http", target: { url: "ftp://a" } }, "system"), /http:\/\/ или https:\/\//); + assert.throws(() => core.createMonitor({ name: "x", kind: "tcp", target: { host: "a.example", port: 1 }, intervalSec: 5 }, "system"), /intervalSec/); + assert.throws(() => core.createMonitor({ name: "x", kind: "nope" as never, target: {} }, "system"), /Неизвестный вид/); + }); + + test("Scenario: down after 3 bad checks, up after 2 good — one message each, with the downtime; a single failure says nothing", async () => { + const chat = 880_101; + const u = await core.upsertUserFromGitea(db, { id: chat, login: "mock-obs-admin" }, { access_token: "x" }); + await db.update(users).set({ telegramChatId: chat, telegramUserId: chat }).where(eq(users.id, u.id)); + await core.setPlatformAdmins(db, ["mock-obs-admin"]); + + const m = core.createMonitor({ name: "mock relay", kind: "http", target: { url: "https://mock-relay.example/" }, intervalSec: 60 }, "system", new Date(clock)); + await pass(); + assert.equal(core.getMonitor(m.id)!.state, "up", "the first good check: up without a message"); + net.http.set("https://mock-relay.example/", "timeout"); + await pass(); + net.http.delete("https://mock-relay.example/"); + await pass(); + assert.equal(core.getMonitor(m.id)!.state, "up"); + assert.equal((await sent("mon:obs:")).length, 0, "a single failure — no message"); + + net.http.set("https://mock-relay.example/", { status: 503, body: "" }); + await pass(); + await pass(); + assert.equal((await sent("mon:obs:")).length, 0, "two bad checks are not enough"); + await pass(); + assert.equal(core.getMonitor(m.id)!.state, "down"); + let msgs = await sent("mon:obs:"); + assert.equal(msgs.length, 1); + assert.equal(msgs[0]!.chat, chat); + assert.match(msgs[0]!.text, /🔴 mock relay не работает: ответ 503/); + await pass(); + assert.equal((await sent("mon:obs:")).length, 1, "still down — nothing new"); + + net.http.delete("https://mock-relay.example/"); + await pass(); + assert.equal(core.getMonitor(m.id)!.state, "down", "one good check is not enough"); + await pass(); + msgs = await sent("mon:obs:"); + assert.equal(msgs.length, 2); + assert.match(msgs[1]!.text, /✅ mock relay снова работает — простой 3 мин/); + const inc = core.monitorIncidents(m.id); + assert.equal(inc.length, 1); + assert.ok(inc[0]!.endedAt); + const view = core.monitorView(core.getMonitor(m.id)!, new Date(clock)); + assert.ok(view.uptime24h! > 0 && view.uptime24h! < 1); + assert.equal(view.recent.length, 9); + core.deleteMonitor(m.id); + }); + + test("Scenario: the system DNS gives unreachable addresses — «unstable» with both address sets", async () => { + net.system.set("mock-sign.example", ["10.0.0.1"]); + net.fallback.set("mock-sign.example", ["10.0.0.9"]); + net.up.add("10.0.0.9"); + const m = core.createMonitor({ name: "mock sign DNS", kind: "dns", target: { host: "mock-sign.example" }, intervalSec: 60, failThreshold: 2 }, "system", new Date(clock)); + await pass(); + await pass(); + const cur = core.getMonitor(m.id)!; + assert.equal(cur.state, "degraded"); + const msgs = await sent("mon:obs:"); + assert.match(msgs.at(-1)!.text, /🟡 mock sign DNS нестабилен: системный DNS отдаёт недоступные адреса 10\.0\.0\.1, рабочие — 10\.0\.0\.9/); + core.deleteMonitor(m.id); + }); + + test("Scenario: the channel is connected — messages go there; while the internet is down others stay quiet", async () => { + await core.setSetting(db, "platform.telegram_channel", { chatId: -100555, title: "mock", check: { ok: true, error: null, at: new Date().toISOString() }, events: { releases: true, services: true, digest: true }, digest: { time: "09:00", timezone: "UTC", users: false } }); + for (const h of ["mock-a.example", "mock-b.example"]) net.system.set(h, [`10.1.0.${h.length}`]); + net.up.add("10.1.0.14"); + const inet = core.createMonitor({ name: "mock internet", kind: "internet", target: { hosts: ["mock-a.example", "mock-b.example"] }, intervalSec: 60, failThreshold: 2 }, "system", new Date(clock)); + const svc = core.createMonitor({ name: "mock service", kind: "tcp", target: { host: "10.1.0.14", port: 443 }, intervalSec: 60, failThreshold: 2 }, "system", new Date(clock)); + await pass(); + assert.equal(core.getMonitor(inet.id)!.state, "up"); + assert.equal(core.getMonitor(svc.id)!.state, "up"); + net.up.clear(); + await pass(); + await pass(); + let msgs = await sent("mon:ch:obs:"); + assert.equal(msgs.length, 1, "one message — about the internet"); + assert.equal(msgs[0]!.chat, -100555); + assert.match(msgs[0]!.text, /mock internet не работает: не открывается ни один из адресов mock-a\.example, mock-b\.example/); + assert.equal(core.getMonitor(svc.id)!.state, "down", "the service is down too, quietly"); + assert.ok(core.monitorIncidents(svc.id)[0]!.quiet); + net.up.add("10.1.0.14"); + await pass(); + await pass(); + msgs = await sent("mon:ch:obs:"); + assert.equal(msgs.length, 2, "only the internet's recovery"); + assert.match(msgs[1]!.text, /mock internet снова работает — простой 2 мин/); + core.deleteMonitor(inet.id); + core.deleteMonitor(svc.id); + }); + + test("Scenario: heartbeat — silent longer than interval + grace = a failed check; a ping fixes it", async () => { + const m = core.createMonitor({ name: "mock cron", kind: "heartbeat", target: { graceSec: 60 }, intervalSec: 300, failThreshold: 1 }, "system", new Date(clock)); + assert.ok(m.token); + assert.equal(core.pingHeartbeat("nope-nope-nope"), false); + clock += 7 * 60_000; + await core.observeTick(db, { probes: net.probes, now: new Date(clock) }); + assert.equal(core.getMonitor(m.id)!.state, "down"); + assert.equal(core.pingHeartbeat(m.token!, new Date(clock)), true); + clock += 5 * 60_000; + await core.observeTick(db, { probes: net.probes, now: new Date(clock) }); + assert.equal(core.monitorChecks(m.id)[0]!.ok, true); + core.deleteMonitor(m.id); + }); + + test("Scenario: retention — checks older than 7 days are deleted, newer stay; a paused monitor is not checked", async () => { + const m = core.createMonitor({ name: "mock old", kind: "tcp", target: { host: "10.9.9.9", port: 80 }, intervalSec: 60 }, "system", new Date(clock)); + await pass(); + const old = new Date(clock); + clock += 8 * 86_400_000; + await pass(); + assert.equal(core.monitorChecks(m.id).length, 2); + core.pruneObserve(new Date(clock)); + const left = core.monitorChecks(m.id); + assert.equal(left.length, 1); + assert.ok(left[0]!.at > old.toISOString()); + core.setMonitorPaused(m.id, true, new Date(clock)); + await pass(); + assert.equal(core.monitorChecks(m.id).length, 1, "paused — no check"); + core.deleteMonitor(m.id); + }); + + test("Scenario: MCP — the platform's agent creates a monitor (journal with the author), another project's agent and a non-superadmin are refused", async () => { + const platform = await project({ turns: [[{ say: "ok" }]] }); + const other = await project({ turns: [[{ say: "ok" }]] }); + process.env.PEPPA_PLATFORM_KEY = platform.key; + try { + const own = await mcp(createAgentServer(db, { defaultKey: platform.key })); + const r = await own("create_monitor", { name: "mock from agent", kind: "http", target: { url: "https://mock-agent.example/" } }); + assert.equal(r.isError, false, r.text); + assert.match(r.text, /Created #\d+ mock from agent/); + const proj = await core.getProject(db, platform.key); + const ev = await db.select().from(events).where(and(eq(events.projectId, proj.id), eq(events.type, "monitor_created"))); + assert.equal(ev.length, 1); + assert.equal((ev[0]!.payload as { author: string }).author, "agent"); + assert.match((await own("list_monitors")).text, /mock from agent/); + + const foreign = await mcp(createAgentServer(db, { defaultKey: other.key })); + const no = await foreign("create_monitor", { name: "mock foreign", kind: "dns", target: { host: "a.example" } }); + assert.equal(no.isError, true); + assert.match(no.text, /Access denied/); + assert.ok(!core.listMonitors().some((m) => m.name === "mock foreign")); + + const pm = await core.upsertUserFromGitea(db, { id: 880_202, login: "mock-obs-pm" }, { access_token: "x" }); + const remote = await mcp(createManagerServer(db, pm, "http://peppa.test")); + const refused = await remote("list_monitors"); + assert.equal(refused.isError, true); + assert.match(refused.text, /superadmin only/); + const admin = await core.getUserByLogin(db, "mock-obs-admin"); + if (admin) { + const ok = await mcp(createManagerServer(db, admin, "http://peppa.test")); + assert.match((await ok("list_monitors")).text, /mock from agent/); + } + } finally { + delete process.env.PEPPA_PLATFORM_KEY; + } + }); + + test("Scenario: the observer is a watched service only once it has reported", async () => { + let names = (await core.serviceStatus(db)).map((s) => s.service); + assert.ok(!names.includes("observer"), "not installed — not counted"); + await core.beat(db, "observer"); + names = (await core.serviceStatus(db)).map((s) => s.service); + assert.ok(names.includes("observer")); + }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index da0c17be..0db1c498 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -191,6 +191,18 @@ importers: specifier: 0.45.4 version: 0.45.4(postgres@4.1.1) + apps/observer: + dependencies: + '@peppa/core': + specifier: workspace:* + version: link:../../packages/core + '@peppa/db': + specifier: workspace:* + version: link:../../packages/db + '@peppa/shared': + specifier: workspace:* + version: link:../../packages/shared + apps/web: dependencies: '@modelcontextprotocol/sdk': diff --git a/scripts/install-launchd.sh b/scripts/install-launchd.sh index e3111fb7..bacd75f4 100755 --- a/scripts/install-launchd.sh +++ b/scripts/install-launchd.sh @@ -5,6 +5,7 @@ # PEPPA_WEB_MODE=dev runs `next dev` instead (HMR: edits in this # checkout go live without build or release — the pre-launch setup) # quest.telecom.peppa.bot — Telegram bot (TELEGRAM_BOT_TOKEN in .env) +# quest.telecom.peppa.observer — Observability monitors (PEP-202), own DB ~/.peppa/observe.db # quest.telecom.peppa.release — Peppa's own prod releases (PEP-18): started by launchd while # ~/.peppa/release-queue has requests (the PM's button) # Prod runs from the release directory: ~/peppa/current/scripts/install-launchd.sh, so every @@ -12,7 +13,7 @@ # Pre-launch (PEP-165): scripts/install-launchd.sh watchdog web bot from the working copy — web in # `start` mode (build first: `next build` in apps/web), no release agent. Never `next dev` on the live # site: its rebuilds made every open tab reload in a loop (16.11). -# Usage: scripts/install-launchd.sh [watchdog] [web] [bot] [release] (default: all) +# Usage: scripts/install-launchd.sh [watchdog] [web] [bot] [observer] [release] (default: all) # Remove: launchctl bootout gui/$(id -u)/
+
+

{t.roles.title}

+
    + {t.roles.items.map((x) =>
  • {x}
  • )} +
+

{t.question}

{t.product}

@@ -149,7 +155,7 @@ export default async function Help() {
  • {rich(t("Подписка проекта — на чём работают агенты. В проекте без подписки сверху появляется подсказка: нажмите «Подключить Claude» или «Подключить ChatGPT», откройте ссылку, войдите в свой аккаунт и (для Claude) вставьте код, который он покажет. Терминал не нужен. Готовый токен или ключ OpenAI API — в «⋯ Настройки проекта → Подписки»."))}
  • {rich(t("Стори берутся сами — в новом проекте карточки перетаскивать не нужно: агент сам берёт стори из бэклога по порядку на доске, вам остаётся «Принять» результат. Уровень «Сам берёт» меняется в «⋯ Настройки проекта → Автономность»."))}
  • {rich(t("Telegram — у каждого пользователя свой бот: в «Настройки → Telegram» три шага — создать бота у @BotFather (команда /newbot), вставить его токен, открыть бота и нажать Start. Из него приходят вопросы агентов и «готово к ревью», ему же можно написать новую задачу. Ему же можно наговорить задачу голосовым, если на сервере включено распознавание речи."))}
  • -
  • {rich(t("Продакт и аналитик — два агента, которые читают новую задачу раньше разработчика. Продакт решает, зачем это и что берём в первую версию (большое делит на несколько стори). Аналитик пишет критерии приёмки и задаёт до трёх вопросов — у каждого есть вариант по умолчанию; не ответите за 30 минут (ночью — до утра), он возьмёт его сам. Их реплики — во вкладке Comments стори и в чате проекта. Включается в «⋯ Настройки проекта → Продакт и аналитик», в новых проектах включено."))}
  • +
  • {rich(t("Аналитик — единственный, кто говорит с владельцем: в чате проекта, на Главной и в Telegram. Вопросы агентов-разработчиков идут через него (MCP ask_pm): технический вопрос и повтор до владельца не доходят, вопрос о продукте — один раз, словами Аналитика, с вариантами. Готовые задачи, которых владелец не ждёт, приходят сводкой в конце рабочего дня; застрявшая задача (агент свободен больше часа, проверки зелёные) — суперадмину. На входе Аналитик одним запросом разбирает новую задачу: цель, урезание, разбивка (не больше четырёх частей; остальные ждут приёмки первой), критерии приёмки, решения на развилках — блок «Фабрика решила за вас» на странице задачи с «Подходит» / «Нужно иначе». Вопросов не задаёт и ответа не ждёт. Включается в «⋯ Настройки проекта → Аналитик на входе задачи», в новых проектах включено. Задачи из чата заводятся только кнопкой «Завести задачи». Находки агента приёмки — одним списком в «Предложено»."))}
  • {rich(t("Команда — ИИ-агенты с кличками (Шустрик, Беркут…), одна команда на все проекты: свободный агент берёт стори и ведёт её до конца, его кличка видна на карточке. В разделе «Команда» суперадмин задаёт агенту характер и специализацию — они добавляются к его промпту."))}
  • {rich(t("Вход — через eGov QR (с телефона — кнопка «Открыть в eGov Mobile») или через Google (кнопка есть, когда суперадмин задал GOOGLE_CLIENT_ID/SECRET); в «Настройках» их можно связать в одну учётку. Первый вход сам создаёт учётку по ИИН или Google-почте: логин из имени в сертификате (например, aigerim.ivanova). Новый пользователь видит только проекты, куда его пригласили, и свои; агенты его проектов работают только на пуле подписок, который назначает суперадмин. У такой учётки нет аккаунта Gitea — код только через Peppa FACTORY, а новые проекты создаются в пространстве peppa-bot."))}
  • {rich(t("Раннер — агент, запущенный по стори в tmux на машине Peppa FACTORY. Все раннеры ваших и общих проектов — в разделе Раннеры: статус, стори, команда tmux attach, сообщение, остановка и resume; фильтры-счётчики «ждут вас / работают / упали / готово» и поиск; строки, где нужны вы, подсвечены, у раннера на лимите — «остановлена · продолжит в HH:MM». Выбери раннер — справа его детали, вопросы, действия и живой терминал: экран агента в реальном времени с историей (прокрутка), размер шрифта A−/A+ и режим во весь экран. Кнопка «Ввод» позволяет печатать агенту прямо в терминал (вставка многострочного текста уходит одной вставкой, для телефона есть Esc, Tab, стрелки, Enter, Ctrl-C); ввод сбрасывает счётчик автопродолжений и отмечается в событиях раннера. Тот же терминал — на странице стори у работающего раннера. Терминал доступен владельцу и участникам проекта."))}
  • @@ -220,7 +226,7 @@ export default async function Help() {

    - {rich(t("Секреты проекта: «⋯ Настройки проекта» → «Секреты» — ключи API и доступы для агентов (например STRIPE_TEST_KEY). Значение шифруется и после сохранения больше не показывается никому; сохранить то же имя — заменить значение. Агенты проекта получают секреты как переменные окружения при следующем запуске сессии, видят через MCP только имена (list_secrets), а в терминале раннера и ленте шагов значение заменяется на «••••» (кроме значений короче 4 символов и значения, разорванного переносом строки). Каждая выдача — событие «secrets_issued» в журнале сессии. Те же секреты получает и выкаченный продукт (версия для проверки и рабочая) — как переменные окружения с тем же именем; после изменения секрета Peppa FACTORY через пару минут сама перезапускает продукт. Если продукту нужен ключ, агент объявляет это, и на странице проекта в карточке «Ваш продукт» появляется пометка «Работает в демо-режиме» с полем, куда вставить ключ. После каждой выкатки продукт смотрит продакт-агент и пишет в обсуждение проекта, как им пользоваться и что ещё не настоящее. Ревизия (суперадмин, раздел «Секреты», CLI peppa secrets audit): секреты платформы, их возраст и кто ими пользуется, MCP-токены по клиентам, подписки и секреты проектов — с пошаговой ротацией. Смена PEPPA_SECRET без потери данных: старый ключ в PEPPA_SECRET_PREVIOUS, новый в PEPPA_SECRET, перезапуск, peppa secrets reencrypt."))} + {rich(t("Секреты проекта: «⋯ Настройки проекта» → «Секреты» — ключи API и доступы для агентов (например STRIPE_TEST_KEY). Значение шифруется и после сохранения больше не показывается никому; сохранить то же имя — заменить значение. Агенты проекта получают секреты как переменные окружения при следующем запуске сессии, видят через MCP только имена (list_secrets), а в терминале раннера и ленте шагов значение заменяется на «••••» (кроме значений короче 4 символов и значения, разорванного переносом строки). Каждая выдача — событие «secrets_issued» в журнале сессии. Те же секреты получает и выкаченный продукт (версия для проверки и рабочая) — как переменные окружения с тем же именем; после изменения секрета Peppa FACTORY через пару минут сама перезапускает продукт. Если продукту нужен ключ, агент объявляет это, и на странице проекта в карточке «Ваш продукт» появляется пометка «Работает в демо-режиме» с полем, куда вставить ключ. После каждой выкатки продукт смотрит агент приёмки, а Аналитик пишет в обсуждение проекта, как им пользоваться и что ещё не настоящее. Ревизия (суперадмин, раздел «Секреты», CLI peppa secrets audit): секреты платформы, их возраст и кто ими пользуется, MCP-токены по клиентам, подписки и секреты проектов — с пошаговой ротацией. Смена PEPPA_SECRET без потери данных: старый ключ в PEPPA_SECRET_PREVIOUS, новый в PEPPA_SECRET, перезапуск, peppa secrets reencrypt."))}

    diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx index f6cafa70..dad5f23a 100644 --- a/apps/web/app/(app)/p/[key]/page.tsx +++ b/apps/web/app/(app)/p/[key]/page.tsx @@ -286,21 +286,17 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr )} - +
    -

    - {t("Продакт решает, зачем это и что берём в первую версию; аналитик пишет критерии приёмки и задаёт до трёх вопросов. Не ответили вовремя — идёт по вариантам по умолчанию (ночью ждёт до утра). {Tasks}, созданные до включения, не трогает.", { Tasks: w.Task("pl") })} + {t("Аналитик решает, зачем это и что берём в первую версию, делит большое (не больше четырёх частей) и пишет критерии приёмки. Вопросов не задаёт: развилки решает сам и показывает решения на странице задачи — «Фабрика решила за вас». {Tasks}, созданные до включения, не трогает.", { Tasks: w.Task("pl") })}

    diff --git a/apps/web/app/(app)/t/[key]/page.tsx b/apps/web/app/(app)/t/[key]/page.tsx index 061c1209..681ccd74 100644 --- a/apps/web/app/(app)/t/[key]/page.tsx +++ b/apps/web/app/(app)/t/[key]/page.tsx @@ -49,7 +49,7 @@ import { } from "@peppa/core"; import { checkRuns } from "@peppa/db"; import { desc, eq } from "drizzle-orm"; -import { getTeamMatch, matchLine } from "@peppa/core"; +import { getDecisions, getTeamMatch, matchLine } from "@peppa/core"; import { PanelSection } from "@/components/ActivityAside"; import { Hidden, SessionCard } from "@/components/cards"; import { ago, Disclosure, Flash, PageHeader, Section, StatusBadge } from "@/components/common"; @@ -62,6 +62,7 @@ import { Workspace } from "@/components/Workspace"; import { ReviewPreview } from "@/components/ReviewPreview"; import { requireUser, uiMode } from "@/lib/auth"; import { StoryProduct } from "@/components/StoryProduct"; +import { TaskDecisions } from "@/components/TaskDecisions"; import { db } from "@/lib/db"; import { taskActivity, taskForUser } from "@/lib/queries"; import { cn } from "@/lib/utils"; @@ -119,9 +120,9 @@ export default async function StoryPage({ params, searchParams }: { params: Prom // Only the open tab reads the rest (Gitea for the merge request). const comments = tab === "comments" ? await storyComments(db, task.id) : []; const commentRefining = tab === "comments" && (await refinePending(db, task)); - // PEP-84: is the story still with «продакт» and «аналитик»? + // PEP-84 / PEP-198: is the story still with the analyst? const intake = task.status === "backlog" ? await getIntakeState(db, task.id) : null; - const refining = task.status === "backlog" && intakePending(await getIntakeSettings(db, ref.project.id), task, intake) ? (intake?.stage ?? "product") : null; + const refining = task.status === "backlog" && intakePending(await getIntakeSettings(db, ref.project.id), task, intake) ? (intake?.stage ?? "analyst") : null; const runs: CheckRunRow[] = tab === "tests" && ci.sha ? (await db.select().from(checkRuns).where(eq(checkRuns.taskId, task.id)).orderBy(desc(checkRuns.updatedAt))).filter((r) => r.sha === ci.sha).sort((a, b) => a.check.localeCompare(b.check)) @@ -267,7 +268,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom <> {refining && (

    - {refining === "waiting" ? t("Аналитик ждёт ваших ответов") : t("Продакт и аналитик уточняют задачу")} + {refining === "waiting" ? t("Аналитик ждёт ваших ответов") : t("Аналитик уточняет задачу")} {refining === "waiting" ? t("— вопрос во вкладке «Comments». Не ответите — возьмёт варианты по умолчанию и отдаст стори в работу.") : t("— через минуту здесь появятся критерии приёмки. Агент-разработчик возьмёт стори после этого.")} @@ -454,6 +455,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom )} + {engineer ? ( body ) : ( diff --git a/apps/web/components/Board.tsx b/apps/web/components/Board.tsx index a01be5b1..2ee2683b 100644 --- a/apps/web/components/Board.tsx +++ b/apps/web/components/Board.tsx @@ -30,7 +30,7 @@ export interface Card { blocked?: string | null; /** PEP-75: the persona working on the story right now. */ agent?: string | null; - /** PEP-84: «продакт» and «аналитик» still hold the story ("уточняется" / "ждёт ваших ответов"). */ + /** PEP-84 / PEP-198: the analyst still holds the story ("уточняется" / "ждёт ваших ответов"). */ refining?: string | null; /** PEP-127: accepted over a conflict — the agent updates the changes, the story closes by itself. */ accepted?: string | null; @@ -211,7 +211,7 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) { )}

    {card.refining && ( - + {t.text(card.refining)} )} diff --git a/apps/web/components/ProductCard.tsx b/apps/web/components/ProductCard.tsx index b56c2908..cfe3b504 100644 --- a/apps/web/components/ProductCard.tsx +++ b/apps/web/components/ProductCard.tsx @@ -202,7 +202,7 @@ export async function ProductCard({
    )}

    - {t("Продукт посмотрел продакт-агент {when} — подробности в", { when: ago(new Date(review.at), t) })} {t("обсуждении проекта")}. + {t("Продукт посмотрел агент приёмки {when} — подробности в", { when: ago(new Date(review.at), t) })} {t("обсуждении проекта")}.

    diff --git a/apps/web/components/TaskDecisions.tsx b/apps/web/components/TaskDecisions.tsx new file mode 100644 index 00000000..cefb7efa --- /dev/null +++ b/apps/web/components/TaskDecisions.tsx @@ -0,0 +1,70 @@ +// PEP-198: «Фабрика решила за вас» — the analyst's product decisions of a story, right under its +// title (both views): each one with «Подходит» and «Нужно иначе» (a field «Как нужно?»); the +// split of a request — «Подходит» and «Не делить». Work does not wait for them. +import { decisionAction } from "@/app/(app)/actions"; +import { Hidden } from "@/components/cards"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Textarea } from "@/components/ui/input"; +import { getT } from "@/lib/i18n"; +import { DECISION_STATUS_LABEL, type Decision } from "@peppa/core"; + +const VARIANT = { default: "muted", confirmed: "ok", changed: "info" } as const; + +export async function TaskDecisions({ taskKey, decisions, back }: { taskKey: string; decisions: Decision[]; back: string }) { + if (!decisions.length) return null; + const t = await getT(); + return ( +
    +

    + {t("Фабрика решила за вас")} +

    +

    {t("Работа не ждёт: агент уже идёт по этим решениям. Если что-то нужно иначе — скажите здесь.")}

    +
      + {decisions.map((d) => ( +
    • +
      + {d.text} + + {t(DECISION_STATUS_LABEL[d.status])} + +
      + {d.status === "changed" && d.was && {t("Было: {text}", { text: d.was })}} + {d.status === "default" && ( +
      +
      + + + + {d.kind === "split" ? ( +
      + + + + ) : ( +
      + {t("Нужно иначе")} +
      + +