Короткое напоминание только если осмысленное сообщение было менее 24 часов назад (last_meaningful, миграция 039, п.86)
All checks were successful
ci / test (push) Successful in 38s
ci / deploy (push) Successful in 2m37s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 08:47:46 +03:00
parent 198eafa86f
commit 213ef36bcf
9 changed files with 35 additions and 13 deletions

View File

@@ -0,0 +1,3 @@
-- Длина ответа ассистента в словах (без упоминаний): по ней отличаем короткое напоминание от осмысленного сообщения.
-- Короткое напоминание допустимо, только если последнее осмысленное сообщение ассистента было менее 24 часов назад.
alter table chat_timing add column if not exists reply_words integer;

View File

@@ -2,7 +2,7 @@ import { readFileSync } from "node:fs";
import { basename } from "node:path";
import { describe, expect, it } from "vitest";
import { CHAT_TOOLS } from "./agents/cli-runner.js";
import { startOfLocalDay } from "./slack/chat.js";
import { SHORT_REPLY_WORDS, replyWordCount, startOfLocalDay } from "./slack/chat.js";
import { fillVars, listPromptFiles, loadFragment, loadPrompt, parseFragments, parsePromptFile, type PromptSide } from "./agents/prompts.js";
const SIDES: PromptSide[] = ["approved", "proposed"];
@@ -33,7 +33,7 @@ const LIVE_FRAGMENTS: Record<string, Record<string, string[]>> = {
"p-long-living-agents.md": { "Продолжение диалога": [], "Правила долгоживущего агента": [], "Todo менеджера": ["membership"], "Сведение памяти": [] },
"p-chat-events.md": { "Беседа в проектном канале затихла": [], "События todo": ["events"] },
"p-todo-tool.md": { "Todo: khb-todo": ["person_id"] },
"p-chat-environment.md": { "Менеджер": ["name", "mention"], "Частота сообщений": ["last_assistant", "last_human", "unanswered", "assistant_today", "replied_today"] },
"p-chat-environment.md": { "Менеджер": ["name", "mention"], "Частота сообщений": ["last_assistant", "last_human", "unanswered", "last_meaningful", "assistant_today", "replied_today"] },
};
const vars = (text: string) => [...new Set([...text.matchAll(/\{\{(\w+)\}\}/g)].map((m) => m[1]!))].sort();
@@ -112,8 +112,14 @@ describe("промты в docs модуля (p-*.md)", () => {
expect(text).not.toContain(old);
expect(text).toContain("4-8 слов");
expect(text).toContain("Any notes on the above?");
// короткая фраза - только если осмысленное сообщение было менее 24 часов назад, иначе снова осмысленное сообщение
expect(text).toContain("last_meaningful");
expect(text).toContain("24 часов");
}
expect(loadFragment("p-chat-environment.md", "Частота сообщений", {}, "proposed")).toContain("менеджер сегодня отвечал: {{replied_today}}");
expect(loadFragment("p-chat-environment.md", "Частота сообщений", {}, "proposed")).toContain("{{last_meaningful}}");
expect(replyWordCount("<@U123> Any notes on the above?")).toBe(5);
expect(replyWordCount("Hi <@U1>! Quick question about the framing inspection today and tomorrow's schedule?")).toBeGreaterThan(SHORT_REPLY_WORDS - 4);
});
it("проектный канал (proposed): тихий режим, recap, подтверждение, Huddle и новые разделы вывода", () => {

View File

@@ -271,13 +271,14 @@ export async function handleManagerMessages(
const { rows: fr } = await ctx.pool.query(
`select (select max(reply_at) from chat_timing where manager_person_id = $1) as last_assistant,
(select max(received_at) from slack_message_log where manager_person_id = $1) as last_human,
(select max(reply_at) from chat_timing where manager_person_id = $1 and (reply_words is null or reply_words > $3)) as last_meaningful,
(select count(*)::int from chat_timing where manager_person_id = $1 and reply_at >= $2::timestamptz) as assistant_today,
exists(select 1 from slack_message_log where manager_person_id = $1 and received_at >= $2::timestamptz) as replied_today,
(select count(*)::int from chat_timing where manager_person_id = $1 and reply_at > coalesce((select max(received_at) from slack_message_log where manager_person_id = $1), '-infinity')) as unanswered`,
[manager.personId, startOfLocalDay(now, deps.timezone)],
[manager.personId, startOfLocalDay(now, deps.timezone), SHORT_REPLY_WORDS],
);
const mgrText = optFragment("p-chat-environment.md", "Менеджер", { name: manager.name, mention: manager.slackUserId ? `<@${manager.slackUserId}>` : manager.name });
const freqText = optFragment("p-chat-environment.md", "Частота сообщений", { last_assistant: iso(fr[0]?.last_assistant), last_human: iso(fr[0]?.last_human), unanswered: String(fr[0]?.unanswered ?? 0), assistant_today: String(fr[0]?.assistant_today ?? 0), replied_today: fr[0]?.replied_today ? "да" : "нет" });
const freqText = optFragment("p-chat-environment.md", "Частота сообщений", { last_assistant: iso(fr[0]?.last_assistant), last_human: iso(fr[0]?.last_human), unanswered: String(fr[0]?.unanswered ?? 0), last_meaningful: iso(fr[0]?.last_meaningful), assistant_today: String(fr[0]?.assistant_today ?? 0), replied_today: fr[0]?.replied_today ? "да" : "нет" });
if (mgrText) freqBlocks.push("", `# Менеджер\n${mgrText}`);
if (freqText) freqBlocks.push("", `# Частота сообщений\n${freqText}`);
}
@@ -374,6 +375,7 @@ ${recapBlock(st, deps.timezone)}`);
const pr = await publishReply(deps, manager, channel, reply);
({ published, audioSent } = pr);
tm.replySlackTs = pr.replyTs;
tm.replyWords = replyWordCount(reply);
tm.publishMs = Date.now() - tp;
}
if (reply && opts.systemEvent) {
@@ -396,6 +398,12 @@ ${recapBlock(st, deps.timezone)}`);
}
/** Публикует ответ по настройке чата: текст / текст и аудио / только аудио. Любой сбой аудио - ответ уходит текстом, ИТ видит проблему в логе. */
/** Короткое напоминание - до 12 слов (4-8 слов фразы и упоминание); длиннее - осмысленное сообщение. */
export const SHORT_REPLY_WORDS = 12;
/** Число слов ответа без упоминаний Slack (<@U…>). */
export const replyWordCount = (text: string): number => text.replace(/<@[^>]+>/g, " ").split(/\s+/).filter(Boolean).length;
export async function publishReply(deps: ChatDeps, manager: ManagerInfo, channel: string, reply: string): Promise<{ published: boolean; audioSent: boolean; replyTs: string | null }> {
const mode = manager.replyMode ?? "text";
const voice = normalizeVoice(manager.ttsVoice) ?? normalizeVoice(deps.defaultVoice) ?? "Aoede";

View File

@@ -11,6 +11,8 @@ export interface ChatTiming {
messageTs?: string;
receivedAt?: Date | null;
replySlackTs?: string | null;
/** Длина ответа в словах без упоминаний: по ней отличаем короткое напоминание от осмысленного сообщения. */
replyWords?: number | null;
inputsMs?: number;
driveMs?: number;
promptMs?: number;
@@ -44,12 +46,12 @@ export async function saveChatTiming(pool: Pool, t: ChatTiming, log?: { warn(o:
const replyAt = slackTsToDate(t.replySlackTs);
const modelMs = sum(runs.map((r) => r.timing?.turnMs ?? r.wallMs));
await pool.query(
`insert into chat_timing (manager_person_id, channel_id, kind, agent_version, status, error, message_ts, message_at, received_at, started_at, reply_slack_ts, reply_at,
`insert into chat_timing (manager_person_id, channel_id, kind, agent_version, status, error, message_ts, message_at, received_at, started_at, reply_slack_ts, reply_at, reply_words,
slack_in_ms, debounce_ms, inputs_ms, drive_ms, prompt_ms, prompt_chars, queue_ms, start_ms, model_ms, api_ms, first_event_ms, tool_calls, num_turns, attempts, cost_usd,
post_ms, publish_ms, final_ms, processing_ms, total_ms, steps)
values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$30,$31,$32,$33)`,
values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$30,$31,$32,$33,$34)`,
[
t.managerId, t.channel, t.kind, t.agentVersion, t.status, t.error?.slice(0, 500) ?? null, t.messageTs ?? null, messageAt, t.receivedAt ?? null, t.startedAt, t.replySlackTs ?? null, replyAt,
t.managerId, t.channel, t.kind, t.agentVersion, t.status, t.error?.slice(0, 500) ?? null, t.messageTs ?? null, messageAt, t.receivedAt ?? null, t.startedAt, t.replySlackTs ?? null, replyAt, t.replyWords ?? null,
int(messageAt && t.receivedAt ? t.receivedAt.getTime() - messageAt.getTime() : null),
int(t.receivedAt ? t.startedAt.getTime() - t.receivedAt.getTime() : null),
int(t.inputsMs), int(t.driveMs), int(t.promptMs), int(t.promptChars), int(t.agent?.queueMs),