// PEP-151: one state — one message. A message for the user carries a fingerprint of the story's // state; the same fingerprint again does not make a second message: the previous one gets the // fresh text, an «обновлено» time and a repeat counter (and waits for an answer again). // The state lives in `settings` (no schema change): questions without a row are older than the // rule and are never matched. import { checkRuns, questions, settings, tasks, type Db } from "@peppa/db"; import { createHash } from "node:crypto"; import { and, desc, eq, gt, inArray, isNull, like, lt } from "drizzle-orm"; import { getSetting, setSetting } from "./settings.ts"; import type { Question, QuestionKind } from "./tasks.ts"; /** * What kind of message it is when the text cannot tell: `turn` — the agent ended its turn and * says so in its own words, `review` — «готово к ревью». With a topic the text stays out of the * fingerprint (the same state retold is the same message). */ export type MessageTopic = "turn" | "review"; export interface QuestionState { fp: string; /** How many times the same state came again after the first message. */ repeats: number; /** When it was last repeated or reminded about (ms); null — never. */ updatedAt: number | null; } export interface MessageScope { projectId: number; taskId: number | null; sessionId: number | null; kind: QuestionKind; text: string; options?: string[]; awaitingHook?: boolean; topic?: MessageTopic; /** Head commit of the result when the caller knows it (the review gate); else from check_runs. */ head?: string | null; } /** Messages older than this are not matched (shorter than the chat TTL: the projection is still there). */ export const REPEAT_WINDOW_MS = 7 * 24 * 3600_000; const PREFIX = "question.state:"; const key = (id: number) => `${PREFIX}${id}`; /** Text without what changes between two reports of the same thing: numbers, times, hashes, punctuation. */ export function normalizeMessage(text: string): string { return text .toLowerCase() .replace(/\b(?=[0-9a-f]*\d)[0-9a-f]{7,40}\b/g, " ") .replace(/\d+/g, " ") .replace(/[^\p{L}]+/gu, " ") .trim(); } /** Fingerprint of the state a message reports: story, type, status, result, head commit, checks, text. */ export async function messageFingerprint(db: Db, m: MessageScope): Promise { let status = ""; let pr = ""; let head = m.head ?? ""; let checks = ""; if (m.taskId) { const [t] = await db.select({ status: tasks.status, prUrl: tasks.prUrl }).from(tasks).where(eq(tasks.id, m.taskId)); // «Готово» is sent around the move to review: the status of the moment must not split it. status = m.topic === "review" ? "review" : (t?.status ?? ""); pr = t?.prUrl ?? ""; const runs = await db.select({ sha: checkRuns.sha, check: checkRuns.check, state: checkRuns.state }).from(checkRuns).where(eq(checkRuns.taskId, m.taskId)).orderBy(desc(checkRuns.id)).limit(60); head ||= runs[0]?.sha ?? ""; checks = runs.filter((r) => r.sha === head).map((r) => `${r.check}:${r.state}`).sort().join(","); } const scope = m.taskId ? `t${m.taskId}` : m.sessionId ? `s${m.sessionId}` : `p${m.projectId}`; const said = m.topic ? "" : `${normalizeMessage(m.text)}|${(m.options ?? []).map(normalizeMessage).join("|")}`; return createHash("sha1").update([scope, m.kind, m.topic ?? "", status, pr, head, checks, said].join("\n")).digest("hex"); } export async function questionStates(db: Db, ids: number[]): Promise> { const out = new Map(); if (!ids.length) return out; for (const r of await db.select().from(settings).where(inArray(settings.key, ids.map(key)))) out.set(Number(r.key.slice(PREFIX.length)), r.value as QuestionState); return out; } export const questionState = (db: Db, id: number) => getSetting(db, key(id)); /** * The earlier message this one repeats: an open one with the same fingerprint, or the story's * last message, or (for «готово») any message about the same result. Answered questions, * permissions and approvals are never reused: asking again after an answer is a new question. */ export async function findRepeat(db: Db, m: MessageScope, fp: string, now = Date.now()): Promise { const where = m.taskId ? eq(questions.taskId, m.taskId) : m.sessionId ? and(eq(questions.sessionId, m.sessionId), isNull(questions.taskId)) : null; if (!where) return null; const rows = await db.select().from(questions).where(and(where, gt(questions.createdAt, new Date(now - REPEAT_WINDOW_MS)))).orderBy(desc(questions.id)).limit(30); const states = await questionStates(db, rows.map((r) => r.id)); for (const [i, q] of rows.entries()) { if (q.kind !== m.kind || states.get(q.id)?.fp !== fp) continue; if (!q.answeredAt) return q; if (m.kind === "attention" && (i === 0 || m.topic === "review")) return q; } return null; } /** A new message: remembers its fingerprint so that a repeat finds it. */ export const rememberState = (db: Db, questionId: number, fp: string) => setSetting(db, key(questionId), { fp, repeats: 0, updatedAt: null } satisfies QuestionState); /** The same state again: the earlier message takes the fresh text and waits for an answer again. */ export async function bumpRepeat(db: Db, prev: Question, m: MessageScope, fp: string, now = Date.now()): Promise { const st = await questionState(db, prev.id); const [row] = await db .update(questions) .set({ text: m.text, options: m.options ?? null, sessionId: m.sessionId ?? prev.sessionId, awaitingHook: m.awaitingHook ?? false, answer: null, answeredVia: null, answeredAt: null }) .where(eq(questions.id, prev.id)) .returning(); await setSetting(db, key(prev.id), { fp, repeats: (st?.repeats ?? 0) + 1, updatedAt: now } satisfies QuestionState); return row!; } /** A reminder about an open question refreshes its message instead of adding one. */ export async function touchQuestion(db: Db, questionId: number, now = Date.now()): Promise { const st = await questionState(db, questionId); await setSetting(db, key(questionId), { fp: st?.fp ?? "", repeats: st?.repeats ?? 0, updatedAt: now } satisfies QuestionState); } /** * Creates the message unless it repeats an earlier one. Never fails because of the fingerprint: * a message the user must get is worth more than a missed duplicate. */ export async function raiseOnce(db: Db, m: MessageScope, create: () => Promise): Promise { let fp: string | null = null; try { fp = await messageFingerprint(db, m); const prev = await findRepeat(db, m, fp); if (prev) return await bumpRepeat(db, prev, m, fp); } catch { fp = null; } const row = await create(); if (fp) await rememberState(db, row.id, fp).catch(() => {}); return row; } // ── repeated events of a chat thread ──────────────────────────────────────────────── export interface ChatRepeat { /** How many events the line stands for. */ n: number; /** When the last of them happened (ms). */ at: number; /** Id of the last event counted (a re-run of the projection does not count it twice). */ last: number; } const CHAT_PREFIX = "chat.repeat:"; export const chatRepeatKey = (messageId: number) => `${CHAT_PREFIX}${messageId}`; export async function chatRepeats(db: Db, messageIds: number[]): Promise> { const out = new Map(); if (!messageIds.length) return out; for (const r of await db.select().from(settings).where(inArray(settings.key, messageIds.map(chatRepeatKey)))) out.set(Number(r.key.slice(CHAT_PREFIX.length)), r.value as ChatRepeat); return out; } /** Drops the state of messages nobody can repeat any more. */ export async function pruneMessageStates(db: Db, before: Date): Promise { await db.delete(settings).where(and(like(settings.key, `${PREFIX}%`), lt(settings.updatedAt, before))); await db.delete(settings).where(and(like(settings.key, `${CHAT_PREFIX}%`), lt(settings.updatedAt, before))); }