801 lines
63 KiB
TypeScript
801 lines
63 KiB
TypeScript
import { writeFileSync } from "node:fs";
|
||
import { join } from "node:path";
|
||
import { tmpdir } from "node:os";
|
||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||
import { createLogger, createTestDb, testDatabaseUrl, type TestDb } from "khb_common";
|
||
import { UsageLog } from "./usage.js";
|
||
import { ClaudeError, type ClaudeCall, type ClaudeResult } from "./agents/cli-runner.js";
|
||
import { KeyedMutex, Semaphore } from "./agents/pool.js";
|
||
import { parseSections } from "./agents/sections.js";
|
||
import { AgentFailure, closeOrphanRuns, runManagerAgent, type AgentContext } from "./agents/session.js";
|
||
import { runStep2, saveProblems } from "./agents/step2.js";
|
||
import Fastify from "fastify";
|
||
import { registerAgentRoutes } from "./agents-api.js";
|
||
import { buildApi } from "./http-api.js";
|
||
import { listManagers } from "./managers.js";
|
||
import { pauseState } from "./pause.js";
|
||
import { handleManagerMessages } from "./slack/chat.js";
|
||
import { TodoEventPoller } from "./slack/todo-events.js";
|
||
import { createServer } from "node:http";
|
||
import type { DriveClient } from "./gdrive/client.js";
|
||
import { DriveInbox } from "./slack/drive-inbox.js";
|
||
import { SlackIntake } from "./slack/intake.js";
|
||
|
||
describe("разбор разделов ответа агента", () => {
|
||
it("делит по ## и игнорирует регистр", () => {
|
||
const s = parseSections("вступление\n## Список\n1. a\n2. b\n\n## ПАМЯТЬ\nm\n### вложенный\nx");
|
||
expect(s.get("список")).toBe("1. a\n2. b");
|
||
expect(s.get("память")).toBe("m\n### вложенный\nx");
|
||
});
|
||
});
|
||
|
||
describe("пул и очередь", () => {
|
||
it("Semaphore ограничивает параллельность, KeyedMutex - по ключу последовательно", async () => {
|
||
const sem = new Semaphore(2);
|
||
let active = 0;
|
||
let peak = 0;
|
||
await Promise.all(Array.from({ length: 6 }, () => sem.run(async () => { active++; peak = Math.max(peak, active); await new Promise((r) => setTimeout(r, 10)); active--; })));
|
||
expect(peak).toBe(2);
|
||
const m = new KeyedMutex();
|
||
const order: string[] = [];
|
||
await Promise.all([
|
||
m.run("k", async () => { await new Promise((r) => setTimeout(r, 20)); order.push("a"); }),
|
||
m.run("k", async () => { order.push("b"); }),
|
||
]);
|
||
expect(order).toEqual(["a", "b"]);
|
||
});
|
||
});
|
||
|
||
const url = testDatabaseUrl();
|
||
const d = url ? describe : describe.skip;
|
||
const MGR = "00000000-0000-0000-0000-0000000000a1";
|
||
|
||
d("консольные агенты (временная БД, фейковый claude)", () => {
|
||
let db: TestDb;
|
||
let calls: ClaudeCall[];
|
||
let script: ((c: ClaudeCall, n: number) => Promise<ClaudeResult>)[];
|
||
const it_messages: string[] = [];
|
||
let usageLog: UsageLog;
|
||
const ctx = (): AgentContext => ({
|
||
pool: db.pool, log: createLogger("test", "silent"),
|
||
usageLog,
|
||
settings: { concurrency: 2, claudeBin: "claude", workRoot: tmpdir() + "/llmtest-agents", timeoutMs: 1000, maxFixRetries: 2, allowedJobIds: ["llmtest-job"], connectorRetry: { windowSeconds: 0, pauseSeconds: 0 } },
|
||
runner: async (c) => { calls.push(c); const fn = script.shift(); if (!fn) throw new Error("нет сценария"); return fn(c, calls.length); },
|
||
gate: new Semaphore(2), locks: new KeyedMutex(),
|
||
notifyIt: async (t) => { it_messages.push(t); },
|
||
});
|
||
const ok = (text: string) => async (c: ClaudeCall): Promise<ClaudeResult> => ({ text, sessionId: c.sessionId });
|
||
|
||
beforeAll(async () => {
|
||
db = await createTestDb(url!);
|
||
usageLog = new UsageLog(db.pool, createLogger("test", "silent"));
|
||
await db.pool.query("insert into person (id, display_name, jt_membership_id, slack_user_id) values ($1,'llmtest-Manager','m1','ULLMTEST')", [MGR]);
|
||
await db.pool.query("insert into construction_manager (person_id, slack_user_id, slack_channel_id) values ($1,'ULLMTEST','CLLMTEST')", [MGR]);
|
||
await db.pool.query("delete from agent_passive_window"); // миграция сеет вторник; результаты тестов не должны зависеть от дня недели
|
||
});
|
||
afterAll(async () => { await db?.drop(); });
|
||
|
||
it("потерянная сессия: стартует новая сессия с тем же промтом", async () => {
|
||
calls = [];
|
||
await db.pool.query("insert into agent_manager_memory (manager_person_id, claude_session_id) values ($1,'11111111-1111-4111-8111-111111111111') on conflict (manager_person_id) do update set claude_session_id = excluded.claude_session_id", [MGR]);
|
||
script = [async () => { throw new ClaudeError("No conversation found with session ID", "no_session"); }, ok("## Список\nx\n## Память\ny")];
|
||
const out = await runManagerAgent(ctx(), { managerId: MGR, step: "step2", tools: "none", prompt: "P", required: ["список", "память"] });
|
||
expect(calls).toHaveLength(2);
|
||
expect(calls[0]).toMatchObject({ resume: true, sessionId: "11111111-1111-4111-8111-111111111111" });
|
||
expect(calls[1]!.resume).toBe(false);
|
||
expect(calls[1]!.sessionId).not.toBe(calls[0]!.sessionId);
|
||
expect(calls[1]!.prompt).toBe("P");
|
||
const saved = await db.pool.query("select claude_session_id from agent_manager_memory where manager_person_id = $1", [MGR]);
|
||
expect(saved.rows[0].claude_session_id).toBe(out.sessionId);
|
||
});
|
||
|
||
it("сессия продолжается (resume) только при живом процессе или после сбоя; если прошлый запуск успешен - новая сессия с памятью в полном промте", async () => {
|
||
const SID = "22222222-2222-4222-8222-222222222222";
|
||
const setRun = async (status: string) =>
|
||
(await db.pool.query("insert into agent_run (manager_person_id, step, attempt, session_id, resumed, status, started_at) values ($1,'step2',1,$2,false,$3, now() + interval '1 hour') returning id", [MGR, SID, status])).rows[0].id as string;
|
||
await db.pool.query("update agent_manager_memory set claude_session_id = $2 where manager_person_id = $1", [MGR, SID]);
|
||
// прошлый запуск успешен: память сохранена, resume не нужен, короткий промт заменяется полным
|
||
let id = await setRun("ok");
|
||
calls = [];
|
||
script = [ok("## Ответ менеджеру\nx\n## Память\ny")];
|
||
await runManagerAgent(ctx(), { managerId: MGR, step: "step2", tools: "none", prompt: "short", fullPrompt: "FULL", required: ["память"] });
|
||
expect(calls[0]).toMatchObject({ resume: false, prompt: "FULL" });
|
||
expect(calls[0]!.sessionId).not.toBe(SID);
|
||
await db.pool.query("delete from agent_run where id = $1", [id]);
|
||
// прошлый запуск упал: память не обновилась, продолжаем сессию
|
||
await db.pool.query("update agent_manager_memory set claude_session_id = $2 where manager_person_id = $1", [MGR, SID]);
|
||
id = await setRun("failed");
|
||
calls = [];
|
||
script = [ok("## Ответ менеджеру\nx\n## Память\ny")];
|
||
await runManagerAgent(ctx(), { managerId: MGR, step: "step2", tools: "none", prompt: "short", fullPrompt: "FULL", required: ["память"] });
|
||
expect(calls[0]).toMatchObject({ resume: true, sessionId: SID, prompt: "short" });
|
||
await db.pool.query("delete from agent_run where id = $1", [id]);
|
||
});
|
||
|
||
it("нет обязательного раздела: просит исправить формат в той же сессии, затем принимает", async () => {
|
||
calls = [];
|
||
script = [ok("просто текст"), ok("## Список\nx\n## Память\ny")];
|
||
const out = await runManagerAgent(ctx(), { managerId: MGR, step: "step2", tools: "none", prompt: "P", required: ["список", "память"] });
|
||
expect(out.attempts).toBe(2);
|
||
expect(calls[1]).toMatchObject({ resume: true });
|
||
expect(calls[1]!.prompt).toContain("не принят");
|
||
expect(calls[1]!.sessionId).toBe(calls[0]!.sessionId);
|
||
});
|
||
|
||
it("после исчерпания повторов - сбой, шаг 2 уведомляет ИТ и не пишет список", async () => {
|
||
calls = [];
|
||
it_messages.length = 0;
|
||
script = [ok("плохо 1"), ok("плохо 2"), ok("плохо 3")];
|
||
await expect(runManagerAgent(ctx(), { managerId: MGR, step: "step2", tools: "none", prompt: "P", required: ["список"] })).rejects.toBeInstanceOf(AgentFailure);
|
||
expect(calls).toHaveLength(3);
|
||
|
||
calls = [];
|
||
script = [ok("плохо 1"), ok("плохо 2"), ok("плохо 3")];
|
||
const pkg = (await db.pool.query("select gen_random_uuid() as id")).rows[0].id as string;
|
||
const r = await runStep2(ctx(), MGR, "llmtest-Manager", [pkg], "2026-10-14");
|
||
expect(r.status).toBe("failed");
|
||
expect(it_messages.some((m) => m.includes("шаг 2") && m.includes("llmtest-Manager"))).toBe(true);
|
||
const lists = await db.pool.query("select count(*)::int n from manager_day_list");
|
||
expect(lists.rows[0].n).toBe(0);
|
||
});
|
||
|
||
it("шаг 2: пишет проблемы агента (обращение в ИТ - в Slack ИТ, лог - в журнал)", async () => {
|
||
calls = [];
|
||
it_messages.length = 0;
|
||
script = [ok("## Список\n1. llmtest-задача\n## Память\nм\n## Обращение в ИТ\nllmtest нет доступа к X\n## Лог проблем\nllmtest мелочь")];
|
||
const pkg = (await db.pool.query("insert into assistant_project (jt_job_id, manager_person_id) values ('llmtest-job',$1) returning id", [MGR])).rows[0].id as string;
|
||
const p = (await db.pool.query("insert into ap_input_package (assistant_project_id, package_date, kind, content_hash, item_count) values ($1,'2026-10-14','morning','h',0) returning id", [pkg])).rows[0].id as string;
|
||
const r = await runStep2(ctx(), MGR, "llmtest-Manager", [p], "2026-10-14");
|
||
expect(r.status).toBe("ok");
|
||
const log = await db.pool.query("select severity from agent_problem_log order by severity");
|
||
expect(log.rows.map((x) => x.severity)).toEqual(["it_request", "log"]);
|
||
expect(it_messages.some((m) => m.includes("llmtest нет доступа"))).toBe(true);
|
||
});
|
||
|
||
it("шаг 4: сообщения менеджера с вложением -> агент -> ответ в Slack, память, изменения", async () => {
|
||
calls = [];
|
||
const posted: { channel: string; text: string }[] = [];
|
||
const downloads: string[] = [];
|
||
script = [ok("## Ответ менеджеру\nПринял, спасибо! llmtest\n## Память\nпамять-4\n## Изменения JobTread\ncreateDailyLog llmtest-")];
|
||
const deps = {
|
||
ctx: ctx(),
|
||
timezone: "America/New_York",
|
||
slack: {
|
||
postMessage: async (channel: string, text: string) => { posted.push({ channel, text }); return true; },
|
||
fileInfo: async (id: string) => ({ id, name: "voice.m4a", mimetype: "audio/mp4", size: 3, urlPrivateDownload: "https://llmtest.invalid/f" }),
|
||
download: async (f: { name: string }, to: string) => { downloads.push(to); const { writeFileSync } = await import("node:fs"); writeFileSync(to, "abc"); return 3; },
|
||
},
|
||
drive: { upload: async () => ({ "slack_F1_voice.m4a": "https://drive.google.com/file/d/llmtest/view" }) },
|
||
};
|
||
const mgr = { personId: MGR, name: "llmtest-Manager", slackUserId: "ULLMTEST", slackChannelId: "CLLMTEST" };
|
||
const res = await handleManagerMessages(deps, mgr, [{ channel: "CLLMTEST", ts: "1791741165.045849", text: "вот отчёт", fileIds: ["F1"] }]);
|
||
expect(res.reply).toContain("Принял");
|
||
expect(posted).toEqual([{ channel: "CLLMTEST", text: expect.stringContaining("Принял") }]);
|
||
expect(downloads).toHaveLength(1);
|
||
expect(calls[0]).toMatchObject({ tools: "chat" });
|
||
expect(calls[0]!.prompt).toContain("вот отчёт");
|
||
expect(calls[0]!.prompt).toContain("slack_F1_voice.m4a");
|
||
expect(calls[0]!.prompt).toContain("https://drive.google.com/file/d/llmtest/view");
|
||
expect(calls[0]!.prompt).toContain("llmtest-job"); // ограничение на проекты
|
||
const mem = await db.pool.query("select memory_text from agent_manager_memory where manager_person_id = $1", [MGR]);
|
||
expect(mem.rows[0].memory_text).toBe("память-4");
|
||
const run = await db.pool.query("select changes from agent_run where step = 'step4' and status = 'ok'");
|
||
expect(run.rows[0].changes).toContain("createDailyLog");
|
||
});
|
||
|
||
it("отключённый проект: агенту сказано не общаться по нему, запись в него не разрешена", async () => {
|
||
calls = [];
|
||
await db.pool.query("update assistant_project set is_enabled = false where jt_job_id = 'llmtest-job'");
|
||
await db.pool.query("insert into assistant_project (jt_job_id, manager_person_id, mode, is_enabled) values ('llmtest-job-on',$1,'test',true)", [MGR]);
|
||
try {
|
||
script = [ok("## Ответ менеджеру\n(без ответа)\n## Память\nм\n## Изменения JobTread\nнет")];
|
||
const deps = { ctx: ctx(), timezone: "America/New_York", slack: { postMessage: async () => true, fileInfo: async () => null, download: async () => 0 } };
|
||
const mgr = { personId: MGR, name: "llmtest-Manager", slackUserId: "ULLMTEST", slackChannelId: "CLLMTEST" };
|
||
await handleManagerMessages({ ...deps, dryPublish: true }, mgr, [{ channel: "CLLMTEST", ts: "1791741200.000001", text: "про отключённый", fileIds: [] }]);
|
||
const p = calls[0]!.prompt;
|
||
expect(p).toContain("ОТКЛЮЧЁННЫЕ проекты");
|
||
expect(p).toContain("(llmtest-job)");
|
||
expect(p).toContain("Запись в JobTread запрещена");
|
||
} finally {
|
||
await db.pool.query("delete from assistant_project where jt_job_id = 'llmtest-job-on'");
|
||
await db.pool.query("update assistant_project set is_enabled = true where jt_job_id = 'llmtest-job'");
|
||
}
|
||
});
|
||
|
||
it("новая версия агента: только для менеджеров из agent.live.managerIds; в диалоге промт короткий (без инструкций, списка и памяти)", async () => {
|
||
calls = [];
|
||
const liveCalls: ClaudeCall[] = [];
|
||
let active = false;
|
||
let lastSid = "";
|
||
const liveRunner = {
|
||
run: async (c: ClaudeCall) => { liveCalls.push(c); active = true; lastSid = c.sessionId; return { text: "## Ответ менеджеру\n(без ответа)\n## Память\nлайв-память", sessionId: c.sessionId }; },
|
||
isActive: () => active, activeSession: () => (active ? lastSid : null), close: () => { active = false; }, closeAll: () => undefined, activeCount: () => (active ? 1 : 0),
|
||
};
|
||
const base = ctx();
|
||
const liveCtx = { ...base, liveRunner, settings: { ...base.settings, live: { managerIds: [MGR], idleMinutes: 10, warmupSeconds: 0 }, sql: { agentUrl: "postgres://ro-agent", ceoUrl: "postgres://ro-ceo" } } };
|
||
const slack = { postMessage: async () => true, fileInfo: async () => null, download: async () => 0 };
|
||
const mgr = { personId: MGR, name: "llmtest-Manager", slackUserId: "ULLMTEST", slackChannelId: "CLLMTEST" };
|
||
const msg = (text: string, ts: string) => [{ channel: "CLLMTEST", ts, text, fileIds: [] }];
|
||
await handleManagerMessages({ ctx: liveCtx, timezone: "America/New_York", slack, dryPublish: true }, mgr, msg("первое сообщение", "1791741300.000001"));
|
||
await handleManagerMessages({ ctx: liveCtx, timezone: "America/New_York", slack, dryPublish: true }, mgr, msg("второе сообщение", "1791741310.000001"));
|
||
expect(calls).toHaveLength(0); // прежний раннер не использовался
|
||
expect(liveCalls[0]!.env).toEqual({ KHB_SQL_URL: "postgres://ro-agent" }); // чтение Supabase: роль менеджеров
|
||
expect(liveCalls).toHaveLength(2);
|
||
expect(liveCalls[0]!.prompt).toContain("# Память");
|
||
expect(liveCalls[0]!.prompt).toContain("JobTread недоступен или запись не проходит");
|
||
expect(liveCalls[0]!.prompt).toMatch(/менеджер сегодня отвечал: (да|нет)/);
|
||
expect(liveCalls[0]!.prompt).toContain("Todo самого менеджера");
|
||
expect(liveCalls[0]!.prompt).toContain("его membership в JobTread: m1");
|
||
expect(liveCalls[1]!.prompt).toContain("# Продолжение диалога");
|
||
expect(liveCalls[1]!.prompt).toContain("второе сообщение");
|
||
expect(liveCalls[1]!.prompt).not.toContain("\n# Память\n");
|
||
expect(liveCalls[1]!.prompt).not.toContain("# Список задач на сегодня");
|
||
// менеджер не из списка: прежняя версия, полный промт каждый раз
|
||
script = [ok("## Ответ менеджеру\n(без ответа)\n## Память\nм")];
|
||
const other = { ...liveCtx, settings: { ...liveCtx.settings, live: { managerIds: ["other"], idleMinutes: 10, warmupSeconds: 0 } } };
|
||
await handleManagerMessages({ ctx: other, timezone: "America/New_York", slack, dryPublish: true }, mgr, msg("третье", "1791741320.000001"));
|
||
expect(liveCalls).toHaveLength(2);
|
||
expect(calls).toHaveLength(1);
|
||
expect(calls[0]!.prompt).toContain("# Память");
|
||
});
|
||
|
||
it("тайминг чата: строка chat_timing с этапами от сообщения в Slack до ответа в Slack", async () => {
|
||
calls = [];
|
||
const base = Math.floor(Date.now() / 1000) - 20; // относительно «сейчас»: фиксированная дата ломала бы int-поле debounce_ms через 24.8 суток
|
||
const reply = ["## Ответ менеджеру", "тайминг", "## Память", "м"].join(String.fromCharCode(10));
|
||
script = [async (c) => ({ text: reply, sessionId: c.sessionId, usage: { inputTokens: 12, outputTokens: 34, cacheReadTokens: 56, cacheCreationTokens: 7, model: "m-test" }, timing: { startMs: 50, turnMs: 1234, apiMs: 1000, numTurns: 3, toolCalls: 2 } })];
|
||
await db.pool.query("delete from chat_timing");
|
||
await db.pool.query("insert into slack_message_log (channel_id, message_ts, manager_person_id, status, received_at) values ('CLLMTEST',$2,$1,'received', to_timestamp($3))", [MGR, `${base}.000001`, base + 1.5]);
|
||
const slack = { postMessage: async () => true, postMessageTs: async () => `${base + 9}.000100`, fileInfo: async () => null, download: async () => 0 };
|
||
const mgr = { personId: MGR, name: "llmtest-Manager", slackUserId: "ULLMTEST", slackChannelId: "CLLMTEST" };
|
||
await handleManagerMessages({ ctx: ctx(), timezone: "America/New_York", slack }, mgr, [{ channel: "CLLMTEST", ts: `${base}.000001`, text: "замер", fileIds: [] }]);
|
||
const r = (await db.pool.query("select * from chat_timing")).rows;
|
||
expect(r).toHaveLength(1);
|
||
// учёт токенов: вызов попал в память, пачкой ушёл в agent_usage с операцией chat:manager
|
||
await usageLog.flush();
|
||
const u = (await db.pool.query("select * from agent_usage where manager_person_id = $1 order by id desc limit 1", [MGR])).rows[0];
|
||
expect(u).toMatchObject({ op: "chat:manager", ok: true, live: false, model: "m-test", input_tokens: 12, output_tokens: 34, cache_read_tokens: 56, cache_creation_tokens: 7, num_turns: 3 });
|
||
expect(r[0]).toMatchObject({ kind: "message", agent_version: "classic", status: "ok", reply_slack_ts: `${base + 9}.000100`, slack_in_ms: 1500, total_ms: 9000, model_ms: 1234, start_ms: 50, api_ms: 1000, num_turns: 3, tool_calls: 2, attempts: 1 });
|
||
expect(r[0].cost_usd).toBeNull(); // деньги не ведём: тариф Team считает проценты окон, а не доллары
|
||
for (const k of ["inputs_ms", "drive_ms", "prompt_ms", "queue_ms", "post_ms", "publish_ms", "final_ms", "processing_ms"]) expect(r[0][k], k).not.toBeNull();
|
||
expect(r[0].prompt_chars).toBeGreaterThan(100);
|
||
expect(r[0].steps.runs).toHaveLength(1);
|
||
});
|
||
|
||
it("отключение агента: на время и до команды; события и сообщения менеджера не идут, после включения всё работает", async () => {
|
||
calls = [];
|
||
const app = Fastify();
|
||
registerAgentRoutes(app, db.pool);
|
||
await db.pool.query("insert into assistant_project (jt_job_id, manager_person_id, mode, is_enabled) values ('llmtest-pause',$1,'test',true)", [MGR]);
|
||
const ids = async (includePaused = false) => (await listManagers(db.pool, ["test"], { includePaused })).map((m) => m.personId);
|
||
const post = (url: string, payload?: object) => app.inject({ method: "POST", url, payload: payload ?? {} });
|
||
const nl = String.fromCharCode(10);
|
||
const intakeSend = async (ts: string, text: string) => {
|
||
const posted: string[] = [];
|
||
const deps = { ctx: ctx(), timezone: "America/New_York", slack: { postMessage: async (_c: string, x: string) => { posted.push(x); return true; }, fileInfo: async () => null, download: async () => 0 } };
|
||
const intake = new SlackIntake(deps, { channelIds: [], debounceMs: 600_000 });
|
||
await intake.onEvent({ type: "message", channel: "CLLMTEST", user: "ULLMTEST", ts, text });
|
||
await intake.flush(MGR);
|
||
await intake.idle();
|
||
intake.stop();
|
||
return posted;
|
||
};
|
||
try {
|
||
expect(await ids()).toContain(MGR);
|
||
|
||
// до команды владельца (срок не задан), режим passive по умолчанию: сам молчит, на сообщения отвечает
|
||
let r = await post("/agents/" + MGR + "/pause", { reason: "тест" });
|
||
expect(r.json()).toMatchObject({ ok: true, paused: true, mode: "passive", indefinite: true, until: null, reason: "тест" });
|
||
expect(await ids()).not.toContain(MGR); // системные события ему не идут
|
||
expect(await ids(true)).toContain(MGR); // ручные запуски владельца - идут
|
||
script = [ok(["## Ответ менеджеру", "ответ пассивного", "## Память", "м"].join(nl))];
|
||
expect(await intakeSend("7.0", "пишут пассивному")).toEqual(["ответ пассивного"]);
|
||
expect(calls).toHaveLength(1);
|
||
|
||
// режим off: вообще ничего, сообщение только фиксируется
|
||
calls = [];
|
||
r = await post("/agents/" + MGR + "/pause", { reason: "тест off", mode: "off" });
|
||
expect(r.json()).toMatchObject({ ok: true, paused: true, mode: "off", indefinite: true });
|
||
expect(await intakeSend("7.1", "сообщение отключённому")).toEqual([]);
|
||
expect(calls).toHaveLength(0); // агент не запускался
|
||
const ignored = await db.pool.query("select status from slack_message_log where message_ts = '7.1'");
|
||
expect(ignored.rows).toEqual([{ status: "ignored" }]);
|
||
const listed = ((await app.inject("/agents")).json() as Array<Record<string, unknown>>).find((a) => a.id === MGR);
|
||
expect(listed).toMatchObject({ paused: true, paused_indefinitely: true, pause_mode: "off" });
|
||
expect((await post("/agents/" + MGR + "/pause", { mode: "что-то" })).statusCode).toBe(400);
|
||
|
||
// включить обратно
|
||
r = await post("/agents/" + MGR + "/resume");
|
||
expect(r.json()).toMatchObject({ ok: true, paused: false });
|
||
expect(await ids()).toContain(MGR);
|
||
script = [ok(["## Ответ менеджеру", "после включения", "## Память", "м"].join(nl))];
|
||
expect(await intakeSend("7.2", "сообщение после включения")).toEqual(["после включения"]);
|
||
|
||
// на время
|
||
r = await post("/agents/" + MGR + "/pause", { hours: 2 });
|
||
const j = r.json() as { paused: boolean; indefinite: boolean; until: string };
|
||
expect(j).toMatchObject({ paused: true, indefinite: false });
|
||
expect(new Date(j.until).getTime() - Date.now()).toBeGreaterThan(1.9 * 3600_000);
|
||
expect(await ids()).not.toContain(MGR);
|
||
await db.pool.query("update construction_manager set paused_until = now() - interval '1 minute' where person_id = $1", [MGR]); // срок истёк
|
||
expect(await ids()).toContain(MGR);
|
||
expect((await post("/agents/" + MGR + "/pause", { until: "2020-01-01T00:00:00Z" })).statusCode).toBe(400);
|
||
expect((await post("/agents/" + MGR + "/pause", { until: "не дата" })).statusCode).toBe(400);
|
||
expect((await post("/agents/" + MGR + "/pause", { days: 4000 })).statusCode).toBe(400);
|
||
expect((await post("/agents/00000000-0000-4000-8000-000000000000/pause")).statusCode).toBe(404);
|
||
|
||
// все менеджеры
|
||
const all = (await post("/agents/pause-all", { reason: "общая остановка" })).json() as { managers: number };
|
||
expect(all.managers).toBeGreaterThanOrEqual(1);
|
||
expect(await ids()).not.toContain(MGR);
|
||
expect(((await post("/agents/resume-all")).json() as { managers: number }).managers).toBeGreaterThanOrEqual(1);
|
||
expect(await ids()).toContain(MGR);
|
||
} finally {
|
||
await db.pool.query("update construction_manager set agent_paused = false, paused_until = null where person_id = $1", [MGR]);
|
||
await db.pool.query("delete from assistant_project where jt_job_id = 'llmtest-pause'");
|
||
await app.close();
|
||
}
|
||
});
|
||
|
||
it("календарь пассивных окон: во вторник (по Тампе) события не идут никому, сообщения менеджеров обрабатываются как обычно", async () => {
|
||
calls = [];
|
||
const app = Fastify();
|
||
registerAgentRoutes(app, db.pool);
|
||
await db.pool.query("insert into assistant_project (jt_job_id, manager_person_id, mode, is_enabled) values ('llmtest-window',$1,'test',true)", [MGR]);
|
||
const TUE = new Date("2026-10-20T15:00:00Z"); // вторник 11:00 по Тампе
|
||
const TUE_LATE = new Date("2026-10-21T03:30:00Z"); // вторник 23:30 по Тампе (в UTC уже среда)
|
||
const MON = new Date("2026-10-19T15:00:00Z");
|
||
const WED = new Date("2026-10-21T04:30:00Z"); // среда 00:30 по Тампе
|
||
try {
|
||
const post = (url: string, payload: object) => app.inject({ method: "POST", url, payload });
|
||
expect((await post("/agents/passive-windows", { weekday: "tue", note: "встреча менеджеров" })).statusCode).toBe(200); // весь день
|
||
expect((await post("/agents/passive-windows", { weekday: 9 })).statusCode).toBe(400);
|
||
expect((await post("/agents/passive-windows", { weekday: "fri", from: "13:00", to: "12:00" })).statusCode).toBe(400);
|
||
expect((await post("/agents/passive-windows", { weekday: "fri", timezone: "Mars/Olympus" })).statusCode).toBe(400);
|
||
const ids = async (now: Date) => (await listManagers(db.pool, ["test"], { now })).map((m) => m.personId);
|
||
expect(await ids(MON)).toContain(MGR);
|
||
expect(await ids(TUE)).toEqual([]); // вторник: события не идут никому
|
||
expect(await ids(TUE_LATE)).toEqual([]); // вторник по Тампе, хотя в UTC уже среда
|
||
expect(await ids(WED)).toContain(MGR);
|
||
expect((await listManagers(db.pool, ["test"], { includePaused: true, now: TUE })).map((m) => m.personId)).toContain(MGR); // ручные запуски владельца идут
|
||
expect(await pauseState(db.pool, MGR, TUE)).toMatchObject({ paused: true, mode: "passive", by: "calendar" });
|
||
expect((await pauseState(db.pool, MGR, MON)).paused).toBe(false);
|
||
const w = (await app.inject("/agents/passive-windows")).json() as { windows: Array<{ id: string; weekday: number; fromMinute: number; toMinute: number }> };
|
||
expect(w.windows).toHaveLength(1);
|
||
expect(w.windows[0]).toMatchObject({ weekday: 2, fromMinute: 0, toMinute: 1440 });
|
||
// окно с интервалом
|
||
expect((await post("/agents/passive-windows", { weekday: "mon", from: "09:00", to: "12:00" })).statusCode).toBe(200);
|
||
expect(await ids(new Date("2026-10-19T14:00:00Z"))).toEqual([]); // понедельник 10:00
|
||
expect(await ids(new Date("2026-10-19T16:30:00Z"))).toContain(MGR); // понедельник 12:30
|
||
// удаление
|
||
expect((await app.inject({ method: "DELETE", url: "/agents/passive-windows/" + w.windows[0]!.id })).statusCode).toBe(200);
|
||
expect(await ids(TUE)).toContain(MGR);
|
||
// сообщение менеджера в пассивное окно обрабатывается как обычно
|
||
await post("/agents/passive-windows", { weekday: "tue" });
|
||
const nl = String.fromCharCode(10);
|
||
script = [ok(["## Ответ менеджеру", "ответ во вторник", "## Память", "м"].join(nl))];
|
||
const posted: string[] = [];
|
||
const deps = { ctx: ctx(), timezone: "America/New_York", slack: { postMessage: async (_c: string, x: string) => { posted.push(x); return true; }, fileInfo: async () => null, download: async () => 0 } };
|
||
const intake = new SlackIntake(deps, { channelIds: [], debounceMs: 600_000 });
|
||
await intake.onEvent({ type: "message", channel: "CLLMTEST", user: "ULLMTEST", ts: "8.1", text: "пишу во вторник" });
|
||
await intake.flush(MGR);
|
||
await intake.idle();
|
||
intake.stop();
|
||
expect(posted).toEqual(["ответ во вторник"]);
|
||
} finally {
|
||
await db.pool.query("delete from agent_passive_window");
|
||
await db.pool.query("delete from assistant_project where jt_job_id = 'llmtest-window'");
|
||
await app.close();
|
||
}
|
||
});
|
||
|
||
it("событие ассистента: напоминание пишется в историю, ответ менеджера закрывает его; через followup агент спрашивает `что-то ещё`", async () => {
|
||
calls = [];
|
||
const posted: string[] = [];
|
||
script = [
|
||
ok("## Ответ менеджеру\nПривет! Как дела на объекте? llmtest\n## Память\nм6"),
|
||
ok("## Ответ менеджеру\nСпасибо! llmtest\n## Память\nм7"),
|
||
ok("## Ответ менеджеру\nЧто-то ещё по llmtest-job?\n## Память\nм8"),
|
||
];
|
||
const deps = {
|
||
ctx: ctx(), timezone: "America/New_York",
|
||
slack: { postMessage: async (_c: string, t: string) => { posted.push(t); return true; }, fileInfo: async () => null, download: async () => 0 },
|
||
};
|
||
const mgr = { personId: MGR, name: "llmtest-Manager", slackUserId: "ULLMTEST", slackChannelId: "CLLMTEST" };
|
||
await handleManagerMessages(deps, mgr, [], { systemEvent: "12:00" });
|
||
const r1 = await db.pool.query("select reminder_text, reply_at from reminder_history where reminder_text like '%llmtest%'");
|
||
expect(r1.rows).toHaveLength(1);
|
||
expect(r1.rows[0].reply_at).toBeNull();
|
||
expect(calls[0]!.prompt).toContain("# Системное событие");
|
||
|
||
const intake = new SlackIntake(deps, { channelIds: ["CLLMTEST"], debounceMs: 600_000, followupMs: 300 });
|
||
await intake.onEvent({ type: "message", channel: "CLLMTEST", user: "ULLMTEST", ts: "2.1", text: "делаю, всё идёт хорошо" });
|
||
await intake.flush(MGR);
|
||
const r2 = await db.pool.query("select reply_summary, reply_outcome from reminder_history where reminder_text like '%llmtest%'");
|
||
expect(r2.rows[0]).toEqual({ reply_summary: "делаю, всё идёт хорошо", reply_outcome: "other" });
|
||
await new Promise((r) => setTimeout(r, 1500)); // сработал followup
|
||
await intake.idle();
|
||
intake.stop();
|
||
expect(calls).toHaveLength(3);
|
||
expect(calls[2]!.prompt).toContain("Что-то ещё по");
|
||
expect(posted[posted.length - 1]).toContain("Что-то ещё");
|
||
});
|
||
|
||
it("приём события Slack: фильтры, дубли, накопление и запуск шага 4", async () => {
|
||
calls = [];
|
||
const posted: string[] = [];
|
||
script = [ok("## Ответ менеджеру\nответ llmtest\n## Память\nм5")];
|
||
const deps = {
|
||
ctx: ctx(), timezone: "America/New_York",
|
||
slack: { postMessage: async (_c: string, t: string) => { posted.push(t); return true; }, fileInfo: async () => null, download: async () => 0 },
|
||
};
|
||
const intake = new SlackIntake(deps, { channelIds: [], debounceMs: 600_000 });
|
||
const ev = (over: Record<string, unknown>) => ({ type: "message", channel: "CLLMTEST", user: "ULLMTEST", ts: "1.1", text: "привет", ...over });
|
||
await intake.onEvent(ev({ bot_id: "B1", ts: "1.0" })); // бот
|
||
await intake.onEvent(ev({ user: "UOTHER", ts: "1.2", text: "от коллеги" })); // другой участник канала - как сообщение менеджера
|
||
await intake.onEvent(ev({ channel: "CELSE", ts: "1.3" })); // не тот канал
|
||
await intake.onEvent(ev({ subtype: "message_changed", ts: "1.4" }));
|
||
await intake.onEvent(ev({ ts: "1.5", text: "первое" }));
|
||
await intake.onEvent(ev({ ts: "1.5", text: "первое" })); // дубль события
|
||
await intake.onEvent(ev({ ts: "1.6", text: "второе" }));
|
||
await intake.flush(MGR); // вместо ожидания debounce
|
||
await intake.idle();
|
||
intake.stop();
|
||
expect(calls).toHaveLength(1); // два сообщения - один запуск
|
||
expect(calls[0]!.prompt).toContain("первое");
|
||
expect(calls[0]!.prompt).toContain("второе");
|
||
expect(calls[0]!.prompt).toContain("от коллеги");
|
||
expect(posted).toEqual(["ответ llmtest"]);
|
||
const log = await db.pool.query("select message_ts, status, sender_slack_user_id as sender from slack_message_log where message_ts like '1.%' order by message_ts");
|
||
expect(log.rows).toEqual([{ message_ts: "1.2", status: "done", sender: "UOTHER" }, { message_ts: "1.5", status: "done", sender: "ULLMTEST" }, { message_ts: "1.6", status: "done", sender: "ULLMTEST" }]);
|
||
});
|
||
it("обращения в ИТ: повтор не отправляется, изменённый текст идёт как обновление; осиротевшие запуски закрываются при старте", async () => {
|
||
it_messages.length = 0;
|
||
await db.pool.query("delete from agent_problem_log where manager_person_id = $1 and severity = 'it_request'", [MGR]);
|
||
const c = ctx();
|
||
const sec = (t: string) => new Map([["обращение в ит", t]]);
|
||
await saveProblems(c, MGR, "step4", sec("llmtest применить даты A"));
|
||
await saveProblems(c, MGR, "step4", sec("llmtest применить даты A")); // тот же текст - пропуск
|
||
await saveProblems(c, MGR, "step4", sec("llmtest применить даты A и B")); // изменился - обновление
|
||
expect(it_messages).toHaveLength(2);
|
||
expect(it_messages[0]).toContain("Обращение агента в ИТ");
|
||
expect(it_messages[1]).toContain("ОБНОВЛЕНИЕ");
|
||
const rows = await db.pool.query("select count(*)::int as n from agent_problem_log where manager_person_id = $1 and severity = 'it_request' and body like 'llmtest%'", [MGR]);
|
||
expect(rows.rows[0].n).toBe(2);
|
||
|
||
await db.pool.query("insert into agent_run (manager_person_id, step, status, started_at) values ($1,'step4','running', now() - interval '3 hours')", [MGR]);
|
||
expect(await closeOrphanRuns(c)).toBeGreaterThanOrEqual(1);
|
||
const st = await db.pool.query("select status, error from agent_run where manager_person_id = $1 and error like '%осиротевший%'", [MGR]);
|
||
expect(st.rows[0].status).toBe("failed");
|
||
expect(it_messages.at(-1)).toContain("осиротевших");
|
||
});
|
||
it("агент сообщил о недоступности коннектора JobTread: сессия сбрасывается", async () => {
|
||
calls = [];
|
||
script = [ok("## Ответ менеджеру\n(без ответа)\n## Память\nм8\n## Изменения JobTread\nнет. Коннектор JobTread недоступен (удалён из конфигурации сессии)")];
|
||
await db.pool.query("update agent_manager_memory set claude_session_id = $2 where manager_person_id = $1", [MGR, "11111111-2222-3333-4444-555555555555"]);
|
||
await runManagerAgent(ctx(), { managerId: MGR, step: "step4", tools: "chat", prompt: "llmtest", required: ["ответ менеджеру", "память"] });
|
||
const r = await db.pool.query("select claude_session_id from agent_manager_memory where manager_person_id = $1", [MGR]);
|
||
expect(r.rows[0].claude_session_id).toBeNull();
|
||
});
|
||
it("коннектор JobTread не поднялся: запуск повторяется в новой сессии, ответ неудачной попытки менеджеру не уходит", async () => {
|
||
calls = [];
|
||
const nl = String.fromCharCode(10);
|
||
const down = ["## Ответ менеджеру", "I can't write to JobTread right now", "## Память", "м-неудача", "## Изменения JobTread", "нет. Коннектор JobTread недоступен"].join(nl);
|
||
const good = ["## Ответ менеджеру", "Done: updated.", "## Память", "м-успех", "## Изменения JobTread", "записано"].join(nl);
|
||
script = [ok(down), ok(down), ok(good)];
|
||
const c = ctx();
|
||
const live = { ...c, settings: { ...c.settings, connectorRetry: { windowSeconds: 600, pauseSeconds: 0 } } };
|
||
const r = await runManagerAgent(live, { managerId: MGR, step: "step4", tools: "chat", prompt: "короткий промт", fullPrompt: "ПОЛНЫЙ промт", required: ["ответ менеджеру", "память"] });
|
||
expect(r.sections.get("ответ менеджеру")).toBe("Done: updated.");
|
||
expect(calls).toHaveLength(3);
|
||
expect(calls[1]!.prompt).toContain("ПОЛНЫЙ промт");
|
||
expect(calls[1]!.prompt).toContain("повтор запуска №1");
|
||
expect(calls[2]!.prompt).toContain("повтор запуска №2");
|
||
expect(calls[1]!.resume).toBe(false);
|
||
expect(calls[1]!.sessionId).not.toBe(calls[0]!.sessionId);
|
||
const runs = await db.pool.query("select status, error from agent_run where manager_person_id = $1 order by started_at desc limit 3", [MGR]);
|
||
expect(runs.rows.filter((x) => x.status === "failed" && /повтор запуска/.test(x.error ?? ""))).toHaveLength(2);
|
||
|
||
// окно исчерпано: отчёт о неудаче уходит как есть
|
||
calls = [];
|
||
script = [ok(down)];
|
||
const noRetry = { ...c, settings: { ...c.settings, connectorRetry: { windowSeconds: 0, pauseSeconds: 0 } } };
|
||
const r2 = await runManagerAgent(noRetry, { managerId: MGR, step: "step4", tools: "chat", prompt: "p", required: ["ответ менеджеру", "память"] });
|
||
expect(r2.sections.get("ответ менеджеру")).toContain("can't write");
|
||
expect(calls).toHaveLength(1);
|
||
});
|
||
it("чат руководителя (chat_kind = ceo): свой промт, раздел «Ответ Arthur», без списка задач на день", async () => {
|
||
const liveCalls: ClaudeCall[] = [];
|
||
const nl = String.fromCharCode(10);
|
||
const liveRunner = {
|
||
run: async (c: ClaudeCall) => { liveCalls.push(c); return { text: ["## Ответ Arthur", "Got it, Arthur.", "## Память", "ceo-память"].join(nl), sessionId: c.sessionId }; },
|
||
isActive: () => false, activeSession: () => null, close: () => undefined, closeAll: () => undefined, activeCount: () => 0,
|
||
};
|
||
const base = ctx();
|
||
const ceoCtx = { ...base, liveRunner, settings: { ...base.settings, live: { managerIds: [MGR], idleMinutes: 10, warmupSeconds: 0 }, sql: { agentUrl: "postgres://ro-agent", ceoUrl: "postgres://ro-ceo" } } };
|
||
const posted: string[] = [];
|
||
const slack = { postMessage: async (_c: string, x: string) => { posted.push(x); return true; }, fileInfo: async () => null, download: async () => 0 };
|
||
const ceo = { personId: MGR, name: "Arthur Atanoff", slackUserId: "ULLMTEST", slackChannelId: "CLLMTEST", chatKind: "ceo" as const };
|
||
const res = await handleManagerMessages({ ctx: ceoCtx, timezone: "America/New_York", slack }, ceo, [{ channel: "CLLMTEST", ts: "1791741400.000001", text: "what is overdue?", fileIds: [] }]);
|
||
expect(res.reply).toBe("Got it, Arthur.");
|
||
expect(posted).toEqual(["Got it, Arthur."]);
|
||
const p = liveCalls[0]!.prompt;
|
||
expect(p).toContain("личный ассистент Arthur Atanoff"); // промт руководителя
|
||
expect(p).not.toContain("# Список задач на сегодня");
|
||
expect(p).toContain("# Память");
|
||
expect(p).toContain("what is overdue?");
|
||
expect(liveCalls[0]!.env).toEqual({ KHB_SQL_URL: "postgres://ro-ceo" }); // чтение Supabase: роль руководителя
|
||
});
|
||
it("язык ответов: по умолчанию английский во входе; владелец просит сменить - меняется только его строка; по системному событию не меняется", async () => {
|
||
const OTHER = "00000000-0000-0000-0000-0000000000a9";
|
||
await db.pool.query("insert into person (id, display_name, jt_membership_id) values ($1,'llmtest-Other','m9')", [OTHER]);
|
||
await db.pool.query("insert into construction_manager (person_id) values ($1)", [OTHER]);
|
||
expect((await db.pool.query("select language from construction_manager where person_id = $1", [MGR])).rows[0].language).toBe("English");
|
||
const slack = { postMessage: async () => true, fileInfo: async () => null, download: async () => 0 };
|
||
const mgr = { personId: MGR, name: "llmtest-Manager", slackUserId: "ULLMTEST", slackChannelId: "CLLMTEST" };
|
||
const msg = (text: string, ts: string) => [{ channel: "CLLMTEST", ts, text, fileIds: [] as string[] }];
|
||
calls = [];
|
||
script = [ok("## Ответ менеджеру\nOK\n## Память\nм1")];
|
||
await handleManagerMessages({ ctx: ctx(), timezone: "America/New_York", slack, dryPublish: true }, mgr, msg("Привет, как дела? Ответь по-русски", "1791742000.000001"));
|
||
expect(calls[0]!.prompt).toContain("# Язык ответов");
|
||
expect(calls[0]!.prompt).toContain("Язык ответов владельцу агента (llmtest-Manager): English");
|
||
// владелец сам просит сменить язык: запись только в его строку
|
||
script = [ok("## Ответ менеджеру\nХорошо, отвечаю по-испански.\n## Память\nм2\n## Язык\n`spanish`.")];
|
||
await handleManagerMessages({ ctx: ctx(), timezone: "America/New_York", slack, dryPublish: true }, mgr, msg("Please answer me in Spanish from now on", "1791742010.000001"));
|
||
expect((await db.pool.query("select language from construction_manager where person_id = $1", [MGR])).rows[0].language).toBe("Spanish");
|
||
expect((await db.pool.query("select language from construction_manager where person_id = $1", [OTHER])).rows[0].language).toBe("English");
|
||
calls = [];
|
||
script = [ok("## Ответ менеджеру\nOK\n## Память\nм3")];
|
||
await handleManagerMessages({ ctx: ctx(), timezone: "America/New_York", slack, dryPublish: true }, mgr, msg("hola", "1791742020.000001"));
|
||
expect(calls[0]!.prompt).toContain("Язык ответов владельцу агента (llmtest-Manager): Spanish");
|
||
// системное событие язык не меняет, мусор в разделе игнорируется
|
||
script = [ok("## Ответ менеджеру\nOK\n## Память\nм4\n## Язык\nFrench")];
|
||
await handleManagerMessages({ ctx: ctx(), timezone: "America/New_York", slack, dryPublish: true }, mgr, [], { systemEvent: "12:00" });
|
||
script = [ok("## Ответ менеджеру\nOK\n## Память\nм5\n## Язык\nпереключи на русский, пожалуйста, очень прошу тебя!!!")];
|
||
await handleManagerMessages({ ctx: ctx(), timezone: "America/New_York", slack, dryPublish: true }, mgr, msg("x", "1791742030.000001"));
|
||
expect((await db.pool.query("select language from construction_manager where person_id = $1", [MGR])).rows[0].language).toBe("Spanish");
|
||
await db.pool.query("update construction_manager set language = 'English' where person_id = $1", [MGR]);
|
||
await db.pool.query("delete from construction_manager where person_id = $1", [OTHER]);
|
||
await db.pool.query("delete from person where id = $1", [OTHER]);
|
||
});
|
||
|
||
it("API агентов: память читается и пишется с аудитом, сброс сессии, история", async () => {
|
||
const app = buildApi({ pool: db.pool, token: "t", run: async () => { throw new Error("не нужен"); } });
|
||
const h = { authorization: "Bearer t" };
|
||
const un = await app.inject({ method: "GET", url: `/agents/${MGR}/memory` });
|
||
expect(un.statusCode).toBe(401);
|
||
await db.pool.query("update agent_manager_memory set memory_text = 'llmtest старая память', claude_session_id = $2 where manager_person_id = $1", [MGR, "11111111-2222-3333-4444-555555555555"]);
|
||
const get = await app.inject({ method: "GET", url: `/agents/${MGR}/memory`, headers: h });
|
||
expect(get.json()).toMatchObject({ memoryText: "llmtest старая память", hasSession: true });
|
||
const bad = await app.inject({ method: "PUT", url: `/agents/${MGR}/memory`, headers: h, payload: {} });
|
||
expect(bad.statusCode).toBe(400);
|
||
expect((await app.inject({ method: "GET", url: "/agents/not-a-uuid/memory", headers: h })).statusCode).toBe(404);
|
||
const put = await app.inject({ method: "PUT", url: `/agents/${MGR}/memory`, headers: h, payload: { memoryText: "llmtest новая память", note: "тест", resetSession: true } });
|
||
expect(put.json()).toMatchObject({ ok: true, sessionReset: true });
|
||
const after = await app.inject({ method: "GET", url: `/agents/${MGR}/memory`, headers: h });
|
||
expect(after.json()).toMatchObject({ memoryText: "llmtest новая память", hasSession: false });
|
||
const hist = (await app.inject({ method: "GET", url: `/agents/${MGR}/history?limit=5`, headers: h })).json();
|
||
expect(hist.problems.some((p: { body: string }) => p.body.startsWith("[memory-edit] тест") && p.body.includes("llmtest старая память"))).toBe(true);
|
||
expect(Array.isArray(hist.runs) && Array.isArray(hist.messages) && Array.isArray(hist.reminders)).toBe(true);
|
||
const list = (await app.inject({ method: "GET", url: "/agents", headers: h })).json();
|
||
expect(list.some((a: { id: string }) => a.id === MGR)).toBe(true);
|
||
await app.close();
|
||
});
|
||
it("проектный канал: проект задан каналом, huddle принимается, чужой бот игнорируется", async () => {
|
||
calls = [];
|
||
const posted: string[] = [];
|
||
script = [ok("## Ответ менеджеру\nответ проект llmtest\n## Память\nм7")];
|
||
await db.pool.query("insert into project_channel (channel_id, jt_job_id, channel_name, is_enabled) values ('CPROJ1','llmtest-job','proj-llmtest', true) on conflict do nothing");
|
||
const deps = {
|
||
ctx: ctx(), timezone: "America/New_York",
|
||
slack: { postMessage: async (_c: string, t: string) => { posted.push(t); return true; }, fileInfo: async () => null, download: async () => 0 },
|
||
};
|
||
const intake = new SlackIntake(deps, { channelIds: [], debounceMs: 600_000 });
|
||
await intake.onEvent({ type: "message", channel: "CPROJ1", user: "UANY", ts: "2.1", text: "tile was ordered" });
|
||
await intake.onEvent({ type: "message", channel: "CPROJ1", bot_id: "B1", ts: "2.2", text: "bot" }); // чужой бот
|
||
await intake.onEvent({ type: "message", channel: "CPROJ1", bot_id: "B2", user: "USLACKBOT", subtype: "huddle_thread", ts: "2.3", text: "A huddle started" }); // без файлов
|
||
await intake.onEvent({ type: "message", channel: "CPROJ1", bot_id: "B2", user: "USLACKBOT", ts: "2.4", text: "", files: [{ id: "F1", name: "huddle_transcript.json", mimetype: "application/json" }] });
|
||
await intake.flush(MGR);
|
||
await intake.idle();
|
||
intake.stop();
|
||
expect(calls).toHaveLength(1);
|
||
const prompt = calls[0]!.prompt;
|
||
expect(prompt).toContain("# Проектный канал");
|
||
expect(prompt).toContain("llmtest-job");
|
||
expect(prompt).toContain("tile was ordered");
|
||
expect(prompt).toContain("<@UANY>: tile was ordered"); // автор реплики указан: ответ адресуется отправителю, а не ответственному менеджеру
|
||
expect(prompt).toContain("Slack huddle");
|
||
expect(prompt).not.toContain("A huddle started");
|
||
expect(posted).toEqual(["ответ проект llmtest"]);
|
||
});
|
||
it("папка приёма Drive: файлы и текст из builder_assistant/<channel> становятся сообщениями чата", async () => {
|
||
calls = [];
|
||
const posted: string[] = [];
|
||
script = [ok("## Ответ менеджеру\nответ drive llmtest\n## Память\nм6")];
|
||
const deps = {
|
||
ctx: ctx(), timezone: "America/New_York",
|
||
slack: { postMessage: async (_c: string, t: string) => { posted.push(t); return true; }, fileInfo: async () => null, download: async () => 0 },
|
||
};
|
||
const intake = new SlackIntake(deps, { channelIds: [], debounceMs: 600_000 });
|
||
const moved: string[] = [];
|
||
let listed = [
|
||
{ id: "idnote0001xx", name: "note.txt", mimeType: "text/plain", modifiedTime: "2026-01-01T10:00:00Z" },
|
||
{ id: "idvoice002xx", name: "voice.m4a", mimeType: "audio/mp4", modifiedTime: "2026-01-01T10:00:05Z" },
|
||
{ id: "x", name: "_processed", mimeType: "application/vnd.google-apps.folder" },
|
||
];
|
||
const client = {
|
||
findChild: async (_p: string, name: string) => (name === "CLLMTEST" ? { id: "CHAN", name } : null),
|
||
children: async () => listed,
|
||
ensureFolder: async () => ({ id: "PROC", name: "_processed" }),
|
||
downloadTo: async (id: string, dest: string) => writeFileSync(dest, id.startsWith("idnote") ? "llmtest drive text message" : "audio"),
|
||
move: async (id: string) => { moved.push(id); listed = listed.filter((f) => f.id !== id); return {}; },
|
||
} as unknown as DriveClient;
|
||
const inbox = new DriveInbox({ client, rootFolderId: "ROOT", localRoot: join(tmpdir(), "llmtest-inbox"), channels: async () => ["CLLMTEST"], accept: (f) => intake.onDriveFile(f) });
|
||
expect(await inbox.scan()).toBe(2);
|
||
expect(moved).toHaveLength(2);
|
||
expect(await inbox.scan()).toBe(0);
|
||
await intake.flush(MGR);
|
||
await intake.idle();
|
||
intake.stop();
|
||
expect(calls).toHaveLength(1);
|
||
expect(calls[0]!.prompt).toContain("llmtest drive text message");
|
||
expect(calls[0]!.prompt).toContain("voice.m4a");
|
||
expect(posted).toEqual(["ответ drive llmtest"]);
|
||
});
|
||
|
||
it("Google Drive агентов: строителям (в том числе проектным чатам) - ключ builder, руководителю - полный; без ключей переменной нет", async () => {
|
||
const liveCalls: ClaudeCall[] = [];
|
||
const reply = (t: string) => ["## Ответ менеджеру", t, "## Ответ Arthur", t, "## Память", "м"].join(String.fromCharCode(10));
|
||
const liveRunner = {
|
||
run: async (c: ClaudeCall) => { liveCalls.push(c); return { text: reply("ок"), sessionId: c.sessionId }; },
|
||
isActive: () => false, activeSession: () => null, close: () => undefined, closeAll: () => undefined, activeCount: () => 0,
|
||
};
|
||
const base = ctx();
|
||
const slack = { postMessage: async () => true, fileInfo: async () => null, download: async () => 0 };
|
||
const driveKeys = { full: '{"k":"FULL"}', builder: '{"k":"BUILDER"}' };
|
||
const withLive = { ...base, liveRunner, settings: { ...base.settings, live: { managerIds: [MGR], idleMinutes: 10, warmupSeconds: 0 } } };
|
||
const mgr = { personId: MGR, name: "llmtest-Manager", slackUserId: "ULLMTEST", slackChannelId: "CLLMTEST" };
|
||
const msg = (ts: string) => [{ channel: "CLLMTEST", ts, text: "проверка ключа", fileIds: [] }];
|
||
await handleManagerMessages({ ctx: withLive, timezone: "America/New_York", slack, driveKeys, dryPublish: true }, mgr, msg("1791741500.000001"));
|
||
expect(liveCalls[0]!.env).toEqual({ KHB_DRIVE_KEY: '{"k":"BUILDER"}' });
|
||
// проектный канал (менеджер проекта - строитель) тоже builder
|
||
await handleManagerMessages({ ctx: withLive, timezone: "America/New_York", slack, driveKeys, dryPublish: true }, mgr, [{ channel: "CPROJ", ts: "1791741510.000001", text: "в проектном канале", fileIds: [], project: { jobId: "J1", jobName: "Проект", channel: "CPROJ", senderName: null, isHuddle: false } } as never]);
|
||
expect(liveCalls[1]!.env).toEqual({ KHB_DRIVE_KEY: '{"k":"BUILDER"}' });
|
||
// руководитель - полный ключ
|
||
await handleManagerMessages({ ctx: withLive, timezone: "America/New_York", slack, driveKeys, dryPublish: true }, { ...mgr, chatKind: "ceo" as const }, msg("1791741520.000001"));
|
||
expect(liveCalls[2]!.env).toEqual({ KHB_DRIVE_KEY: '{"k":"FULL"}' });
|
||
// ключ builder не задан - строителю доступ к Drive не выдаётся (полный ключ ему не отдаётся)
|
||
await handleManagerMessages({ ctx: withLive, timezone: "America/New_York", slack, driveKeys: { full: '{"k":"FULL"}' }, dryPublish: true }, mgr, msg("1791741530.000001"));
|
||
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");
|
||
});
|
||
|
||
it("события todo_service: агент получает событие, ответ уходит, события подтверждаются; вне окна и при pause off - не шлются", async () => {
|
||
const nl = String.fromCharCode(10);
|
||
const texts: string[] = [["## Ответ менеджеру", "Walter closed the tile todo - you can close your Control todo.", "## Память", "м-todo-1"].join(nl), ["## Ответ менеджеру", "Reminder sent.", "## Память", "м-todo-2"].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 } } };
|
||
// фальшивый todo_service: лента событий и подтверждение
|
||
let pending = [
|
||
{ id: "11", event_type: "control_done", task_id: "CTRLa", person_id: MGR, payload: { executorTaskId: "EXa", executorName: "Order tile", controlTaskId: "CTRLa" } },
|
||
{ id: "12", event_type: "review_due", task_id: "TODOb", person_id: MGR, payload: { reviewDate: "2026-10-21", name: "Check conduit" } },
|
||
{ id: "13", event_type: "write_failed", task_id: null, person_id: null, payload: { requestId: "R1", op: "close" } },
|
||
];
|
||
const acked: number[] = [];
|
||
const auth: (string | undefined)[] = [];
|
||
const srv = createServer((req, res) => {
|
||
auth.push(req.headers.authorization);
|
||
if (req.method === "GET" && req.url === "/events?pending=1") { res.setHeader("content-type", "application/json"); res.end(JSON.stringify(pending)); return; }
|
||
if (req.method === "POST" && req.url === "/events/ack") {
|
||
let body = "";
|
||
req.on("data", (c) => (body += c));
|
||
req.on("end", () => { const ids = (JSON.parse(body).ids as number[]) ?? []; acked.push(...ids); pending = pending.filter((e) => !ids.includes(Number(e.id))); res.setHeader("content-type", "application/json"); res.end(JSON.stringify({ acked: ids.length })); });
|
||
return;
|
||
}
|
||
res.statusCode = 404; res.end("{}");
|
||
});
|
||
await new Promise<void>((r) => srv.listen(0, "127.0.0.1", () => r()));
|
||
const port = (srv.address() as { port: number }).port;
|
||
const posted: string[] = [];
|
||
const slack = { postMessage: async (_c: string, t: string) => { posted.push(t); return true; }, fileInfo: async () => null, download: async () => 0 };
|
||
const mgr = { personId: MGR, name: "llmtest-Manager", slackUserId: "ULLMTEST", slackChannelId: "CLLMTEST" };
|
||
const noon = new Date("2026-10-21T16:00:00Z");
|
||
const mk = (now: Date) => new TodoEventPoller({ ctx: live, timezone: "America/New_York", slack, now: () => now }, { url: `http://127.0.0.1:${port}`, token: "tok-llmtest", loadManager: async () => mgr, intervalMs: 0 });
|
||
try {
|
||
// ночью (вне окна 7-19 по Тампе) события остаются в ленте
|
||
expect(await mk(new Date("2026-10-21T05:00:00Z")).tick()).toBe(0);
|
||
expect(acked).toEqual([]);
|
||
// pause_mode = off: события остаются
|
||
await db.pool.query("update construction_manager set agent_paused = true, pause_mode = 'off' where person_id = $1", [MGR]);
|
||
expect(await mk(noon).tick()).toBe(0);
|
||
await db.pool.query("update construction_manager set agent_paused = false, pause_mode = 'passive' where person_id = $1", [MGR]);
|
||
// в окне: одно сообщение агенту, события адресата подтверждены, событие без адресата осталось
|
||
expect(await mk(noon).tick()).toBe(1);
|
||
expect(liveCalls[0]!.prompt).toContain("control_done: исполнитель закрыл todo EXa «Order tile»");
|
||
expect(liveCalls[0]!.prompt).toContain("review_due: наступила дата пересмотра (2026-10-21) todo TODOb «Check conduit»");
|
||
expect(liveCalls[0]!.prompt).not.toContain("запрос R1"); // событие без адресата агенту не уходит
|
||
expect(acked).toEqual([11, 12]);
|
||
expect(pending.map((e) => e.id)).toEqual(["13"]);
|
||
expect(auth.every((a) => a === "Bearer tok-llmtest")).toBe(true);
|
||
expect(posted).toHaveLength(1);
|
||
// повторная проверка ничего не шлёт
|
||
expect(await mk(noon).tick()).toBe(0);
|
||
} finally {
|
||
await new Promise<void>((r) => srv.close(() => r()));
|
||
}
|
||
});
|
||
|
||
});
|