// 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, // MockGitea as the history of FORGE's main branch for builds (PEP-292: no .git in the image). import assert from "node:assert/strict"; import { execFile } from "node:child_process"; import { promisify } from "node:util"; import { 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 { MockGitea } from "../src/mock-gitea.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 gitea = new MockGitea(mkdtempSync(join(tmpdir(), "peppa-pch-gitea-"))); await gitea.start(); process.env.GITEA_URL = gitea.url; process.env.GITEA_PLATFORM_REPO = "peppa/peppa"; const GITEA_BOT = { id: 73, login: "peppa-bot", token: "mock-token-pch-bot" }; process.env.GITEA_TOKEN = GITEA_BOT.token; gitea.addUser(GITEA_BOT); gitea.addRepo("peppa", "peppa", { admins: [GITEA_BOT.login], files: { "README.md": "# FORGE\n" } }); 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 gitea.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("Выкатка в контейнере без .git: ветка стори не объявляется, main — одно сообщение с задачами из Gitea", async () => { await connectChannel(); // The platform image: package.json, no .git — the commit comes from PEPPA_COMMIT. const root = mkdtempSync(join(tmpdir(), "peppa-image-")); writeFileSync(join(root, "package.json"), JSON.stringify({ version: "0.15.0" })); assert.equal(runner.deployedCommit(root, undefined), null, "без .git и PEPPA_COMMIT коммит неизвестен — git не вызывается"); const logs: string[] = []; const log = (l: string) => logs.push(l); const now = new Date("2026-03-02T10:00:00Z"); const k = pep.key; const base = gitea.sha("peppa", "peppa", "main"); await runner.platformBuildTick(db, { root, commit: runner.deployedCommit(root, base) ?? undefined, force: true, now, log }); assert.equal((await core.getPlatformBuild(db))?.commit, base, "первая версия только запоминается"); assert.equal((await queued(CHANNEL)).length, 0); // A story branch build: not on main — not a release. const wip = gitea.commit("peppa", "peppa", `task/${k.toLowerCase()}-70`, { "a.txt": "a" }, `${k}-70: work in progress`); assert.equal(await runner.platformBuildTick(db, { root, commit: wip, force: true, now, log }), false); assert.equal((await core.getPlatformBuild(db))?.commit, base); // Merged into main and deployed: one message with the stories between the versions. gitea.commit("peppa", "peppa", "main", { "a.txt": "a" }, `Merge pull request '${k}-70: канал' (#9) from task/${k.toLowerCase()}-70 into main`); const head = gitea.commit("peppa", "peppa", "main", { "b.txt": "b" }, `${k}-72: bump`); writeFileSync(join(root, "package.json"), JSON.stringify({ version: "0.16.0" })); assert.equal(await runner.platformBuildTick(db, { root, commit: runner.deployedCommit(root, head.slice(0, 8)) ?? undefined, force: true, now, log }), true, "короткий SHA выкатки тоже узнаётся"); const msgs = await queued(CHANNEL); assert.equal(msgs.length, 1, msgs.join("\n")); assert.match(msgs[0]!, new RegExp(`FORGE v0\\.16\\.0 · ${head.slice(0, 7)}`)); assert.match(msgs[0]!, new RegExp(`Задачи: ${k}-70, ${k}-72`)); assert.equal((await core.getPlatformBuild(db))?.commit, head, "запоминается полный SHA из Gitea"); // The same version on the next tick — nothing new. assert.equal(await runner.platformBuildTick(db, { root, commit: head, force: true, now, log }), false); assert.equal((await queued(CHANNEL)).length, 1); assert.ok(!logs.some((l) => /not a git repository/.test(l)), logs.join("\n")); }); test("Gitea недоступна — версия не запоминается, после восстановления одно сообщение", async () => { await connectChannel(); const root = mkdtempSync(join(tmpdir(), "peppa-image-")); writeFileSync(join(root, "package.json"), JSON.stringify({ version: "0.17.0" })); const now = new Date("2026-03-02T11:00:00Z"); const k = pep.key; const prev = gitea.sha("peppa", "peppa", "main"); await core.announcePlatformBuild(db, { version: "0.16.0", commit: prev, tasks: [] }); const head = gitea.commit("peppa", "peppa", "main", { "c.txt": "c" }, `${k}-80: что-то`); const logs: string[] = []; gitea.down = true; try { assert.equal(await runner.platformBuildTick(db, { root, commit: head, force: true, now, log: (l) => logs.push(l) }), false); } finally { gitea.down = false; } assert.equal((await core.getPlatformBuild(db))?.commit, prev); assert.match(logs.join("\n"), /retry later/); // Not forced within 10 minutes: Gitea is not asked again. assert.equal(await runner.platformBuildTick(db, { root, commit: head, now: new Date(now.getTime() + 2 * MIN) }), false); assert.equal(await runner.platformBuildTick(db, { root, commit: head, now: new Date(now.getTime() + 11 * MIN) }), true); const msgs = await queued(CHANNEL); assert.equal(msgs.length, 1, msgs.join("\n")); assert.match(msgs[0]!, new RegExp(`Задачи: ${k}-80`)); }); 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(); } }); });