Ночная проверка: уверенно найденное Daily Log обрабатывается сразу, в it-support - итог по каждому (обработано/не уверена/не получилось)
All checks were successful
ci / test (push) Successful in 53s
ci / deploy (push) Successful in 2m57s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-29 09:57:41 +03:00
parent 5fedd4c508
commit 54b38d9076
5 changed files with 98 additions and 17 deletions

View File

@@ -91,7 +91,7 @@ const chat = chatDeps
},
async event(kind: string) {
// ночная проверка упущенного (02:00 по Тампе): не событие менеджерам, а разбор чатов за сутки
if (kind === "audit_missed") return runMissedAudit(ctx, slackApi!, { summaryChannelIds: service.slack?.dailySummaryChannelIds ?? [] });
if (kind === "audit_missed") return runMissedAudit(ctx, slackApi!, { summaryChannelIds: service.slack?.dailySummaryChannelIds ?? [], chat: chatDeps });
const title = EVENT_TITLE[kind];
if (!title) throw new Error(`неизвестное событие ${kind}`);
const out = [];

View File

@@ -32,7 +32,11 @@ describe("ночная проверка упущенного", () => {
});
it("разбирает раздел «Упущенные»", () => {
expect([...parseMissed("1 | сводка по Placido не записана\n#3: вопрос без ответа")]).toEqual([[1, "сводка по Placido не записана"], [3, "вопрос без ответа"]]);
expect([...parseMissed("1 | high | да | сводка по Placido не записана\n#3 | low | нет | вопрос без ответа\n4 | старый формат")]).toEqual([
[1, { confident: true, dailyLog: true, reason: "сводка по Placido не записана" }],
[3, { confident: false, dailyLog: false, reason: "вопрос без ответа" }],
[4, { confident: false, dailyLog: false, reason: "старый формат" }],
]);
expect(parseMissed("нет").size).toBe(0);
expect(parseMissed(undefined).size).toBe(0);
});

View File

@@ -10,12 +10,18 @@ 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 {
@@ -47,17 +53,69 @@ export function pickUnanswered(msgs: SlackHistoryMessage[], logged: Map<string,
.map((m) => ({ msg: m, logged: logged.get(m.ts) ?? null }));
}
/** Разбор раздела «Упущенные»: строки «<номер> | <причина>». */
export function parseMissed(text: string | undefined): Map<number, string> {
const out = new Map<number, string>();
export interface MissedItem {
reason: string;
/** Claude уверен, что сообщение нужно обработать как Daily Log. */
confident: boolean;
dailyLog: boolean;
}
/** Разбор раздела «Упущенные»: строки «<номер> | <high/low> | <да/нет> | <причина>» (старый формат «<номер> | <причина>» - без обработки). */
export function parseMissed(text: string | undefined): Map<number, MissedItem> {
const out = new Map<number, MissedItem>();
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());
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<Outcome, string> = {
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) values ($1,$2,$3,false,'processing',$4) 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]);
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;
@@ -70,7 +128,7 @@ export interface AuditResult {
export async function runMissedAudit(
ctx: AgentContext,
slack: SlackApi,
o: { summaryChannelIds: string[]; sinceHours?: number; dryRun?: boolean },
o: { summaryChannelIds: string[]; sinceHours?: number; dryRun?: boolean; /** Без chat проверка только протоколирует. */ chat?: ChatDeps; /** Обрабатывать как Daily Log уверенно найденное (по умолчанию да, если есть chat). */ autoProcess?: boolean },
): Promise<AuditResult> {
if (!slack.history) throw new Error("Slack API без history");
const now = Date.now() / 1000;
@@ -82,8 +140,8 @@ export async function runMissedAudit(
try {
// каналы: проектные, общие со сводками, личные чаты менеджеров (тестового менеджера не проверяем)
const channels = new Map<string, AuditChannel>();
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" });
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%'",
@@ -91,6 +149,7 @@ export async function runMissedAudit(
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<string, { userId: string | null; full: string }>();
const unavailable: string[] = [];
let seen = 0;
for (const ch of channels.values()) {
@@ -107,10 +166,11 @@ export async function runMissedAudit(
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 });
senders.set(`${ch.id}:${p.msg.ts}`, { userId: p.msg.userId, full: p.msg.text });
}
}
const flagged: { c: AuditCandidate; reason: string }[] = [];
const flagged: { c: AuditCandidate; item: MissedItem; outcome: Outcome; note: string }[] = [];
if (candidates.length) {
const cwd = join(ctx.settings.workRoot, "audit");
mkdirSync(cwd, { recursive: true });
@@ -122,20 +182,31 @@ export async function runMissedAudit(
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) {
for (const [n, item] of missed) {
const c = batch.find((x) => x.n === n);
if (c) flagged.push({ c, reason });
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, 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)}`)
.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, 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 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"));
}

View File

@@ -114,13 +114,14 @@ export function buildSections(parsed: ParsedSummary, jobs: { id: string; name: s
export async function summaryContextFor(
pool: { query(sql: string): Promise<{ rows: Record<string, unknown>[] }> },
tz: string,
o: { channel: string; ts: string; text: string; senderName: string | null },
o: { channel: string; ts: string; text: string; senderName: string | null; /** Проект канала: для сообщения без разделов и упоминаний (проектный канал). */ defaultJob?: { id: string; name: string | null } },
): Promise<SummaryContext> {
const { rows } = await pool.query("select distinct j.id, j.name from assistant_project ap join jt_job j on j.id = ap.jt_job_id where ap.is_enabled");
const parsed = parseDailySummary(o.text);
const messageDate = localDate(new Date(Number(o.ts) * 1000), tz);
const jobs = rows.map((r) => ({ id: String(r.id), name: (r.name as string | null) ?? null }));
const sections = buildSections(parsed, jobs);
const candidates = sections.length ? [] : mentionedJobs(o.text, jobs);
let candidates = sections.length ? [] : mentionedJobs(o.text, jobs);
if (!sections.length && !candidates.length && o.defaultJob) candidates = [o.defaultJob];
return { channel: o.channel, ts: o.ts, date: summaryDate(parsed, messageDate), senderName: o.senderName, sections, candidates, relevant: isSummaryCandidate(o.text, sections.length ? sections : candidates) };
}