Агенты: переключение на 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

@@ -6,7 +6,6 @@ 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 { parseControlTodos, saveControlTodos } from "./control.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";
@@ -237,6 +236,9 @@ export async function handleManagerMessages(
const membershipId = (((await ctx.pool.query("select jt_membership_id from person where id = $1", [manager.personId])).rows[0]?.jt_membership_id as string | null | undefined) ?? null);
const todoText = optFragment("p-long-living-agents.md", "Todo менеджера", { membership: membershipId ? `; его membership в JobTread: ${membershipId}` : "" });
const todoRules = todoText ? `\n${todoText}` : "";
// todo - командой khb-todo (todo_service); фрагмент есть только в согласованных промтах стороны, иначе блок пропускается
const todoToolText = ctx.settings.todo ? optFragment("p-todo-tool.md", "Todo: khb-todo", { person_id: manager.personId }) : null;
const todoToolRules = todoToolText ? `\n${todoToolText}` : "";
const liveRules = live ? `\n${fragment("p-long-living-agents.md", "Правила долгоживущего агента")}` : "";
const testJobs = ctx.settings.testJobIds ?? [];
const writeRules = writableJobs.length
@@ -271,6 +273,8 @@ export async function handleManagerMessages(
const agentEnv: Record<string, string> = {
...(sqlCfg ? { KHB_SQL_URL: isCeo ? (sqlCfg.ceoUrl ?? sqlCfg.agentUrl) : sqlCfg.agentUrl } : {}),
...(driveKey ? { KHB_DRIVE_KEY: driveKey } : {}),
// todo_service: команда khb-todo; права по вызывающему (person id менеджера, у руководителя - все todo)
...(ctx.settings.todo ? { KHB_TODO_URL: ctx.settings.todo.url, KHB_TODO_TOKEN: ctx.settings.todo.token, KHB_TODO_CALLER: manager.personId } : {}),
};
const sqlEnv = Object.keys(agentEnv).length ? agentEnv : undefined;
const replyKey = isCeo ? "ответ arthur" : "ответ менеджеру";
@@ -301,7 +305,7 @@ ${recapBlock(st, deps.timezone)}`);
? ["", `# Память\n${mem.memoryText.trim() || "(пусто)"}`]
: ["", `# Список задач на сегодня\n${listText}`, "", `# Память\n${mem.memoryText.trim() || "(пусто)"}`]),
"",
`# Ограничения среды\nМенеджер: ${manager.name}. ${writeRules}${disabledRules}${liveRules}${todoRules}`,
`# Ограничения среды\nМенеджер: ${manager.name}. ${writeRules}${disabledRules}${liveRules}${todoRules}${todoToolRules}`,
"",
`# Новые сообщения менеджера\n${msgBlock}\n\nВложения (локальные пути):\n${attBlock}`,
].join("\n");
@@ -339,9 +343,6 @@ ${recapBlock(st, deps.timezone)}`);
if (!deps.dryPublish && deps.slack.addReaction)
for (const r of parseReactions(out.sections.get("реакции"))) await deps.slack.addReaction(channel, r.ts, r.emoji).catch((e) => ctx.log.warn({ err: String(e) }, "реакция не поставлена"));
}
// "Control:" todo: агент записал пары (todo исполнителя - парное todo контролёра) - дальше за ними следит ControlWatcher
const controlPairs = parseControlTodos(out.sections.get("control todo"));
if (controlPairs.length) await saveControlTodos(ctx.pool, manager.personId, controlPairs);
const replyRaw = out.sections.get(replyKey)!;
const reply = /^\(без ответа\)\.?$/i.test(replyRaw) ? null : replyRaw;
let published = false;

View File

@@ -1,143 +0,0 @@
import { localDate, type Pool } from "khb_common";
import { loadFragment } from "../agents/prompts.js";
import { promptSideFor } from "../agents/session.js";
import { pauseState } from "../pause.js";
import { handleManagerMessages, type ChatDeps, type ManagerInfo } from "./chat.js";
import { recapDelayMs } from "./recap.js";
/**
* "Control:" todo: исполнителю поставили задачу, контролёр (например CEO) получил парное todo "Control: ...".
* Агент записывает пару в раздел вывода `## Control todo`; сервис следит за исполнителем и будит агента контролёра, когда
* исполнитель закрыл todo ("(выполнено)") или после срока 2 дня не было действий ("(просрочено)").
*/
export interface ControlPair {
controlTaskId: string;
executorTaskId: string;
/** Срок Control todo (YYYY-MM-DD); null - срок не указан, "просрочено" не ставится. */
controlDue: string | null;
}
const ID = "[A-Za-z0-9]{8,16}";
/** Раздел `## Control todo`: строки `<id Control todo> <id todo исполнителя> [YYYY-MM-DD]`; прочее пропускается. */
export function parseControlTodos(v: string | undefined): ControlPair[] {
const out: ControlPair[] = [];
for (const line of (v ?? "").split(/\r?\n/)) {
const m = line.match(new RegExp(`(${ID})\\s+(${ID})(?:\\s+(\\d{4}-\\d{2}-\\d{2}))?`));
if (m && m[1] !== m[2]) out.push({ controlTaskId: m[1]!, executorTaskId: m[2]!, controlDue: m[3] ?? null });
}
return out.slice(0, 20);
}
export async function saveControlTodos(pool: Pool, controllerId: string, pairs: ControlPair[]): Promise<void> {
for (const p of pairs)
await pool.query(
`insert into control_todo (controller_person_id, executor_task_id, control_task_id, control_due)
values ($1,$2,$3,$4)
on conflict (control_task_id) do update set executor_task_id = $2, control_due = coalesce($4, control_todo.control_due),
controller_person_id = $1, updated_at = now()`,
[controllerId, p.executorTaskId, p.controlTaskId, p.controlDue],
);
}
export interface ControlChange {
id: string;
controllerId: string;
kind: "done" | "overdue";
executorTaskId: string;
executorName: string | null;
controlTaskId: string;
controlDue: string | null;
}
/** Что изменилось у открытых пар. Пары, чей Control todo закрыл сам контролёр, молча переводятся в `closed`. */
export async function findControlChanges(pool: Pool, now: Date, tz: string): Promise<ControlChange[]> {
const { rows } = await pool.query(
`select ct.id, ct.controller_person_id, ct.executor_task_id, ct.control_task_id, to_char(ct.control_due, 'YYYY-MM-DD') as control_due, ct.status,
coalesce(et.name, ct.executor_name) as executor_name,
(coalesce(et.progress, 0) >= 1 or exists (select 1 from jt_event e where e.task_id = ct.executor_task_id and e.kind = 'todo_closed' and e.created_at >= ct.created_at - interval '1 minute')) as exec_done,
(coalesce(cc.progress, 0) >= 1 or exists (select 1 from jt_event e where e.task_id = ct.control_task_id and e.kind = 'todo_closed' and e.created_at >= ct.created_at - interval '1 minute')) as control_closed,
exists (select 1 from jt_event e where e.task_id = ct.executor_task_id and e.created_at > $1::timestamptz - interval '2 days') as recent_activity
from control_todo ct
left join jt_task et on et.id = ct.executor_task_id
left join jt_task cc on cc.id = ct.control_task_id
where ct.status in ('active', 'overdue')
order by ct.created_at`,
[now],
);
const today = localDate(now, tz);
const changes: ControlChange[] = [];
const closed: string[] = [];
for (const r of rows) {
const base = {
id: String(r.id), controllerId: String(r.controller_person_id), executorTaskId: String(r.executor_task_id),
executorName: (r.executor_name as string | null) ?? null, controlTaskId: String(r.control_task_id), controlDue: (r.control_due as string | null) ?? null,
};
if (r.control_closed === true) closed.push(base.id);
else if (r.exec_done === true) changes.push({ ...base, kind: "done" });
else if (r.status === "active" && base.controlDue && base.controlDue <= today && r.recent_activity !== true) changes.push({ ...base, kind: "overdue" });
}
if (closed.length) await pool.query("update control_todo set status = 'closed', updated_at = now() where id = any($1::uuid[])", [closed]);
return changes;
}
const lineOf = (c: ControlChange): string =>
c.kind === "done"
? `- ВЫПОЛНЕНО: исполнитель закрыл todo ${c.executorTaskId}${c.executorName ? ` «${c.executorName}»` : ""}. Control todo ${c.controlTaskId}: допиши в конец названия «(выполнено)» (убери «(просрочено)», если есть).`
: `- ПРОСРОЧЕНО: по todo исполнителя ${c.executorTaskId}${c.executorName ? ` «${c.executorName}»` : ""} 2 дня нет действий и срок Control todo (${c.controlDue}) наступил. Control todo ${c.controlTaskId}: допиши в конец названия «(просрочено)».`;
export interface ControlWatcherOpts {
/** Менеджер-контролёр по person id (чат, в который агент напишет). */
loadManager: (personId: string) => Promise<ManagerInfo | null>;
intervalMs: number;
fromHour?: number;
toHour?: number;
}
/** Периодическая проверка пар "todo исполнителя - Control todo"; при изменении будит агента контролёра. */
export class ControlWatcher {
private timer: NodeJS.Timeout | null = null;
private running = false;
constructor(private deps: ChatDeps, private opts: ControlWatcherOpts) {}
start(): void {
if (!this.opts.intervalMs || this.timer) return;
this.timer = setInterval(() => void this.tick().catch((e) => this.deps.ctx.log.error({ err: String(e) }, "проверка Control todo не удалась")), this.opts.intervalMs);
}
stop(): void {
if (this.timer) clearInterval(this.timer);
this.timer = null;
}
/** Одна проверка; возвращает число сообщений, отправленных контролёрам. Вне окна 7:00-19:00 по Тампе не пишет. */
async tick(): Promise<number> {
if (this.running) return 0;
this.running = true;
try {
const now = (this.deps.now ?? (() => new Date()))();
if (recapDelayMs(now, this.deps.timezone, this.opts.fromHour ?? 7, this.opts.toHour ?? 19) > 0) return 0;
const changes = await findControlChanges(this.deps.ctx.pool, now, this.deps.timezone);
const byController = new Map<string, ControlChange[]>();
for (const c of changes) byController.set(c.controllerId, [...(byController.get(c.controllerId) ?? []), c]);
let sent = 0;
for (const [controllerId, list] of byController) {
const manager = await this.opts.loadManager(controllerId);
if (!manager) continue;
const s = await pauseState(this.deps.ctx.pool, controllerId, now);
if (s.paused && s.mode === "off") continue; // passive допустим: это не напоминание по инициативе, а сообщение о смене статуса
await handleManagerMessages(this.deps, manager, [], {
systemEvent: loadFragment("p-chat-events.md", "Control: исполнитель закрыл или просрочил", { changes: list.map(lineOf).join("\n") }, promptSideFor(this.deps.ctx, controllerId)),
});
for (const c of list)
await this.deps.ctx.pool.query("update control_todo set status = $2, notified_at = now(), updated_at = now() where id = $1", [c.id, c.kind === "done" ? "done" : "overdue"]);
sent++;
}
return sent;
} finally {
this.running = false;
}
}
}

