Промты согласованы и установлены всем менеджерам: recap, Control todo (миграция 023, ControlWatcher), fallback на английском; tasks.md очищен
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
143
packages/khbuild_assistant_prep/src/slack/control.ts
Normal file
143
packages/khbuild_assistant_prep/src/slack/control.ts
Normal file
@@ -0,0 +1,143 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user