Промты согласованы и установлены всем менеджерам: recap, Control todo (миграция 023, ControlWatcher), fallback на английском; tasks.md очищен
All checks were successful
ci / test (push) Successful in 25s
ci / deploy (push) Successful in 2m7s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-29 08:28:06 +03:00
parent 4f287519cc
commit 7c26b38a49
34 changed files with 449 additions and 36 deletions

View File

@@ -6,6 +6,7 @@ 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";
@@ -276,7 +277,7 @@ export async function handleManagerMessages(
const listText = isCeo ? "" : await todayList(ctx, manager.personId, today);
// проектный канал: диалог за сутки с временем (по Тампе) и накопленное для Daily Log
const channelBlocks: string[] = [];
const recapOn = !!proj && !!channel && live; // тихий режим и recap - только новая версия агента (промты proposed)
const recapOn = !!proj && !!channel; // тихий режим и recap проектных каналов - у всех менеджеров (промты согласованы, approved = proposed)
if (recapOn && proj && channel) {
const dialogText = await loadChannelDialog(deps.slack, channel, now, deps.timezone);
const st = await getRecapState(ctx.pool, channel);
@@ -326,7 +327,7 @@ ${recapBlock(st, deps.timezone)}`);
await saveChatTiming(ctx.pool, tm, ctx.log);
ctx.log.error({ manager: manager.personId, err }, "шаг 4 не удался");
await ctx.notifyIt(`:warning: khbuild_assistant_prep: шаг 4 (общение) для ${manager.name} не выполнен: ${err.slice(0, 500)}`);
if (!deps.dryPublish && channel) await deps.slack.postMessage(channel, "Не смог обработать сообщение - уже сообщил ИТ-команде, скоро разберёмся.");
if (!deps.dryPublish && channel) await deps.slack.postMessage(channel, "Sorry, I could not process your message. The IT team has been notified and will sort it out soon.");
throw e;
}
@@ -338,6 +339,9 @@ ${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

@@ -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;
}
}
}

View File

@@ -159,7 +159,6 @@ export class SlackIntake {
const now = (this.deps.now ?? (() => new Date()))();
const st = await getRecapState(this.pool, channel);
if (!st || st.status === "asked" || !st.notes.trim()) return;
if (promptSideFor(this.deps.ctx, manager.personId) !== "proposed") return; // recap - только у новой версии агента
if (now.getTime() - st.lastHumanAt.getTime() > 36 * 3600_000) {
await this.pool.query("delete from channel_recap_state where channel_id = $1", [channel]); // устарело: молча сбрасываем, не тревожим людей
return;