Чат руководителя (chat_kind = ceo, промт p-ceo-assistant, ответ в разделе «Ответ Arthur»); блоки входа и правило про todo - всем версиям, необязательные фрагменты; тесты; docs
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
3
packages/khb_common/migrations/020_chat_kind.sql
Normal file
3
packages/khb_common/migrations/020_chat_kind.sql
Normal file
@@ -0,0 +1,3 @@
|
||||
-- Вид чата ассистента: manager - чат менеджера по стройке, ceo - личный чат руководителя (Arthur): свой промт, без списка задач на день.
|
||||
alter table construction_manager
|
||||
add column chat_kind text not null default 'manager' check (chat_kind in ('manager', 'ceo'));
|
||||
@@ -206,7 +206,6 @@ d("консольные агенты (временная БД, фейковый
|
||||
expect(liveCalls).toHaveLength(2);
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0]!.prompt).toContain("# Память");
|
||||
expect(calls[0]!.prompt).not.toContain("Todo самого менеджера"); // старая версия без изменений
|
||||
});
|
||||
|
||||
it("тайминг чата: строка chat_timing с этапами от сообщения в Slack до ответа в Slack", async () => {
|
||||
@@ -469,6 +468,27 @@ d("консольные агенты (временная БД, фейковый
|
||||
expect(r2.sections.get("ответ менеджеру")).toContain("can't write");
|
||||
expect(calls).toHaveLength(1);
|
||||
});
|
||||
it("чат руководителя (chat_kind = ceo): свой промт, раздел «Ответ Arthur», без списка задач на день", async () => {
|
||||
const liveCalls: ClaudeCall[] = [];
|
||||
const nl = String.fromCharCode(10);
|
||||
const liveRunner = {
|
||||
run: async (c: ClaudeCall) => { liveCalls.push(c); return { text: ["## Ответ Arthur", "Got it, Arthur.", "## Память", "ceo-память"].join(nl), sessionId: c.sessionId }; },
|
||||
isActive: () => false, activeSession: () => null, close: () => undefined, closeAll: () => undefined, activeCount: () => 0,
|
||||
};
|
||||
const base = ctx();
|
||||
const ceoCtx = { ...base, liveRunner, settings: { ...base.settings, live: { managerIds: [MGR], idleMinutes: 10, warmupSeconds: 0 } } };
|
||||
const posted: string[] = [];
|
||||
const slack = { postMessage: async (_c: string, x: string) => { posted.push(x); return true; }, fileInfo: async () => null, download: async () => 0 };
|
||||
const ceo = { personId: MGR, name: "Arthur Atanoff", slackUserId: "ULLMTEST", slackChannelId: "CLLMTEST", chatKind: "ceo" as const };
|
||||
const res = await handleManagerMessages({ ctx: ceoCtx, timezone: "America/New_York", slack }, ceo, [{ channel: "CLLMTEST", ts: "1791741400.000001", text: "what is overdue?", fileIds: [] }]);
|
||||
expect(res.reply).toBe("Got it, Arthur.");
|
||||
expect(posted).toEqual(["Got it, Arthur."]);
|
||||
const p = liveCalls[0]!.prompt;
|
||||
expect(p).toContain("личный ассистент Arthur Atanoff"); // промт руководителя
|
||||
expect(p).not.toContain("# Список задач на сегодня");
|
||||
expect(p).toContain("# Память");
|
||||
expect(p).toContain("what is overdue?");
|
||||
});
|
||||
it("API агентов: память читается и пишется с аудитом, сброс сессии, история", async () => {
|
||||
const app = buildApi({ pool: db.pool, token: "t", run: async () => { throw new Error("не нужен"); } });
|
||||
const h = { authorization: "Bearer t" };
|
||||
|
||||
@@ -11,7 +11,7 @@ export async function listManagers(pool: Pool, modes: string[], opts: { includeP
|
||||
// в пассивное окно календаря (например, вторник) системные события не идут никому
|
||||
if (!opts.includePaused && (await activeWindow(pool, opts.now))) return [];
|
||||
const { rows } = await pool.query(
|
||||
`select distinct cm.person_id, p.display_name, cm.slack_user_id, cm.slack_channel_id, cm.reply_mode, cm.tts_voice
|
||||
`select distinct cm.person_id, p.display_name, cm.slack_user_id, cm.slack_channel_id, cm.reply_mode, cm.tts_voice, cm.chat_kind
|
||||
from construction_manager cm join person p on p.id = cm.person_id
|
||||
join assistant_project ap on ap.manager_person_id = cm.person_id and ap.is_enabled and ap.mode = any($1)
|
||||
where cm.is_active and p.is_active${opts.includePaused ? "" : ` and ${NOT_PAUSED_SQL("cm")}`}`,
|
||||
|
||||
@@ -82,9 +82,6 @@ describe("промты в docs модуля (p-*.md)", () => {
|
||||
it("формулировки не изменились при переносе из кода (approved)", () => {
|
||||
expect(loadFragment("p-chat-environment.md", "Запись в JobTread запрещена", {}, "approved")).toBe("Запись в JobTread запрещена.");
|
||||
expect(loadFragment("p-chat-environment.md", "Запись в JobTread разрешена", { jobs: "a, b" }, "approved")).toBe("Писать в JobTread разрешено ТОЛЬКО в проекты с id: a, b. Остальные проекты не трогай.");
|
||||
expect(loadFragment("p-chat-events.md", "Повтор 13:00", {}, "approved")).toBe(
|
||||
"Наступило 13:00 по Тампе. Если обновления от менеджера до сих пор нет - напомни ещё раз и упомяни следующие 3-5 задач из списка (ротация). Если обновление было - `(без ответа)`.",
|
||||
);
|
||||
expect(loadFragment("p-result-validator.md", "Исправь формат ответа", { error: "E" }, "approved")).toContain("Твой предыдущий ответ не принят: E. Исправь и выведи ответ ЦЕЛИКОМ");
|
||||
});
|
||||
|
||||
@@ -109,8 +106,6 @@ describe("промты в docs модуля (p-*.md)", () => {
|
||||
expect(loadFragment("p-chat-events.md", "Итог дня 16:00", {}, "proposed")).toContain(remind);
|
||||
expect(loadPrompt("p-manager-dialog.md", {}, "proposed")).toContain(remind);
|
||||
expect(loadFragment("p-chat-environment.md", "Частота сообщений", {}, "proposed")).toContain("менеджер сегодня отвечал: {{replied_today}}");
|
||||
// прежняя версия (approved) без изменений
|
||||
expect(loadFragment("p-chat-events.md", "Повтор 13:00", {}, "approved")).not.toContain(remind);
|
||||
});
|
||||
|
||||
it("начало суток по Тампе: полночь в часовом поясе, а не в UTC", () => {
|
||||
@@ -118,4 +113,12 @@ describe("промты в docs модуля (p-*.md)", () => {
|
||||
expect(startOfLocalDay(new Date("2026-10-21T03:30:00Z"), "America/New_York").toISOString()).toBe("2026-10-20T04:00:00.000Z"); // вторник 23:30 по Тампе, в UTC уже среда
|
||||
expect(startOfLocalDay(new Date("2026-12-01T12:00:00Z"), "America/New_York").toISOString()).toBe("2026-12-01T05:00:00.000Z"); // зимой UTC-5
|
||||
});
|
||||
|
||||
it("промт руководителя (proposed): формат вывода с разделом «Ответ Arthur» и подстановкой media_dir", () => {
|
||||
const body = loadPrompt("p-ceo-assistant.md", {}, "proposed");
|
||||
expect(body).toContain("## Ответ Arthur");
|
||||
expect(body).toContain("## Память");
|
||||
expect(body).toContain("JobTread недоступен или запись не проходит");
|
||||
expect(vars(body)).toEqual(["media_dir"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -18,6 +18,8 @@ export interface ManagerInfo {
|
||||
replyMode?: ReplyMode;
|
||||
/** Голос Chirp 3 HD для чата; null - по умолчанию. */
|
||||
ttsVoice?: string | null;
|
||||
/** manager - чат менеджера; ceo - личный чат руководителя (свой промт, ответ в разделе `## Ответ Arthur`, без списка задач на день). */
|
||||
chatKind?: "manager" | "ceo";
|
||||
}
|
||||
|
||||
/** Проектный канал Slack: проект задан каналом, уточнять его у пользователя не нужно. */
|
||||
@@ -193,6 +195,14 @@ export async function handleManagerMessages(
|
||||
const live = useLive(ctx, manager.personId);
|
||||
const side: PromptSide = live ? "proposed" : "approved";
|
||||
const fragment = (file: string, title: string, vars: Record<string, string> = {}) => loadFragment(file, title, vars, side);
|
||||
// блоки, которые согласованные промты могут ожидать у всех версий агента; если на этой стороне фрагмента ещё нет - блок пропускается
|
||||
const optFragment = (file: string, title: string, vars: Record<string, string> = {}): string | null => {
|
||||
try {
|
||||
return loadFragment(file, title, vars, side);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
const projectBlock = proj
|
||||
? [
|
||||
"",
|
||||
@@ -208,8 +218,9 @@ export async function handleManagerMessages(
|
||||
// короткий промт - только если живой процесс продолжает ту же сессию, что записана для менеджера (после сброса сессии нужны полные инструкции)
|
||||
const inDialog = live && mem.sessionId !== null && ctx.liveRunner!.activeSession(managerWorkDir(ctx.settings, manager.personId)) === mem.sessionId;
|
||||
// Новая версия: todo самого менеджера можно закрывать и менять в любом проекте и на уровне организации (обращение ИТ 16.10.2026: todo без проекта агент не трогал)
|
||||
const membershipId = live ? (((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) : null;
|
||||
const todoRules = live ? `\n${fragment("p-long-living-agents.md", "Todo менеджера", { membership: membershipId ? `; его membership в JobTread: ${membershipId}` : "" })}` : "";
|
||||
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}` : "";
|
||||
const liveRules = live ? `\n${fragment("p-long-living-agents.md", "Правила долгоживущего агента")}` : "";
|
||||
const testJobs = ctx.settings.testJobIds ?? [];
|
||||
const writeRules = writableJobs.length
|
||||
@@ -223,7 +234,7 @@ export async function handleManagerMessages(
|
||||
// Новая версия: упоминание менеджера и частота сообщений ассистента (правило «не чаще раза в час»)
|
||||
const iso = (v: unknown) => (v ? new Date(v as string).toISOString() : "нет");
|
||||
const freqBlocks: string[] = [];
|
||||
if (live) {
|
||||
{
|
||||
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,
|
||||
@@ -232,18 +243,18 @@ export async function handleManagerMessages(
|
||||
(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)],
|
||||
);
|
||||
freqBlocks.push(
|
||||
"",
|
||||
`# Менеджер\n${fragment("p-chat-environment.md", "Менеджер", { name: manager.name, mention: manager.slackUserId ? `<@${manager.slackUserId}>` : manager.name })}`,
|
||||
"",
|
||||
`# Частота сообщений\n${fragment("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 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 ? "да" : "нет" });
|
||||
if (mgrText) freqBlocks.push("", `# Менеджер\n${mgrText}`);
|
||||
if (freqText) freqBlocks.push("", `# Частота сообщений\n${freqText}`);
|
||||
}
|
||||
const listText = await todayList(ctx, manager.personId, today);
|
||||
const isCeo = manager.chatKind === "ceo";
|
||||
const replyKey = isCeo ? "ответ arthur" : "ответ менеджеру";
|
||||
const listText = isCeo ? "" : await todayList(ctx, manager.personId, today);
|
||||
const buildPrompt = (dialog: boolean): string => [
|
||||
...(dialog
|
||||
? [`# Продолжение диалога\n${fragment("p-long-living-agents.md", "Продолжение диалога")}`]
|
||||
: [loadPrompt(proj ? "p-project-channel.md" : "p-manager-dialog.md", { media_dir: mediaDir }, side)]),
|
||||
: [loadPrompt(isCeo ? "p-ceo-assistant.md" : proj ? "p-project-channel.md" : "p-manager-dialog.md", { media_dir: mediaDir }, side)]),
|
||||
"",
|
||||
`# Дата и время\n${now.toISOString()} (UTC); дата по Тампе: ${today}; сообщений менеджера за последние сутки: ${todayCount}`,
|
||||
...freqBlocks,
|
||||
@@ -251,7 +262,9 @@ export async function handleManagerMessages(
|
||||
...projectBlock,
|
||||
...(dialog
|
||||
? []
|
||||
: ["", `# Список задач на сегодня\n${listText}`, "", `# Память\n${mem.memoryText.trim() || "(пусто)"}`]),
|
||||
: isCeo
|
||||
? ["", `# Память\n${mem.memoryText.trim() || "(пусто)"}`]
|
||||
: ["", `# Список задач на сегодня\n${listText}`, "", `# Память\n${mem.memoryText.trim() || "(пусто)"}`]),
|
||||
"",
|
||||
`# Ограничения среды\nМенеджер: ${manager.name}. ${writeRules}${disabledRules}${liveRules}${todoRules}`,
|
||||
"",
|
||||
@@ -267,7 +280,7 @@ export async function handleManagerMessages(
|
||||
// 4. агент
|
||||
let out;
|
||||
try {
|
||||
out = await runManagerAgent(ctx, { managerId: manager.personId, step: "step4", tools: "chat", prompt, fullPrompt, required: ["ответ менеджеру", "память"] });
|
||||
out = await runManagerAgent(ctx, { managerId: manager.personId, step: "step4", tools: "chat", prompt, fullPrompt, required: [replyKey, "память"] });
|
||||
tm.agent = out.timing;
|
||||
mark = Date.now();
|
||||
} catch (e) {
|
||||
@@ -286,7 +299,7 @@ export async function handleManagerMessages(
|
||||
// 5. результат
|
||||
await saveMemory(ctx.pool, manager.personId, out.sections.get("память")!);
|
||||
await saveProblems(ctx, manager.personId, "step4", out.sections);
|
||||
const replyRaw = out.sections.get("ответ менеджеру")!;
|
||||
const replyRaw = out.sections.get(replyKey)!;
|
||||
const reply = /^\(без ответа\)\.?$/i.test(replyRaw) ? null : replyRaw;
|
||||
let published = false;
|
||||
let audioSent = false;
|
||||
|
||||
@@ -19,6 +19,7 @@ export function rowToManager(r: Record<string, unknown>): ManagerInfo {
|
||||
slackChannelId: (r.slack_channel_id as string | null) ?? null,
|
||||
replyMode: isReplyMode(r.reply_mode) ? r.reply_mode : "text",
|
||||
ttsVoice: (r.tts_voice as string | null) ?? null,
|
||||
chatKind: r.chat_kind === "ceo" ? "ceo" : "manager",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -42,7 +43,7 @@ export class SlackIntake {
|
||||
|
||||
async findManagerBySlackUser(slackUserId: string): Promise<ManagerInfo | null> {
|
||||
const { rows } = await this.pool.query(
|
||||
`select cm.person_id, p.display_name, cm.slack_user_id, cm.slack_channel_id, cm.reply_mode, cm.tts_voice
|
||||
`select cm.person_id, p.display_name, cm.slack_user_id, cm.slack_channel_id, cm.reply_mode, cm.tts_voice, cm.chat_kind
|
||||
from construction_manager cm join person p on p.id = cm.person_id
|
||||
where cm.slack_user_id = $1 and cm.is_active and p.is_active`,
|
||||
[slackUserId],
|
||||
@@ -119,7 +120,7 @@ export class SlackIntake {
|
||||
|
||||
async findManagerByPerson(personId: string): Promise<ManagerInfo | null> {
|
||||
const { rows } = await this.pool.query(
|
||||
`select cm.person_id, p.display_name, cm.slack_user_id, cm.slack_channel_id, cm.reply_mode, cm.tts_voice
|
||||
`select cm.person_id, p.display_name, cm.slack_user_id, cm.slack_channel_id, cm.reply_mode, cm.tts_voice, cm.chat_kind
|
||||
from construction_manager cm join person p on p.id = cm.person_id where cm.person_id = $1 limit 1`,
|
||||
[personId],
|
||||
);
|
||||
@@ -129,7 +130,7 @@ export class SlackIntake {
|
||||
/** Менеджер чата (по slack_channel_id или единственный активный менеджер для каналов из настроек). */
|
||||
async findManagerByChannel(channel: string): Promise<ManagerInfo | null> {
|
||||
const { rows } = await this.pool.query(
|
||||
`select cm.person_id, p.display_name, cm.slack_user_id, cm.slack_channel_id, cm.reply_mode, cm.tts_voice
|
||||
`select cm.person_id, p.display_name, cm.slack_user_id, cm.slack_channel_id, cm.reply_mode, cm.tts_voice, cm.chat_kind
|
||||
from construction_manager cm join person p on p.id = cm.person_id
|
||||
where cm.slack_channel_id = $1 and cm.is_active and p.is_active order by cm.person_id limit 1`,
|
||||
[channel],
|
||||
|
||||
Reference in New Issue
Block a user