Проектные каналы: тихий режим, recap для Daily Log; Huddle через message_changed; короткие напоминания
All checks were successful
ci / test (push) Successful in 27s
ci / deploy (push) Successful in 2m13s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-22 21:12:07 +03:00
parent 12147fc3eb
commit 4a32a08b6d
18 changed files with 613 additions and 32 deletions

View File

@@ -601,4 +601,72 @@ d("консольные агенты (временная БД, фейковый
expect(liveCalls[3]!.env).toBeUndefined();
});
it("проектный канал (новая версия): молчание и накопление, реакция, recap по тишине, подтверждение «yes»; Huddle через message_changed", async () => {
const nl = String.fromCharCode(10);
const texts: string[] = [
["## Ответ менеджеру", "(без ответа)", "## Накопить для Daily Log", "[Wed 12:00] UANY: tile was ordered", "## Реакции", "1791741700.000100 memo", "## Память", "м-тихо"].join(nl),
["## Ответ менеджеру", "Recap: tile ordered. Should I add this to the Daily Log?", "## Статус recap", "asked", "## Память", "м-recap"].join(nl),
["## Ответ менеджеру", "Done: saved to Daily Log.", "## Статус recap", "recorded", "## Память", "м-yes"].join(nl),
["## Ответ менеджеру", "(без ответа)", "## Память", "м-huddle"].join(nl),
];
const liveCalls: ClaudeCall[] = [];
const liveRunner = {
run: async (c: ClaudeCall) => { liveCalls.push(c); return { text: texts.shift()!, sessionId: c.sessionId }; },
isActive: () => false, activeSession: () => null, close: () => undefined, closeAll: () => undefined, activeCount: () => 0,
};
const base = ctx();
const live = { ...base, liveRunner, settings: { ...base.settings, live: { managerIds: [MGR], idleMinutes: 10, warmupSeconds: 0 } } };
await db.pool.query("insert into project_channel (channel_id, jt_job_id, channel_name, is_enabled) values ('CPROJ3','llmtest-job','proj-llmtest-3', true) on conflict do nothing");
const posted: string[] = [];
const reactions: string[] = [];
const slack = {
postMessage: async (_c: string, t: string) => { posted.push(t); return true; }, fileInfo: async () => null, download: async () => 0,
history: async () => [{ ts: "1791741700.000100", userId: "UANY", botId: null, text: "tile was ordered", threadTs: null, fileNames: [] }],
userName: async () => "Walter", botUserId: async () => "UBOT",
addReaction: async (_c: string, ts: string, e: string) => { reactions.push(ts + " " + e); return true; },
};
const noon = new Date("2026-10-21T16:00:00Z");
const deps = { ctx: live, timezone: "America/New_York", slack, now: () => noon };
const intake = new SlackIntake(deps, { channelIds: [], debounceMs: 600_000, recapSilenceMs: 600_000 });
// 1. люди общаются: агент молчит, копит, ставит реакцию; в промте - диалог за сутки с временем и именами
await intake.onEvent({ type: "message", channel: "CPROJ3", user: "UANY", ts: "1791741700.000100", text: "tile was ordered" });
await intake.flush(MGR);
await intake.idle();
expect(posted).toEqual([]);
expect(reactions).toEqual(["1791741700.000100 memo"]);
expect(liveCalls[0]!.prompt).toContain("# Диалог канала за последние сутки");
expect(liveCalls[0]!.prompt).toContain("Walter: tile was ordered");
expect(liveCalls[0]!.prompt).toContain("# Накопленное для Daily Log");
let st = (await db.pool.query("select status, notes from channel_recap_state where channel_id = 'CPROJ3'")).rows[0];
expect(st).toMatchObject({ status: "collecting" });
expect(st.notes).toContain("tile was ordered");
// 2. тишина: recap одним сообщением, статус asked
intake.scheduleRecap("CPROJ3", { personId: MGR, name: "llmtest-Manager", slackUserId: "ULLMTEST", slackChannelId: "CPROJ3" }, { jobId: "llmtest-job", jobName: null, channel: "CPROJ3", senderName: null, isHuddle: false }, 1);
await new Promise((r) => setTimeout(r, 300));
await intake.idle();
expect(liveCalls[1]!.prompt).toContain("Беседа в проектном канале затихла");
expect(liveCalls[1]!.prompt).toContain("tile was ordered");
expect(posted).toEqual(["Recap: tile ordered. Should I add this to the Daily Log?"]);
st = (await db.pool.query("select status from channel_recap_state where channel_id = 'CPROJ3'")).rows[0];
expect(st.status).toBe("asked");
// 3. «yes» от любого участника: запись, состояние очищено
await intake.onEvent({ type: "message", channel: "CPROJ3", user: "UOTHER", ts: "1791741800.000100", text: "yes" });
await intake.flush(MGR);
await intake.idle();
expect(liveCalls[2]!.prompt).toContain("Вопрос про Daily Log уже задан");
expect(posted[1]).toContain("saved to Daily Log");
expect((await db.pool.query("select 1 from channel_recap_state where channel_id = 'CPROJ3'")).rowCount).toBe(0);
// 4. заметки Huddle приходят правкой родителя (message_changed) и принимаются один раз; "AI huddle notes are ready" - игнорируется
const files = [{ id: "FH1", name: "Huddle notes", mimetype: "application/vnd.slack-docs", filetype: "quip" }];
await intake.onEvent({ type: "message", channel: "CPROJ3", user: "USLACKBOT", ts: "1791741900.000100", text: "AI huddle notes are ready" });
await intake.onEvent({ type: "message", subtype: "message_changed", channel: "CPROJ3", message: { type: "message", subtype: "huddle_thread", user: "USLACKBOT", ts: "1791741900.000200", files } });
await intake.onEvent({ type: "message", subtype: "message_changed", channel: "CPROJ3", message: { type: "message", subtype: "huddle_thread", user: "USLACKBOT", ts: "1791741900.000200", files } });
await intake.flush(MGR);
await intake.idle();
intake.stop();
expect(liveCalls).toHaveLength(4);
expect(liveCalls[3]!.prompt).toContain("[Slack huddle");
expect(liveCalls[3]!.prompt).not.toContain("AI huddle notes are ready");
});
});

