}
+ Платформа>}>
+ Telegram-канал Пеппы: новые версии, падения и перезапуски сервисов и ежедневный дайджест — что нового в Пеппе и что происходит сейчас. Раздел видят только суперадмины.
+ {build && <> Сейчас: v{build.version} · {build.commit.slice(0, 7)}.>}
+
+
+
+
+
+ {c.chatId == null ? (
+ канал не задан
+ ) : !c.check ? (
+ не проверен
+ ) : c.check.ok ? (
+ канал подключён
+ ) : (
+ не работает
+ )}
+ {c.check?.ok && c.title && {c.title}}
+ {c.check && проверен {ago(new Date(c.check.at))}}
+
+ {c.check && !c.check.ok &&
{c.check.error}
}
+
+ {c.chatId != null && (
+
+ )}
+
+ Добавьте бота Пеппы в канал администратором с правом «Публикация сообщений». Пока проверка не прошла, Пеппа перепроверяет канал раз в час и ничего туда не пишет. Ответы в канале бот не читает.
+
За сутки ничего нового и ничего не происходит — дайджест не уйдёт.
+ ) : (
+
{plain(renderPlatformDigest(digest))}
+ )}
+
+
+
+ );
+}
diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx
index 06389f30..b64fb563 100644
--- a/apps/web/app/(app)/settings/page.tsx
+++ b/apps/web/app/(app)/settings/page.tsx
@@ -82,6 +82,9 @@ export default async function Settings({ searchParams }: { searchParams: Promise
+
>
}
>
diff --git a/apps/web/components/Sidebar.tsx b/apps/web/components/Sidebar.tsx
index 0cd5a95d..aade574d 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, House, KeyRound, ScrollText, LifeBuoy, LogOut, Search, Server, Settings, ShieldCheck, Users, type LucideIcon } from "lucide-react";
+import { Bot, Contact, FolderKanban, Megaphone, House, KeyRound, ScrollText, LifeBuoy, LogOut, Search, Server, Settings, ShieldCheck, Users, type LucideIcon } from "lucide-react";
import { Brand } from "@/components/Brand";
import { ThemeToggle } from "@/components/ThemeToggle";
import { Button } from "@/components/ui/button";
@@ -28,6 +28,7 @@ const ITEMS: Item[] = [
{ href: "/secrets", label: "Секреты", icon: ShieldCheck, match: (p) => p.startsWith("/secrets"), admin: true },
{ href: "/hosts", label: "Хосты", icon: Server, match: (p) => p.startsWith("/hosts"), admin: true },
{ href: "/journal", label: "Журнал", icon: ScrollText, match: (p) => p.startsWith("/journal"), admin: true },
+ { href: "/platform", label: "Платформа", icon: Megaphone, match: (p) => p.startsWith("/platform"), admin: true },
{ href: "/users", label: "Пользователи", icon: Users, match: (p) => p.startsWith("/users"), admin: true },
{ href: "/settings", label: "Настройки", icon: Settings, match: (p) => p.startsWith("/settings") },
];
diff --git a/openspec/changes/pep-60-platform-channel-digest/design.md b/openspec/changes/pep-60-platform-channel-digest/design.md
new file mode 100644
index 00000000..bb1a4d4c
--- /dev/null
+++ b/openspec/changes/pep-60-platform-channel-digest/design.md
@@ -0,0 +1,66 @@
+# Design: PEP-60 — канал платформы и дайджест Пеппы
+
+## Настройки (без миграций)
+
+`settings` `platform.telegram_channel` (ключ уже есть в боевой базе: `{chatId, setAt}`) —
+`PlatformChannel` в `core/platform-channel.ts`, поверх умолчаний:
+
+- `chatId`, `title`, `check: {ok, error, at}` — результат последней проверки;
+- `events: {releases, services, digest}` — всё включено;
+- `digest: {time "09:00", timezone (PEPPA_TZ/сервер), users: false}` — личные чаты включает
+ суперадмин (без сюрприза всем пользователям в первый же день).
+
+Менять может только суперадмин (`requireSuperadmin`): веб `/platform` и CLI
+`peppa platform channel chat= [releases=on|off …]` (отрицательный id — через `chat=`:
+`parseArgs` принимает `-100…` за флаг), `peppa platform channel check`, `peppa platform digest [now]`.
+
+## Проверка канала
+
+`checkPlatformChannel` — Bot API напрямую (как прямая доставка вачдога PEP-20):
+`getMe` → `getChat(chat_id)` → `getChatMember(chat_id, bot)`. `chat not found` / 403 →
+«бот не видит канал — добавьте его администратором»; не админ или `can_post_messages: false`
+(в канале) → «бот не может публиковать — дайте право «Публикация сообщений»». Удача —
+`title` канала. Проверка при сохранении, кнопкой и раз в час в вачдоге, пока не ок (PM
+добавит бота — канал заработает сам). Писать в канал только при `check.ok`.
+
+## Отправка
+
+`postToChannel(db, kind, dedupeKey, text)` → тот же `telegram_outbox` (повторы, 429). Ключи
+сервисных событий начинаются с `mon:` — их вачдог доставляет сам, когда упал бот. Канал не
+принимает ответов: кнопок нет, бот на сообщения канала не реагирует (updates `channel_post`
+он и так не обрабатывает).
+
+## События
+
+- **Сервисы** — в `checkServices` (PEP-20) рядом с алертом админам: одно сообщение о
+ падении (без напоминаний) и одно о восстановлении с длительностью простоя; ключи от
+ начала простоя, поэтому бот и вачдог вместе дают одно сообщение. **Перезапуск** — смена
+ `heartbeat.startedAt` без простоя: «🔄 вачдог перезапущен (v0.15.0 · abc1234)».
+- **Релиз**. В heartbeat добавлен `commit` (`peppaCommit()`: `PEPPA_COMMIT` /
+ `NEXT_PUBLIC_PEPPA_COMMIT_FULL` / `git rev-parse HEAD` корня). Вачдог раз в минуту
+ (`platformBuildTick`, runner) берёт HEAD корня Пеппы; если он отличается от
+ `platform.build` и входит в `main` (`git merge-base --is-ancestor HEAD main`) — это выкатка:
+ «🚀 Peppa v0.16.0 · b1c2d3e» и стори из сообщений коммитов `prev..HEAD`
+ (`PEP-N`, с названиями). Так работает и сейчас (dev из рабочей копии: ветка задачи не
+ объявляется, возврат на обновлённый main — объявляется), и в проде PEP-18 (`current` —
+ worktree релиза от `main`). Первый запуск только запоминает сборку.
+
+## Дайджест платформы
+
+`buildPlatformDigest(since, now)`: «Что нового» — стори проекта Пеппы (`PEPPA_PLATFORM_KEY`),
+ставшие `done` после `since`, и сборки, объявленные с тех пор; «Сейчас» — версия · коммит,
+сервисы, активные раннеры, открытые вопросы, лимиты подписок (`listAccountUsage`, ≥ 50% или
+«лимит до»). Пусто (нет нового, нет раннеров, нет вопросов, сервисы в порядке) — не
+отправляется. `platformDigestTick` в `tick` вачдога: в `digest.time` (окно 3 ч, раз в
+местные сутки, `platform.digest.last`), в канал и — если `digest.users` — каждому
+пользователю событием уведомлений `platform` («Обновления Пеппы»: Telegram вкл, push выкл).
+Отписка — «Настройки → Уведомления» (строка появляется сама из `NOTIFY_EVENTS`); личный
+дайджест по проектам (PEP-29, событие `digest`) не меняется.
+
+## Решения
+
+- Без миграций — всё в `settings`, как прочие настройки платформы.
+- Отдельная страница `/platform` для суперадмина (по образцу `/hosts`), пункт меню
+ «Платформа»; не суперадмину — 404.
+- Окно сервиса «упал» — общий порог мониторинга (`PEPPA_MONITOR_STALE_MIN`), отдельный
+ порог для канала не вводим.
diff --git a/openspec/changes/pep-60-platform-channel-digest/tasks.md b/openspec/changes/pep-60-platform-channel-digest/tasks.md
index d84d35c4..7276743f 100644
--- a/openspec/changes/pep-60-platform-channel-digest/tasks.md
+++ b/openspec/changes/pep-60-platform-channel-digest/tasks.md
@@ -1,16 +1,18 @@
# Tasks: PEP-60
## 0. Перед стартом
-- [x] 0.1 Бот — админ канала (проверка `getChat`/тестовое сообщение по согласию PM); роль суперадмина из PEP-16 (иначе только CLI)
+- [x] 0.1 Проверка бота в канале: `getChat(-1004371018094)` → «chat not found» — бот ещё не админ; работаем, канал включится сам после проверки
## 1. Канал
-- [x] 1.1 core: настройки платформы (канал, события, расписание); CLI `peppa platform channel ` и `platform status`
-- [x] 1.2 Веб: «Настройки платформы» для суперадмина с проверкой канала
-- [x] 1.3 События: релиз (из деплоя/CI, PEP-57; до него — при старте веба с новым коммитом), рестарт и падение/восстановление сервисов (heartbeat, PEP-20)
+- [x] 1.1 core `platform-channel.ts`: настройки, проверка канала (Bot API), `postToChannel`; CLI `peppa platform channel`
+- [x] 1.2 Веб `/platform` для суперадмина: Chat ID, проверка, события, расписание; пункт меню
+- [x] 1.3 События сервисов в `checkServices`: падение/восстановление/перезапуск; `commit` в heartbeat
+- [x] 1.4 Релиз: `platformBuildTick` (runner) — новая сборка из `main` со списком стори
## 2. Дайджест
-- [x] 2.1 Сбор: смерженные PR/задачи PEP с прошлого дайджеста, версия, сервисы, раннеры, вопросы, лимиты; пропуск, если пусто
-- [x] 2.2 Расписание и отправка в канал; личный дайджест пользователям (после PEP-2) и отписка в Настройках
+- [x] 2.1 `buildPlatformDigest` + рендер; пропуск, если пусто
+- [x] 2.2 `platformDigestTick` в вачдоге: канал + пользователи (событие `platform`, отписка в Настройках); перепроверка канала раз в час
## 3. Проверка
-- [x] 3.1 Тесты на mock-telegram — по сценарию спецификации на каждый; весь e2e зелёный; `openspec validate`
+- [ ] 3.1 e2e `platform-channel.test.ts` на mock-telegram по сценариям спеки; весь e2e и typecheck зелёные; `openspec validate`
+- [ ] 3.2 Документация: AGENTS.md, `/help`
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 7d3977cf..3b687e59 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -71,6 +71,7 @@ import {
import { createDb, migrateDb } from "@peppa/db";
import { checkHost, ensureSshKey, pushImage, sshArgs } from "@peppa/runner";
import { promoteRunner, queueTaskOnRunner, renameRunner, startFreeRunner, runnerServiceAlive, setRunnerClient, recentRunnerCommands, getWatchdogSettings, setWatchdogSettings } from "@peppa/runner";
+import { checkPlatformChannel, describeChannel, getPlatformChannel, parseChatId, platformDigestTick, setPlatformChannel, PLATFORM_CHANNEL_EVENTS, type PlatformChannelPatch } from "@peppa/core";
import { 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 { answerAndDeliver, connectCi, importIssues, deployProd, listReleases, platformReleaseOffers, setPlatformReleaseOffers, recordRelease, type ReleaseStatus, provisionProject, setProjectVisibility, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner";
@@ -121,6 +122,9 @@ const USAGE = `peppa — Peppa software factory CLI
(PEP-10/27: system → project → story; a story overrides mode/context only)
peppa platform allowlist | allow | deny (who may log into Peppa)
peppa platform release-offers [on|off] ("deploy to prod?" after a green main of Peppa; off before launch)
+ peppa platform channel [chat=|@name|check] [releases|services|digest=on|off time=HH:MM tz= users=on|off]
+ (PEP-60: Telegram channel of the platform — events and the platform digest)
+ peppa platform digest [now] (PEP-60: show the platform digest; now — send it to the channel/users)
peppa platform admins [login,… | -] (who gets service alerts; default: the allowlist)
peppa platform watchdog [key=value… | key=- | reset] (PEP-28: restartMax restartWindowMin restartDelaysMin=1,5,15
stallRestartMin remindMin escalateMin idleStopHours; 0 = off)
@@ -641,6 +645,7 @@ async function main(): Promise {
const paired = new Set((await adminRecipients(db)).map((u) => u.login));
const admins = (await platformAdmins(db)).map((l) => `${l}${paired.has(l) ? " (Telegram)" : " (без Telegram)"}`);
console.log(`админы: ${admins.join(", ") || "нет"}`);
+ console.log(`канал платформы: ${describeChannel(await getPlatformChannel(db))}`);
break;
}
case "telegram pair": {
@@ -674,6 +679,42 @@ async function main(): Promise {
console.log(`${u.login} (#${u.id})`);
break;
}
+ case "platform channel": {
+ // PEP-60: the platform's Telegram channel (superadmin's setting; the CLI is an admin tool).
+ const patch: PlatformChannelPatch = {};
+ let check = false;
+ for (const a of args) {
+ if (a === "check") check = true;
+ else if (a === "-") patch.chatId = null;
+ else if (!a.includes("=")) patch.chatId = parseChatId(a);
+ else {
+ const [k, v] = [a.slice(0, a.indexOf("=")), a.slice(a.indexOf("=") + 1)];
+ const on = v === "on" ? true : v === "off" ? false : null;
+ if (k === "chat") patch.chatId = v === "-" ? null : parseChatId(v);
+ else if ((PLATFORM_CHANNEL_EVENTS as readonly string[]).includes(k) && on != null) patch.events = { ...patch.events, [k]: on };
+ else if (k === "users" && on != null) patch.digest = { ...patch.digest, users: on };
+ else if (k === "time") patch.digest = { ...patch.digest, time: v };
+ else if (k === "tz") patch.digest = { ...patch.digest, timezone: v };
+ else throw new PeppaError(`unknown setting ${a}: chat=, releases|services|digest|users=on|off, time=HH:MM, tz=`);
+ }
+ }
+ let c = Object.keys(patch).length ? await setPlatformChannel(db, patch) : await getPlatformChannel(db);
+ if (c.chatId != null && (check || patch.chatId !== undefined)) c = await checkPlatformChannel(db);
+ console.log(describeChannel(c));
+ console.log(`события: ${PLATFORM_CHANNEL_EVENTS.map((e) => `${e}=${c.events[e] ? "on" : "off"}`).join(" ")}`);
+ console.log(`дайджест: ${c.digest.time} ${c.digest.timezone}, пользователям ${c.digest.users ? "да" : "нет"}`);
+ break;
+ }
+ case "platform digest": {
+ if (args[0] === "now") {
+ const r = await platformDigestTick(db, { force: true, log: console.log });
+ if (!r) console.log("некуда отправлять: канал не подключён и дайджест пользователям выключен");
+ break;
+ }
+ const { buildPlatformDigest, renderPlatformDigest } = await import("@peppa/core");
+ console.log(renderPlatformDigest(await buildPlatformDigest(db, { since: new Date(Date.now() - 24 * 3600_000) })).replace(/<[^>]+>/g, ""));
+ break;
+ }
case "platform release-offers": {
// PEP-18: "deploy to prod?" after a green main of Peppa; off before the official launch.
if (args[0] === "on" || args[0] === "off") await setPlatformReleaseOffers(db, args[0] === "on");
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index f06b1ada..a7c6cda7 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -28,6 +28,7 @@ export * from "./reviews.ts";
export * from "./webpush.ts";
export * from "./notifications.ts";
export * from "./digest.ts";
+export * from "./platform-channel.ts";
export * from "./autonomy.ts";
export * from "./openspec.ts";
export * from "./steps.ts";
diff --git a/packages/core/src/monitor.ts b/packages/core/src/monitor.ts
index 1f67aeb3..64f27ad3 100644
--- a/packages/core/src/monitor.ts
+++ b/packages/core/src/monitor.ts
@@ -1,6 +1,7 @@
// Service monitoring (PEP-20): web, bot and watchdog write heartbeats into `settings`; the
// watchdog and the bot check each other (and the web) and alert the platform admins in
// Telegram through the outbox when a service goes quiet, without spamming.
+import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { hostname } from "node:os";
import { dirname, join } from "node:path";
@@ -9,6 +10,7 @@ import { telegramOutbox, users, type Db } from "@peppa/db";
import { and, count, eq, inArray, isNotNull, sql } from "drizzle-orm";
import { allowedLogins } from "./access.ts";
import { deliverToUser } from "./notifications.ts";
+import { getPlatformChannel, postToChannel } from "./platform-channel.ts";
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
import type { User } from "./users.ts";
@@ -23,6 +25,8 @@ export interface Heartbeat {
pid: number;
host: string;
version: string;
+ /** Commit the process runs (PEP-60); absent in heartbeats of older processes. */
+ commit?: string | null;
}
export interface ServiceState {
@@ -38,6 +42,8 @@ interface AlertState {
alerted: boolean;
reminders: number;
lastAlertAt: string | null;
+ /** PEP-60: the outage was posted to the platform channel (then its recovery is too). */
+ channelPosted?: boolean;
}
export interface MonitorOptions {
@@ -60,14 +66,33 @@ const startedAt = new Date().toISOString();
export const defaultStaleMs = () => Number(process.env.PEPPA_MONITOR_STALE_MIN ?? 5) * MIN;
/** Peppa version from the root package.json (bot, watchdog, CLI run from the checkout). */
-export function peppaVersion(): string {
+export function peppaVersion(root = join(dirname(fileURLToPath(import.meta.url)), "../../..")): string {
try {
- return (JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), "../../../package.json"), "utf8")) as { version?: string }).version ?? "0.0.0";
+ return (JSON.parse(readFileSync(join(root, "package.json"), "utf8")) as { version?: string }).version ?? "0.0.0";
} catch {
return "0.0.0";
}
}
+const ROOT = join(dirname(fileURLToPath(import.meta.url)), "../../..");
+
+/** HEAD of Peppa's checkout right now (null outside git). */
+export function headCommit(root = ROOT): string | null {
+ try {
+ return execFileSync("git", ["rev-parse", "HEAD"], { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim() || null;
+ } catch {
+ return null;
+ }
+}
+
+let processCommit: string | null | undefined;
+
+/** Commit this process runs: PEPPA_COMMIT, the web's build-time commit, or HEAD at first call. */
+export function peppaCommit(): string | null {
+ if (processCommit === undefined) processCommit = process.env.PEPPA_COMMIT || process.env.NEXT_PUBLIC_PEPPA_COMMIT_FULL || headCommit();
+ return processCommit;
+}
+
/** "I'm alive": called every 30–60 s by each service. */
export async function beat(db: Db, service: Service, o: { now?: Date; version?: string } = {}): Promise {
const hb: Heartbeat = {
@@ -76,6 +101,7 @@ export async function beat(db: Db, service: Service, o: { now?: Date; version?:
pid: process.pid,
host: hostname(),
version: o.version ?? peppaVersion(),
+ commit: peppaCommit(),
};
await setSetting(db, hbKey(service), hb);
}
@@ -162,23 +188,39 @@ export async function checkServices(db: Db, o: MonitorOptions & { self: Service
const cooldownMs = o.cooldownMs ?? 15 * MIN;
const log = o.log ?? (() => {});
let queued = 0;
+ const channel = await getPlatformChannel(db);
for (const s of await serviceStatus(db, { now, staleMs: o.staleMs })) {
if (s.service === o.self || !s.heartbeat) continue;
const name = SERVICE_NAMES[s.service];
const st = await getSetting(db, alertKey(s.service));
if (s.ok) {
- if (!st?.since) continue;
+ const restarted = await noteProcess(db, s.service, s.heartbeat);
+ if (!st?.since) {
+ // PEP-60: a new process without an outage = a restart (an outage ends with «снова на связи»).
+ if (restarted) {
+ const build = `v${s.heartbeat.version}${s.heartbeat.commit ? ` · ${s.heartbeat.commit.slice(0, 7)}` : ""}`;
+ await postToChannel(db, "services", `mon:ch:${s.service}:restart:${s.heartbeat.host}:${s.heartbeat.pid}`, `🔄 Пеппа: ${name} перезапущен (${build}).`, channel);
+ }
+ continue;
+ }
// lastAlertAt survives the recovery: it is what the cooldown against flapping counts from.
await setSetting(db, alertKey(s.service), { since: null, alerted: false, reminders: 0, lastAlertAt: st.lastAlertAt });
+ const quiet = minutes(Date.parse(s.heartbeat.at) - Date.parse(st.since));
if (st.alerted) {
- const quiet = minutes(Date.parse(s.heartbeat.at) - Date.parse(st.since));
queued += await alertAdmins(db, `mon:${s.service}:up:${st.since}`, `✅ Пеппа: ${name} снова на связи (молчал ${quiet} мин).`, log);
}
+ if (st.channelPosted && (await postToChannel(db, "services", `mon:ch:${s.service}:up:${st.since}`, `✅ Пеппа: ${name} снова работает — простой ${quiet} мин.`, channel))) queued++;
continue;
}
// Down. A new outage starts when the last heartbeat differs from the remembered one.
const cur: AlertState =
st?.since === s.heartbeat.at ? st : { since: s.heartbeat.at, alerted: false, reminders: 0, lastAlertAt: st?.lastAlertAt ?? null };
+ // PEP-60: the channel hears about an outage once (no reminders, no cooldown games).
+ if (!cur.channelPosted && (await postToChannel(db, "services", `mon:ch:${s.service}:down:${cur.since}`, `⚠️ Пеппа: ${name} не отвечает с ${hhmm(s.heartbeat.at)}.`, channel))) {
+ cur.channelPosted = true;
+ queued++;
+ if (cur === st) await setSetting(db, alertKey(s.service), cur);
+ }
const sinceLast = cur.lastAlertAt ? now.getTime() - Date.parse(cur.lastAlertAt) : Infinity;
const due = cur.alerted ? sinceLast >= remindMs : sinceLast >= cooldownMs;
if (due) {
@@ -192,6 +234,16 @@ export async function checkServices(db: Db, o: MonitorOptions & { self: Service
return queued;
}
+/** Remembers the service's process; true when it differs from a previously seen one. */
+async function noteProcess(db: Db, service: Service, hb: Heartbeat): Promise {
+ const key = `monitor.process:${service}`;
+ const id = `${hb.host}:${hb.pid}:${hb.startedAt}`;
+ const prev = await getSetting(db, key);
+ if (prev === id) return false;
+ await setSetting(db, key, id);
+ return prev != null;
+}
+
/** Monitor messages not delivered yet (the watchdog sends them itself when the bot is down). */
export async function pendingMonitorMessages(db: Db) {
return db
diff --git a/packages/core/src/notifications.ts b/packages/core/src/notifications.ts
index 9774da6a..7812860a 100644
--- a/packages/core/src/notifications.ts
+++ b/packages/core/src/notifications.ts
@@ -8,7 +8,7 @@ import type { Question } from "./tasks.ts";
import type { User } from "./users.ts";
import { enqueuePush, type PushPayload } from "./webpush.ts";
-export const NOTIFY_EVENTS = ["questions", "review", "failures", "releases", "incidents", "monitoring", "digest"] as const;
+export const NOTIFY_EVENTS = ["questions", "review", "failures", "releases", "incidents", "monitoring", "digest", "platform"] as const;
export type NotifyEvent = (typeof NOTIFY_EVENTS)[number];
export const NOTIFY_EVENT_NAMES: Record = {
@@ -19,6 +19,7 @@ export const NOTIFY_EVENT_NAMES: Record = {
incidents: "Ошибки из прода",
monitoring: "Мониторинг Пеппы (админам)",
digest: "Ежедневный дайджест",
+ platform: "Дайджест обновлений Пеппы",
};
export interface Channels {
@@ -47,7 +48,7 @@ export const serverTimezone = () => process.env.PEPPA_TZ || Intl.DateTimeFormat(
export function defaultPrefs(): NotifyPrefs {
const on = { telegram: true, push: true };
return {
- events: { questions: on, review: on, failures: on, releases: on, incidents: on, monitoring: on, digest: { telegram: true, push: false } },
+ events: { questions: on, review: on, failures: on, releases: on, incidents: on, monitoring: on, digest: { telegram: true, push: false }, platform: { telegram: true, push: false } },
quiet: null,
timezone: serverTimezone(),
digestTime: "09:00",
diff --git a/packages/core/src/platform-channel.ts b/packages/core/src/platform-channel.ts
new file mode 100644
index 00000000..4624305a
--- /dev/null
+++ b/packages/core/src/platform-channel.ts
@@ -0,0 +1,371 @@
+// Platform channel and Peppa's own digest (PEP-60): a Telegram channel set by a superadmin
+// gets platform events (releases, service outages, restarts) and the daily platform digest;
+// paired users get the platform digest too (notification event «platform»). No migrations:
+// everything lives in `settings`; messages go through the Telegram outbox with retries.
+import { projects, questions, sessions, tasks, users, type Db } from "@peppa/db";
+import { formatTaskKey, loadEnv } from "@peppa/shared";
+import { and, asc, eq, gte, isNotNull, isNull, notInArray } from "drizzle-orm";
+import { PeppaError } from "./errors.ts";
+import { deliverToUser, hhmmToMinutes, isValidTimezone, localClock, serverTimezone } from "./notifications.ts";
+import { FINISHED_SESSION_STATUSES } from "./sessions.ts";
+import { getSetting, setSetting } from "./settings.ts";
+import { enqueueTelegram } from "./telegram.ts";
+import { describeAccount, listAccountUsage } from "./usage.ts";
+
+export const PLATFORM_CHANNEL_EVENTS = ["releases", "services", "digest"] as const;
+export type PlatformChannelEvent = (typeof PLATFORM_CHANNEL_EVENTS)[number];
+
+export const PLATFORM_CHANNEL_EVENT_NAMES: Record = {
+ releases: "Новые версии Пеппы",
+ services: "Падение, восстановление и перезапуск сервисов",
+ digest: "Ежедневный дайджест",
+};
+
+export interface ChannelCheck {
+ ok: boolean;
+ /** Human-readable reason when not ok. */
+ error: string | null;
+ at: string;
+}
+
+export interface PlatformChannel {
+ /** Telegram Chat ID of the channel («-100…» or «@name»); null = no channel. */
+ chatId: number | string | null;
+ /** Channel title from the last good check. */
+ title: string | null;
+ check: ChannelCheck | null;
+ events: Record;
+ digest: { time: string; timezone: string; users: boolean };
+ setAt?: string;
+}
+
+const KEY = "platform.telegram_channel";
+const HHMM = /^([01]\d|2[0-3]):[0-5]\d$/;
+
+export function defaultPlatformChannel(): PlatformChannel {
+ return {
+ chatId: null,
+ title: null,
+ check: null,
+ events: { releases: true, services: true, digest: true },
+ digest: { time: "09:00", timezone: serverTimezone(), users: false },
+ };
+}
+
+/** Saved channel settings merged over the defaults. */
+export async function getPlatformChannel(db: Db): Promise {
+ const d = defaultPlatformChannel();
+ const s = (await getSetting>(db, KEY)) ?? {};
+ const events = { ...d.events };
+ for (const e of PLATFORM_CHANNEL_EVENTS) if (typeof s.events?.[e] === "boolean") events[e] = s.events[e];
+ return {
+ chatId: s.chatId ?? null,
+ title: s.title ?? null,
+ check: s.check ?? null,
+ events,
+ digest: {
+ time: s.digest?.time && HHMM.test(s.digest.time) ? s.digest.time : d.digest.time,
+ timezone: s.digest?.timezone && isValidTimezone(s.digest.timezone) ? s.digest.timezone : d.digest.timezone,
+ users: s.digest?.users ?? d.digest.users,
+ },
+ ...(s.setAt ? { setAt: s.setAt } : {}),
+ };
+}
+
+/** «-1004371018094» → number, «@name» stays a string; anything else is refused. */
+export function parseChatId(raw: string): number | string {
+ const s = raw.trim();
+ if (/^-?\d{5,20}$/.test(s)) return Number(s);
+ if (/^@[A-Za-z][A-Za-z0-9_]{3,}$/.test(s)) return s;
+ throw new PeppaError("Chat ID канала — число вида -100… или @имя_канала");
+}
+
+export interface PlatformChannelPatch {
+ chatId?: number | string | null;
+ events?: Partial>;
+ digest?: Partial;
+}
+
+/** Changes the settings; a new Chat ID drops the previous check result. */
+export async function setPlatformChannel(db: Db, patch: PlatformChannelPatch): Promise {
+ const cur = await getPlatformChannel(db);
+ const next: PlatformChannel = { ...cur, events: { ...cur.events, ...patch.events }, digest: { ...cur.digest, ...patch.digest } };
+ if (!HHMM.test(next.digest.time)) throw new PeppaError("Время дайджеста: формат ЧЧ:ММ");
+ if (!isValidTimezone(next.digest.timezone)) throw new PeppaError(`Неизвестная таймзона: ${next.digest.timezone}`);
+ if (patch.chatId !== undefined && String(patch.chatId) !== String(cur.chatId)) {
+ Object.assign(next, { chatId: patch.chatId, title: null, check: null, setAt: new Date().toISOString() });
+ }
+ await setSetting(db, KEY, next);
+ return next;
+}
+
+// ── check ──────────────────────────────────────────────────────────────────────────
+
+export interface BotApiAccess {
+ token?: string;
+ apiUrl?: string;
+}
+
+export const CHANNEL_NOT_VISIBLE = "бот не видит канал — добавьте его администратором";
+export const CHANNEL_NO_POST = "бот не может публиковать — дайте ему право «Публикация сообщений»";
+
+type ApiResult = { ok: true; result: T } | { ok: false; error_code?: number; description?: string };
+
+async function botApi(tg: BotApiAccess, method: string, params: Record): Promise> {
+ const token = tg.token ?? process.env.TELEGRAM_BOT_TOKEN;
+ if (!token) return { ok: false, description: "TELEGRAM_BOT_TOKEN не задан" };
+ const base = tg.apiUrl ?? process.env.TELEGRAM_API_URL ?? "https://api.telegram.org";
+ try {
+ const res = await fetch(`${base}/bot${token}/${method}`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(params),
+ signal: AbortSignal.timeout(15_000),
+ });
+ return (await res.json()) as ApiResult;
+ } catch (e) {
+ return { ok: false, description: (e as Error).message };
+ }
+}
+
+/**
+ * Whether the bot can post to the channel: getMe → getChat → getChatMember. Saves the result
+ * (and the channel title) into the settings and returns them.
+ */
+export async function checkPlatformChannel(db: Db, tg: BotApiAccess = {}, o: { now?: Date } = {}): Promise {
+ const cur = await getPlatformChannel(db);
+ if (cur.chatId == null) throw new PeppaError("Канал платформы не задан");
+ const at = (o.now ?? new Date()).toISOString();
+ const verdict = async (): Promise<{ ok: boolean; error: string | null; title: string | null }> => {
+ const me = await botApi<{ id: number }>(tg, "getMe", {});
+ if (!me.ok) return { ok: false, error: `Telegram: ${me.description ?? "нет ответа"}`, title: null };
+ const chat = await botApi<{ title?: string; type: string }>(tg, "getChat", { chat_id: cur.chatId });
+ if (!chat.ok) {
+ const gone = chat.error_code === 400 || chat.error_code === 403 || /chat not found|not a member|kicked/i.test(chat.description ?? "");
+ return { ok: false, error: gone ? CHANNEL_NOT_VISIBLE : `Telegram: ${chat.description ?? "нет ответа"}`, title: null };
+ }
+ const title = chat.result.title ?? null;
+ const member = await botApi<{ status: string; can_post_messages?: boolean }>(tg, "getChatMember", { chat_id: cur.chatId, user_id: me.result.id });
+ if (!member.ok) return { ok: false, error: `Telegram: ${member.description ?? "нет ответа"}`, title };
+ const m = member.result;
+ const canPost = chat.result.type === "channel" ? m.status === "creator" || (m.status === "administrator" && m.can_post_messages !== false) : m.status !== "left" && m.status !== "kicked";
+ return canPost ? { ok: true, error: null, title } : { ok: false, error: m.status === "left" || m.status === "kicked" ? CHANNEL_NOT_VISIBLE : CHANNEL_NO_POST, title };
+ };
+ const v = await verdict();
+ const next: PlatformChannel = { ...cur, title: v.title ?? cur.title, check: { ok: v.ok, error: v.error, at } };
+ await setSetting(db, KEY, next);
+ return next;
+}
+
+/** «канал подключён — Peppa News» / the reason / «не проверен». */
+export function describeChannel(c: PlatformChannel): string {
+ if (c.chatId == null) return "канал не задан";
+ if (!c.check) return `${c.chatId}: не проверен`;
+ return c.check.ok ? `канал подключён${c.title ? ` — ${c.title}` : ""}` : `${c.chatId}: ${c.check.error}`;
+}
+
+/** Watchdog: re-checks a channel that isn't working yet at most once an hour. */
+export async function recheckPlatformChannel(db: Db, o: { now?: Date; tg?: BotApiAccess; log?: (m: string) => void } = {}): Promise {
+ const c = await getPlatformChannel(db);
+ const now = o.now ?? new Date();
+ if (c.chatId == null || c.check?.ok) return false;
+ if (c.check && now.getTime() - Date.parse(c.check.at) < 3600_000) return false;
+ const r = await checkPlatformChannel(db, o.tg, { now });
+ if (r.check?.ok) o.log?.(`platform channel: ${describeChannel(r)}`);
+ return true;
+}
+
+// ── posting ────────────────────────────────────────────────────────────────────────
+
+const esc = (s: string) => s.replace(/&/g, "&").replace(//g, ">");
+
+/**
+ * Queues a message to the platform channel if it is connected and the event is on. Service
+ * events use `mon:` keys so the watchdog delivers them itself when the bot is down.
+ */
+export async function postToChannel(db: Db, event: PlatformChannelEvent, dedupeKey: string, html: string, channel?: PlatformChannel): Promise {
+ const c = channel ?? (await getPlatformChannel(db));
+ if (c.chatId == null || !c.check?.ok || !c.events[event]) return false;
+ return enqueueTelegram(db, {
+ dedupeKey,
+ method: "sendMessage",
+ params: { chat_id: c.chatId, text: html, parse_mode: "HTML", link_preview_options: { is_disabled: true } },
+ });
+}
+
+// ── builds and releases ────────────────────────────────────────────────────────────
+
+/** Key of the project that is Peppa itself. */
+export const platformProjectKey = () => process.env.PEPPA_PLATFORM_KEY || "PEP";
+
+export interface PlatformBuild {
+ version: string;
+ commit: string;
+ at: string;
+ /** Platform stories found in the commits since the previous build. */
+ tasks: string[];
+}
+
+const BUILD = "platform.build";
+const BUILDS = "platform.builds";
+
+export const getPlatformBuild = (db: Db) => getSetting(db, BUILD);
+
+/** Announced builds, newest last (the digest lists the ones since its previous run). */
+export async function recentPlatformBuilds(db: Db): Promise {
+ return (await getSetting(db, BUILDS)) ?? [];
+}
+
+const short = (sha: string) => sha.slice(0, 7);
+
+/** Titles of the platform's stories by key (missing ones are left out). */
+async function storyTitles(db: Db, keys: string[]): Promise
+
+ Новости самой Пеппы — новые версии, падения и перезапуски сервисов, «Дайджест обновлений Пеппы» (что нового и
+ что происходит сейчас) — идут в Telegram-канал платформы, который настраивает суперадмин в разделе «Платформа».
+ Если он включил рассылку в личные чаты, дайджест обновлений приходит и вам; отключить — строка «Дайджест
+ обновлений Пеппы» в Настройках → Уведомления.
+
From 3b23bbad2409a82bb8dfe1c6f24b7c0c07c6a1d9 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Sat, 14 Nov 2026 19:04:49 +0500
Subject: [PATCH 3/5] PEP-60: test scenario type
Co-Authored-By: Claude Opus 5.5
---
packages/testkit/test/platform-channel.test.ts | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/packages/testkit/test/platform-channel.test.ts b/packages/testkit/test/platform-channel.test.ts
index 716b6cdf..42a66e22 100644
--- a/packages/testkit/test/platform-channel.test.ts
+++ b/packages/testkit/test/platform-channel.test.ts
@@ -57,7 +57,7 @@ async function connectChannel() {
}
before(async () => {
- pep = await project({ steps: [] });
+ pep = await project({ turns: [] });
process.env.PEPPA_PLATFORM_KEY = pep.key;
pepId = (await core.getProject(db, pep.key)).id;
await pair(ANNA.login, ANNA.chatId, 9401);
From b13b87d38d8657e90eed049d8fb7afbfdf192985 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Sat, 14 Nov 2026 19:11:13 +0500
Subject: [PATCH 4/5] =?UTF-8?q?PEP-60:=20archive=20change=20=E2=80=94=20pl?=
=?UTF-8?q?atform-notifications=20spec?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Opus 5.5
---
.../.openspec.yaml | 0
.../design.md | 0
.../proposal.md | 0
.../specs/platform-notifications/spec.md | 0
.../tasks.md | 4 +-
openspec/specs/platform-notifications/spec.md | 55 +++++++++++++++++++
6 files changed, 57 insertions(+), 2 deletions(-)
rename openspec/changes/{pep-60-platform-channel-digest => archive/2026-11-14-pep-60-platform-channel-digest}/.openspec.yaml (100%)
rename openspec/changes/{pep-60-platform-channel-digest => archive/2026-11-14-pep-60-platform-channel-digest}/design.md (100%)
rename openspec/changes/{pep-60-platform-channel-digest => archive/2026-11-14-pep-60-platform-channel-digest}/proposal.md (100%)
rename openspec/changes/{pep-60-platform-channel-digest => archive/2026-11-14-pep-60-platform-channel-digest}/specs/platform-notifications/spec.md (100%)
rename openspec/changes/{pep-60-platform-channel-digest => archive/2026-11-14-pep-60-platform-channel-digest}/tasks.md (91%)
create mode 100644 openspec/specs/platform-notifications/spec.md
diff --git a/openspec/changes/pep-60-platform-channel-digest/.openspec.yaml b/openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/.openspec.yaml
similarity index 100%
rename from openspec/changes/pep-60-platform-channel-digest/.openspec.yaml
rename to openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/.openspec.yaml
diff --git a/openspec/changes/pep-60-platform-channel-digest/design.md b/openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/design.md
similarity index 100%
rename from openspec/changes/pep-60-platform-channel-digest/design.md
rename to openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/design.md
diff --git a/openspec/changes/pep-60-platform-channel-digest/proposal.md b/openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/proposal.md
similarity index 100%
rename from openspec/changes/pep-60-platform-channel-digest/proposal.md
rename to openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/proposal.md
diff --git a/openspec/changes/pep-60-platform-channel-digest/specs/platform-notifications/spec.md b/openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/specs/platform-notifications/spec.md
similarity index 100%
rename from openspec/changes/pep-60-platform-channel-digest/specs/platform-notifications/spec.md
rename to openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/specs/platform-notifications/spec.md
diff --git a/openspec/changes/pep-60-platform-channel-digest/tasks.md b/openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/tasks.md
similarity index 91%
rename from openspec/changes/pep-60-platform-channel-digest/tasks.md
rename to openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/tasks.md
index 7276743f..2ea66040 100644
--- a/openspec/changes/pep-60-platform-channel-digest/tasks.md
+++ b/openspec/changes/archive/2026-11-14-pep-60-platform-channel-digest/tasks.md
@@ -14,5 +14,5 @@
- [x] 2.2 `platformDigestTick` в вачдоге: канал + пользователи (событие `platform`, отписка в Настройках); перепроверка канала раз в час
## 3. Проверка
-- [ ] 3.1 e2e `platform-channel.test.ts` на mock-telegram по сценариям спеки; весь e2e и typecheck зелёные; `openspec validate`
-- [ ] 3.2 Документация: AGENTS.md, `/help`
+- [x] 3.1 e2e `platform-channel.test.ts` на mock-telegram по сценариям спеки; весь e2e и typecheck зелёные; `openspec validate`
+- [x] 3.2 Документация: AGENTS.md, `/help`
diff --git a/openspec/specs/platform-notifications/spec.md b/openspec/specs/platform-notifications/spec.md
new file mode 100644
index 00000000..3da90d2a
--- /dev/null
+++ b/openspec/specs/platform-notifications/spec.md
@@ -0,0 +1,55 @@
+# platform-notifications Specification
+
+## Purpose
+Определяет, как Пеппа сообщает о себе: события платформы в Telegram-канал, заданный суперадмином, и дайджесты обновлений и состояния.
+
+## Requirements
+
+### Requirement: Канал платформы
+Суперадмин SHALL задавать Telegram-канал платформы по Chat ID в настройках платформы; Пеппа SHALL проверять, что бот может писать в канал, и показывать результат.
+
+#### Scenario: Бот — админ канала
+- **GIVEN** бот добавлен администратором канала с Chat ID «-1004371018094»
+- **WHEN** суперадмин сохраняет этот Chat ID
+- **THEN** в настройках видно «канал подключён» с названием канала
+
+#### Scenario: Бот не добавлен в канал
+- **GIVEN** бот не состоит в канале «-1004371018094»
+- **WHEN** суперадмин сохраняет этот Chat ID
+- **THEN** настройки показывают «бот не видит канал — добавьте его администратором»
+
+#### Scenario: Не суперадмин
+- **GIVEN** пользователь без роли суперадмина
+- **WHEN** он открывает настройки платформы
+- **THEN** он получает «не найдено»
+
+### Requirement: События платформы в канал
+Пеппа SHALL публиковать в канал платформы новые релизы, перезапуски и падения сервисов и их восстановление.
+
+#### Scenario: Новый релиз
+- **GIVEN** канал платформы подключён и в проде версия «0.15.0» коммит «aa8796a»
+- **WHEN** выкачена версия «0.16.0» коммит «b1c2d3e» с задачами PEP-59 и PEP-61
+- **THEN** в канале появляется сообщение «Peppa v0.16.0 · b1c2d3e» со списком «PEP-59, PEP-61»
+
+#### Scenario: Сервис упал и поднялся
+- **GIVEN** канал платформы подключён
+- **WHEN** бот Пеппы перестал отвечать дольше 2 минут, а затем восстановился
+- **THEN** в канале одно сообщение о падении и одно о восстановлении с длительностью простоя
+
+### Requirement: Дайджест
+Пеппа SHALL по расписанию отправлять в канал дайджест: изменения Пеппы с прошлого дайджеста и текущее состояние платформы; пользователи с привязанным Telegram SHALL получать личный дайджест по своим проектам, если не отписались.
+
+#### Scenario: Ежедневный дайджест
+- **GIVEN** с прошлого дайджеста смержены задачи PEP-59 и PEP-61, сейчас 2 активных раннера и 1 открытый вопрос
+- **WHEN** наступает время дайджеста
+- **THEN** в канале сообщение с разделами «Что нового» (PEP-59, PEP-61), «Сейчас»: раннеров 2, вопросов 1
+
+#### Scenario: Нечего сообщить
+- **GIVEN** с прошлого дайджеста не было изменений и активности
+- **WHEN** наступает время дайджеста
+- **THEN** дайджест не отправляется
+
+#### Scenario: Отписка
+- **GIVEN** пользователь отключил личный дайджест в Настройках
+- **WHEN** наступает время дайджеста
+- **THEN** он личный дайджест не получает, канал — получает
From 6066ce8763107cd4dc437a90a3f0cb0082e8d26c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Sat, 14 Nov 2026 20:14:40 +0500
Subject: [PATCH 5/5] PEP-60: mock-telegram rejects posts only to channels
added with addChannel (supergroups of PEP-62 keep working)
Co-Authored-By: Claude Opus 5.5
---
packages/testkit/src/mock-telegram.ts | 11 +++++------
1 file changed, 5 insertions(+), 6 deletions(-)
diff --git a/packages/testkit/src/mock-telegram.ts b/packages/testkit/src/mock-telegram.ts
index 27d12638..61a7bb33 100644
--- a/packages/testkit/src/mock-telegram.ts
+++ b/packages/testkit/src/mock-telegram.ts
@@ -116,12 +116,11 @@ export class MockTelegram {
return { ok: true, result: { user: this.bot, status: c.bot, ...(c.bot === "administrator" ? { can_post_messages: c.canPost } : {}) } };
}
case "sendMessage": {
- // Channels (-100…): the bot must be an admin that may post.
- if (String(p.chat_id).startsWith("-100")) {
- const c = this.channels.get(Number(p.chat_id));
- if (!c || c.bot === "left") return { ok: false, error_code: 400, description: "Bad Request: chat not found" };
- if (c.bot !== "administrator" || !c.canPost) return { ok: false, error_code: 403, description: "Forbidden: bot is not a member of the channel chat" };
- }
+ // Channels added with addChannel: the bot must be an admin that may post. Other «-100…»
+ // ids are supergroups (PEP-62) and accept messages as before.
+ const ch = this.channels.get(Number(p.chat_id));
+ if (ch && ch.bot === "left") return { ok: false, error_code: 400, description: "Bad Request: chat not found" };
+ if (ch && (ch.bot !== "administrator" || !ch.canPost)) return { ok: false, error_code: 403, description: "Forbidden: bot is not a member of the channel chat" };
const m: MockTgMessage = {
message_id: this.nextMessageId++,
chat_id: Number(p.chat_id),