Агенты: переключение на todo_service (khb-todo, TodoEventPoller вместо ControlWatcher, блок Todo, промты proposed); багрепорты todo_service
Some checks failed
ci / test (push) Failing after 28s
ci / deploy (push) Has been skipped

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-30 08:14:41 +03:00
parent 5d4e7e0779
commit f32d74a265
16 changed files with 262 additions and 213 deletions

View File

@@ -14,7 +14,8 @@ import { buildApi } from "./http-api.js";
import { listManagers } from "./managers.js";
import { pauseState } from "./pause.js";
import { handleManagerMessages } from "./slack/chat.js";
import { ControlWatcher } from "./slack/control.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";
@@ -671,12 +672,9 @@ d("консольные агенты (временная БД, фейковый
expect(liveCalls[3]!.prompt).not.toContain("AI huddle notes are ready");
});
it("Control todo: пара пишется из раздела вывода; исполнитель закрыл - «выполнено», после срока без действий - «просрочено»; статусы меняются", async () => {
it("события todo_service: агент получает событие, ответ уходит, события подтверждаются; вне окна и при pause off - не шлются", async () => {
const nl = String.fromCharCode(10);
const texts: string[] = [
["## Ответ менеджеру", "(без ответа)", "## Control todo", "CTRLcccccc03 EXECcccccc03 2026-10-25", "## Память", "м-control-1"].join(nl),
["## Ответ менеджеру", "Walter closed the tile todo - you can close your Control todo. No action on the plumber todo for 2 days - marked overdue.", "## Память", "м-control-2"].join(nl),
];
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 }; },
@@ -684,37 +682,54 @@ d("консольные агенты (временная БД, фейковый
};
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 deps = { ctx: live, timezone: "America/New_York", slack, now: () => noon };
// 1. агент вывел пару - она записана
await handleManagerMessages({ ...deps, dryPublish: true }, mgr, [{ channel: "CLLMTEST", ts: "1791741800.000001", text: "I noticed missing conduit", fileIds: [] }]);
const saved = (await db.pool.query("select executor_task_id, to_char(control_due,'YYYY-MM-DD') d, status from control_todo where control_task_id = 'CTRLcccccc03'")).rows[0];
expect(saved).toEqual({ executor_task_id: "EXECcccccc03", d: "2026-10-25", status: "active" });
// 2. две другие пары: исполнитель закрыл todo (событие JobTread) и срок Control todo прошёл без действий
await db.pool.query("insert into control_todo (controller_person_id, executor_task_id, control_task_id, executor_name, control_due) values ($1,'EXECaaaaaa01','CTRLaaaaaa01','Order tile','2026-10-30'), ($1,'EXECbbbbbb02','CTRLbbbbbb02','Call plumber','2026-10-20')", [MGR]);
await db.pool.query("insert into jt_event (id, type, created_at, task_id, kind) values ('llmtest-ev-ctl-1', 'taskUpdated', now(), 'EXECaaaaaa01', 'todo_closed')");
const watcher = new ControlWatcher(deps, { loadManager: async () => mgr, intervalMs: 0 });
expect(await watcher.tick()).toBe(1);
const prompt = liveCalls[1]!.prompt;
expect(prompt).toContain("ВЫПОЛНЕНО: исполнитель закрыл todo EXECaaaaaa01 «Order tile». Control todo CTRLaaaaaa01");
expect(prompt).toContain("ПРОСРОЧЕНО: по todo исполнителя EXECbbbbbb02 «Call plumber»");
expect(prompt).not.toContain("EXECcccccc03"); // срок 10/25 ещё не наступил (сегодня 10/21)
const st = (await db.pool.query("select control_task_id, status from control_todo order by control_task_id")).rows;
expect(st).toEqual([{ control_task_id: "CTRLaaaaaa01", status: "done" }, { control_task_id: "CTRLbbbbbb02", status: "overdue" }, { control_task_id: "CTRLcccccc03", status: "active" }]);
expect(posted).toHaveLength(1);
// 3. повторная проверка ничего не шлёт; ночью (вне окна 7-19 по Тампе) тоже
expect(await watcher.tick()).toBe(0);
const night = new ControlWatcher({ ...deps, now: () => new Date("2026-10-21T05:00:00Z") }, { loadManager: async () => mgr, intervalMs: 0 });
expect(await night.tick()).toBe(0);
// 4. исполнитель после «просрочено» всё же закрыл todo - снова сообщение, статус done
texts.push(["## Ответ менеджеру", "Plumber todo is done now.", "## Память", "м-control-3"].join(nl));
await db.pool.query("insert into jt_event (id, type, created_at, task_id, kind) values ('llmtest-ev-ctl-2', 'taskUpdated', now(), 'EXECbbbbbb02', 'todo_closed')");
expect(await watcher.tick()).toBe(1);
expect(liveCalls[2]!.prompt).toContain("ВЫПОЛНЕНО: исполнитель закрыл todo EXECbbbbbb02");
expect((await db.pool.query("select status from control_todo where control_task_id = 'CTRLbbbbbb02'")).rows[0].status).toBe("done");
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()));
}
});
});