// PEP-60, spec platform-notifications: the platform channel (check through the Bot API), // platform events (new build, outage/recovery, restart) and the platform digest to the // channel and to users — mock-telegram as the Bot API, the real bot delivers the outbox, // a temp git repo as FORGE's checkout for builds. import assert from "node:assert/strict"; import { execFile, execFileSync } from "node:child_process"; import { promisify } from "node:util"; import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { after, before, beforeEach, describe, test } from "node:test"; // helpers must load first: it sets the isolated test env that runner modules read on load. import { core, db, project, runner, teardown, waitFor } from "./helpers.ts"; import { MockTelegram } from "../src/mock-telegram.ts"; import { questions, sessions, tasks, telegramOutbox, users } from "@peppa/db"; import { eq, like, sql } from "drizzle-orm"; const { createBot } = await import("@peppa/bot"); const { TelegramApi } = await import("@peppa/bot/telegram"); const ROOT = resolve(fileURLToPath(import.meta.url), "../../../.."); const MIN = 60_000; const CHANNEL = -1004371018094; const tg = await new MockTelegram().start(); const TG = { token: tg.token, apiUrl: tg.url }; process.env.TELEGRAM_BOT_TOKEN = tg.token; process.env.TELEGRAM_API_URL = tg.url; process.env.PEPPA_SECRET = "mock-secret-for-tests"; process.env.PEPPA_TZ = "UTC"; const ANNA = { login: "mock-anna", chatId: 9301 }; const BEK = { login: "mock-bek", chatId: 9302 }; let pep: Awaited>; let pepId = 0; async function pair(login: string, chatId: number, giteaId: number) { const u = await core.upsertUserFromGitea(db, { id: giteaId, login }, { access_token: "x" }); await db.update(users).set({ telegramChatId: chatId, telegramUserId: chatId }).where(eq(users.id, u.id)); return u; } /** Texts queued for a chat, oldest first. */ async function queued(chatId: number, keyLike = "%"): Promise { const rows = await db .select() .from(telegramOutbox) .where(sql`${telegramOutbox.dedupeKey} like ${keyLike} and cast(json_extract(${telegramOutbox.params}, '$.chat_id') as text) = ${String(chatId)}`) .orderBy(telegramOutbox.id); return rows.map((r) => String(r.params.text)); } async function connectChannel() { tg.addChannel(CHANNEL, "FORGE News"); await core.setPlatformChannel(db, { chatId: CHANNEL }); return core.checkPlatformChannel(db, TG); } before(async () => { 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); await pair(BEK.login, BEK.chatId, 9402); }); beforeEach(async () => { db.run(sql`delete from settings where key like 'platform.%' or key like 'heartbeat:%' or key like 'monitor.%' or key like 'notify.prefs:%'`); await db.delete(telegramOutbox); await db.delete(sessions); tg.channels.clear(); }); after(async () => { await tg.stop(); await teardown(); }); describe("Канал платформы", () => { test("Бот — админ канала", async () => { const c = await connectChannel(); assert.equal(c.check?.ok, true); assert.equal(core.describeChannel(c), "канал подключён — FORGE News"); assert.equal((await core.getPlatformChannel(db)).title, "FORGE News"); }); test("Бот не добавлен в канал", async () => { await core.setPlatformChannel(db, { chatId: CHANNEL }); const c = await core.checkPlatformChannel(db, TG); assert.equal(c.check?.ok, false); assert.equal(c.check?.error, "бот не видит канал — добавьте его администратором"); // Not posting while the channel doesn't work. assert.equal(await core.postToChannel(db, "releases", "pch:test", "x"), false); }); test("Бот в канале без права публикации", async () => { tg.addChannel(CHANNEL, "FORGE News", { canPost: false }); await core.setPlatformChannel(db, { chatId: CHANNEL }); const c = await core.checkPlatformChannel(db, TG); assert.equal(c.check?.error, core.CHANNEL_NO_POST); }); test("FORGE перепроверяет неработающий канал раз в час и включает его", async () => { await core.setPlatformChannel(db, { chatId: CHANNEL }); const t0 = new Date("2026-03-01T10:00:00Z"); assert.equal(await core.recheckPlatformChannel(db, { now: t0, tg: TG }), true); assert.equal((await core.getPlatformChannel(db)).check?.ok, false); tg.addChannel(CHANNEL, "FORGE News"); assert.equal(await core.recheckPlatformChannel(db, { now: new Date(t0.getTime() + 30 * MIN), tg: TG }), false, "не раньше часа"); assert.equal(await core.recheckPlatformChannel(db, { now: new Date(t0.getTime() + 61 * MIN), tg: TG }), true); assert.equal((await core.getPlatformChannel(db)).check?.ok, true); }); test("Неверный Chat ID и сброс проверки при смене канала", async () => { assert.throws(() => core.parseChatId("канал"), /Chat ID/); assert.equal(core.parseChatId("@peppa_news"), "@peppa_news"); await connectChannel(); const c = await core.setPlatformChannel(db, { chatId: -1009999999999 }); assert.equal(c.check, null); }); test("Не суперадмин", async () => { await core.setPlatformAdmins(db, [ANNA.login]); await assert.rejects(core.requireSuperadmin(db, { login: BEK.login })); await core.requireSuperadmin(db, { login: ANNA.login }); }); test("CLI: peppa platform channel", async () => { tg.addChannel(CHANNEL, "FORGE News"); // Async: the mock Bot API lives in this process. const { stdout: out } = await promisify(execFile)(process.execPath, [join(ROOT, "packages/cli/src/index.ts"), "platform", "channel", `chat=${CHANNEL}`, "services=off", "time=08:30"], { encoding: "utf8", env: process.env }); assert.match(out, /канал подключён — FORGE News/); assert.match(out, /services=off/); assert.match(out, /дайджест: 08:30/); }); }); describe("События платформы в канал", () => { test("Новый релиз", async () => { await connectChannel(); await db.insert(tasks).values([ { projectId: pepId, number: 59, title: "Версия и коммит в футере веба" }, { projectId: pepId, number: 61, title: "Меню сверху" }, ]); const k = (n: number) => `${pep.key}-${n}`; assert.equal(await core.announcePlatformBuild(db, { version: "0.15.0", commit: "aa8796a".padEnd(40, "0"), tasks: [] }), false, "первая сборка только запоминается"); assert.equal(await core.announcePlatformBuild(db, { version: "0.16.0", commit: "b1c2d3e".padEnd(40, "1"), tasks: [k(59), k(61)] }), true); const [msg] = await queued(CHANNEL); assert.match(msg!, /FORGE v0\.16\.0 · b1c2d3e/); assert.match(msg!, new RegExp(`Задачи: ${k(59)}, ${k(61)}`)); assert.match(msg!, /Версия и коммит в футере веба/); // The same commit again — nothing new. assert.equal(await core.announcePlatformBuild(db, { version: "0.16.0", commit: "b1c2d3e".padEnd(40, "1"), tasks: [] }), false); assert.equal((await queued(CHANNEL)).length, 1); }); test("Сборка из ветки стори не объявляется, из main — со стори из коммитов", async () => { await connectChannel(); const repo = mkdtempSync(join(tmpdir(), "peppa-build-")); const git = (...a: string[]) => execFileSync("git", ["-C", repo, "-c", "user.name=t", "-c", "user.email=t@t", ...a], { encoding: "utf8" }).trim(); git("init", "-q", "-b", "main"); writeFileSync(join(repo, "package.json"), JSON.stringify({ version: "0.15.0" })); git("add", "-A"); git("commit", "-qm", "base"); const now = new Date("2026-03-02T10:00:00Z"); await runner.platformBuildTick(db, { root: repo, force: true, now }); assert.equal((await core.getPlatformBuild(db))?.version, "0.15.0"); // A story branch checked out: not a release. git("checkout", "-qb", `task/${pep.key.toLowerCase()}-70`); mkdirSync(join(repo, "src")); writeFileSync(join(repo, "src/a.txt"), "a"); git("add", "-A"); git("commit", "-qm", `${pep.key}-70: work in progress`); assert.equal(await runner.platformBuildTick(db, { root: repo, force: true, now }), false); // Merged into main with a version bump: announced with the stories of the merged commits. git("checkout", "-q", "main"); git("merge", "-q", "--no-ff", "-m", `Merge pull request '${pep.key}-70: канал' (#9) from task/${pep.key.toLowerCase()}-70 into main`, `task/${pep.key.toLowerCase()}-70`); writeFileSync(join(repo, "package.json"), JSON.stringify({ version: "0.16.0" })); git("commit", "-qam", `${pep.key}-72: bump`); assert.equal(await runner.platformBuildTick(db, { root: repo, force: true, now }), true); const [msg] = await queued(CHANNEL); assert.match(msg!, new RegExp(`FORGE v0\\.16\\.0 · ${git("rev-parse", "--short=7", "HEAD")}`)); assert.match(msg!, new RegExp(`Задачи: ${pep.key}-70, ${pep.key}-72`)); }); test("Сервис упал и поднялся", async () => { await connectChannel(); const T0 = Date.parse("2026-03-03T12:00:00Z"); const at = (m: number) => new Date(T0 + m * MIN); const staleMs = 2 * MIN; await core.beat(db, "bot", { now: at(0) }); for (const m of [1, 3, 4, 10]) { await core.checkServices(db, { self: "watchdog", now: at(m), staleMs }); await core.checkServices(db, { self: "web", now: at(m), staleMs }); } await core.beat(db, "bot", { now: at(12) }); await core.checkServices(db, { self: "watchdog", now: at(12), staleMs }); await core.checkServices(db, { self: "web", now: at(12.5), staleMs }); const msgs = await queued(CHANNEL, "mon:ch:%"); assert.equal(msgs.length, 2, msgs.join("\n")); assert.match(msgs[0]!, /бот не отвечает с/); assert.match(msgs[1]!, /бот снова работает — простой 12 мин/); }); test("Перезапуск сервиса без простоя", async () => { await connectChannel(); const now = new Date(); const hb = (pid: number) => ({ at: now.toISOString(), startedAt: new Date(now.getTime() - pid).toISOString(), pid, host: "mac", version: "0.15.0", commit: "abc1234".padEnd(40, "0") }); await core.setSetting(db, "heartbeat:web", hb(100)); await core.checkServices(db, { self: "watchdog", now }); assert.equal((await queued(CHANNEL)).length, 0, "первый процесс только запоминается"); await core.setSetting(db, "heartbeat:web", hb(200)); await core.checkServices(db, { self: "watchdog", now }); await core.checkServices(db, { self: "bot", now }); const msgs = await queued(CHANNEL); assert.deepEqual(msgs, ["🔄 FORGE: веб перезапущен (v0.15.0 · abc1234)."]); }); test("Выключенные события сервисов в канал не идут", async () => { await connectChannel(); await core.setPlatformChannel(db, { events: { services: false } }); const T0 = Date.parse("2026-03-04T12:00:00Z"); await core.beat(db, "bot", { now: new Date(T0) }); await core.checkServices(db, { self: "watchdog", now: new Date(T0 + 10 * MIN), staleMs: 2 * MIN }); assert.equal((await queued(CHANNEL, "mon:ch:%")).length, 0); }); }); describe("Дайджест", () => { const day = (h: number, d = 5) => new Date(`2026-03-${String(d).padStart(2, "0")}T${String(h).padStart(2, "0")}:05:00Z`); async function activity() { // Stories finished after the previous digest, two live runners and one open question. await db.insert(tasks).values([ { projectId: pepId, number: 159, title: "Футер с версией", status: "done", updatedAt: day(6) }, { projectId: pepId, number: 161, title: "Меню сверху", status: "done", updatedAt: day(7) }, ]); await db.insert(sessions).values([ { projectId: pepId, tmuxName: "mock-digest-1", status: "running" }, { projectId: pepId, tmuxName: "mock-digest-2", status: "idle" }, ]); await db.insert(questions).values({ projectId: pepId, kind: "question", text: "Какой цвет?" }); } async function cleanActivity() { await db.delete(questions); await db.delete(tasks).where(sql`${tasks.number} in (159, 161)`); } test("Ежедневный дайджест", async () => { await connectChannel(); await core.setSetting(db, "platform.digest.last", { date: "2026-03-04", at: day(9, 4).toISOString() }); await activity(); try { assert.equal(await core.platformDigestTick(db, { now: day(8) }), null, "до времени дайджеста — ничего"); const r = await core.platformDigestTick(db, { now: day(9) }); assert.deepEqual(r, { channel: true, users: 0 }); const [msg] = await queued(CHANNEL, "pch:digest:%"); assert.match(msg!, /Что нового<\/b>/); assert.match(msg!, new RegExp(`Сделано: ${pep.key}-159, ${pep.key}-161`)); assert.match(msg!, /Сейчас<\/b>/); assert.match(msg!, /Агентов за работой: 2/); assert.match(msg!, /Вопросов: 1/); assert.equal(await core.platformDigestTick(db, { now: day(10) }), null, "раз в сутки"); } finally { await cleanActivity(); } }); test("Нечего сообщить", async () => { await connectChannel(); await core.setSetting(db, "platform.digest.last", { date: "2026-03-04", at: day(9, 4).toISOString() }); const r = await core.platformDigestTick(db, { now: day(9) }); assert.deepEqual(r, { channel: false, users: 0 }); assert.equal((await queued(CHANNEL)).length, 0); }); test("Отписка", async () => { await connectChannel(); await core.setPlatformChannel(db, { digest: { users: true } }); const anna = (await core.getUserByLogin(db, ANNA.login))!; const prefs = await core.getNotifyPrefs(db, anna.id); await core.setNotifyPrefs(db, anna.id, { ...prefs, events: { ...prefs.events, platform: { telegram: false, push: false } } }); await core.setSetting(db, "platform.digest.last", { date: "2026-03-04", at: day(9, 4).toISOString() }); await activity(); try { const r = await core.platformDigestTick(db, { now: day(9) }); assert.equal(r?.channel, true); assert.equal((await queued(ANNA.chatId, "pdigest:%")).length, 0, "отписавшийся не получает"); assert.equal((await queued(BEK.chatId, "pdigest:%")).length, 1); assert.equal((await queued(CHANNEL, "pch:digest:%")).length, 1, "канал получает"); } finally { await cleanActivity(); } }); test("Бот доставляет сообщения канала из outbox", async () => { await connectChannel(); await core.setPlatformChannel(db, { digest: { users: false } }); await core.postToChannel(db, "releases", "pch:release:mock", "🚀 FORGE v9.9.9 · mock000"); const bot = createBot({ db, api: new TelegramApi(tg.token, tg.url), secret: tg.token, webUrl: "http://peppa.test", pollTimeoutSec: 1, outboxIntervalMs: 100, reconcileIntervalMs: 5000, heartbeatIntervalMs: 60_000 }); await bot.start(); try { await waitFor("channel message delivered", async () => tg.botMessages(CHANNEL).some((m) => /FORGE v9\.9\.9/.test(m.text))); const [row] = await db.select().from(telegramOutbox).where(like(telegramOutbox.dedupeKey, "pch:release:mock")); assert.equal(row?.status, "sent"); } finally { await bot.stop(); } }); });