View File

@@ -106,7 +106,8 @@ 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 });
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 });
void intake.restoreRecapTimers().catch((e) => log.error({ err: String(e) }, "восстановление таймеров recap не удалось"));
startSocketMode({ appToken: service.slack.appToken, log, onEvent: (ev) => void intake.onEvent(ev).catch((e) => log.error({ err: String(e) }, "ошибка приёма события Slack")) });
if (service.drive && driveClient && service.drive.inboxScanSeconds > 0) {
const d = service.drive;

View File

@@ -30,6 +30,7 @@ const FRAGMENTS: Record<string, Record<string, string[]>> = {
/** Только новая версия агента (proposed). */
const LIVE_FRAGMENTS: Record<string, Record<string, string[]>> = {
"p-long-living-agents.md": { "Продолжение диалога": [], "Правила долгоживущего агента": [], "Todo менеджера": ["membership"] },
"p-chat-events.md": { "Беседа в проектном канале затихла": [] },
"p-chat-environment.md": { "Менеджер": ["name", "mention"], "Частота сообщений": ["last_assistant", "last_human", "unanswered", "assistant_today", "replied_today"] },
};
@@ -103,14 +104,32 @@ describe("промты в docs модуля (p-*.md)", () => {
expect(ceo).toContain("полный доступ ко всем общим дискам");
});
it("если менеджер сегодня не отвечал - только короткое напоминание про голосовую заметку (новая версия, proposed)", () => {
const remind = "Please send a quick voice note, even a short one.";
expect(loadFragment("p-chat-events.md", "Повтор 13:00", {}, "proposed")).toContain(remind);
expect(loadFragment("p-chat-events.md", "Итог дня 16:00", {}, "proposed")).toContain(remind);
expect(loadPrompt("p-manager-dialog.md", {}, "proposed")).toContain(remind);
it("если менеджер не ответил - только короткая фраза на 4-8 слов, не «простыня» и не фиксированный текст (новая версия, proposed)", () => {
const old = "Please send a quick voice note, even a short one.";
for (const text of [loadFragment("p-chat-events.md", "Повтор 13:00", {}, "proposed"), loadFragment("p-chat-events.md", "Итог дня 16:00", {}, "proposed"), loadPrompt("p-manager-dialog.md", {}, "proposed")]) {
expect(text).not.toContain(old);
expect(text).toContain("4-8 слов");
expect(text).toContain("Any notes on the above?");
}
expect(loadFragment("p-chat-environment.md", "Частота сообщений", {}, "proposed")).toContain("менеджер сегодня отвечал: {{replied_today}}");
});
it("проектный канал (proposed): тихий режим, recap, подтверждение, Huddle и новые разделы вывода", () => {
const t = loadPrompt("p-project-channel.md", { media_dir: "/m" }, "proposed");
for (const part of ["## Когда отвечать, а когда молчать", "## Тихий режим: накопление", "## Recap", "## Подтверждение recap", "## Huddle", "Should I add this to the Daily Log?", "ЛЮБОГО участника", "`## Накопить для Daily Log`", "`## Статус recap`", "`## Реакции`", "# Диалог канала за последние сутки"])
expect(t, part).toContain(part);
expect(t).not.toContain("Каждое действие в JobTread подтверждай одной строкой");
expect(t).not.toContain("Daily log не требует подтверждения");
});
it("Huddle: правило про заметки и расшифровку есть у менеджера и руководителя (proposed)", () => {
for (const name of ["p-manager-dialog.md", "p-ceo-assistant.md"]) {
const t = loadPrompt(name, { media_dir: "/m" }, "proposed");
expect(t, name).toContain("huddle_transcript");
expect(t, name).toContain("AI huddle notes are ready");
}
});
it("начало суток по Тампе: полночь в часовом поясе, а не в UTC", () => {
expect(startOfLocalDay(new Date("2026-10-20T15:00:00Z"), "America/New_York").toISOString()).toBe("2026-10-20T04:00:00.000Z"); // EDT = UTC-4
expect(startOfLocalDay(new Date("2026-10-21T03:30:00Z"), "America/New_York").toISOString()).toBe("2026-10-20T04:00:00.000Z"); // вторник 23:30 по Тампе, в UTC уже среда

View File

@@ -0,0 +1,88 @@
import { describe, expect, it } from "vitest";
import { formatChannelDialog, loadChannelDialog, parseReactions, parseRecapStatus, recapBlock, recapDelayMs, sectionText, stampLocal } from "./slack/recap.js";
import { normalizeHuddleEvent } from "./slack/intake.js";
const TZ = "America/New_York";
describe("диалог проектного канала для агента", () => {
it("время по Тампе, имена вместо упоминаний, сообщения бота помечены, ts для реакций", () => {
const names = new Map([["U1", "Walter"], ["U2", "Maria"]]);
const out = formatChannelDialog(
[
{ ts: "1761152700.000100", userId: "U1", botId: null, text: "<@U2> tile arrived\nbring a cart", threadTs: null, fileNames: ["a.jpg"] },
{ ts: "1761152760.000200", userId: "UBOT", botId: "B1", text: "Recap: ...", threadTs: null, fileNames: [] },
{ ts: "1761152820.000300", userId: "U2", botId: null, text: "ok", threadTs: "1761152700.000100", fileNames: [] },
],
{ tz: TZ, botUserId: "UBOT", names },
);
const lines = out.split("\n");
expect(lines[0]).toContain("(ts 1761152700.000100) Walter: @Maria tile arrived ⏎ bring a cart [файлы: a.jpg]");
expect(lines[0]).toMatch(/^- \[\w{3} 10\/22 \d\d:\d\d\]/);
expect(lines[1]).toContain("ASSISTANT (ты): Recap");
expect(lines[2]).toContain("Maria (в треде): ok");
});
it("пустой канал и сбой Slack не ломают обработку", async () => {
expect(formatChannelDialog([], { tz: TZ, botUserId: null, names: new Map() })).toContain("сообщений нет");
const bad = { history: async () => { throw new Error("boom"); } };
expect(await loadChannelDialog(bad, "C1", new Date(), TZ)).toContain("не загрузилась: boom");
expect(await loadChannelDialog({}, "C1", new Date(), TZ)).toContain("недоступна");
});
it("stampLocal: день недели и время в часовом поясе", () => {
expect(stampLocal(new Date("2026-10-22T03:30:00Z"), TZ)).toBe("Wed 10/21 23:30");
});
});
describe("разделы вывода агента", () => {
it("статус recap: английские и русские варианты, пустые - null", () => {
expect(parseRecapStatus("asked")).toBe("asked");
expect(parseRecapStatus("Спрошено")).toBe("asked");
expect(parseRecapStatus("recorded - 2 todo")).toBe("recorded");
expect(parseRecapStatus("записано")).toBe("recorded");
expect(parseRecapStatus("discarded")).toBe("discarded");
expect(parseRecapStatus("collecting")).toBe("collecting");
expect(parseRecapStatus("нет")).toBeNull();
expect(parseRecapStatus(undefined)).toBeNull();
});
it("реакции: ts и имя эмодзи, мусор пропускается", () => {
expect(parseReactions("1761152700.000100 memo\n- 1761152760.000200 :white_check_mark:\nчто-то ещё")).toEqual([
{ ts: "1761152700.000100", emoji: "memo" },
{ ts: "1761152760.000200", emoji: "white_check_mark" },
]);
expect(parseReactions("нет")).toEqual([]);
});
it("sectionText: «нет» и пусто - отсутствие", () => {
expect(sectionText("(нет)")).toBe("");
expect(sectionText(" none ")).toBe("");
expect(sectionText("факт")).toBe("факт");
});
it("блок накопленного для агента", () => {
expect(recapBlock(null, TZ)).toContain("ничего не накоплено");
const st = { channelId: "C", jobId: "J", notes: "[Wed 10:00] Walter: tile arrived", status: "asked" as const, lastHumanAt: new Date("2026-10-21T14:00:00Z"), askedAt: new Date("2026-10-21T14:10:00Z"), attempts: 0 };
expect(recapBlock(st, TZ)).toContain("уже задан");
expect(recapBlock({ ...st, status: "collecting" }, TZ)).toContain("ещё не задавался");
});
});
describe("окно recap по Тампе (7:00-19:00)", () => {
it("внутри окна - сразу, ночью и вечером - до 7:00", () => {
expect(recapDelayMs(new Date("2026-10-21T16:00:00Z"), TZ)).toBe(0); // 12:00
expect(recapDelayMs(new Date("2026-10-21T04:00:00Z"), TZ)).toBe(7 * 3600_000); // 00:00 -> 07:00 (UTC-4)
expect(recapDelayMs(new Date("2026-10-21T23:30:00Z"), TZ)).toBe(11.5 * 3600_000); // 19:30 -> 07:00 завтра
});
});
describe("Huddle в Slack", () => {
const files = [{ id: "F1", name: "Huddle notes", mimetype: "application/vnd.slack-docs", filetype: "quip" }];
it("message_changed с файлами заметок превращается в сообщение того же ts, прочие правки отбрасываются", () => {
const ev = { type: "message", subtype: "message_changed", channel: "C1", message: { type: "message", subtype: "huddle_thread", ts: "1.1", files } };
expect(normalizeHuddleEvent(ev)).toMatchObject({ type: "message", subtype: "huddle_thread", ts: "1.1", channel: "C1" });
expect(normalizeHuddleEvent({ type: "message", subtype: "message_changed", channel: "C1", message: { ts: "2.2", text: "edit" } })).toBeNull();
const plain = { type: "message", ts: "3.3", text: "hi" };
expect(normalizeHuddleEvent(plain)).toBe(plain);
});
});

View File

@@ -45,6 +45,11 @@ export const slackSchema = z.object({
debounceSeconds: z.number().default(8),
/** Через сколько минут после последнего сообщения менеджера агент спрашивает "Что-то ещё?" (0 - отключено). */
followupMinutes: z.number().default(8),
/** Проектные каналы: тишина (минуты) после последнего сообщения людей, по которой ассистент предлагает recap для Daily Log. */
recapSilenceMinutes: z.number().default(10),
/** Часы по Тампе, когда можно задавать вопрос про Daily Log (остальное откладывается до начала окна). */
recapFromHour: z.number().default(7),
recapToHour: z.number().default(19),
});
export type SlackSettings = z.infer<typeof slackSchema>;

View File

@@ -9,12 +9,30 @@ export interface SlackFile {
urlPrivateDownload: string;
}
/** Сообщение из истории канала (для контекста агента проектного канала). */
export interface SlackHistoryMessage {
ts: string;
userId: string | null;
botId: string | null;
text: string;
threadTs: string | null;
fileNames: string[];
}
export interface SlackApi {
postMessage(channel: string, text: string, threadTs?: string): Promise<boolean>;
/** То же, но возвращает ts отправленного сообщения (null - не отправлено): по нему считается время ответа для chat_timing. */
postMessageTs?(channel: string, text: string, threadTs?: string): Promise<string | null>;
fileInfo(fileId: string): Promise<SlackFile | null>;
download(file: SlackFile, toPath: string): Promise<number>;
/** История канала с момента oldest (unix-секунды) по возрастанию времени, вместе с ответами в тредах. */
history?(channel: string, oldest: number): Promise<SlackHistoryMessage[]>;
/** Отображаемое имя пользователя Slack (кэшируется); null - не удалось узнать. */
userName?(userId: string): Promise<string | null>;
/** Ставит эмодзи-реакцию на сообщение (нужен scope reactions:write); ошибка already_reacted не считается сбоем. */
addReaction?(channel: string, ts: string, emoji: string): Promise<boolean>;
/** Slack id самого бота (чтобы пометить его сообщения в истории). */
botUserId?(): Promise<string | null>;
/** Загружает файл в канал (нужен scope files:write). */
uploadFile?(channel: string, filename: string, data: Buffer, title?: string): Promise<void>;
}
@@ -34,8 +52,55 @@ export function createSlackApi(botToken: string, fetchFn: typeof fetch = fetch):
const r = await call("chat.postMessage", { channel, text: text.slice(0, 35000), ...(threadTs ? { thread_ts: threadTs } : {}) });
return r.ok === true ? (typeof r.ts === "string" ? r.ts : "") : null;
};
const get = async (method: string, params: Record<string, string>) => {
const res = await fetchFn(`https://slack.com/api/${method}?${new URLSearchParams(params)}`, { headers: { authorization: `Bearer ${botToken}` } });
return (await res.json()) as { ok?: boolean; error?: string; messages?: Record<string, unknown>[]; user?: Record<string, unknown>; user_id?: string; response_metadata?: { next_cursor?: string } };
};
const toMsg = (m: Record<string, unknown>): SlackHistoryMessage => ({
ts: String(m.ts),
userId: typeof m.user === "string" ? m.user : null,
botId: typeof m.bot_id === "string" ? m.bot_id : null,
text: String(m.text ?? ""),
threadTs: typeof m.thread_ts === "string" ? m.thread_ts : null,
fileNames: ((m.files as { name?: string }[] | undefined) ?? []).map((f) => String(f.name ?? "file")),
});
const names = new Map<string, string | null>();
let botId: string | null | undefined;
return {
postMessageTs: postTs,
async history(channel, oldest) {
const out = new Map<string, SlackHistoryMessage>();
let cursor = "";
for (let page = 0; page < 10; page++) {
const r = await get("conversations.history", { channel, oldest: String(oldest), limit: "200", ...(cursor ? { cursor } : {}) });
if (!r.ok) throw new Error(`Slack conversations.history: ${r.error}`);
for (const m of r.messages ?? []) out.set(String(m.ts), toMsg(m));
cursor = r.response_metadata?.next_cursor ?? "";
if (!cursor) break;
}
// ответы в тредах (в history только родители)
for (const m of [...out.values()].filter((x) => x.threadTs === x.ts).slice(0, 20)) {
const r = await get("conversations.replies", { channel, ts: m.ts, oldest: String(oldest), limit: "100" });
if (r.ok) for (const x of r.messages ?? []) out.set(String(x.ts), toMsg(x));
}
return [...out.values()].sort((a, b) => Number(a.ts) - Number(b.ts));
},
async userName(userId) {
if (names.has(userId)) return names.get(userId)!;
const r = await get("users.info", { user: userId });
const u = r.user as { real_name?: string; name?: string; profile?: { display_name?: string; real_name?: string } } | undefined;
const n = r.ok && u ? u.profile?.display_name || u.real_name || u.profile?.real_name || u.name || null : null;
names.set(userId, n);
return n;
},
async addReaction(channel, ts, emoji) {
const r = await call("reactions.add", { channel, timestamp: ts, name: emoji.replace(/:/g, "") });
return r.ok === true || r.error === "already_reacted";
},
async botUserId() {
if (botId === undefined) botId = (await get("auth.test", {})).user_id ?? null;
return botId;
},
async postMessage(channel, text, threadTs) {
return (await postTs(channel, text, threadTs)) !== null;
},

View File

@@ -6,6 +6,7 @@ import { loadFragment, loadPrompt, type PromptSide } from "../agents/prompts.js"
import { saveProblems } from "../agents/step2.js";
import type { DriveSync } from "./drive.js";
import type { SlackApi } from "./api.js";
import { applyRecapOutput, getRecapState, loadChannelDialog, parseReactions, recapBlock } from "./recap.js";
import { saveChatTiming, type ChatTiming } from "./timing.js";
import { normalizeVoice, speechText, type ReplyMode, type Tts } from "./tts.js";
@@ -46,7 +47,7 @@ export interface IncomingMessage {
export interface ChatDeps {
ctx: AgentContext;
slack: Pick<SlackApi, "postMessage" | "postMessageTs" | "fileInfo" | "download" | "uploadFile">;
slack: Pick<SlackApi, "postMessage" | "postMessageTs" | "fileInfo" | "download" | "uploadFile" | "history" | "userName" | "botUserId" | "addReaction">;
/** Синтез речи; без него ответы всегда текстовые. */
tts?: Tts;
defaultVoice?: string;
@@ -87,7 +88,7 @@ export async function handleManagerMessages(
deps: ChatDeps,
manager: ManagerInfo,
messages: IncomingMessage[],
opts: { systemEvent?: string } = {},
opts: { systemEvent?: string; project?: ProjectContext; channel?: string } = {},
): Promise<ChatResult> {
const { ctx } = deps;
const t0 = Date.now();
@@ -100,7 +101,7 @@ export async function handleManagerMessages(
};
const now = (deps.now ?? (() => new Date()))();
const today = localDate(now, deps.timezone);
const channel = messages[0]?.channel ?? manager.slackChannelId;
const channel = opts.channel ?? messages[0]?.channel ?? manager.slackChannelId;
const sub = `${isoStamp(now)}_${channel ?? "nochannel"}`;
const mediaDir = join(managerWorkDir(ctx.settings, manager.personId), "media", sub);
mkdirSync(mediaDir, { recursive: true });
@@ -192,7 +193,7 @@ export async function handleManagerMessages(
const attBlock = attachments.length
? attachments.map((a) => `- ${a.path} (${a.mimetype || "?"}, ${a.size} байт)${a.link ? ` | Drive: ${a.link}` : ""}`).join("\n")
: "(вложений нет)";
const proj = messages.find((m) => m.project)?.project;
const proj = opts.project ?? messages.find((m) => m.project)?.project;
// Новая версия (долгоживущий агент) читает промты из proposed, прежняя (остальные менеджеры) - из approved
const live = useLive(ctx, manager.personId);
const side: PromptSide = live ? "proposed" : "approved";
@@ -261,6 +262,16 @@ export async function handleManagerMessages(
const sqlEnv = Object.keys(agentEnv).length ? agentEnv : undefined;
const replyKey = isCeo ? "ответ arthur" : "ответ менеджеру";
const listText = isCeo ? "" : await todayList(ctx, manager.personId, today);
// проектный канал: диалог за сутки с временем (по Тампе) и накопленное для Daily Log
const channelBlocks: string[] = [];
const recapOn = !!proj && !!channel && live; // тихий режим и recap - только новая версия агента (промты proposed)
if (recapOn && proj && channel) {
const dialogText = await loadChannelDialog(deps.slack, channel, now, deps.timezone);
const st = await getRecapState(ctx.pool, channel);
channelBlocks.push("", `# Диалог канала за последние сутки (время по Тампе)
${dialogText}`, "", `# Накопленное для Daily Log
${recapBlock(st, deps.timezone)}`);
}
const buildPrompt = (dialog: boolean): string => [
...(dialog
? [`# Продолжение диалога\n${fragment("p-long-living-agents.md", "Продолжение диалога")}`]
@@ -270,6 +281,7 @@ export async function handleManagerMessages(
...freqBlocks,
...(opts.systemEvent ? ["", `# Системное событие\n${opts.systemEvent}`] : []),
...projectBlock,
...channelBlocks,
...(dialog
? []
: isCeo
@@ -309,6 +321,11 @@ export async function handleManagerMessages(
// 5. результат
await saveMemory(ctx.pool, manager.personId, out.sections.get("память")!);
await saveProblems(ctx, manager.personId, "step4", out.sections);
if (recapOn && proj && channel) {
await applyRecapOutput(ctx.pool, { channel, managerId: manager.personId, jobId: proj.jobId, sections: out.sections, humanMessage: messages.length > 0, now });
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) }, "реакция не поставлена"));
}
const replyRaw = out.sections.get(replyKey)!;
const reply = /^\(без ответа\)\.?$/i.test(replyRaw) ? null : replyRaw;
let published = false;

View File

@@ -3,6 +3,7 @@ import { isReplyMode } from "./tts.js";
import { loadFragment } from "../agents/prompts.js";
import { pauseState } from "../pause.js";
import { promptSideFor } from "../agents/session.js";
import { getRecapState, recapDelayMs } from "./recap.js";
import { handleManagerMessages, type ChatDeps, type IncomingMessage, type ManagerInfo, type ProjectContext } from "./chat.js";
interface Pending {
@@ -25,16 +26,32 @@ export function rowToManager(r: Record<string, unknown>): ManagerInfo {
const ACCEPTED_SUBTYPES = new Set([undefined, "file_share", "thread_broadcast"]);
type SlackFileRef = { id?: string; name?: string; mimetype?: string; filetype?: string };
const huddleFilesOf = (ev: Record<string, unknown>): SlackFileRef[] =>
((ev.files as SlackFileRef[] | undefined) ?? []).filter((f) => /huddle|vnd\.slack-docs/i.test(`${f.name ?? ""} ${f.mimetype ?? ""} ${f.filetype ?? ""}`));
/**
* Заметки Huddle Slack прикрепляет к родительскому сообщению (subtype huddle_thread) правкой - приходит message_changed.
* Правка с файлами заметок превращается в обычное сообщение того же ts (дубли отсекает журнал); прочие правки не обрабатываются.
*/
export function normalizeHuddleEvent(ev: Record<string, unknown>): Record<string, unknown> | null {
if (ev.subtype !== "message_changed") return ev;
const inner = ev.message as Record<string, unknown> | undefined;
if (!inner || !huddleFilesOf(inner).length) return null;
return { ...inner, type: "message", channel: ev.channel };
}
/** Приём сообщений Slack: фильтр, журнал (защита от дублей), накопление сообщений менеджера (debounce) и запуск шага 4. */
export class SlackIntake {
private pending = new Map<string, Pending>();
private inflight = new Set<Promise<void>>();
private followups = new Map<string, NodeJS.Timeout>();
private recapTimers = new Map<string, NodeJS.Timeout>();
constructor(
private deps: ChatDeps,
private opts: { channelIds: string[]; debounceMs: number; followupMs?: number },
private opts: { channelIds: string[]; debounceMs: number; followupMs?: number; recapSilenceMs?: number; recapFromHour?: number; recapToHour?: number },
) {}
private get pool(): Pool {
@@ -62,19 +79,26 @@ export class SlackIntake {
private async handle(ev: Record<string, unknown>): Promise<void> {
if (ev.type !== "message") return;
const norm = normalizeHuddleEvent(ev);
if (!norm) return;
ev = norm;
const channel = String(ev.channel ?? "");
const user = String(ev.user ?? "");
const ts = String(ev.ts ?? "");
if (!channel || !ts) return;
const project = await this.findProjectByChannel(channel);
if (project) return this.handleProjectEvent(ev, project);
if (ev.bot_id || !user || !ACCEPTED_SUBTYPES.has(ev.subtype as string | undefined)) return;
const huddle = ev.subtype === "huddle_thread" || huddleFilesOf(ev).length > 0;
if (huddle) {
// заметки Huddle от Slackbot: принимаются только с вложениями; "AI huddle notes are ready" без файлов и прочие сообщения Slackbot - нет
if (!((ev.files as unknown[] | undefined)?.length)) return;
} else if (ev.bot_id || !user || user === "USLACKBOT" || !ACCEPTED_SUBTYPES.has(ev.subtype as string | undefined)) return;
// чат менеджера: пишет любой участник канала, обрабатывается как сообщение менеджера (отправитель сохраняется в журнале)
let manager = await this.findManagerByChannel(channel);
if (!manager && this.opts.channelIds.includes(channel)) manager = await this.findManagerBySlackUser(user);
if (!manager && this.opts.channelIds.includes(channel) && user) manager = await this.findManagerBySlackUser(user);
if (!manager) return;
const files = ((ev.files as { id?: string }[] | undefined) ?? []).map((f) => String(f.id)).filter(Boolean);
await this.accept(manager, { channel, ts, text: String(ev.text ?? ""), fileIds: files, senderUserId: user });
await this.accept(manager, { channel, ts, text: (huddle ? "[Slack huddle: заметки и расшифровка во вложениях] " : "") + String(ev.text ?? ""), fileIds: files, senderUserId: user || undefined });
}
/** Проектный канал: проект определяется каналом (таблица project_channel). */
@@ -97,7 +121,7 @@ export class SlackIntake {
const rawFiles = (ev.files as { id?: string; name?: string; mimetype?: string; filetype?: string }[] | undefined) ?? [];
const huddleFiles = rawFiles.filter((f) => /huddle|vnd\.slack-docs/i.test(`${f.name ?? ""} ${f.mimetype ?? ""} ${f.filetype ?? ""}`));
const isHuddle = ev.subtype === "huddle_thread" || huddleFiles.length > 0;
if (ev.bot_id && !isHuddle) return; // собственные ответы и прочие боты
if ((ev.bot_id || user === "USLACKBOT") && !isHuddle) return; // собственные ответы, прочие боты и служебные сообщения Slackbot ("AI huddle notes are ready")
if (!isHuddle && !ACCEPTED_SUBTYPES.has(ev.subtype as string | undefined)) return;
if (isHuddle && !rawFiles.length) return; // "A huddle started" без материалов
const sender = user ? (await this.pool.query("select id, display_name from person where slack_user_id = $1 and is_active", [user])).rows[0] : undefined;
@@ -115,7 +139,57 @@ export class SlackIntake {
const manager = (await this.findManagerByPerson(String(owner.id))) ?? { personId: String(owner.id), name: String(owner.display_name), slackUserId: null, slackChannelId: channel };
const ctx: ProjectContext = { jobId: project.jobId, jobName: project.jobName, channel, senderName: (sender?.display_name as string | undefined) ?? null, isHuddle };
const text = (isHuddle ? "[Slack huddle: заметки и расшифровка во вложениях] " : "") + String(ev.text ?? "");
await this.accept({ ...manager, slackChannelId: channel }, { channel, ts, text, fileIds: rawFiles.map((f) => String(f.id)).filter(Boolean), senderUserId: user || undefined, project: ctx });
const accepted = await this.accept({ ...manager, slackChannelId: channel }, { channel, ts, text, fileIds: rawFiles.map((f) => String(f.id)).filter(Boolean), senderUserId: user || undefined, project: ctx });
if (accepted) this.scheduleRecap(channel, { ...manager, slackChannelId: channel }, ctx);
}
/** Проектный канал: через recapSilenceMinutes после последнего сообщения людей агент решает, спрашивать ли про Daily Log. */
scheduleRecap(channel: string, manager: ManagerInfo, ctx: ProjectContext, delayMs?: number): void {
const silence = this.opts.recapSilenceMs;
if (!silence) return;
clearTimeout(this.recapTimers.get(channel));
const t = setTimeout(() => {
this.recapTimers.delete(channel);
this.track(this.runRecap(channel, manager, ctx).catch((e) => this.deps.ctx.log.error({ channel, err: String(e) }, "recap проектного канала не удался")));
}, delayMs ?? silence);
this.recapTimers.set(channel, t);
}
private async runRecap(channel: string, manager: ManagerInfo, ctx: ProjectContext): Promise<void> {
const now = (this.deps.now ?? (() => new Date()))();
const st = await getRecapState(this.pool, channel);
if (!st || st.status === "asked" || !st.notes.trim()) return;
if (promptSideFor(this.deps.ctx, manager.personId) !== "proposed") return; // recap - только у новой версии агента
if (now.getTime() - st.lastHumanAt.getTime() > 36 * 3600_000) {
await this.pool.query("delete from channel_recap_state where channel_id = $1", [channel]); // устарело: молча сбрасываем, не тревожим людей
return;
}
if ((await pauseState(this.pool, manager.personId)).paused) return;
const wait = recapDelayMs(now, this.deps.timezone, this.opts.recapFromHour, this.opts.recapToHour);
if (wait > 0) return this.scheduleRecap(channel, manager, ctx, wait + 1000);
await handleManagerMessages(this.deps, manager, [], {
systemEvent: loadFragment("p-chat-events.md", "Беседа в проектном канале затихла", {}, promptSideFor(this.deps.ctx, manager.personId)),
project: ctx,
channel,
});
const after = await getRecapState(this.pool, channel);
if (after && after.status === "collecting") {
// агент решил подождать (например, последняя реплика - вопрос к кому-то): ещё до трёх попыток через тот же интервал
if (after.attempts >= 3) return;
await this.pool.query("update channel_recap_state set attempts = attempts + 1 where channel_id = $1", [channel]);
this.scheduleRecap(channel, manager, ctx);
}
}
/** После перезапуска сервиса: восстанавливает таймеры recap для каналов с накопленным. */
async restoreRecapTimers(): Promise<void> {
const { rows } = await this.pool.query("select channel_id, job_id, manager_person_id from channel_recap_state where status = 'collecting' and notes <> ''");
for (const r of rows) {
const proj = await this.findProjectByChannel(String(r.channel_id));
const mgr = r.manager_person_id ? await this.findManagerByPerson(String(r.manager_person_id)) : null;
if (!proj || !mgr) continue;
this.scheduleRecap(String(r.channel_id), { ...mgr, slackChannelId: String(r.channel_id) }, { jobId: proj.jobId, jobName: proj.jobName, channel: String(r.channel_id), senderName: null, isHuddle: false });
}
}
async findManagerByPerson(personId: string): Promise<ManagerInfo | null> {
@@ -238,5 +312,7 @@ export class SlackIntake {
this.pending.clear();
for (const t of this.followups.values()) clearTimeout(t);
this.followups.clear();
for (const t of this.recapTimers.values()) clearTimeout(t);
this.recapTimers.clear();
}
}

View File

@@ -0,0 +1,161 @@
import type { Pool } from "khb_common";
import type { SlackApi, SlackHistoryMessage } from "./api.js";
/**
* Проектные каналы: ассистент молчит, пока люди общаются между собой, копит факты для Daily Log (таблица channel_recap_state)
* и по тишине (или после заметок Huddle) одним сообщением спрашивает "Should I add this to the Daily Log?".
*/
export type RecapStatus = "collecting" | "asked";
export interface RecapState {
channelId: string;
jobId: string | null;
notes: string;
status: RecapStatus;
lastHumanAt: Date;
askedAt: Date | null;
attempts: number;
}
/** Время в формате "10/21 14:05" по часовому поясу tz. */
export function stampLocal(d: Date, tz: string): string {
const p = new Intl.DateTimeFormat("en-US", { timeZone: tz, month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hourCycle: "h23", weekday: "short" }).formatToParts(d);
const g = (k: string) => p.find((x) => x.type === k)?.value ?? "";
return `${g("weekday")} ${g("month")}/${g("day")} ${g("hour")}:${g("minute")}`;
}
/** Диалог канала для агента: время по Тампе, автор, текст; упоминания заменены именами; сообщения бота помечены. */
export function formatChannelDialog(
msgs: SlackHistoryMessage[],
opts: { tz: string; botUserId: string | null; names: Map<string, string> },
): string {
if (!msgs.length) return "(за последние сутки сообщений нет)";
const who = (id: string | null) => (id ? (opts.names.get(id) ?? id) : "?");
const resolve = (t: string) => t.replace(/<@([UW][A-Z0-9]+)>/g, (_m, id: string) => `@${who(id)}`).replace(/<!channel>|<!here>|<!everyone>/g, "@channel");
return msgs
.map((m) => {
const fromBot = (m.userId && m.userId === opts.botUserId) || (m.botId && !m.userId);
const author = fromBot ? "ASSISTANT (ты)" : m.botId && m.userId ? `${who(m.userId)} (бот)` : who(m.userId);
const thread = m.threadTs && m.threadTs !== m.ts ? " (в треде)" : "";
const files = m.fileNames.length ? ` [файлы: ${m.fileNames.join(", ")}]` : "";
return `- [${stampLocal(new Date(Number(m.ts) * 1000), opts.tz)}] (ts ${m.ts}) ${author}${thread}: ${resolve(m.text).replace(/\n/g, " ⏎ ").trim() || "(без текста)"}${files}`;
})
.join("\n");
}
/** Загружает диалог канала за последние hours часов (по умолчанию сутки). Сбой Slack - пустая строка-заглушка, обработка не останавливается. */
export async function loadChannelDialog(
slack: Pick<SlackApi, "history" | "userName" | "botUserId">,
channel: string,
now: Date,
tz: string,
hours = 24,
): Promise<string> {
if (!slack.history) return "(история канала недоступна)";
try {
const msgs = await slack.history(channel, Math.floor(now.getTime() / 1000) - hours * 3600);
const names = new Map<string, string>();
if (slack.userName) {
const ids = new Set<string>();
for (const m of msgs) {
if (m.userId) ids.add(m.userId);
for (const x of m.text.matchAll(/<@([UW][A-Z0-9]+)>/g)) ids.add(x[1]!);
}
for (const id of ids) {
const n = await slack.userName(id);
if (n) names.set(id, n);
}
}
return formatChannelDialog(msgs, { tz, botUserId: (await slack.botUserId?.()) ?? null, names });
} catch (e) {
return `(история канала не загрузилась: ${e instanceof Error ? e.message : String(e)})`;
}
}
export async function getRecapState(pool: Pool, channel: string): Promise<RecapState | null> {
const { rows } = await pool.query("select channel_id, job_id, notes, status, last_human_at, asked_at, attempts from channel_recap_state where channel_id = $1", [channel]);
const r = rows[0];
return r
? { channelId: String(r.channel_id), jobId: (r.job_id as string | null) ?? null, notes: String(r.notes), status: r.status === "asked" ? "asked" : "collecting", lastHumanAt: new Date(r.last_human_at as string), askedAt: r.asked_at ? new Date(r.asked_at as string) : null, attempts: Number(r.attempts) }
: null;
}
/** Раздел `## Реакции`: строки `<ts> <эмодзи>` (например `1729612345.000100 memo`). */
export function parseReactions(v: string | undefined): { ts: string; emoji: string }[] {
const out: { ts: string; emoji: string }[] = [];
for (const line of sectionText(v).split(/\r?\n/)) {
const m = line.match(/(\d{9,11}\.\d{3,6})\s+:?([a-z0-9_+\-]+):?/i);
if (m) out.push({ ts: m[1]!, emoji: m[2]!.toLowerCase() });
}
return out.slice(0, 20);
}
/** Блок входа агента: что накоплено и спрошено в этом канале. */
export function recapBlock(st: RecapState | null, tz: string): string {
if (!st || !st.notes.trim()) return "(ничего не накоплено, вопрос про Daily Log не задавался)";
const head =
st.status === "asked"
? `Вопрос про Daily Log уже задан (${stampLocal(st.askedAt ?? st.lastHumanAt, tz)}), ждём ответ участников.`
: `Вопрос про Daily Log ещё не задавался. Последнее сообщение людей: ${stampLocal(st.lastHumanAt, tz)}.`;
return `${head}\nНакопленное:\n${st.notes.trim()}`;
}
const EMPTY = /^\(?\s*(нет|none|-|—|пусто|nothing)\s*\)?\.?$/i;
/** Значение раздела вывода агента: пустые варианты («нет», «(нет)») считаются отсутствием. */
export function sectionText(v: string | undefined): string {
const t = (v ?? "").trim();
return !t || EMPTY.test(t) ? "" : t;
}
export type RecapOutcome = "asked" | "recorded" | "discarded" | "collecting";
/** Разбор раздела `## Статус recap`: asked / recorded / discarded / collecting (по первому слову, русские варианты тоже). */
export function parseRecapStatus(v: string | undefined): RecapOutcome | null {
const t = sectionText(v).toLowerCase();
if (!t) return null;
if (/^(asked|спрошено|вопрос задан)/.test(t)) return "asked";
if (/^(recorded|written|записано|записан)/.test(t)) return "recorded";
if (/^(discarded|отброшено|отклонено|declined)/.test(t)) return "discarded";
if (/^(collecting|копим|накоплен|ждём|ждем|wait)/.test(t)) return "collecting";
return null;
}
/** Применяет разделы `## Накопить для Daily Log` и `## Статус recap` ответа агента к состоянию канала. */
export async function applyRecapOutput(
pool: Pool,
p: { channel: string; managerId: string; jobId: string; sections: Map<string, string>; humanMessage: boolean; now: Date },
): Promise<{ outcome: RecapOutcome | null; hasNotes: boolean }> {
const add = sectionText(p.sections.get("накопить для daily log"));
const outcome = parseRecapStatus(p.sections.get("статус recap"));
if (outcome === "recorded" || outcome === "discarded") {
await pool.query("delete from channel_recap_state where channel_id = $1", [p.channel]);
return { outcome, hasNotes: false };
}
const cur = await getRecapState(pool, p.channel);
if (!add && !cur) return { outcome, hasNotes: false };
// новые факты после вопроса про Daily Log - снова сбор (вопрос задаётся заново позже), если агент не сказал asked
const status: RecapStatus = outcome === "asked" ? "asked" : add ? "collecting" : (cur?.status ?? "collecting");
const notes = [cur?.notes.trim(), add].filter(Boolean).join("\n");
await pool.query(
`insert into channel_recap_state (channel_id, manager_person_id, job_id, notes, status, last_human_at, asked_at, attempts, updated_at)
values ($1,$2,$3,$4,$5,$6,$7,0,now())
on conflict (channel_id) do update set manager_person_id = $2, job_id = $3, notes = $4, status = $5,
last_human_at = case when $8 then $6 else channel_recap_state.last_human_at end,
asked_at = case when $5 = 'asked' then coalesce($7, channel_recap_state.asked_at) else null end,
attempts = case when $5 = 'asked' or $8 then 0 else channel_recap_state.attempts end, updated_at = now()`,
[p.channel, p.managerId, p.jobId, notes, status, p.now, status === "asked" ? p.now : null, p.humanMessage],
);
return { outcome, hasNotes: true };
}
/** Окно, когда можно задавать вопрос про Daily Log: 7:00-19:00 по Тампе. Возвращает задержку (мс) до ближайшего разрешённого момента (0 - можно сейчас). */
export function recapDelayMs(now: Date, tz: string, fromHour = 7, toHour = 19): number {
const p = new Intl.DateTimeFormat("en-US", { timeZone: tz, hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23" }).formatToParts(now);
const g = (k: string) => Number(p.find((x) => x.type === k)?.value ?? 0);
const secOfDay = g("hour") * 3600 + g("minute") * 60 + g("second");
if (secOfDay >= fromHour * 3600 && secOfDay < toHour * 3600) return 0;
const target = secOfDay < fromHour * 3600 ? fromHour * 3600 : 24 * 3600 + fromHour * 3600;
return (target - secOfDay) * 1000;
}