/** * Ночная проверка упущенного (02:00 по Тампе): Claude просматривает сообщения людей во всех чатах ассистента с момента прошлой проверки * (проектные каналы, общие каналы со сводками, личные чаты менеджеров) и отбирает те, что по смыслу содержат информацию для Daily Log или проекта, * но за которыми не последовал ответ/обработка агента. Находки протоколируются (message_audit_run) и уходят в it-support. */ import { clipForAgent, FULLTEXT_PROMPT_NOTE } from "../fulltext.js"; 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 { findManagerById } from "../managers.js"; import { handleManagerMessages, type ChatDeps } from "./chat.js"; import { summaryContextFor } from "./daily-summary.js"; import type { SlackApi, SlackHistoryMessage } from "./api.js"; export interface AuditChannel { id: string; label: string; kind: "project" | "general" | "dm"; /** Проект канала (проектный канал). */ jobId?: string; jobName?: string | null; } 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 = 20; /** Фрагмент сообщения в списке для классификатора; остальное агент читает MCP-инструментом read_full_text (политика размеров, fulltext.ts). */ const EXCERPT_CHARS = 1500; /** Сообщения людей без ответа агента: нет сообщения бота в окне после него (и в его треде), текст не служебный. */ 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 interface MissedItem { reason: string; /** Claude уверен, что сообщение нужно обработать как Daily Log. */ confident: boolean; dailyLog: boolean; } /** Разбор раздела «Упущенные»: строки «<номер> | | <да/нет> | <причина>» (старый формат «<номер> | <причина>» - без обработки). */ 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) continue; const parts = m[2]!.split("|").map((x) => x.trim()); const full = parts.length >= 3 && /^(high|low)$/i.test(parts[0]!); out.set(Number(m[1]), full ? { confident: /^high$/i.test(parts[0]!), dailyLog: /^(да|yes)$/i.test(parts[1]!), reason: parts.slice(2).join(" | ") } : { confident: false, dailyLog: false, reason: m[2]!.trim() }); } return out; } export type Outcome = "processed" | "low_confidence" | "failed" | "not_daily_log" | "skipped"; const OUTCOME_TEXT: Record = { processed: ":white_check_mark: обработано как Daily Log", low_confidence: ":grey_question: не обработано: недостаточно уверенности", failed: ":x: не получилось обработать", not_daily_log: ":information_source: не Daily Log, только протокол", skipped: ":information_source: не обработано автоматически", }; /** Менеджер для обработки: владелец проекта канала; в общем канале - автор (если он менеджер с чатом). */ async function managerFor(ctx: AgentContext, c: AuditCandidate, senderSlackUserId: string | null) { if (c.channel.kind === "project" && c.channel.jobId) { const r = await ctx.pool.query("select manager_person_id from assistant_project where jt_job_id = $1 and is_enabled", [c.channel.jobId]); return r.rows[0] ? findManagerById(ctx.pool, String(r.rows[0].manager_person_id)) : null; } if (c.channel.kind === "general" && senderSlackUserId) { const r = await ctx.pool.query("select cm.person_id from construction_manager cm where cm.slack_user_id = $1 and cm.is_active and cm.chat_kind <> 'accounting'", [senderSlackUserId]); if (r.rows[0]) return findManagerById(ctx.pool, String(r.rows[0].person_id)); } return null; } /** Обработка упущенного сообщения как Daily Log (тот же путь, что у сводки из общего канала); ответ уходит в тред сообщения. */ async function processAsDailyLog(ctx: AgentContext, chat: ChatDeps, c: AuditCandidate, senderSlackUserId: string | null, fullText: string): Promise<{ outcome: Outcome; note: string }> { const manager = await managerFor(ctx, c, senderSlackUserId); if (!manager) return { outcome: "skipped", note: "не найден менеджер проекта" }; const defaultJob = c.channel.jobId ? { id: c.channel.jobId, name: c.channel.jobName ?? null } : undefined; const summary = await summaryContextFor(ctx.pool, chat.timezone, { channel: c.channel.id, ts: c.ts, text: fullText, senderName: c.author, defaultJob }); await ctx.pool.query( "insert into slack_message_log (channel_id, message_ts, manager_person_id, has_files, status, sender_slack_user_id, received_at) values ($1,$2,$3,false,'processing',$4, to_timestamp($2::numeric)) on conflict (channel_id, message_ts) do update set status = 'processing'", [c.channel.id, c.ts, manager.personId, senderSlackUserId], ); try { const r = await handleManagerMessages(chat, manager, [{ channel: c.channel.id, ts: c.ts, text: fullText, fileIds: [], senderUserId: senderSlackUserId ?? undefined }], { summary, channel: c.channel.id }); await ctx.pool.query("update slack_message_log set status = 'done', processed_at = now() where channel_id = $1 and message_ts = $2", [c.channel.id, c.ts]); // агент ответил «(без ответа)»: он решил ничего не записывать (например, по памяти копит такие сообщения для recap канала) - это не обработка if (!r.reply) return { outcome: "skipped", note: "агент ничего не записал и не ответил (решил копить для recap или счёл несущественным)" }; return { outcome: "processed", note: r.reply.slice(0, 200) }; } catch (e) { await ctx.pool.query("update slack_message_log set status = 'failed', processed_at = now() where channel_id = $1 and message_ts = $2", [c.channel.id, c.ts]); return { outcome: "failed", note: String(e).slice(0, 200) }; } } 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; /** Без chat проверка только протоколирует. */ chat?: ChatDeps; /** Обрабатывать как Daily Log уверенно найденное (по умолчанию да, если есть chat). */ autoProcess?: 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, pc.jt_job_id, j.name as jname, 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 and pc.jt_job_id is not null"); for (const r of pc.rows) channels.set(String(r.channel_id), { id: String(r.channel_id), label: `проект ${r.name}`, kind: "project", jobId: String(r.jt_job_id), jobName: (r.jname as string | null) ?? null }); 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 senders = new Map(); 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: clipForAgent(p.msg.text, EXCERPT_CHARS, { ref: `slack:${ch.id}:${p.msg.ts}` }), logged: p.logged }); senders.set(`${ch.id}:${p.msg.ts}`, { userId: p.msg.userId, full: p.msg.text }); } } const flagged: { c: AuditCandidate; item: MissedItem; outcome: Outcome; note: 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${FULLTEXT_PROMPT_NOTE}\n\n# Сообщения без ответа агента\n${list}`; const res = await ctx.runner({ prompt, cwd, sessionId: randomUUID(), resume: false, tools: "fulltext" }); const missed = parseMissed(parseSections(res.text).get("упущенные")); for (const [n, item] of missed) { const c = batch.find((x) => x.n === n); if (!c) continue; let outcome: Outcome = "not_daily_log"; let note = ""; if (item.dailyLog && c.channel.kind !== "dm") { if (!item.confident) outcome = "low_confidence"; else if (o.dryRun || !o.chat || o.autoProcess === false) outcome = "skipped"; else { const sd = senders.get(`${c.channel.id}:${c.ts}`); ({ outcome, note } = await processAsDailyLog(ctx, o.chat, c, sd?.userId ?? null, sd?.full ?? c.text)); } } flagged.push({ c, item, outcome, note }); } } } const report = flagged .map(({ c, item, outcome, note }) => `${new Date(Number(c.ts) * 1000).toISOString().slice(0, 16)}Z | ${c.channel.label} | ${c.author} | ${outcome}${note ? ` (${note})` : ""} | ${item.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, item, outcome, note }) => `• ${OUTCOME_TEXT[outcome]}${note ? ` (${note})` : ""}\n ${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)}» - ${item.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; } }