View File

@@ -0,0 +1,118 @@
import { loadFragment, type PromptSide } from "../agents/prompts.js";
import { promptSideFor } from "../agents/session.js";
import { pauseState } from "../pause.js";
import { handleManagerMessages, type ChatDeps, type ManagerInfo } from "./chat.js";
import { recapDelayMs } from "./recap.js";
/**
* События todo_service для агентов. Сервис решает, ЧТО произошло (Control: исполнитель закрыл / просрочено, наступила дата пересмотра,
* запись не прошла), агент решает, ЧТО сказать. Агентский сервис раз в минуту читает ленту `GET /events?pending=1`, будит агента адресата
* системным событием (только 7:00-19:00 по Тампе, не при pause_mode = off) и подтверждает доставленное `POST /events/ack`.
* Слежение за парами Control, прежде жившее здесь (`ControlWatcher`), переехало в todo_service.
*/
export interface TodoEvent {
id: string | number;
event_type: string;
task_id: string | null;
person_id: string | null;
payload: Record<string, unknown>;
}
const s = (v: unknown): string => (v === undefined || v === null ? "" : String(v));
const quoted = (v: unknown): string => (s(v) ? ` «${s(v)}»` : "");
/** Строка события для агента (инструкция, что случилось). */
export function formatTodoEvent(e: TodoEvent): string {
const p = e.payload ?? {};
switch (e.event_type) {
case "control_done":
return `- control_done: исполнитель закрыл todo ${s(p.executorTaskId)}${quoted(p.executorName)}. Control todo ${s(p.controlTaskId ?? e.task_id)}: сервис уже дописал в название «(выполнено)». Сообщи контролёру.`;
case "control_overdue":
return `- control_overdue: срок Control todo ${s(p.controlTaskId ?? e.task_id)} (${s(p.controlDue)}) наступил, по todo исполнителя ${s(p.executorTaskId)}${quoted(p.executorName)} 2 дня нет действий; сервис уже дописал в название «(просрочено)». Сообщи контролёру.`;
case "review_due":
return `- review_due: наступила дата пересмотра (${s(p.reviewDate)}) todo ${s(e.task_id)}${quoted(p.name)}. Напомни о нём коротко.`;
case "write_failed":
return `- write_failed: запись todo не прошла (запрос ${s(p.requestId)}, операция ${s(p.op)}). Опиши это в «## Обращение в ИТ»; менеджеру об этом не пиши.`;
default:
return `- ${e.event_type}: ${JSON.stringify(p)}`;
}
}
/** Фрагмент «События todo»: на стороне approved его может ещё не быть (до согласования) - тогда берётся proposed. */
function eventFragment(list: TodoEvent[], side: PromptSide): string {
const vars = { events: list.map(formatTodoEvent).join("\n") };
try {
return loadFragment("p-chat-events.md", "События todo", vars, side);
} catch (e) {
if (side === "proposed") throw e;
return loadFragment("p-chat-events.md", "События todo", vars, "proposed");
}
}
export interface TodoEventPollerOpts {
/** Адрес todo_service во внутренней сети (http://khb-todo-service:8094) и токен (права администратора: лента всех адресатов). */
url: string;
token: string;
loadManager: (personId: string) => Promise<ManagerInfo | null>;
intervalMs: number;
fromHour?: number;
toHour?: number;
fetchFn?: typeof fetch;
}
export class TodoEventPoller {
private timer: NodeJS.Timeout | null = null;
private running = false;
constructor(private deps: ChatDeps, private opts: TodoEventPollerOpts) {}
start(): void {
if (!this.opts.intervalMs || this.timer) return;
this.timer = setInterval(() => void this.tick().catch((e) => this.deps.ctx.log.error({ err: String(e) }, "чтение событий todo не удалось")), this.opts.intervalMs);
}
stop(): void {
if (this.timer) clearInterval(this.timer);
this.timer = null;
}
private async call(method: string, path: string, body?: unknown): Promise<unknown> {
const f = this.opts.fetchFn ?? fetch;
const res = await f(this.opts.url.replace(/\/$/, "") + path, {
method,
headers: { authorization: `Bearer ${this.opts.token}`, ...(body !== undefined ? { "content-type": "application/json" } : {}) },
body: body === undefined ? undefined : JSON.stringify(body),
});
if (!res.ok) throw new Error(`todo_service ${method} ${path}: HTTP ${res.status}`);
return res.json();
}
/** Одна проверка; возвращает число сообщений, отправленных агентам. Вне окна 7:00-19:00 по Тампе события остаются в ленте. */
async tick(): Promise<number> {
if (this.running) return 0;
this.running = true;
try {
const now = (this.deps.now ?? (() => new Date()))();
if (recapDelayMs(now, this.deps.timezone, this.opts.fromHour ?? 7, this.opts.toHour ?? 19) > 0) return 0;
const events = (await this.call("GET", "/events?pending=1")) as TodoEvent[];
const byPerson = new Map<string, TodoEvent[]>();
for (const e of Array.isArray(events) ? events : []) if (e.person_id) byPerson.set(e.person_id, [...(byPerson.get(e.person_id) ?? []), e]);
let sent = 0;
for (const [personId, list] of byPerson) {
const manager = await this.opts.loadManager(personId);
if (!manager) continue;
const st = await pauseState(this.deps.ctx.pool, personId, now);
if (st.paused && st.mode === "off") continue; // passive допустим: это сообщение о смене статуса, а не напоминание по инициативе
await handleManagerMessages(this.deps, manager, [], {
systemEvent: eventFragment(list, promptSideFor(this.deps.ctx, personId)),
});
await this.call("POST", "/events/ack", { ids: list.map((e) => Number(e.id)) });
sent++;
}
return sent;
} finally {
this.running = false;
}
}
}