Агенты: пилот compact вместо явной памяти по простою (п.81): /compact через 4 или 55 минут по статусу диалога от агента, resume с полным промтом, оценка токенов в agent_usage, предупреждение на 50% недельного лимита
Some checks failed
ci / deploy (push) Has been cancelled
ci / test (push) Has been cancelled

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-09 23:24:45 +03:00
parent 1f763f4800
commit a104112326
15 changed files with 234 additions and 13 deletions

View File

@@ -9,6 +9,7 @@ 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 { compactIdle } from "./agents/idle-memory.js";
import Fastify from "fastify";
import { registerAgentRoutes } from "./agents-api.js";
import { buildApi } from "./http-api.js";
@@ -239,6 +240,77 @@ d("консольные агенты (временная БД, фейковый
expect(calls[0]!.prompt).toContain("# Память");
});
it("пилот compact: агент сам выбирает паузу (TALK_FINISHED - 4 мин, WAITING_RESPONSE - 55, после напоминаний - 4); сессия продолжается с полным промтом; сбой compact - явная память и новая сессия", async () => {
const nl2 = String.fromCharCode(10);
const mkReply = (status: string | null) => ["## Ответ менеджеру", "(без ответа)", ...(status ? ["## Статус диалога", status] : []), "## Память", "м-compact"].join(nl2);
const outputs: string[] = [mkReply("TALK_FINISHED"), mkReply("WAITING_RESPONSE"), mkReply(null), mkReply("WAITING_RESPONSE")];
const liveCalls: ClaudeCall[] = [];
const scheduled: number[] = [];
let active = false;
let lastSid = "";
let compactResult: { compact: { preTokens: number; postTokens: number; durationMs: number }; idleMs: number; text: string; sessionId: string } | null = null;
const liveRunner = {
run: async (c: ClaudeCall) => { liveCalls.push(c); active = true; lastSid = c.sessionId; return { text: outputs.shift() ?? mkReply(null), sessionId: c.sessionId }; },
isActive: () => active, activeSession: () => (active ? lastSid : null), close: () => { active = false; }, closeAll: () => undefined, activeCount: () => (active ? 1 : 0),
scheduleIdle: (_cwd: string, ms: number) => { scheduled.push(ms); },
compact: async () => compactResult,
};
const base = ctx();
const liveCtx = { ...base, liveRunner, settings: { ...base.settings, live: { managerIds: [MGR], idleMinutes: 10, warmupSeconds: 0, compact: { enabled: true, finishedMinutes: 4, waitingMinutes: 55 } } } };
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: [] }];
const deps = { ctx: liveCtx, timezone: "America/New_York", slack, dryPublish: true };
await handleManagerMessages(deps, mgr, msg("диалог закрыт", "1791742100.000001"));
expect(scheduled).toEqual([4 * 60_000]);
await handleManagerMessages(deps, mgr, msg("жду ответ", "1791742110.000001"));
expect(scheduled).toEqual([4 * 60_000, 55 * 60_000]);
// нет раздела статуса - ждём ответ (55); событие-напоминание - всегда 4 минуты, даже если агент написал WAITING_RESPONSE
await handleManagerMessages(deps, mgr, msg("без статуса", "1791742120.000001"));
expect(scheduled[2]).toBe(55 * 60_000);
await handleManagerMessages(deps, mgr, [], { systemEvent: "12:00" });
expect(scheduled[3]).toBe(4 * 60_000);
// живой процесс: промт короткий; после compact процесс закрыт, но сессия продолжается (resume) с полным промтом (инструкции и память)
expect(liveCalls[1]!.prompt).toContain("# Продолжение диалога");
expect(liveCalls[1]!.resume).toBe(true);
active = false;
outputs.push(mkReply("TALK_FINISHED"));
await handleManagerMessages(deps, mgr, msg("после compact", "1791742130.000001"));
const last = liveCalls[liveCalls.length - 1]!;
expect(last.resume).toBe(true);
expect(last.sessionId).toBe(liveCalls[0]!.sessionId);
expect(last.prompt).toContain("JobTread недоступен или запись не проходит");
expect(last.prompt).toContain("# Память");
// compactIdle: успех - запись в agent_usage (оценка по размерам контекста), сессия не сбрасывается
compactResult = { compact: { preTokens: 40_000, postTokens: 7_000, durationMs: 5000 }, idleMs: 240_000, text: "", sessionId: lastSid };
await db.pool.query("delete from agent_usage where manager_person_id = $1 and op = 'compact'", [MGR]);
await compactIdle(liveCtx as unknown as AgentContext, MGR);
await liveCtx.usageLog?.flush();
const u = (await db.pool.query("select * from agent_usage where manager_person_id = $1 and op = 'compact'", [MGR])).rows;
expect(u).toHaveLength(1);
expect(u[0]).toMatchObject({ ok: true, live: true, output_tokens: 7000, cache_read_tokens: 40000, cache_creation_tokens: 0 });
expect((await db.pool.query("select claude_session_id from agent_manager_memory where manager_person_id = $1", [MGR])).rows[0].claude_session_id).toBe(lastSid);
// простой дольше часа: кэш остыл - чтение контекста считается как запись
compactResult = { ...compactResult, idleMs: 3 * 3600_000 };
await compactIdle(liveCtx as unknown as AgentContext, MGR);
await liveCtx.usageLog?.flush();
const cold = (await db.pool.query("select * from agent_usage where manager_person_id = $1 and op = 'compact' order by id desc limit 1", [MGR])).rows[0];
expect(cold).toMatchObject({ cache_read_tokens: 0, cache_creation_tokens: 40000 });
// сбой compact (claude не подтвердил): сводим явную память и сбрасываем сессию - следующий запуск начнётся заново
compactResult = null;
outputs.push(["## Память", "явная память после сбоя compact"].join(nl2));
await compactIdle(liveCtx as unknown as AgentContext, MGR);
const mem = (await db.pool.query("select memory_text, claude_session_id from agent_manager_memory where manager_person_id = $1", [MGR])).rows[0];
expect(mem.memory_text).toContain("явная память после сбоя compact");
expect(mem.claude_session_id).toBeNull();
// режим выключен (enabled: false): прежняя схема, пауза не назначается
const before = scheduled.length;
const off = { ...liveCtx, settings: { ...liveCtx.settings, live: { ...liveCtx.settings.live, compact: { enabled: false, finishedMinutes: 4, waitingMinutes: 55 } } } };
outputs.push(mkReply("TALK_FINISHED"));
await handleManagerMessages({ ...deps, ctx: off }, mgr, msg("режим выключен", "1791742140.000001"));
expect(scheduled.length).toBe(before);
});
it("тайминг чата: строка chat_timing с этапами от сообщения в Slack до ответа в Slack", async () => {
calls = [];
const base = Math.floor(Date.now() / 1000) - 20; // относительно «сейчас»: фиксированная дата ломала бы int-поле debounce_ms через 24.8 суток