diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts index 930188f3..e4c85b05 100644 --- a/apps/bot/src/bot.ts +++ b/apps/bot/src/bot.ts @@ -13,7 +13,13 @@ import { listenEvents, answeredQuestionMessages, projectForUser, - questionRecipients, + buildDigest, + deliverToUser, + flushPushOutbox, + projectAudience, + questionEvent, + renderDigest, + type NotifyEvent, telegramUser, userProjectIds, type User, @@ -59,7 +65,27 @@ const HELP = `Я бот Пеппы. Присылаю вопросы от аге • Кнопки под сообщением — быстрый ответ. • Ответ реплаем на сообщение — свой текст, он уйдёт прямо в сессию. -• /status — активные сессии и открытые вопросы.`; +• /status — активные сессии и открытые вопросы. +• /digest — сводка за сутки по твоим проектам (каждый день приходит сама; время и что присылать — в Настройках → Уведомления).`; + +const PUSH_MAX_AGE_MS = 30 * 60_000; + +const PUSH_TITLE: Record = { + questions: "Агент ждёт ответа", + review: "Готово к ревью", + failures: "Раннер остановился", + releases: "Релиз", + incidents: "Ошибка в проде", + monitoring: "Мониторинг", + digest: "Сводка", +}; + +/** Browser notification text for a question. */ +function pushFor(q: Question, event: NotifyEvent, ctx: { taskKey: string | null; taskTitle: string | null }): { title: string; body: string } { + const title = `${ctx.taskKey ? `${ctx.taskKey}: ` : ""}${q.kind === "approval" ? "нужно одобрение" : q.kind === "permission" ? "нужно разрешение" : PUSH_TITLE[event]}`; + const body = q.text.length > 200 ? `${q.text.slice(0, 199)}…` : q.text; + return { title, body }; +} export function createBot(o: BotOptions) { const { db, api } = o; @@ -86,19 +112,36 @@ export function createBot(o: BotOptions) { return { taskKey: null, taskTitle: null, session: null, webUrl: o.webUrl }; } - /** Makes sure every open question has a message and every closed one an edit. */ - /** Makes sure every open question has a message for each recipient, and every closed one an edit. */ + /** + * Makes sure every open question reaches each person of its project by their notification + * settings (PEP-35): a Telegram message and/or a browser push; every closed one gets an edit. + */ async function reconcile(): Promise { - for (const q of await pendingQuestions(db)) { - const recipients = await questionRecipients(db, q.projectId); - if (!recipients.length) continue; - const r = renderQuestion(q, await context(q)); - for (const u of recipients) { - await enqueueTelegram(db, { + const open = await pendingQuestions(db); + const projectsOf = new Map>(); + const waitingFor = async (userId: number) => { + if (!projectsOf.has(userId)) projectsOf.set(userId, new Set(await userProjectIds(db, userId))); + const ids = projectsOf.get(userId)!; + return open.filter((x) => ids.has(x.projectId)).length; + }; + for (const q of open) { + const audience = await projectAudience(db, q.projectId); + if (!audience.length) continue; + const ctx = await context(q); + const event = questionEvent(q, { taskStatus: ctx.taskStatus, sessionStatus: ctx.session?.status }); + const r = renderQuestion(q, ctx); + // A push is a "now" signal: questions older than this don't pop up on a fresh subscription. + const fresh = Date.now() - q.createdAt.getTime() < PUSH_MAX_AGE_MS; + const url = ctx.taskKey ? `/t/${ctx.taskKey}` : `/p/${await projectKey(q.projectId)}`; + for (const u of audience) { + await deliverToUser(db, u, { + event, + projectId: q.projectId, dedupeKey: `q:${q.id}:${u.telegramChatId}`, - method: "sendMessage", - questionId: q.id, - params: { chat_id: u.telegramChatId, text: r.text, parse_mode: "HTML", reply_markup: { inline_keyboard: r.buttons } }, + pushKey: `q:${q.id}:u${u.id}`, + telegram: { questionId: q.id, params: { text: r.text, parse_mode: "HTML", reply_markup: { inline_keyboard: r.buttons } } }, + push: fresh ? { ...pushFor(q, event, ctx), url, tag: `q:${q.id}`, count: await waitingFor(u.id) } : undefined, + urgency: event === "questions" || event === "failures" ? "high" : "normal", }); } } @@ -119,6 +162,11 @@ export function createBot(o: BotOptions) { wakeOutbox?.(); } + async function projectKey(projectId: number): Promise { + const [p] = await db.select({ key: projects.key }).from(projects).where(eq(projects.id, projectId)); + return p?.key ?? ""; + } + function scheduleReconcile() { if (reconcileQueued) return; reconcileQueued = true; @@ -150,6 +198,8 @@ export function createBot(o: BotOptions) { async function flushOutbox(): Promise { for (const row of await dueOutbox(db)) await deliver(row); + // Browser pushes (PEP-55) go out of the same loop. + await flushPushOutbox(db, { log }); } // ── Telegram → answers ───────────────────────────────────────────────────────── @@ -199,6 +249,11 @@ export function createBot(o: BotOptions) { if (/^\/(start|help)\b/.test(text)) return reply(m.chat.id, HELP).then(() => "done"); if (/^\/status\b/.test(text)) return reply(m.chat.id, await status(user)).then(() => "done"); + if (/^\/digest\b/.test(text)) { + const d = await buildDigest(db, user); + await api.sendMessage(m.chat.id, renderDigest(d, { webUrl: o.webUrl, title: "Сводка за сутки" }), { link_preview_options: { is_disabled: true } }).catch((e) => log(`digest: ${e.message}`)); + return "done"; + } if (m.reply_to_message) { const q = await questionByTelegramMessage(db, m.chat.id, m.reply_to_message.message_id); diff --git a/packages/core/src/digest.ts b/packages/core/src/digest.ts new file mode 100644 index 00000000..69218583 --- /dev/null +++ b/packages/core/src/digest.ts @@ -0,0 +1,173 @@ +// Daily digest (PEP-29): per user, per project — done in the last day, in progress, in +// review, waiting for the user, stuck, limits. Sent from the watchdog tick at the user's +// time; /digest in the bot renders it on demand. +import { projects, pushSubscriptions, questions, sessions, tasks, users, type Db } from "@peppa/db"; +import { formatTaskKey, loadEnv } from "@peppa/shared"; +import { and, asc, gte, inArray, isNull, notInArray } from "drizzle-orm"; +import { deliverToUser, getNotifyPrefs, hhmmToMinutes, localClock, type NotifyPrefs } from "./notifications.ts"; +import { FINISHED_SESSION_STATUSES } from "./sessions.ts"; +import { getSetting, setSetting } from "./settings.ts"; +import { listUserProjects, type User } from "./users.ts"; + +const DAY = 24 * 3600_000; +/** After the chosen time the digest may still go out for this long (a watchdog restart). */ +const WINDOW_MIN = 180; + +type TaskLine = { key: string; title: string }; + +export interface ProjectDigest { + key: string; + name: string; + done: TaskLine[]; + inProgress: TaskLine[]; + review: TaskLine[]; + blocked: TaskLine[]; + waiting: number; + stalled: number; + rateLimited: number; + limitResumes: number; +} + +export interface Digest { + projects: ProjectDigest[]; + totals: { done: number; inProgress: number; review: number; waiting: number; stuck: number }; +} + +/** What happened in the user's projects (muted ones left out) since `now - 24h`. */ +export async function buildDigest(db: Db, user: Pick, o: { now?: Date; prefs?: NotifyPrefs } = {}): Promise { + const now = o.now ?? new Date(); + const since = new Date(now.getTime() - DAY); + const prefs = o.prefs ?? (await getNotifyPrefs(db, user.id)); + const list = (await listUserProjects(db, user.id)).filter((p) => !prefs.mutedProjects.includes(p.id)); + const out: Digest = { projects: [], totals: { done: 0, inProgress: 0, review: 0, waiting: 0, stuck: 0 } }; + if (!list.length) return out; + const ids = list.map((p) => p.id); + const taskRows = await db + .select({ projectId: tasks.projectId, number: tasks.number, title: tasks.title, status: tasks.status, updatedAt: tasks.updatedAt }) + .from(tasks) + .where(and(inArray(tasks.projectId, ids), inArray(tasks.status, ["done", "proposing", "in_progress", "review", "blocked"]))) + .orderBy(asc(tasks.number)); + const open = await db + .select({ projectId: questions.projectId }) + .from(questions) + .where(and(inArray(questions.projectId, ids), isNull(questions.answeredAt))); + const runners = await db + .select({ projectId: sessions.projectId, status: sessions.status, limitResumes: sessions.limitResumes, limitResumedAt: sessions.limitResumedAt }) + .from(sessions) + .where(and(inArray(sessions.projectId, ids), notInArray(sessions.status, FINISHED_SESSION_STATUSES))); + const resumed = await db + .select({ projectId: sessions.projectId }) + .from(sessions) + .where(and(inArray(sessions.projectId, ids), gte(sessions.limitResumedAt, since))); + + for (const p of list) { + const line = (t: { number: number; title: string }) => ({ key: formatTaskKey(p.key, t.number), title: t.title }); + const mine = taskRows.filter((t) => t.projectId === p.id); + const d: ProjectDigest = { + key: p.key, + name: p.name, + done: mine.filter((t) => t.status === "done" && t.updatedAt >= since).map(line), + inProgress: mine.filter((t) => t.status === "in_progress" || t.status === "proposing").map(line), + review: mine.filter((t) => t.status === "review").map(line), + blocked: mine.filter((t) => t.status === "blocked").map(line), + waiting: open.filter((q) => q.projectId === p.id).length, + stalled: runners.filter((s) => s.projectId === p.id && s.status === "stalled").length, + rateLimited: runners.filter((s) => s.projectId === p.id && s.status === "rate_limited").length, + limitResumes: resumed.filter((s) => s.projectId === p.id).length, + }; + const any = d.done.length + d.inProgress.length + d.review.length + d.blocked.length + d.waiting + d.stalled + d.rateLimited + d.limitResumes; + if (!any) continue; + out.projects.push(d); + out.totals.done += d.done.length; + out.totals.inProgress += d.inProgress.length; + out.totals.review += d.review.length; + out.totals.waiting += d.waiting; + out.totals.stuck += d.blocked.length + d.stalled + d.rateLimited; + } + return out; +} + +const esc = (s: string) => s.replace(/&/g, "&").replace(//g, ">"); +const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}…` : s); + +function taskList(webUrl: string, items: TaskLine[], max = 8): string { + const shown = items.slice(0, max).map((t) => `${esc(t.key)} ${esc(clip(t.title, 60))}`); + if (items.length > max) shown.push(`…и ещё ${items.length - max}`); + return shown.map((s) => ` • ${s}`).join("\n"); +} + +/** Telegram HTML text of the digest. */ +export function renderDigest(d: Digest, o: { webUrl: string; title?: string }): string { + const lines = [`${esc(o.title ?? "☀️ Сводка за сутки")}`]; + if (!d.projects.length) { + lines.push("", "Всё тихо: за сутки ничего не сделано, ничего не в работе и ничего не ждёт тебя."); + return lines.join("\n"); + } + for (const p of d.projects) { + lines.push("", `${esc(p.name)} (${esc(p.key)}) — доска`); + if (p.done.length) lines.push(`✅ Сделано: ${p.done.length}`, taskList(o.webUrl, p.done)); + if (p.inProgress.length) lines.push(`🔨 В работе: ${p.inProgress.length}`, taskList(o.webUrl, p.inProgress, 5)); + if (p.review.length) lines.push(`👀 На ревью: ${p.review.length}`, taskList(o.webUrl, p.review)); + if (p.waiting) lines.push(`⏳ Ждёт тебя: ${p.waiting}`); + if (p.blocked.length) lines.push(`⛔ Заблокировано: ${p.blocked.length}`, taskList(o.webUrl, p.blocked)); + if (p.stalled) lines.push(`🧊 Зависло раннеров: ${p.stalled}`); + if (p.rateLimited || p.limitResumes) { + lines.push(`⌛ Лимит: ${[p.rateLimited ? `ждут сброса ${p.rateLimited}` : null, p.limitResumes ? `авто-продолжений за сутки ${p.limitResumes}` : null].filter(Boolean).join(", ")}`); + } + } + if (d.totals.waiting) lines.push("", `Открыть Пеппу — ответить на ${d.totals.waiting}.`); + return lines.join("\n"); +} + +/** One-line summary for a push notification. */ +export function digestSummary(d: Digest): string { + const t = d.totals; + return [t.done && `сделано ${t.done}`, t.inProgress && `в работе ${t.inProgress}`, t.review && `на ревью ${t.review}`, t.waiting && `ждёт тебя ${t.waiting}`, t.stuck && `зависло ${t.stuck}`] + .filter(Boolean) + .join(" · "); +} + +const lastKey = (userId: number) => `digest.last:${userId}`; + +/** + * Sends today's digest to every user whose time has come (watchdog tick). At most one per + * local day; an empty digest isn't sent. Returns the number of users it went to. + */ +export async function digestTick(db: Db, o: { now?: Date; log?: (m: string) => void } = {}): Promise { + const now = o.now ?? new Date(); + const webUrl = loadEnv().PEPPA_WEB_URL; + const withPush = new Set((await db.selectDistinct({ id: pushSubscriptions.userId }).from(pushSubscriptions)).map((r) => r.id)); + const all = (await db.select().from(users)).filter((u) => !u.disabledAt && (u.telegramChatId || withPush.has(u.id))); + let sent = 0; + for (const u of all) { + try { + const prefs = await getNotifyPrefs(db, u.id); + const ch = prefs.events.digest; + if (!ch.telegram && !ch.push) continue; + const clock = localClock(now, prefs.timezone); + const target = hhmmToMinutes(prefs.digestTime); + if (clock.minutes < target || clock.minutes >= target + WINDOW_MIN) continue; + if ((await getSetting(db, lastKey(u.id))) === clock.date) continue; + await setSetting(db, lastKey(u.id), clock.date); + const d = await buildDigest(db, u, { now, prefs }); + if (!d.projects.length) continue; + const r = await deliverToUser( + db, + u, + { + event: "digest", + dedupeKey: `digest:u${u.id}:${clock.date}`, + telegram: { params: { text: renderDigest(d, { webUrl }), parse_mode: "HTML", link_preview_options: { is_disabled: true } } }, + push: { title: "Сводка за сутки", body: digestSummary(d), url: "/", tag: "digest" }, + now, + }, + prefs, + ); + if (r.telegram || r.push) sent++; + } catch (e) { + o.log?.(`digest u${u.id}: ${(e as Error).message}`); + } + } + if (sent) o.log?.(`digest: sent to ${sent}`); + return sent; +} diff --git a/packages/core/src/incidents.ts b/packages/core/src/incidents.ts index bf7f6eb3..8cea68c5 100644 --- a/packages/core/src/incidents.ts +++ b/packages/core/src/incidents.ts @@ -10,7 +10,8 @@ import { PeppaError } from "./errors.ts"; import { notify } from "./notify.ts"; import { createGoal, listGoals, type Project } from "./projects.ts"; import { createTask, type TaskRef } from "./tasks.ts"; -import { enqueueTelegram, questionRecipients } from "./telegram.ts"; +import { enqueueTelegram } from "./telegram.ts"; +import { deliverToUser, projectAudience } from "./notifications.ts"; export type Incident = typeof incidents.$inferSelect; export type IncidentStatus = Incident["status"]; @@ -313,24 +314,36 @@ export function renderIncidentMessage(project: Pick, i: return lines.join("\n"); } -/** Sends an incident message to everyone who gets the project's questions in Telegram. */ +/** Sends an incident message to the project's people by their notification settings (PEP-35). */ export async function sendIncidentMessage(db: Db, i: Incident, m: IncidentMessage): Promise { - const recipients = await questionRecipients(db, i.projectId); - if (!recipients.length) return 0; + const audience = await projectAudience(db, i.projectId); + if (!audience.length) return 0; const [project] = await db.select().from(projects).where(eq(projects.id, i.projectId)); if (!project) return 0; const text = renderIncidentMessage(project, i, m, loadEnv().PEPPA_WEB_URL); const markup = m.kind === "ask" || (m.kind === "regressed" && !m.task) ? { inline_keyboard: incidentButtons(i.id) } : undefined; const kind = m.kind === "ask" || markup ? "ask" : m.kind; - for (const u of recipients) { - await enqueueTelegram(db, { + const taskKey = m.kind === "task" ? m.task.key : m.kind === "regressed" ? m.task?.key : null; + let sent = 0; + for (const u of audience) { + const r = await deliverToUser(db, u, { + event: "incidents", + projectId: i.projectId, dedupeKey: `inc:${i.id}:${kind}:r${i.regressions}:${u.telegramChatId}`, - method: "sendMessage", - params: { chat_id: u.telegramChatId, text, parse_mode: "HTML", link_preview_options: { is_disabled: true }, ...(markup ? { reply_markup: markup } : {}) }, + pushKey: `inc:${i.id}:${kind}:r${i.regressions}:u${u.id}`, + telegram: { params: { text, parse_mode: "HTML", link_preview_options: { is_disabled: true }, ...(markup ? { reply_markup: markup } : {}) } }, + push: { + title: `${m.kind === "regressed" ? "Ошибка вернулась" : "Ошибка"} в ${project.name}`, + body: clip(i.title, 200), + url: taskKey ? `/t/${taskKey}` : `/p/${project.key}`, + tag: `inc:${i.id}`, + }, + urgency: kind === "ask" ? "high" : "normal", }); + if (r.telegram || r.push) sent++; } await notify(db, { type: "incident", incidentId: i.id }); - return recipients.length; + return sent; } /** Closes delivered decision messages: original text + the decision, buttons removed. */ diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index e42317b0..8a0aea00 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -22,3 +22,6 @@ export * from "./local-users.ts"; export * from "./specs.ts"; export * from "./subscriptions.ts"; export * from "./reviews.ts"; +export * from "./webpush.ts"; +export * from "./notifications.ts"; +export * from "./digest.ts"; diff --git a/packages/core/src/monitor.ts b/packages/core/src/monitor.ts index ba584c31..1f67aeb3 100644 --- a/packages/core/src/monitor.ts +++ b/packages/core/src/monitor.ts @@ -8,7 +8,7 @@ import { fileURLToPath } from "node:url"; import { telegramOutbox, users, type Db } from "@peppa/db"; import { and, count, eq, inArray, isNotNull, sql } from "drizzle-orm"; import { allowedLogins } from "./access.ts"; -import { enqueueTelegram } from "./telegram.ts"; +import { deliverToUser } from "./notifications.ts"; import { deleteSetting, getSetting, setSetting } from "./settings.ts"; import type { User } from "./users.ts"; @@ -128,16 +128,24 @@ export async function adminRecipients(db: Db): Promise { // ── checks ───────────────────────────────────────────────────────────────────────── export async function alertAdmins(db: Db, key: string, text: string, log: (m: string) => void): Promise { - const to = await adminRecipients(db); - if (!to.length) { - log(`monitor: ${text} (нет админа с Telegram)`); - return 0; - } + const logins = await platformAdmins(db); + const admins = logins.length ? (await db.select().from(users).where(inArray(users.login, logins))).filter((u) => !u.disabledAt) : []; let queued = 0; - for (const u of to) { - if (await enqueueTelegram(db, { dedupeKey: `${key}:${u.telegramChatId}`, method: "sendMessage", params: { chat_id: u.telegramChatId, text } })) queued++; + let reached = 0; + for (const u of admins) { + // Monitoring goes by each admin's notification settings (PEP-35). + const r = await deliverToUser(db, u, { + event: "monitoring", + dedupeKey: `${key}:${u.telegramChatId}`, + pushKey: `${key}:u${u.id}`, + telegram: { params: { text } }, + push: { title: "Мониторинг Пеппы", body: text, url: "/", tag: key.split(":").slice(0, 2).join(":") }, + urgency: "high", + }); + if (r.telegram) queued++; + if (r.telegram || r.push || (u.telegramChatId && !r.muted)) reached++; } - log(`monitor: ${text}`); + log(reached ? `monitor: ${text}` : `monitor: ${text} (нет админа с Telegram)`); return queued; } diff --git a/packages/core/src/notifications.ts b/packages/core/src/notifications.ts new file mode 100644 index 00000000..8b8cdcd0 --- /dev/null +++ b/packages/core/src/notifications.ts @@ -0,0 +1,176 @@ +// Notification preferences and routing (PEP-35): every notification belongs to an event, +// the user picks channels per event (Telegram, browser push), quiet hours and projects. +import { projectMembers, projects, users, type Db } from "@peppa/db"; +import { eq, inArray } from "drizzle-orm"; +import { getSetting, setSetting } from "./settings.ts"; +import { enqueueTelegram, type OutboxRow } from "./telegram.ts"; +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 type NotifyEvent = (typeof NOTIFY_EVENTS)[number]; + +export const NOTIFY_EVENT_NAMES: Record = { + questions: "Вопросы агентов (одобрения, вопросы, разрешения)", + review: "Готово к ревью", + failures: "Сбои, зависания и лимиты раннеров", + releases: "Релизы и выкаты", + incidents: "Ошибки из прода", + monitoring: "Мониторинг Пеппы (админам)", + digest: "Ежедневный дайджест", +}; + +export interface Channels { + telegram: boolean; + push: boolean; +} + +export interface NotifyPrefs { + events: Record; + /** "HH:MM"–"HH:MM" in `timezone`; may cross midnight. null = off. */ + quiet: { from: string; to: string } | null; + /** IANA zone for quiet hours and the digest. */ + timezone: string; + /** "HH:MM" local time of the daily digest. */ + digestTime: string; + /** Sound for browser notifications and the open tab. */ + sound: boolean; + /** Projects the user doesn't want notifications from. */ + mutedProjects: number[]; +} + +const prefsKey = (userId: number) => `notify.prefs:${userId}`; + +export const serverTimezone = () => process.env.PEPPA_TZ || Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; + +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 } }, + quiet: null, + timezone: serverTimezone(), + digestTime: "09:00", + sound: true, + mutedProjects: [], + }; +} + +const HHMM = /^([01]\d|2[0-3]):[0-5]\d$/; + +export function isValidTimezone(tz: string): boolean { + try { + new Intl.DateTimeFormat("en-US", { timeZone: tz }); + return true; + } catch { + return false; + } +} + +/** Saved preferences merged over the defaults (new events get their default). */ +export async function getNotifyPrefs(db: Db, userId: number): Promise { + const d = defaultPrefs(); + const s = (await getSetting>(db, prefsKey(userId))) ?? {}; + const events = { ...d.events }; + for (const e of NOTIFY_EVENTS) if (s.events?.[e]) events[e] = { ...d.events[e], ...s.events[e] }; + return { + events, + quiet: s.quiet && HHMM.test(s.quiet.from) && HHMM.test(s.quiet.to) ? s.quiet : null, + timezone: s.timezone && isValidTimezone(s.timezone) ? s.timezone : d.timezone, + digestTime: s.digestTime && HHMM.test(s.digestTime) ? s.digestTime : d.digestTime, + sound: s.sound ?? d.sound, + mutedProjects: Array.isArray(s.mutedProjects) ? s.mutedProjects.filter((n) => Number.isInteger(n)) : [], + }; +} + +export async function setNotifyPrefs(db: Db, userId: number, p: NotifyPrefs): Promise { + if (p.quiet && (!HHMM.test(p.quiet.from) || !HHMM.test(p.quiet.to))) throw new Error("Тихие часы: время в формате ЧЧ:ММ"); + if (p.quiet && p.quiet.from === p.quiet.to) throw new Error("Тихие часы: начало и конец совпадают"); + if (!HHMM.test(p.digestTime)) throw new Error("Время дайджеста: формат ЧЧ:ММ"); + if (!isValidTimezone(p.timezone)) throw new Error(`Неизвестная таймзона: ${p.timezone}`); + await setSetting(db, prefsKey(userId), p); + return getNotifyPrefs(db, userId); +} + +/** Local wall clock of `now` in `tz`: date "YYYY-MM-DD" and minutes since midnight. */ +export function localClock(now: Date, tz: string): { date: string; minutes: number; hhmm: string } { + const parts = Object.fromEntries( + new Intl.DateTimeFormat("en-CA", { timeZone: tz, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hourCycle: "h23" }) + .formatToParts(now) + .map((p) => [p.type, p.value]), + ); + const minutes = Number(parts.hour) * 60 + Number(parts.minute); + return { date: `${parts.year}-${parts.month}-${parts.day}`, minutes, hhmm: `${parts.hour}:${parts.minute}` }; +} + +export const hhmmToMinutes = (s: string) => Number(s.slice(0, 2)) * 60 + Number(s.slice(3, 5)); + +export function inQuietHours(prefs: Pick, now = new Date()): boolean { + if (!prefs.quiet) return false; + const m = localClock(now, prefs.timezone).minutes; + const from = hhmmToMinutes(prefs.quiet.from); + const to = hhmmToMinutes(prefs.quiet.to); + return from < to ? m >= from && m < to : m >= from || m < to; +} + +/** Which event a PM question stands for. */ +export function questionEvent(q: Pick, ctx: { taskStatus?: string | null; sessionStatus?: string | null }): NotifyEvent { + if (q.kind !== "attention") return q.taskId == null && q.sessionId == null ? "releases" : "questions"; + if (ctx.taskStatus === "review") return "review"; + if (ctx.sessionStatus && ["failed", "rate_limited", "stalled"].includes(ctx.sessionStatus)) return "failures"; + if (q.taskId == null && q.sessionId == null) return "releases"; + return "questions"; +} + +/** Owner and members of a project (whether or not they paired Telegram). */ +export async function projectAudience(db: Db, projectId: number): Promise { + const [p] = await db.select({ ownerId: projects.ownerId }).from(projects).where(eq(projects.id, projectId)); + const members = await db.select({ id: projectMembers.userId }).from(projectMembers).where(eq(projectMembers.projectId, projectId)); + const ids = [...new Set([p?.ownerId, ...members.map((m) => m.id)].filter((x): x is number => x != null))]; + if (!ids.length) return []; + return (await db.select().from(users).where(inArray(users.id, ids))).filter((u) => !u.disabledAt); +} + +export interface Delivery { + event: NotifyEvent; + /** Muting a project silences it; null = not about a project (monitoring, digest). */ + projectId?: number | null; + /** Telegram outbox key for this user's message (push keys derive from it). */ + dedupeKey: string; + /** Push outbox key prefix if it must not depend on the Telegram key (default: dedupeKey). */ + pushKey?: string; + telegram?: { method?: OutboxRow["method"]; params: Record; questionId?: number }; + push?: PushPayload; + urgency?: "normal" | "high"; + now?: Date; +} + +export interface Delivered { + telegram: boolean; + push: number; + /** Skipped by preferences (muted project / event off). */ + muted: boolean; +} + +/** Routes one notification to one user by their preferences. */ +export async function deliverToUser(db: Db, user: User, d: Delivery, prefs?: NotifyPrefs): Promise { + const p = prefs ?? (await getNotifyPrefs(db, user.id)); + const out: Delivered = { telegram: false, push: 0, muted: false }; + if (d.projectId != null && p.mutedProjects.includes(d.projectId)) return { ...out, muted: true }; + const ch = p.events[d.event]; + if (!ch.telegram && !ch.push) return { ...out, muted: true }; + // The digest comes at a time the user picked, so quiet hours don't apply to it. + const quiet = d.event !== "digest" && inQuietHours(p, d.now); + if (ch.telegram && d.telegram && user.telegramChatId) { + out.telegram = await enqueueTelegram(db, { + dedupeKey: d.dedupeKey, + method: d.telegram.method ?? "sendMessage", + questionId: d.telegram.questionId, + params: { ...d.telegram.params, chat_id: user.telegramChatId, ...(quiet ? { disable_notification: true } : {}) }, + }); + } + if (ch.push && d.push && !quiet) { + out.push = await enqueuePush(db, user.id, { dedupeKey: d.pushKey ?? d.dedupeKey, payload: { ...d.push, sound: d.push.sound ?? p.sound }, urgency: d.urgency }); + } + return out; +} diff --git a/packages/core/src/webpush.ts b/packages/core/src/webpush.ts new file mode 100644 index 00000000..cd3632d0 --- /dev/null +++ b/packages/core/src/webpush.ts @@ -0,0 +1,203 @@ +// Web Push (PEP-55) on node:crypto: VAPID (RFC 8292) + aes128gcm payload encryption +// (RFC 8291 / RFC 8188), a durable outbox delivered by the bot, and the subscriptions table. +import { createECDH, createPrivateKey, generateKeyPairSync, hkdfSync, randomBytes, createCipheriv, sign } from "node:crypto"; +import { pushOutbox, pushSubscriptions, type Db } from "@peppa/db"; +import { loadEnv } from "@peppa/shared"; +import { and, asc, eq, lte } from "drizzle-orm"; +import { getSetting, setSetting } from "./settings.ts"; + +export type PushSubscriptionRow = typeof pushSubscriptions.$inferSelect; +export type PushOutboxRow = typeof pushOutbox.$inferSelect; + +/** What the service worker shows (apps/web/public/sw.js). */ +export interface PushPayload { + title: string; + body: string; + /** Opened on click (path on the Peppa web). */ + url: string; + /** Same tag replaces the previous notification. */ + tag?: string; + /** Play the system sound (user preference «звук»). */ + sound?: boolean; + /** Waiting items for the app badge. */ + count?: number; +} + +const VAPID = "push.vapid"; +const b64u = (b: Buffer) => b.toString("base64url"); +const fromB64u = (s: string) => Buffer.from(s, "base64url"); + +interface VapidKeys { + /** Uncompressed P-256 point, base64url (applicationServerKey in the browser). */ + publicKey: string; + /** PKCS#8 PEM. */ + privateKey: string; +} + +/** VAPID key pair of this Peppa: created on first use, kept in settings. */ +export async function vapidKeys(db: Db): Promise { + const saved = await getSetting(db, VAPID); + if (saved) return saved; + const { publicKey, privateKey } = generateKeyPairSync("ec", { namedCurve: "prime256v1" }); + const jwk = publicKey.export({ format: "jwk" }); + const raw = Buffer.concat([Buffer.from([4]), fromB64u(jwk.x!), fromB64u(jwk.y!)]); + const keys = { publicKey: b64u(raw), privateKey: privateKey.export({ format: "pem", type: "pkcs8" }).toString() }; + await setSetting(db, VAPID, keys); + // Another process may have raced us: whoever wrote last wins, read it back. + return (await getSetting(db, VAPID))!; +} + +export const vapidPublicKey = async (db: Db) => (await vapidKeys(db)).publicKey; + +/** `Authorization: vapid t=, k=` for the push service at `endpoint`. */ +export function vapidAuthorization(keys: VapidKeys, endpoint: string, subject: string, now = Date.now()): string { + const header = b64u(Buffer.from(JSON.stringify({ typ: "JWT", alg: "ES256" }))); + const claims = b64u(Buffer.from(JSON.stringify({ aud: new URL(endpoint).origin, exp: Math.floor(now / 1000) + 12 * 3600, sub: subject }))); + const data = `${header}.${claims}`; + const sig = sign("sha256", Buffer.from(data), { key: createPrivateKey(keys.privateKey), dsaEncoding: "ieee-p1363" }); + return `vapid t=${data}.${b64u(sig)}, k=${keys.publicKey}`; +} + +/** RFC 8291 aes128gcm body for the subscription's keys (one record). */ +export function encryptPayload(plaintext: Buffer, p256dh: string, auth: string): Buffer { + const uaPublic = fromB64u(p256dh); + const authSecret = fromB64u(auth); + const ecdh = createECDH("prime256v1"); + const asPublic = ecdh.generateKeys(); + const shared = ecdh.computeSecret(uaPublic); + const keyInfo = Buffer.concat([Buffer.from("WebPush: info\0"), uaPublic, asPublic]); + const ikm = Buffer.from(hkdfSync("sha256", shared, authSecret, keyInfo, 32)); + const salt = randomBytes(16); + const cek = Buffer.from(hkdfSync("sha256", ikm, salt, Buffer.from("Content-Encoding: aes128gcm\0"), 16)); + const nonce = Buffer.from(hkdfSync("sha256", ikm, salt, Buffer.from("Content-Encoding: nonce\0"), 12)); + const cipher = createCipheriv("aes-128-gcm", cek, nonce); + // 0x02 = padding delimiter of the last (only) record. + const body = Buffer.concat([cipher.update(Buffer.concat([plaintext, Buffer.from([2])])), cipher.final(), cipher.getAuthTag()]); + const rs = Buffer.alloc(4); + rs.writeUInt32BE(4096); + return Buffer.concat([salt, rs, Buffer.from([asPublic.length]), asPublic, body]); +} + +export type PushResult = { ok: true } | { ok: false; gone: boolean; retryAfterSec?: number; status: number; error: string }; + +/** One push to one subscription. `gone` = the subscription no longer exists (404/410). */ +export async function sendWebPush( + db: Db, + sub: Pick, + payload: PushPayload, + o: { urgency?: "normal" | "high"; ttlSec?: number } = {}, +): Promise { + const keys = await vapidKeys(db); + const body = encryptPayload(Buffer.from(JSON.stringify(payload)), sub.p256dh, sub.auth); + try { + const res = await fetch(sub.endpoint, { + method: "POST", + headers: { + Authorization: vapidAuthorization(keys, sub.endpoint, loadEnv().PEPPA_WEB_URL), + "Content-Encoding": "aes128gcm", + "Content-Type": "application/octet-stream", + TTL: String(o.ttlSec ?? 24 * 3600), + Urgency: o.urgency ?? "normal", + }, + body: new Uint8Array(body), + signal: AbortSignal.timeout(15_000), + }); + if (res.ok) return { ok: true }; + const text = (await res.text().catch(() => "")).slice(0, 300); + const retryAfter = Number(res.headers.get("retry-after")); + return { + ok: false, + gone: res.status === 404 || res.status === 410, + status: res.status, + retryAfterSec: Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter : undefined, + error: `${res.status} ${text}`.trim(), + }; + } catch (e) { + return { ok: false, gone: false, status: 0, error: (e as Error).message }; + } +} + +// ── subscriptions ─────────────────────────────────────────────────────────────────── + +export async function savePushSubscription( + db: Db, + userId: number, + s: { endpoint: string; keys: { p256dh: string; auth: string }; userAgent?: string | null }, +): Promise { + if (!/^https:\/\//.test(s.endpoint) && !/^http:\/\/(127\.0\.0\.1|localhost)[:/]/.test(s.endpoint)) throw new Error("Неверный адрес push-подписки"); + if (fromB64u(s.keys.p256dh).length !== 65 || fromB64u(s.keys.auth).length < 16) throw new Error("Неверные ключи push-подписки"); + const values = { userId, endpoint: s.endpoint, p256dh: s.keys.p256dh, auth: s.keys.auth, userAgent: s.userAgent?.slice(0, 300) ?? null }; + const [row] = await db + .insert(pushSubscriptions) + .values(values) + // The same browser re-subscribing (or another user on it) takes the endpoint over. + .onConflictDoUpdate({ target: pushSubscriptions.endpoint, set: values }) + .returning(); + return row!; +} + +export async function deletePushSubscription(db: Db, userId: number, endpoint: string): Promise { + await db.delete(pushSubscriptions).where(and(eq(pushSubscriptions.userId, userId), eq(pushSubscriptions.endpoint, endpoint))); +} + +export async function userPushSubscriptions(db: Db, userId: number): Promise { + return db.select().from(pushSubscriptions).where(eq(pushSubscriptions.userId, userId)).orderBy(asc(pushSubscriptions.id)); +} + +// ── outbox ────────────────────────────────────────────────────────────────────────── + +/** Queues a push for every subscription of the user. Returns the number queued. */ +export async function enqueuePush(db: Db, userId: number, m: { dedupeKey: string; payload: PushPayload; urgency?: "normal" | "high" }): Promise { + let queued = 0; + for (const s of await userPushSubscriptions(db, userId)) { + const rows = await db + .insert(pushOutbox) + .values({ dedupeKey: `${m.dedupeKey}:push:${s.id}`, subscriptionId: s.id, payload: { ...m.payload }, urgency: m.urgency ?? "normal" }) + .onConflictDoNothing() + .returning(); + queued += rows.length; + } + return queued; +} + +const MAX_ATTEMPTS = 6; + +/** Delivers due pushes; called from the bot's outbox loop. Returns the number delivered. */ +export async function flushPushOutbox(db: Db, o: { log?: (m: string) => void; limit?: number } = {}): Promise { + const due = await db + .select({ row: pushOutbox, sub: pushSubscriptions }) + .from(pushOutbox) + .leftJoin(pushSubscriptions, eq(pushOutbox.subscriptionId, pushSubscriptions.id)) + .where(and(eq(pushOutbox.status, "pending"), lte(pushOutbox.nextAttemptAt, new Date()))) + .orderBy(asc(pushOutbox.id)) + .limit(o.limit ?? 20); + let sent = 0; + for (const { row, sub } of due) { + if (!sub) { + await db.update(pushOutbox).set({ status: "failed", error: "subscription removed" }).where(eq(pushOutbox.id, row.id)); + continue; + } + const r = await sendWebPush(db, sub, row.payload as unknown as PushPayload, { urgency: row.urgency }); + const attempts = row.attempts + 1; + if (r.ok) { + sent++; + await db.update(pushOutbox).set({ status: "sent", sentAt: new Date(), attempts, error: null }).where(eq(pushOutbox.id, row.id)); + await db.update(pushSubscriptions).set({ lastOkAt: new Date() }).where(eq(pushSubscriptions.id, sub.id)); + continue; + } + o.log?.(`push #${row.id}: ${r.error}`); + if (r.gone) { + // The browser unsubscribed or the subscription expired: forget it (and its queue). + await db.update(pushOutbox).set({ status: "failed", attempts, error: r.error }).where(eq(pushOutbox.subscriptionId, sub.id)); + await db.delete(pushSubscriptions).where(eq(pushSubscriptions.id, sub.id)); + continue; + } + const permanent = r.status >= 400 && r.status < 500 && r.status !== 429; + const delayMs = r.retryAfterSec != null ? r.retryAfterSec * 1000 : Math.min(10 * 60_000, 2000 * 2 ** attempts); + await db + .update(pushOutbox) + .set({ attempts, error: r.error, status: permanent || attempts >= MAX_ATTEMPTS ? "failed" : "pending", nextAttemptAt: new Date(Date.now() + delayMs) }) + .where(eq(pushOutbox.id, row.id)); + } + return sent; +} diff --git a/packages/db/migrations/0005_push_notifications.sql b/packages/db/migrations/0005_push_notifications.sql new file mode 100644 index 00000000..eff8f95e --- /dev/null +++ b/packages/db/migrations/0005_push_notifications.sql @@ -0,0 +1,29 @@ +CREATE TABLE `push_outbox` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `dedupe_key` text NOT NULL, + `subscription_id` integer, + `payload` text NOT NULL, + `urgency` text DEFAULT 'normal' NOT NULL, + `status` text DEFAULT 'pending' NOT NULL, + `attempts` integer DEFAULT 0 NOT NULL, + `next_attempt_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `error` text, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `sent_at` integer, + FOREIGN KEY (`subscription_id`) REFERENCES `push_subscriptions`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE UNIQUE INDEX `push_outbox_dedupe_key_unique` ON `push_outbox` (`dedupe_key`);--> statement-breakpoint +CREATE TABLE `push_subscriptions` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `user_id` integer NOT NULL, + `endpoint` text NOT NULL, + `p256dh` text NOT NULL, + `auth` text NOT NULL, + `user_agent` text, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + `last_ok_at` integer, + FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE UNIQUE INDEX `push_subscriptions_endpoint_unique` ON `push_subscriptions` (`endpoint`); \ No newline at end of file diff --git a/packages/db/migrations/meta/0005_snapshot.json b/packages/db/migrations/meta/0005_snapshot.json new file mode 100644 index 00000000..f0ca33b9 --- /dev/null +++ b/packages/db/migrations/meta/0005_snapshot.json @@ -0,0 +1,2967 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "01595f06-03c2-470a-8d64-60ecf41afd6d", + "prevId": "e01baa2c-52bb-40aa-b39c-2490acbcd458", + "tables": { + "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 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "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" + } + }, + "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": {} + }, + "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 + }, + "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" + } + }, + "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 + }, + "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 + }, + "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 + }, + "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": {} + }, + "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 + }, + "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" + } + }, + "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": {} + }, + "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 + }, + "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 + } + }, + "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 + }, + "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" + } + }, + "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 + }, + "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 + }, + "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 + } + }, + "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 3345217f..f19de56e 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -36,6 +36,13 @@ "when": 1794613008393, "tag": "0004_code_reviewer", "breakpoints": true + }, + { + "idx": 5, + "version": "6", + "when": 1794614987778, + "tag": "0005_push_notifications", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index e0bd7cb7..daf06b76 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -325,6 +325,33 @@ export const telegramUpdates = sqliteTable("telegram_updates", { createdAt: createdAt(), }); +/** PEP-55: a browser's Web Push subscription (PushSubscription.toJSON()). */ +export const pushSubscriptions = sqliteTable("push_subscriptions", { + id: integer("id").primaryKey({ autoIncrement: true }), + userId: integer("user_id").notNull().references(() => users.id, { onDelete: "cascade" }), + endpoint: text("endpoint").notNull().unique(), + p256dh: text("p256dh").notNull(), + auth: text("auth").notNull(), + userAgent: text("user_agent"), + createdAt: createdAt(), + lastOkAt: integer("last_ok_at", { mode: "timestamp_ms" }), +}); + +/** PEP-55: durable Web Push outbox, delivered by the bot with retries (like telegram_outbox). */ +export const pushOutbox = sqliteTable("push_outbox", { + id: integer("id").primaryKey({ autoIncrement: true }), + dedupeKey: text("dedupe_key").notNull().unique(), + subscriptionId: integer("subscription_id").references(() => pushSubscriptions.id, { onDelete: "set null" }), + payload: text("payload", { mode: "json" }).$type>().notNull(), + urgency: text("urgency", { enum: ["normal", "high"] }).notNull().default("normal"), + status: text("status", { enum: ["pending", "sent", "failed"] }).notNull().default("pending"), + attempts: integer("attempts").notNull().default(0), + nextAttemptAt: integer("next_attempt_at", { mode: "timestamp_ms" }).notNull().default(nowMs), + error: text("error"), + createdAt: createdAt(), + sentAt: integer("sent_at", { mode: "timestamp_ms" }), +}); + /** OAuth clients registered dynamically (RFC 7591), e.g. ChatGPT connectors. */ export const oauthClients = sqliteTable("oauth_clients", { id: text("id").primaryKey(), diff --git a/packages/runner/src/watchdog.ts b/packages/runner/src/watchdog.ts index 6c985242..7f6616f6 100644 --- a/packages/runner/src/watchdog.ts +++ b/packages/runner/src/watchdog.ts @@ -3,6 +3,7 @@ import { createHash } from "node:crypto"; import { backupDb, + digestTick, expireSessionQuestions, listSessions, logSessionEvent, @@ -52,6 +53,8 @@ export async function tick(db: Db, opts: WatchdogOptions): Promise { } // Errors of running products (PEP-58): Bugsink poll + incident policies. await incidentTick(db, { now: opts.now, log }).catch((e) => log(`incidents: ${(e as Error).message}`)); + // Daily digest at each user's time (PEP-29); a no-op outside their window. + await digestTick(db, { now: opts.now, log }).catch((e) => log(`digest: ${(e as Error).message}`)); } async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, log: (m: string) => void) { diff --git a/packages/testkit/src/mock-push.ts b/packages/testkit/src/mock-push.ts new file mode 100644 index 00000000..ca70aa98 --- /dev/null +++ b/packages/testkit/src/mock-push.ts @@ -0,0 +1,118 @@ +// Mock Web Push service (PEP-55) for tests: plays the browser + push service (FCM) side. +// `subscribe()` returns what PushSubscription.toJSON() gives in a browser; POSTs to the +// endpoint are checked like a real push service does (VAPID JWT signed by `k`, aud, +// exp, aes128gcm) and decrypted with the subscription's private key (RFC 8291). +import { createDecipheriv, createECDH, createPublicKey, hkdfSync, randomBytes, randomUUID, verify } from "node:crypto"; +import { createServer, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; + +export interface MockPushMessage { + subscription: string; + payload: Record; + urgency: string | null; + ttl: string | null; +} + +interface MockSub { + ecdh: ReturnType; + auth: Buffer; + /** Answer with this status instead of 201 (e.g. 410 = unsubscribed). */ + status?: number; +} + +export class MockPushService { + readonly messages: MockPushMessage[] = []; + readonly rejected: Array<{ subscription: string; reason: string }> = []; + private subs = new Map(); + private server: Server | null = null; + url = ""; + + async start(): Promise { + this.server = createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (c) => chunks.push(c)); + req.on("end", () => { + const id = /^\/push\/([\w-]+)$/.exec(req.url ?? "")?.[1] ?? ""; + const sub = this.subs.get(id); + const fail = (status: number, reason: string) => { + this.rejected.push({ subscription: id, reason }); + res.writeHead(status).end(reason); + }; + if (req.method !== "POST" || !sub) return fail(404, "no such subscription"); + if (sub.status) return fail(sub.status, "mock status"); + try { + this.checkVapid(String(req.headers.authorization ?? "")); + if (req.headers["content-encoding"] !== "aes128gcm") throw new Error("Content-Encoding must be aes128gcm"); + if (!req.headers.ttl) throw new Error("TTL header required"); + const payload = JSON.parse(this.decrypt(sub, Buffer.concat(chunks)).toString("utf8")); + this.messages.push({ subscription: id, payload, urgency: (req.headers.urgency as string) ?? null, ttl: (req.headers.ttl as string) ?? null }); + res.writeHead(201).end(); + } catch (e) { + fail(400, (e as Error).message); + } + }); + }); + await new Promise((r) => this.server!.listen(0, "127.0.0.1", r)); + this.url = `http://127.0.0.1:${(this.server.address() as AddressInfo).port}`; + return this; + } + + async stop() { + await new Promise((r) => this.server?.close(() => r()) ?? r()); + } + + /** A new browser subscription: { endpoint, keys: { p256dh, auth } }. */ + subscribe(): { id: string; endpoint: string; keys: { p256dh: string; auth: string } } { + const id = randomUUID(); + const ecdh = createECDH("prime256v1"); + ecdh.generateKeys(); + const auth = randomBytes(16); + this.subs.set(id, { ecdh, auth }); + return { id, endpoint: `${this.url}/push/${id}`, keys: { p256dh: ecdh.getPublicKey().toString("base64url"), auth: auth.toString("base64url") } }; + } + + /** From now on the push service answers `status` for this subscription (410 = gone). */ + setStatus(id: string, status: number | undefined) { + const s = this.subs.get(id); + if (s) s.status = status; + } + + for(id: string) { + return this.messages.filter((m) => m.subscription === id); + } + + private checkVapid(authorization: string) { + const m = /^vapid t=([\w-]+\.[\w-]+\.[\w-]+), k=([\w-]+)$/.exec(authorization); + if (!m) throw new Error("Authorization must be 'vapid t=…, k=…'"); + const [h, c, s] = m[1]!.split(".") as [string, string, string]; + const raw = Buffer.from(m[2]!, "base64url"); + if (raw.length !== 65 || raw[0] !== 4) throw new Error("k must be an uncompressed P-256 point"); + const key = createPublicKey({ key: { kty: "EC", crv: "P-256", x: raw.subarray(1, 33).toString("base64url"), y: raw.subarray(33).toString("base64url") }, format: "jwk" }); + if (!verify("sha256", Buffer.from(`${h}.${c}`), { key, dsaEncoding: "ieee-p1363" }, Buffer.from(s, "base64url"))) throw new Error("bad VAPID signature"); + const header = JSON.parse(Buffer.from(h, "base64url").toString()); + const claims = JSON.parse(Buffer.from(c, "base64url").toString()); + if (header.alg !== "ES256") throw new Error("alg must be ES256"); + if (claims.aud !== this.url) throw new Error(`aud ${claims.aud} != ${this.url}`); + if (!(claims.exp > Date.now() / 1000) || claims.exp > Date.now() / 1000 + 24 * 3600) throw new Error("bad exp"); + if (!/^(https?:|mailto:)/.test(String(claims.sub))) throw new Error("sub must be a URL or mailto:"); + } + + private decrypt(sub: MockSub, body: Buffer): Buffer { + const salt = body.subarray(0, 16); + const idlen = body[20]!; + const asPublic = body.subarray(21, 21 + idlen); + const ct = body.subarray(21 + idlen); + const uaPublic = sub.ecdh.getPublicKey(); + const shared = sub.ecdh.computeSecret(asPublic); + const ikm = Buffer.from(hkdfSync("sha256", shared, sub.auth, Buffer.concat([Buffer.from("WebPush: info\0"), uaPublic, asPublic]), 32)); + const cek = Buffer.from(hkdfSync("sha256", ikm, salt, Buffer.from("Content-Encoding: aes128gcm\0"), 16)); + const nonce = Buffer.from(hkdfSync("sha256", ikm, salt, Buffer.from("Content-Encoding: nonce\0"), 12)); + const d = createDecipheriv("aes-128-gcm", cek, nonce); + d.setAuthTag(ct.subarray(ct.length - 16)); + const plain = Buffer.concat([d.update(ct.subarray(0, ct.length - 16)), d.final()]); + let end = plain.length - 1; + while (end >= 0 && plain[end] === 0) end--; + if (plain[end] !== 2) throw new Error("bad padding delimiter"); + return plain.subarray(0, end); + } +} diff --git a/packages/testkit/test/notifications.test.ts b/packages/testkit/test/notifications.test.ts new file mode 100644 index 00000000..c4b0396a --- /dev/null +++ b/packages/testkit/test/notifications.test.ts @@ -0,0 +1,235 @@ +// PEP-29 / PEP-35 / PEP-55: notification settings, quiet hours, browser push and the daily +// digest — the real bot against mock-telegram and mock-push, controlled clock for the digest. +import assert from "node:assert/strict"; +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, teardown, waitFor } from "./helpers.ts"; +import { MockTelegram } from "../src/mock-telegram.ts"; +import { MockPushService } from "../src/mock-push.ts"; +import { projects, pushOutbox, pushSubscriptions, questions, sessions, settings, tasks, telegramOutbox, users } from "@peppa/db"; +import { eq, like, sql } from "drizzle-orm"; +import type { Bot } from "@peppa/bot"; + +const { createBot } = await import("@peppa/bot"); +const { TelegramApi } = await import("@peppa/bot/telegram"); + +process.env.PEPPA_SECRET = "mock-secret-for-tests"; +const TZ = "Europe/Moscow"; // UTC+3, no DST +const tg = await new MockTelegram().start(); +const push = await new MockPushService().start(); +const PM = { id: 601, chatId: 601 }; +const BOB = { id: 602, chatId: 602 }; +let bot: Bot; +let pm: Awaited>; +let bob: typeof pm; +let seq = 0; + +async function newProject(name: string) { + const key = `N${String.fromCharCode(65 + seq++)}`; + const p = await core.createProject(db, { slug: key.toLowerCase(), key, name, giteaOwner: "test", workspacePath: "/tmp/none", ownerId: pm.id }); + await core.addMember(db, p, bob.login, pm.id); + return p; +} +async function newTask(p: { id: number; key: string }, title = "Стори") { + const ref = await core.createTask(db, { projectId: p.id, title }); + return core.resolveTask(db, ref.key); +} +const prefs = (u: { id: number }) => core.getNotifyPrefs(db, u.id); +async function setPrefs(u: { id: number }, patch: Partial>>) { + await core.setNotifyPrefs(db, u.id, { ...(await prefs(u)), ...patch }); +} +const sentTo = (chatId: number, needle: string) => tg.calls.filter((c) => c.method === "sendMessage" && c.params.chat_id === chatId && String(c.params.text).includes(needle)); + +before(async () => { + pm = await core.upsertUserFromGitea(db, { id: 71, login: "mock-pm" }, { access_token: "x" }); + bob = await core.upsertUserFromGitea(db, { id: 72, login: "mock-bob" }, { access_token: "y" }); + await db.update(users).set({ telegramChatId: PM.chatId, telegramUserId: PM.id }).where(eq(users.id, pm.id)); + await db.update(users).set({ telegramChatId: BOB.chatId, telegramUserId: BOB.id }).where(eq(users.id, bob.id)); + pm = (await core.getUser(db, pm.id))!; + bob = (await core.getUser(db, bob.id))!; + bot = createBot({ db, api: new TelegramApi(tg.token, tg.url), secret: tg.token, webUrl: "http://peppa.test", pollTimeoutSec: 1, outboxIntervalMs: 100, reconcileIntervalMs: 300, log: (m) => process.env.MOCK_DEBUG && console.log(m) }); + await bot.start(); +}); +after(async () => { + await bot.stop(); + await tg.stop(); + await push.stop(); + await teardown(); +}); +beforeEach(async () => { + // Earlier tests' open questions would pop up on a fresh push subscription. + await db.delete(questions); + await db.delete(pushSubscriptions); + for (const u of [pm, bob]) await core.setNotifyPrefs(db, u.id, { ...core.defaultPrefs(), timezone: TZ }); +}); + +describe("settings", () => { + test("defaults: everything on except the digest in the browser; garbage is rejected", async () => { + const p = await prefs(pm); + assert.deepEqual(p.events.questions, { telegram: true, push: true }); + assert.deepEqual(p.events.digest, { telegram: true, push: false }); + assert.equal(p.digestTime, "09:00"); + await assert.rejects(core.setNotifyPrefs(db, pm.id, { ...p, quiet: { from: "25:00", to: "08:00" } }), /ЧЧ:ММ/); + await assert.rejects(core.setNotifyPrefs(db, pm.id, { ...p, timezone: "Mars/Olympus" }), /таймзона/); + }); + + test("quiet hours cross midnight in the user's timezone", () => { + const q = { quiet: { from: "23:00", to: "08:00" }, timezone: TZ }; + assert.equal(core.inQuietHours(q, new Date("2026-03-01T23:00:00Z")), true); // 02:00 MSK + assert.equal(core.inQuietHours(q, new Date("2026-03-01T19:59:00Z")), false); // 22:59 MSK + assert.equal(core.inQuietHours(q, new Date("2026-03-01T05:00:00Z")), false); // 08:00 MSK + assert.equal(core.inQuietHours({ quiet: null, timezone: TZ }, new Date()), false); + }); + + test("question events", () => { + const base = { taskId: 1, sessionId: 1 }; + assert.equal(core.questionEvent({ ...base, kind: "approval" }, {}), "questions"); + assert.equal(core.questionEvent({ ...base, kind: "attention" }, { taskStatus: "review" }), "review"); + assert.equal(core.questionEvent({ ...base, kind: "attention" }, { sessionStatus: "rate_limited" }), "failures"); + assert.equal(core.questionEvent({ kind: "question", taskId: null, sessionId: null }, {}), "releases"); + }); +}); + +describe("routing in the bot", () => { + test("Сценарий: выключены вопросы агентов в Telegram — сообщения нет, у участника есть", async () => { + await setPrefs(pm, { events: { ...(await prefs(pm)).events, questions: { telegram: false, push: true } } }); + const p = await newProject("Routing"); + const ref = await newTask(p); + const q = await core.askPm(db, ref, { kind: "question", text: "Какую БД взять?" }); + await waitFor("bob got the question", async () => sentTo(BOB.chatId, "Какую БД взять").length > 0); + await new Promise((r) => setTimeout(r, 800)); // a couple of reconcile rounds + assert.equal(sentTo(PM.chatId, "Какую БД взять").length, 0); + assert.equal((await core.pendingQuestions(db, p.id)).some((x) => x.id === q.id), true, "still visible in the web"); + }); + + test("Сценарий: проект выключен — ни Telegram, ни push; участник получает", async () => { + const p = await newProject("Demo"); + const sub = push.subscribe(); + await core.savePushSubscription(db, pm.id, sub); + await setPrefs(pm, { mutedProjects: [p.id] }); + const ref = await newTask(p, "Ревью-стори"); + await core.updateTask(db, ref, { status: "review" }); + await core.askPm(db, ref, { kind: "attention", text: "Готово, проверь." }); + await waitFor("bob got review", async () => sentTo(BOB.chatId, "Готово, проверь").length > 0); + await new Promise((r) => setTimeout(r, 800)); + assert.equal(sentTo(PM.chatId, "Готово, проверь").length, 0); + assert.equal(push.for(sub.id).length, 0); + await db.delete(pushSubscriptions); + }); + + test("Сценарий: тихие часы — Telegram без звука, push не отправляется", async () => { + const sub = push.subscribe(); + await core.savePushSubscription(db, pm.id, sub); + // Quiet the whole day around now, whatever the clock says. + const now = core.localClock(new Date(), TZ).minutes; + const hh = (m: number) => `${String(Math.floor(((m + 1440) % 1440) / 60)).padStart(2, "0")}:${String(((m + 1440) % 1440) % 60).padStart(2, "0")}`; + await setPrefs(pm, { quiet: { from: hh(now - 60), to: hh(now + 60) } }); + const p = await newProject("Night"); + const ref = await newTask(p); + await core.askPm(db, ref, { kind: "permission", text: "Можно rm -rf node_modules?" }); + const [msg] = await waitFor("silent message", async () => { const a = sentTo(PM.chatId, "rm -rf node_modules"); return a.length && a; }); + assert.equal(msg!.params.disable_notification, true); + assert.equal(sentTo(BOB.chatId, "rm -rf node_modules")[0]?.params.disable_notification, undefined, "bob has no quiet hours"); + await new Promise((r) => setTimeout(r, 600)); + assert.equal(push.for(sub.id).length, 0); + await db.delete(pushSubscriptions); + }); + + test("Сценарий: готово к ревью в браузер — уведомление со ссылкой на стори", async () => { + const sub = push.subscribe(); + await core.savePushSubscription(db, pm.id, { ...sub, userAgent: "Mock Chrome" }); + const p = await newProject("Push"); + const ref = await newTask(p, "Кнопка входа"); + await core.updateTask(db, ref, { status: "review" }); + await core.askPm(db, ref, { kind: "attention", text: "PR готов." }); + const [m] = await waitFor("push delivered", async () => { const a = push.for(sub.id); return a.length && a; }); + assert.equal(m!.payload.url, `/t/${ref.project.key}-${ref.task.number}`); + assert.match(String(m!.payload.title), /Готово к ревью/); + assert.equal(m!.payload.body, "PR готов."); + assert.equal(m!.payload.sound, true); + assert.ok(Number(m!.payload.count) >= 1); + assert.equal(push.rejected.length, 0, JSON.stringify(push.rejected)); + // One push per question, not one per reconcile round. + await new Promise((r) => setTimeout(r, 800)); + assert.equal(push.for(sub.id).filter((x) => x.payload.body === "PR готов.").length, 1); + await db.delete(pushSubscriptions); + }); + + test("Сценарий: подписка протухла — 410 удаляет её, повторов нет", async () => { + const sub = push.subscribe(); + await core.savePushSubscription(db, pm.id, sub); + push.setStatus(sub.id, 410); + const p = await newProject("Gone"); + const ref = await newTask(p); + await core.askPm(db, ref, { kind: "question", text: "Есть кто?" }); + await waitFor("subscription removed", async () => (await core.userPushSubscriptions(db, pm.id)).length === 0); + const rows = await db.select().from(pushOutbox).where(like(pushOutbox.dedupeKey, "q:%")); + assert.ok(rows.every((r) => r.status !== "pending")); + const n = push.rejected.filter((r) => r.subscription === sub.id).length; + await new Promise((r) => setTimeout(r, 800)); + assert.equal(push.rejected.filter((r) => r.subscription === sub.id).length, n, "no retries"); + }); + + test("a test push straight from the web action path (sendWebPush)", async () => { + const sub = push.subscribe(); + const r = await core.sendWebPush(db, { endpoint: sub.endpoint, ...sub.keys }, { title: "Пеппа", body: "Проверка", url: "/settings" }); + assert.deepEqual(r, { ok: true }); + assert.equal(push.for(sub.id)[0]?.payload.body, "Проверка"); + }); +}); + +describe("incidents and monitoring follow the settings", () => { + test("monitoring off in Telegram → admin gets no message", async () => { + await core.setPlatformAdmins(db, [pm.login, bob.login]); + await setPrefs(pm, { events: { ...(await prefs(pm)).events, monitoring: { telegram: false, push: false } } }); + const n = await core.alertAdmins(db, "mon:test:1", "Бот молчит 6 мин", () => {}); + assert.equal(n, 1); + const rows = await db.select().from(telegramOutbox).where(like(telegramOutbox.dedupeKey, "mon:test:1:%")); + assert.deepEqual(rows.map((r) => r.params.chat_id), [BOB.chatId]); + }); +}); + +describe("daily digest", () => { + // 2026-03-10 09:01 MSK = 06:01 UTC + const at = (hhmm: string, day = 10) => new Date(`2026-03-${String(day).padStart(2, "0")}T${String(Number(hhmm.slice(0, 2)) - 3).padStart(2, "0")}:${hhmm.slice(3)}:00Z`); + + test("Сценарий: утренний дайджест — одна сводка за день с сделанным, в работе и ждущим", async () => { + await db.delete(questions); + await db.delete(settings).where(like(settings.key, "digest.last:%")); + // Only this project counts for the digest (older ones are muted for the PM). + await setPrefs(pm, { mutedProjects: (await db.select({ id: projects.id }).from(projects)).map((p) => p.id) }); + const p = await newProject("Digest"); + const done = await newTask(p, "Вход через Gitea"); + const wip = await newTask(p, "Доска"); + await core.updateTask(db, done, { status: "done" }); + await db.update(tasks).set({ updatedAt: at("20:00", 9) }).where(eq(tasks.id, done.task.id)); + await core.updateTask(db, wip, { status: "in_progress" }); + await core.askPm(db, wip, { kind: "question", text: "Цвет кнопки?" }); + + const before = tg.calls.length; + assert.equal(await core.digestTick(db, { now: at("08:59") }), 0, "too early"); + assert.ok((await core.digestTick(db, { now: at("09:01") })) >= 1); + assert.equal(await core.digestTick(db, { now: at("09:30") }), 0, "once a day"); + const [m] = await waitFor("digest delivered", async () => { const a = sentTo(PM.chatId, "Сводка за сутки").filter((c) => tg.calls.indexOf(c) >= before); return a.length && a; }); + const text = String(m!.params.text); + assert.match(text, /Digest/); + assert.match(text, new RegExp(`Сделано: 1[\\s\\S]*${done.project.key}-${done.task.number}`)); + assert.match(text, new RegExp(`В работе: 1[\\s\\S]*${wip.project.key}-${wip.task.number}`)); + assert.match(text, /Ждёт тебя: 1/); + // The next day it comes again. + assert.ok((await core.digestTick(db, { now: at("09:05", 11) })) >= 1); + }); + + test("Сценарий: выкат вечером — до завтрашних 09:00 сводки нет; выключенный дайджест не приходит", async () => { + await db.delete(settings).where(like(settings.key, "digest.last:%")); + assert.equal(await core.digestTick(db, { now: at("20:00", 12) }), 0); + await setPrefs(pm, { events: { ...(await prefs(pm)).events, digest: { telegram: false, push: false } } }); + await setPrefs(bob, { events: { ...(await prefs(bob)).events, digest: { telegram: false, push: false } } }); + assert.equal(await core.digestTick(db, { now: at("09:10", 13) }), 0); + }); + + test("/digest in the bot answers right away", async () => { + tg.userSends({ id: PM.id, chatId: PM.chatId, username: "pm" }, "/digest"); + await waitFor("digest reply", async () => tg.botMessages(PM.chatId).some((m) => /Сводка за сутки/.test(m.text))); + }); +});