/** * Ночная проверка упущенного (02:00 по Тампе): Claude просматривает сообщения людей во всех чатах ассистента с момента прошлой проверки * (проектные каналы, общие каналы со сводками, личные чаты менеджеров) и отбирает те, что по смыслу содержат информацию для Daily Log или проекта, * но за которыми не последовал ответ/обработка агента. Находки протоколируются (message_audit_run) и уходят в it-support. */ import { randomUUID } from "node:crypto"; import { mkdirSync } from "node:fs"; import { join } from "node:path"; import { loadPrompt } from "../agents/prompts.js"; import { parseSections } from "../agents/sections.js"; import type { AgentContext } from "../agents/session.js"; import type { SlackApi, SlackHistoryMessage } from "./api.js"; export interface AuditChannel { id: string; label: string; kind: "project" | "general" | "dm"; } export interface AuditCandidate { n: number; channel: AuditChannel; ts: string; author: string; text: string; /** Статус обработки в slack_message_log (done/failed/ignored/...) или null, если сообщения в журнале нет. */ logged: string | null; } /** Окно, в котором ответ агента (сообщение бота после сообщения человека) считается реакцией на него. */ export const REPLY_WINDOW_SEC = 2 * 3600; /** Короткие реплики («ok», «thanks») и служебные сообщения не проверяем. */ export const MIN_TEXT = 20; const BATCH = 50; /** Сообщения людей без ответа агента: нет сообщения бота в окне после него (и в его треде), текст не служебный. */ export function pickUnanswered(msgs: SlackHistoryMessage[], logged: Map): { msg: SlackHistoryMessage; logged: string | null }[] { // «Sorry, I could not process your message» - сообщение об ошибке, а не ответ по существу const botTs = msgs.filter((m) => m.botId && !/could not process your message/i.test(m.text)).map((m) => Number(m.ts)); return msgs .filter((m) => m.userId && !m.botId && m.text.trim().length >= MIN_TEXT && !/has (joined|left) the channel/i.test(m.text)) .filter((m) => { const t = Number(m.ts); return logged.get(m.ts) === "failed" || !botTs.some((b) => b > t && b - t <= REPLY_WINDOW_SEC); }) .map((m) => ({ msg: m, logged: logged.get(m.ts) ?? null })); } /** Разбор раздела «Упущенные»: строки «<номер> | <причина>». */ export function parseMissed(text: string | undefined): Map { const out = new Map(); if (!text || /^(нет|none)\.?$/i.test(text.trim())) return out; for (const line of text.split("\n")) { const m = /^\s*[-*]?\s*#?(\d+)\s*[|:.-]\s*(.+)$/.exec(line); if (m) out.set(Number(m[1]), m[2]!.trim()); } return out; } export interface AuditResult { runId: string; sinceTs: number; messagesSeen: number; candidates: number; flagged: number; unavailable: string[]; } export async function runMissedAudit( ctx: AgentContext, slack: SlackApi, o: { summaryChannelIds: string[]; sinceHours?: number; dryRun?: boolean }, ): Promise { if (!slack.history) throw new Error("Slack API без history"); const now = Date.now() / 1000; const last = await ctx.pool.query("select max(until_ts) as t from message_audit_run where error is null"); const lastTs = last.rows[0]?.t ? Number(last.rows[0].t) : 0; const sinceTs = o.sinceHours ? now - o.sinceHours * 3600 : Math.max(lastTs || now - 26 * 3600, now - 72 * 3600); const runId = randomUUID(); await ctx.pool.query("insert into message_audit_run (id, since_ts, until_ts) values ($1,$2,$3)", [runId, sinceTs, now]); try { // каналы: проектные, общие со сводками, личные чаты менеджеров (тестового менеджера не проверяем) const channels = new Map(); const pc = await ctx.pool.query("select pc.channel_id, coalesce(j.name, pc.channel_id) as name from project_channel pc left join jt_job j on j.id = pc.jt_job_id where pc.is_enabled"); for (const r of pc.rows) channels.set(String(r.channel_id), { id: String(r.channel_id), label: `проект ${r.name}`, kind: "project" }); for (const id of o.summaryChannelIds) channels.set(id, { id, label: "общий канал (#2-general-all)", kind: "general" }); const dm = await ctx.pool.query( "select cm.slack_channel_id, p.display_name from construction_manager cm join person p on p.id = cm.person_id where cm.is_active and cm.slack_channel_id is not null and p.display_name not like 'llmtest%'", ); for (const r of dm.rows) channels.set(String(r.slack_channel_id), { id: String(r.slack_channel_id), label: `личный чат ${r.display_name}`, kind: "dm" }); const candidates: AuditCandidate[] = []; const unavailable: string[] = []; let seen = 0; for (const ch of channels.values()) { let msgs: SlackHistoryMessage[]; try { msgs = await slack.history(ch.id, sinceTs); } catch (e) { unavailable.push(`${ch.label}: ${String(e).slice(0, 80)}`); continue; } seen += msgs.filter((m) => m.userId && !m.botId).length; const lg = await ctx.pool.query("select message_ts, status from slack_message_log where channel_id = $1 and message_ts::numeric > $2", [ch.id, sinceTs - 1]); const picked = pickUnanswered(msgs, new Map(lg.rows.map((r) => [String(r.message_ts), String(r.status)]))); for (const p of picked) { const author = (p.msg.userId && (await slack.userName?.(p.msg.userId))) || p.msg.userId || "?"; candidates.push({ n: candidates.length + 1, channel: ch, ts: p.msg.ts, author, text: p.msg.text.slice(0, 700), logged: p.logged }); } } const flagged: { c: AuditCandidate; reason: string }[] = []; if (candidates.length) { const cwd = join(ctx.settings.workRoot, "audit"); mkdirSync(cwd, { recursive: true }); for (let i = 0; i < candidates.length; i += BATCH) { const batch = candidates.slice(i, i + BATCH); const list = batch .map((c) => `#${c.n} [${c.channel.label}] ${new Date(Number(c.ts) * 1000).toISOString().slice(0, 16)}Z ${c.author} (журнал: ${c.logged ?? "нет"}): ${c.text.replace(/\s+/g, " ")}`) .join("\n"); const prompt = `${loadPrompt("p-missed-audit.md", {}, "proposed")}\n\n# Сообщения без ответа агента\n${list}`; const res = await ctx.runner({ prompt, cwd, sessionId: randomUUID(), resume: false, tools: "none" }); const missed = parseMissed(parseSections(res.text).get("упущенные")); for (const [n, reason] of missed) { const c = batch.find((x) => x.n === n); if (c) flagged.push({ c, reason }); } } } const report = flagged .map(({ c, reason }) => `${new Date(Number(c.ts) * 1000).toISOString().slice(0, 16)}Z | ${c.channel.label} | ${c.author} | ${reason} | ${c.text.replace(/\s+/g, " ").slice(0, 300)}`) .join("\n"); await ctx.pool.query("update message_audit_run set finished_at = now(), messages_seen = $2, candidates = $3, flagged = $4, report = $5 where id = $1", [runId, seen, candidates.length, flagged.length, report || null]); if (!o.dryRun && (flagged.length || unavailable.length)) { const head = `:mag: Ночная проверка упущенного: сообщений людей ${seen}, без ответа агента ${candidates.length}, по смыслу упущено ${flagged.length}.`; const body = flagged.slice(0, 15).map(({ c, reason }) => `• ${c.channel.label}, ${c.author}, ${new Date(Number(c.ts) * 1000).toISOString().slice(5, 16).replace("T", " ")}Z: «${c.text.replace(/\s+/g, " ").slice(0, 160)}» - ${reason}`); const tail = [flagged.length > 15 ? `…и ещё ${flagged.length - 15} (протокол: message_audit_run ${runId})` : "", unavailable.length ? `Каналы без доступа: ${unavailable.join("; ")}` : ""].filter(Boolean); await ctx.notifyIt([head, ...body, ...tail].join("\n")); } return { runId, sinceTs, messagesSeen: seen, candidates: candidates.length, flagged: flagged.length, unavailable }; } catch (e) { await ctx.pool.query("update message_audit_run set finished_at = now(), error = $2 where id = $1", [runId, String(e).slice(0, 500)]); await ctx.notifyIt(`:warning: Ночная проверка упущенного не выполнена: ${String(e).slice(0, 400)}`); throw e; } }