Ассистент: сводка Daily Log по проектам из общего канала (#2-general-all)
Разбор сводки по проектам, запись в Daily Log каждого агентом (p-daily-summary.md), ответ в тред, simulate с summary. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -11,7 +11,7 @@ import { resolveForManager, sendForManager, type MailDeps } from "./mail/service
|
||||
|
||||
export interface ChatApi {
|
||||
/** Имитация входящего сообщения менеджера (без Slack): текст и локальные файлы; publish - слать ли ответ в Slack. */
|
||||
simulate(opts: { managerId?: string; text: string; files?: string[]; publish?: boolean }): Promise<unknown>;
|
||||
simulate(opts: { managerId?: string; text: string; files?: string[]; publish?: boolean; summary?: boolean }): Promise<unknown>;
|
||||
/** Системное событие ассистента (напоминания 12:00/13:00/16:00 и т.п.) всем менеджерам режима. */
|
||||
event(kind: string): Promise<unknown>;
|
||||
/** Разовое поручение агенту менеджера от ИТ/владельца (например, применить подтверждённые изменения); ответ уходит в чат менеджера, если publish. */
|
||||
@@ -129,11 +129,11 @@ export function buildApi(deps: PrepApiDeps): FastifyInstance {
|
||||
);
|
||||
return id;
|
||||
};
|
||||
app.post<{ Body: { managerId?: string; text?: string; files?: string[]; publish?: boolean } }>("/chat/simulate", async (req, reply) => {
|
||||
app.post<{ Body: { managerId?: string; text?: string; files?: string[]; publish?: boolean; summary?: boolean } }>("/chat/simulate", async (req, reply) => {
|
||||
if (!deps.chat) return reply.code(501).send({ error: "chat не настроен" });
|
||||
const b = req.body ?? {};
|
||||
if (!b.text) return reply.code(400).send({ error: "нужен text" });
|
||||
return reply.code(202).send({ chatRunId: startChat(() => deps.chat!.simulate({ managerId: b.managerId, text: b.text!, files: b.files, publish: b.publish })) });
|
||||
return reply.code(202).send({ chatRunId: startChat(() => deps.chat!.simulate({ managerId: b.managerId, text: b.text!, files: b.files, publish: b.publish, summary: b.summary })) });
|
||||
});
|
||||
app.post<{ Body: { kind?: string } }>("/chat/event", async (req, reply) => {
|
||||
if (!deps.chat) return reply.code(501).send({ error: "chat не настроен" });
|
||||
|
||||
@@ -18,6 +18,7 @@ import { DriveClient } from "./gdrive/client.js";
|
||||
import { createTokenProvider, parseServiceAccountKey } from "./gdrive/service-account.js";
|
||||
import { createGoogleDrive } from "./slack/drive.js";
|
||||
import { DriveInbox } from "./slack/drive-inbox.js";
|
||||
import { summaryContextFor } from "./slack/daily-summary.js";
|
||||
import { SlackIntake, rowToManager } from "./slack/intake.js";
|
||||
import { TodoEventPoller } from "./slack/todo-events.js";
|
||||
import { createGoogleTts } from "./slack/tts.js";
|
||||
@@ -73,15 +74,14 @@ const EVENT_TITLE: Record<string, string> = { noon: "Напоминание 12:0
|
||||
|
||||
const chat = chatDeps
|
||||
? {
|
||||
async simulate(o: { managerId?: string; text: string; files?: string[]; publish?: boolean }) {
|
||||
async simulate(o: { managerId?: string; text: string; files?: string[]; publish?: boolean; summary?: boolean }) {
|
||||
const all = await managers(service.modes, true);
|
||||
const m = o.managerId ? (all.find((x) => x.personId === o.managerId) ?? (await findManagerById(pool, o.managerId))) : all[0];
|
||||
if (!m) throw new Error("менеджер не найден");
|
||||
return handleManagerMessages(
|
||||
{ ...chatDeps, dryPublish: !o.publish },
|
||||
m,
|
||||
[{ channel: m.slackChannelId ?? "simulated", ts: String(Date.now() / 1000), text: o.text, fileIds: [], localFiles: o.files }],
|
||||
);
|
||||
const msg = { channel: m.slackChannelId ?? "simulated", ts: String(Date.now() / 1000), text: o.text, fileIds: [], localFiles: o.files };
|
||||
// сводка Daily Log по проектам (как из #2-general-all): разбор по проектам и запись агентом; без publish ответ в Slack не уходит
|
||||
const summary = o.summary ? await summaryContextFor(pool, common.timezone, { channel: msg.channel, ts: msg.ts, text: o.text, senderName: m.name }) : undefined;
|
||||
return handleManagerMessages({ ...chatDeps, dryPublish: !o.publish }, m, [msg], summary ? { summary, channel: msg.channel } : {});
|
||||
},
|
||||
async apply(o: { managerId: string; text: string; publish?: boolean }) {
|
||||
const m = (await managers(service.modes, true)).find((x) => x.personId === o.managerId) ?? (await findManagerById(pool, o.managerId));
|
||||
@@ -145,7 +145,7 @@ await app.listen({ host: service.http.host, port: service.http.port });
|
||||
log.info({ port: service.http.port }, "khbuild_assistant_prep запущен");
|
||||
|
||||
if (service.slack && chatDeps) {
|
||||
const intake = new SlackIntake(chatDeps, { channelIds: service.slack.channelIds, debounceMs: service.slack.debounceSeconds * 1000, followupMs: service.slack.followupMinutes * 60_000, recapSilenceMs: service.slack.recapSilenceMinutes * 60_000, recapFromHour: service.slack.recapFromHour, recapToHour: service.slack.recapToHour });
|
||||
const intake = new SlackIntake(chatDeps, { channelIds: service.slack.channelIds, summaryChannelIds: service.slack.dailySummaryChannelIds, debounceMs: service.slack.debounceSeconds * 1000, followupMs: service.slack.followupMinutes * 60_000, recapSilenceMs: service.slack.recapSilenceMinutes * 60_000, recapFromHour: service.slack.recapFromHour, recapToHour: service.slack.recapToHour });
|
||||
if (service.slack.todoPollSeconds > 0 && service.agent.todo)
|
||||
new TodoEventPoller(chatDeps, { url: service.agent.todo.url, token: service.agent.todo.token, loadManager: (id) => intake.findManagerByPerson(id), intervalMs: service.slack.todoPollSeconds * 1000, fromHour: service.slack.recapFromHour, toHour: service.slack.recapToHour }).start();
|
||||
void intake.restoreRecapTimers().catch((e) => log.error({ err: String(e) }, "восстановление таймеров recap не удалось"));
|
||||
|
||||
@@ -52,6 +52,8 @@ export const slackSchema = z.object({
|
||||
appToken: z.string(),
|
||||
/** Каналы, сообщения которых принимаются (дополнительно к construction_manager.slack_channel_id). */
|
||||
channelIds: z.array(z.string()).default([]),
|
||||
/** Общие каналы со сводками Daily Log по нескольким проектам (например, #2-general-all): сводка разбирается по проектам и записывается в Daily Log каждого. */
|
||||
dailySummaryChannelIds: z.array(z.string()).default([]),
|
||||
/** Пауза накопления сообщений менеджера перед запуском агента. */
|
||||
debounceSeconds: z.number().default(8),
|
||||
/** Через сколько минут после последнего сообщения менеджера агент спрашивает "Что-то ещё?" (0 - отключено). */
|
||||
|
||||
@@ -11,6 +11,7 @@ import type { DriveSync } from "./drive.js";
|
||||
import type { SlackApi } from "./api.js";
|
||||
import { applyRecapOutput, getRecapState, loadChannelDialog, parseReactions, recapBlock } from "./recap.js";
|
||||
import { managerLanguage, parseLanguage, setManagerLanguage } from "./language.js";
|
||||
import type { SummarySection } from "./daily-summary.js";
|
||||
import { saveChatTiming, type ChatTiming } from "./timing.js";
|
||||
import { normalizeVoice, speechText, type ReplyMode, type Tts } from "./tts.js";
|
||||
|
||||
@@ -36,6 +37,17 @@ export interface ProjectContext {
|
||||
isHuddle: boolean;
|
||||
}
|
||||
|
||||
/** Сводка Daily Log по нескольким проектам из общего канала: разделы уже привязаны к проектам JobTread. */
|
||||
export interface SummaryContext {
|
||||
channel: string;
|
||||
/** ts сообщения сводки: ответ уходит в его тред, реакция ставится на него. */
|
||||
ts: string;
|
||||
/** Дата записи Daily Log (YYYY-MM-DD). */
|
||||
date: string;
|
||||
senderName: string | null;
|
||||
sections: SummarySection[];
|
||||
}
|
||||
|
||||
export interface IncomingMessage {
|
||||
/** Контекст проектного канала (если сообщение пришло из него). */
|
||||
project?: ProjectContext;
|
||||
@@ -96,7 +108,7 @@ export async function handleManagerMessages(
|
||||
deps: ChatDeps,
|
||||
manager: ManagerInfo,
|
||||
messages: IncomingMessage[],
|
||||
opts: { systemEvent?: string; project?: ProjectContext; channel?: string } = {},
|
||||
opts: { systemEvent?: string; project?: ProjectContext; summary?: SummaryContext; channel?: string } = {},
|
||||
): Promise<ChatResult> {
|
||||
const { ctx } = deps;
|
||||
const t0 = Date.now();
|
||||
@@ -223,8 +235,9 @@ export async function handleManagerMessages(
|
||||
: "(вложений нет)";
|
||||
const proj = opts.project ?? messages.find((m) => m.project)?.project;
|
||||
// Новая версия (долгоживущий агент) читает промты из proposed, прежняя (остальные менеджеры) - из approved
|
||||
// сводка Daily Log по проектам - новая функция, её промт лежит в proposed для всех менеджеров
|
||||
const live = useLive(ctx, manager.personId);
|
||||
const side: PromptSide = live ? "proposed" : "approved";
|
||||
const side: PromptSide = live || opts.summary ? "proposed" : "approved";
|
||||
const fragment = (file: string, title: string, vars: Record<string, string> = {}) => loadFragment(file, title, vars, side);
|
||||
// блоки, которые согласованные промты могут ожидать у всех версий агента; если на этой стороне фрагмента ещё нет - блок пропускается
|
||||
const optFragment = (file: string, title: string, vars: Record<string, string> = {}): string | null => {
|
||||
@@ -245,6 +258,18 @@ export async function handleManagerMessages(
|
||||
})}${writableJobs.includes(proj.jobId) ? "" : `\n${fragment("p-project-channel-context.md", "Запись в проект не разрешена")}`}`,
|
||||
]
|
||||
: [];
|
||||
const summaryBlock = opts.summary
|
||||
? [
|
||||
"",
|
||||
`# Сводка Daily Log по проектам\nКанал общий, сводку выложил ${opts.summary.senderName ?? "менеджер"}. Дата записи Daily Log: ${opts.summary.date}. ts сообщения: ${opts.summary.ts}.\n\n` +
|
||||
opts.summary.sections
|
||||
.map((s, i) => {
|
||||
const state = !s.jobId ? "проект НЕ найден среди проектов ассистента - не записывай, назови его в ответе" : writableJobs.includes(s.jobId) ? `писать в проект ${s.jobName ?? s.jobId} (job id ${s.jobId})` : `запись в проект ${s.jobName ?? s.jobId} (${s.jobId}) НЕ разрешена - не записывай, назови его в ответе`;
|
||||
return `## Раздел ${i + 1}: ${s.name} - ${state}\n${s.body}`;
|
||||
})
|
||||
.join("\n\n"),
|
||||
]
|
||||
: [];
|
||||
// Новая версия (долгоживущий агент): если процесс уже в диалоге, инструкции, список задач и память не повторяются - только новое
|
||||
// короткий промт - только если живой процесс продолжает ту же сессию, что записана для менеджера (после сброса сессии нужны полные инструкции)
|
||||
const inDialog = live && mem.sessionId !== null && ctx.liveRunner!.activeSession(managerWorkDir(ctx.settings, manager.personId)) === mem.sessionId;
|
||||
@@ -318,12 +343,13 @@ ${recapBlock(st, deps.timezone)}`);
|
||||
const buildPrompt = (dialog: boolean): string => [
|
||||
...(dialog
|
||||
? [`# Продолжение диалога\n${fragment("p-long-living-agents.md", "Продолжение диалога")}`]
|
||||
: [loadPrompt(isAcc ? "p-accounting-assistant.md" : isCeo ? "p-ceo-assistant.md" : proj ? "p-project-channel.md" : "p-manager-dialog.md", { media_dir: mediaDir }, side)]),
|
||||
: [loadPrompt(isAcc ? "p-accounting-assistant.md" : isCeo ? "p-ceo-assistant.md" : opts.summary ? "p-daily-summary.md" : proj ? "p-project-channel.md" : "p-manager-dialog.md", { media_dir: mediaDir }, side)]),
|
||||
"",
|
||||
`# Дата и время\n${now.toISOString()} (UTC); дата по Тампе: ${today}; сообщений менеджера за последние сутки: ${todayCount}`,
|
||||
...freqBlocks,
|
||||
...(opts.systemEvent ? ["", `# Системное событие\n${opts.systemEvent}`] : []),
|
||||
...projectBlock,
|
||||
...summaryBlock,
|
||||
...channelBlocks,
|
||||
...(dialog
|
||||
? []
|
||||
@@ -346,7 +372,7 @@ ${recapBlock(st, deps.timezone)}`);
|
||||
// 4. агент
|
||||
let out;
|
||||
try {
|
||||
out = await runManagerAgent(ctx, { managerId: manager.personId, step: "step4", op: opts.project ? "chat:project" : opts.systemEvent ? "chat:event" : "chat:manager", tools: "chat", prompt, fullPrompt, env: sqlEnv, required: [replyKey, "память"] });
|
||||
out = await runManagerAgent(ctx, { managerId: manager.personId, step: "step4", op: opts.summary ? "chat:summary" : opts.project ? "chat:project" : opts.systemEvent ? "chat:event" : "chat:manager", tools: "chat", prompt, fullPrompt, env: sqlEnv, required: [replyKey, "память"] });
|
||||
tm.agent = out.timing;
|
||||
mark = Date.now();
|
||||
} catch (e) {
|
||||
@@ -374,13 +400,15 @@ ${recapBlock(st, deps.timezone)}`);
|
||||
if (!deps.dryPublish && deps.slack.addReaction)
|
||||
for (const r of parseReactions(out.sections.get("реакции"))) await deps.slack.addReaction(channel, r.ts, r.emoji).catch((e) => ctx.log.warn({ err: String(e) }, "реакция не поставлена"));
|
||||
}
|
||||
if (opts.summary && channel && !deps.dryPublish && deps.slack.addReaction)
|
||||
for (const r of parseReactions(out.sections.get("реакции"))) await deps.slack.addReaction(channel, r.ts, r.emoji).catch((e) => ctx.log.warn({ err: String(e) }, "реакция не поставлена"));
|
||||
const replyRaw = out.sections.get(replyKey)!;
|
||||
const reply = /^\(без ответа\)\.?$/i.test(replyRaw) ? null : replyRaw;
|
||||
let published = false;
|
||||
let audioSent = false;
|
||||
if (reply && channel && !deps.dryPublish) {
|
||||
const tp = Date.now();
|
||||
const pr = await publishReply(deps, manager, channel, reply);
|
||||
const pr = await publishReply(deps, manager, channel, reply, opts.summary?.ts);
|
||||
({ published, audioSent } = pr);
|
||||
tm.replySlackTs = pr.replyTs;
|
||||
tm.replyWords = replyWordCount(reply);
|
||||
@@ -412,7 +440,7 @@ export const SHORT_REPLY_WORDS = 12;
|
||||
/** Число слов ответа без упоминаний Slack (<@U…>). */
|
||||
export const replyWordCount = (text: string): number => text.replace(/<@[^>]+>/g, " ").split(/\s+/).filter(Boolean).length;
|
||||
|
||||
export async function publishReply(deps: ChatDeps, manager: ManagerInfo, channel: string, reply: string): Promise<{ published: boolean; audioSent: boolean; replyTs: string | null }> {
|
||||
export async function publishReply(deps: ChatDeps, manager: ManagerInfo, channel: string, reply: string, threadTs?: string): Promise<{ published: boolean; audioSent: boolean; replyTs: string | null }> {
|
||||
const mode = manager.replyMode ?? "text";
|
||||
const voice = normalizeVoice(manager.ttsVoice) ?? normalizeVoice(deps.defaultVoice) ?? "Aoede";
|
||||
let audioSent = false;
|
||||
@@ -431,9 +459,9 @@ export async function publishReply(deps: ChatDeps, manager: ManagerInfo, channel
|
||||
let replyTs: string | null = null;
|
||||
if (needText) {
|
||||
if (deps.slack.postMessageTs) {
|
||||
replyTs = await deps.slack.postMessageTs(channel, reply);
|
||||
replyTs = await deps.slack.postMessageTs(channel, reply, threadTs);
|
||||
published = replyTs !== null;
|
||||
} else published = await deps.slack.postMessage(channel, reply);
|
||||
} else published = await deps.slack.postMessage(channel, reply, threadTs);
|
||||
}
|
||||
return { published: published || audioSent, audioSent, replyTs: replyTs || null };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { loadPrompt } from "../agents/prompts.js";
|
||||
import { buildSections, isDailySummary, matchJob, parseDailySummary, summaryDate } from "./daily-summary.js";
|
||||
|
||||
const TEXT = [
|
||||
"_Daily Log — Wed 11/25_",
|
||||
"",
|
||||
"_1919 Arrowhead_",
|
||||
"_Done_",
|
||||
"• City OK’d sidewalk extension layout (11/24)",
|
||||
"_Left for CO_",
|
||||
"• Target CO ~end of next week",
|
||||
"",
|
||||
"_7841 3rd Ave_",
|
||||
"_Open_",
|
||||
"• Sewer smell, owner bathroom: status :question:",
|
||||
"",
|
||||
"_586 182nd Ave E_",
|
||||
"_Done_",
|
||||
"• New vanity sinks delivered (11/19)",
|
||||
"",
|
||||
"_999 Unknown St_",
|
||||
"_Open_",
|
||||
"• Something",
|
||||
].join("\n");
|
||||
|
||||
const JOBS = [
|
||||
{ id: "j1", name: "04. 1919 Arrowhead" },
|
||||
{ id: "j2", name: "03. 7841 3rd" },
|
||||
{ id: "j3", name: "06. 586 182nd" },
|
||||
{ id: "j4", name: "02. 408 161st" },
|
||||
];
|
||||
|
||||
describe("сводка Daily Log по проектам", () => {
|
||||
it("распознаёт сводку по заголовку", () => {
|
||||
expect(isDailySummary(TEXT)).toBe(true);
|
||||
expect(isDailySummary("*Daily Log* for today")).toBe(true);
|
||||
expect(isDailySummary("Good morning, daily log is coming")).toBe(false);
|
||||
expect(isDailySummary("Day Off\nAlena")).toBe(false);
|
||||
});
|
||||
|
||||
it("делит текст на разделы проектов, не принимая Done/Open за проекты", () => {
|
||||
const p = parseDailySummary(TEXT);
|
||||
expect(p.month).toBe(11);
|
||||
expect(p.day).toBe(25);
|
||||
expect(p.sections.map((s) => s.name)).toEqual(["1919 Arrowhead", "7841 3rd Ave", "586 182nd Ave E", "999 Unknown St"]);
|
||||
expect(p.sections[0]!.body).toContain("_Done_");
|
||||
expect(p.sections[0]!.body).toContain("Target CO");
|
||||
expect(p.sections[1]!.body).toContain(":question:");
|
||||
});
|
||||
|
||||
it("привязывает проекты по номеру дома и первому слову улицы", () => {
|
||||
expect(matchJob("7841 3rd Ave", JOBS)?.id).toBe("j2");
|
||||
expect(matchJob("586 182nd Ave E", JOBS)?.id).toBe("j3");
|
||||
expect(matchJob("408 161st Ave", JOBS)?.id).toBe("j4");
|
||||
expect(matchJob("999 Unknown St", JOBS)).toBeNull();
|
||||
const s = buildSections(parseDailySummary(TEXT), JOBS);
|
||||
expect(s.map((x) => x.jobId)).toEqual(["j1", "j2", "j3", null]);
|
||||
});
|
||||
|
||||
it("дата записи: месяц и день из заголовка, год - по дате сообщения", () => {
|
||||
const p = parseDailySummary(TEXT);
|
||||
expect(summaryDate(p, "2026-11-26")).toBe("2026-11-25");
|
||||
expect(summaryDate(p, "2027-01-03")).toBe("2026-11-25"); // конец года: ноябрь прошлого года
|
||||
expect(summaryDate({ month: null, day: null, sections: [] }, "2026-11-26")).toBe("2026-11-26");
|
||||
});
|
||||
|
||||
it("промт сводки найден в proposed", () => {
|
||||
const t = loadPrompt("p-daily-summary.md", { media_dir: "/m" }, "proposed");
|
||||
expect(t).toContain("Сводка Daily Log по проектам");
|
||||
expect(t).toContain("## Ответ менеджеру");
|
||||
});
|
||||
});
|
||||
105
packages/khbuild_assistant_prep/src/slack/daily-summary.ts
Normal file
105
packages/khbuild_assistant_prep/src/slack/daily-summary.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
/** Сводка Daily Log по нескольким проектам в общем канале (#2-general-all): разбор текста и привязка разделов к проектам JobTread. */
|
||||
|
||||
import { localDate } from "khb_common";
|
||||
import type { SummaryContext } from "./chat.js";
|
||||
|
||||
export interface SummarySection {
|
||||
/** Название проекта, как в сообщении (например, "7841 3rd Ave"). */
|
||||
name: string;
|
||||
/** Текст раздела (строки без заголовка проекта). */
|
||||
body: string;
|
||||
jobId: string | null;
|
||||
jobName: string | null;
|
||||
}
|
||||
|
||||
export interface ParsedSummary {
|
||||
/** Дата из заголовка (MM/DD) или null, если не распознана. */
|
||||
month: number | null;
|
||||
day: number | null;
|
||||
sections: { name: string; body: string }[];
|
||||
}
|
||||
|
||||
/** Сообщение - сводка Daily Log: первая непустая строка начинается с «Daily Log» (с учётом разметки Slack). */
|
||||
export function isDailySummary(text: string): boolean {
|
||||
const first = text.split(/\r?\n/).find((l) => l.trim()) ?? "";
|
||||
return /^[\s_*~>]*daily\s*log\b/i.test(first);
|
||||
}
|
||||
|
||||
const SUBHEADER = /^(done|open|left for co|in progress|this week|next week|today|tomorrow|blocked|issues|notes|week of\b.*|next\b.*)$/i;
|
||||
|
||||
/** Заголовок проекта: строка целиком в `_..._` или `*...*`, после пустой строки, не подзаголовок (Done/Open/...). */
|
||||
function headerOf(line: string): string | null {
|
||||
const m = /^\s*([_*])(.+?)\1\s*$/.exec(line);
|
||||
if (!m) return null;
|
||||
const t = m[2]!.trim();
|
||||
return t && !SUBHEADER.test(t) ? t : null;
|
||||
}
|
||||
|
||||
export function parseDailySummary(text: string): ParsedSummary {
|
||||
const lines = text.split(/\r?\n/);
|
||||
const firstIdx = lines.findIndex((l) => l.trim());
|
||||
const title = firstIdx >= 0 ? lines[firstIdx]! : "";
|
||||
const d = /(\d{1,2})\/(\d{1,2})/.exec(title);
|
||||
const sections: { name: string; lines: string[] }[] = [];
|
||||
let prevBlank = true;
|
||||
for (let i = firstIdx + 1; i < lines.length; i++) {
|
||||
const line = lines[i]!;
|
||||
if (!line.trim()) {
|
||||
prevBlank = true;
|
||||
continue;
|
||||
}
|
||||
const h = prevBlank ? headerOf(line) : null;
|
||||
if (h) sections.push({ name: h, lines: [] });
|
||||
else if (sections.length) sections[sections.length - 1]!.lines.push(line.replace(/\s+$/, ""));
|
||||
prevBlank = false;
|
||||
}
|
||||
return { month: d ? Number(d[1]) : null, day: d ? Number(d[2]) : null, sections: sections.map((s) => ({ name: s.name, body: s.lines.join("\n") })).filter((s) => s.body.trim()) };
|
||||
}
|
||||
|
||||
const norm = (s: string) => s.toLowerCase().replace(/[^a-z0-9 ]+/g, " ").replace(/\s+/g, " ").trim();
|
||||
|
||||
/** Имя проекта в JobTread начинается с номера «NN. » и затем адрес: сравниваем номер дома и первое слово улицы. */
|
||||
export function matchJob(name: string, jobs: { id: string; name: string | null }[]): { id: string; name: string | null } | null {
|
||||
const [num, word] = norm(name).split(" ");
|
||||
if (!num || !word) return null;
|
||||
const hits = jobs.filter((j) => {
|
||||
const [n, w] = norm((j.name ?? "").replace(/^\s*\d+\.\s*/, "")).split(" ");
|
||||
return n === num && !!w && (w === word || w.startsWith(word) || word.startsWith(w));
|
||||
});
|
||||
if (hits.length === 1) return hits[0]!;
|
||||
// название проекта без адреса (например, тестовый проект): полное совпадение имени без номера «NN. »
|
||||
const exact = jobs.filter((j) => norm((j.name ?? "").replace(/^s*d+.s*/, "")) === norm(name));
|
||||
return exact.length === 1 ? exact[0]! : null;
|
||||
}
|
||||
|
||||
/** Календарная дата записи (YYYY-MM-DD): месяц и день из заголовка, год - по дате сообщения (по Тампе); дата из будущего более чем на неделю - прошлый год. */
|
||||
export function summaryDate(parsed: ParsedSummary, messageDate: string): string {
|
||||
if (!parsed.month || !parsed.day || parsed.month > 12 || parsed.day > 31) return messageDate;
|
||||
let year = Number(messageDate.slice(0, 4));
|
||||
const pad = (n: number) => String(n).padStart(2, "0");
|
||||
let iso = `${year}-${pad(parsed.month)}-${pad(parsed.day)}`;
|
||||
if (Date.parse(`${iso}T00:00:00Z`) - Date.parse(`${messageDate}T00:00:00Z`) > 7 * 86400_000) {
|
||||
year -= 1;
|
||||
iso = `${year}-${pad(parsed.month)}-${pad(parsed.day)}`;
|
||||
}
|
||||
return iso;
|
||||
}
|
||||
|
||||
export function buildSections(parsed: ParsedSummary, jobs: { id: string; name: string | null }[]): SummarySection[] {
|
||||
return parsed.sections.map((s) => {
|
||||
const j = matchJob(s.name, jobs);
|
||||
return { name: s.name, body: s.body, jobId: j?.id ?? null, jobName: j?.name ?? null };
|
||||
});
|
||||
}
|
||||
|
||||
/** Контекст сводки для агента: разбор текста, проекты ассистента из БД, дата записи (по часовому поясу компании). */
|
||||
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 },
|
||||
): 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);
|
||||
return { channel: o.channel, ts: o.ts, date: summaryDate(parsed, messageDate), senderName: o.senderName, sections: buildSections(parsed, rows.map((r) => ({ id: String(r.id), name: (r.name as string | null) ?? null }))) };
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { loadFragment } from "../agents/prompts.js";
|
||||
import { pauseState } from "../pause.js";
|
||||
import { promptSideFor } from "../agents/session.js";
|
||||
import { getRecapState, recapDelayMs } from "./recap.js";
|
||||
import { isDailySummary, summaryContextFor } from "./daily-summary.js";
|
||||
import { handleManagerMessages, type ChatDeps, type IncomingMessage, type ManagerInfo, type ProjectContext } from "./chat.js";
|
||||
|
||||
interface Pending {
|
||||
@@ -51,7 +52,7 @@ export class SlackIntake {
|
||||
|
||||
constructor(
|
||||
private deps: ChatDeps,
|
||||
private opts: { channelIds: string[]; debounceMs: number; followupMs?: number; recapSilenceMs?: number; recapFromHour?: number; recapToHour?: number },
|
||||
private opts: { channelIds: string[]; summaryChannelIds?: string[]; debounceMs: number; followupMs?: number; recapSilenceMs?: number; recapFromHour?: number; recapToHour?: number },
|
||||
) {}
|
||||
|
||||
private get pool(): Pool {
|
||||
@@ -86,6 +87,7 @@ export class SlackIntake {
|
||||
const user = String(ev.user ?? "");
|
||||
const ts = String(ev.ts ?? "");
|
||||
if (!channel || !ts) return;
|
||||
if (this.opts.summaryChannelIds?.includes(channel)) return this.handleSummaryEvent(ev);
|
||||
const project = await this.findProjectByChannel(channel);
|
||||
if (project) return this.handleProjectEvent(ev, project);
|
||||
const huddle = ev.subtype === "huddle_thread" || huddleFilesOf(ev).length > 0;
|
||||
@@ -106,6 +108,44 @@ export class SlackIntake {
|
||||
await this.accept(manager, { channel, ts, text: (huddle ? "[Slack huddle: заметки и расшифровка во вложениях] " : "") + String(ev.text ?? ""), fileIds: files, senderUserId: user || undefined });
|
||||
}
|
||||
|
||||
/**
|
||||
* Общий канал со сводками Daily Log (#2-general-all): сообщение «Daily Log - <дата>» от менеджера разбирается по проектам,
|
||||
* агент записывает раздел каждого проекта в его Daily Log. Остальные сообщения канала игнорируются. Сводка обрабатывается сразу (без накопления с чатом менеджера).
|
||||
*/
|
||||
private async handleSummaryEvent(ev: Record<string, unknown>): Promise<void> {
|
||||
const channel = String(ev.channel);
|
||||
const ts = String(ev.ts);
|
||||
const user = String(ev.user ?? "");
|
||||
if (ev.bot_id || !user || user === "USLACKBOT" || !ACCEPTED_SUBTYPES.has(ev.subtype as string | undefined)) return;
|
||||
const text = String(ev.text ?? "");
|
||||
if (!isDailySummary(text)) return;
|
||||
const manager = await this.findManagerBySlackUser(user);
|
||||
if (!manager || manager.chatKind === "accounting") {
|
||||
this.deps.ctx.log.warn({ channel, user }, "сводка Daily Log от человека без чата ассистента - пропущена");
|
||||
return;
|
||||
}
|
||||
if (await this.isOff(manager.personId)) return;
|
||||
const ins = await this.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,'received',$4) on conflict do nothing returning message_ts",
|
||||
[channel, ts, manager.personId, user],
|
||||
);
|
||||
if (!ins.rowCount) return; // дубль
|
||||
const summary = await summaryContextFor(this.pool, this.deps.timezone, { channel, ts, text, senderName: manager.name });
|
||||
const setStatus = (status: string) => this.pool.query("update slack_message_log set status = $3, processed_at = case when $3 in ('done','failed') then now() else null end where channel_id = $1 and message_ts = $2", [channel, ts, status]);
|
||||
this.track(
|
||||
(async () => {
|
||||
await setStatus("processing");
|
||||
try {
|
||||
await handleManagerMessages(this.deps, manager, [{ channel, ts, text, fileIds: [], senderUserId: user }], { summary, channel });
|
||||
await setStatus("done");
|
||||
} catch (e) {
|
||||
this.deps.ctx.log.error({ channel, err: String(e) }, "обработка сводки Daily Log не удалась");
|
||||
await setStatus("failed");
|
||||
}
|
||||
})(),
|
||||
);
|
||||
}
|
||||
|
||||
/** Проектный канал: проект определяется каналом (таблица project_channel). */
|
||||
async findProjectByChannel(channel: string): Promise<{ jobId: string; jobName: string | null } | null> {
|
||||
const { rows } = await this.pool.query(
|
||||
|
||||
Reference in New Issue
Block a user