Ночная проверка упущенного (02:00 Тампа), мониторинг хоста, чистка образов в deploy.sh
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
14
packages/khb_common/migrations/074_message_audit_run.sql
Normal file
14
packages/khb_common/migrations/074_message_audit_run.sql
Normal file
@@ -0,0 +1,14 @@
|
||||
-- Ночная проверка упущенного (khbuild_assistant_prep, 02:00 по Тампе): протокол запусков и находок.
|
||||
create table if not exists message_audit_run (
|
||||
id uuid primary key,
|
||||
started_at timestamptz not null default now(),
|
||||
finished_at timestamptz,
|
||||
since_ts numeric not null,
|
||||
until_ts numeric not null,
|
||||
messages_seen integer,
|
||||
candidates integer,
|
||||
flagged integer,
|
||||
report text,
|
||||
error text
|
||||
);
|
||||
alter table message_audit_run enable row level security;
|
||||
@@ -19,6 +19,7 @@ import { createTokenProvider, parseServiceAccountKey } from "./gdrive/service-ac
|
||||
import { createGoogleDrive } from "./slack/drive.js";
|
||||
import { DriveInbox } from "./slack/drive-inbox.js";
|
||||
import { summaryContextFor } from "./slack/daily-summary.js";
|
||||
import { runMissedAudit } from "./slack/audit.js";
|
||||
import { SlackIntake, rowToManager } from "./slack/intake.js";
|
||||
import { TodoEventPoller } from "./slack/todo-events.js";
|
||||
import { createGoogleTts } from "./slack/tts.js";
|
||||
@@ -89,6 +90,8 @@ const chat = chatDeps
|
||||
return handleManagerMessages({ ...chatDeps, dryPublish: !o.publish }, m, [], { systemEvent: o.text });
|
||||
},
|
||||
async event(kind: string) {
|
||||
// ночная проверка упущенного (02:00 по Тампе): не событие менеджерам, а разбор чатов за сутки
|
||||
if (kind === "audit_missed") return runMissedAudit(ctx, slackApi!, { summaryChannelIds: service.slack?.dailySummaryChannelIds ?? [] });
|
||||
const title = EVENT_TITLE[kind];
|
||||
if (!title) throw new Error(`неизвестное событие ${kind}`);
|
||||
const out = [];
|
||||
|
||||
32
packages/khbuild_assistant_prep/src/slack/audit.test.ts
Normal file
32
packages/khbuild_assistant_prep/src/slack/audit.test.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { loadPrompt } from "../agents/prompts.js";
|
||||
import { parseMissed, pickUnanswered } from "./audit.js";
|
||||
|
||||
const m = (ts: string, text: string, o: { userId?: string | null; botId?: string | null } = {}) => ({ ts, userId: o.userId === undefined ? "U1" : o.userId, botId: o.botId ?? null, text, threadTs: null, fileNames: [] });
|
||||
|
||||
describe("ночная проверка упущенного", () => {
|
||||
it("оставляет сообщения людей без ответа бота в течение двух часов", () => {
|
||||
const msgs = [
|
||||
m("1000", "Stucco crew started at 734 Placido today, inspection Friday"),
|
||||
m("1060", "ok thanks"),
|
||||
m("2000", "Tile delivered to 1919 Arrowhead, install starts Monday"),
|
||||
m("2100", "Saved to Daily Log", { userId: null, botId: "B1" }),
|
||||
m("20000", "Roofer quote came in for 256 Bayside, sending later"),
|
||||
];
|
||||
msgs.push(m("30000", "Elevator contract still not signed at 586 182nd, calling again"));
|
||||
const r = pickUnanswered(msgs, new Map([["20000", "failed"]]));
|
||||
expect(r.map((x) => x.msg.ts)).toEqual(["20000", "30000"]);
|
||||
expect(r[0]!.logged).toBe("failed");
|
||||
expect(r[1]!.logged).toBeNull();
|
||||
});
|
||||
|
||||
it("разбирает раздел «Упущенные»", () => {
|
||||
expect([...parseMissed("1 | сводка по Placido не записана\n#3: вопрос без ответа")]).toEqual([[1, "сводка по Placido не записана"], [3, "вопрос без ответа"]]);
|
||||
expect(parseMissed("нет").size).toBe(0);
|
||||
expect(parseMissed(undefined).size).toBe(0);
|
||||
});
|
||||
|
||||
it("промт найден в proposed", () => {
|
||||
expect(loadPrompt("p-missed-audit.md", {}, "proposed")).toContain("## Упущенные");
|
||||
});
|
||||
});
|
||||
147
packages/khbuild_assistant_prep/src/slack/audit.ts
Normal file
147
packages/khbuild_assistant_prep/src/slack/audit.ts
Normal file
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* Ночная проверка упущенного (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<string, string>): { msg: SlackHistoryMessage; logged: string | null }[] {
|
||||
const botTs = msgs.filter((m) => m.botId).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 !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<number, string> {
|
||||
const out = new Map<number, string>();
|
||||
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<AuditResult> {
|
||||
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<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" });
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user