Календарь пассивных окон по дням недели (вторник весь день по Тампе): агенты в режиме passive; API; тесты; docs
All checks were successful
ci / test (push) Successful in 26s
ci / deploy (push) Successful in 1m33s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-19 21:13:38 +03:00
parent c59ac87486
commit 2a92458106
8 changed files with 166 additions and 4 deletions

View File

@@ -0,0 +1,15 @@
-- Календарь пассивных окон по дням недели: в это время все агенты в режиме passive (сами не пишут, на сообщения отвечают как обычно).
-- Первое окно: встреча менеджеров по вторникам (обсуждают статус работ).
create table agent_passive_window (
id uuid primary key default gen_random_uuid(),
weekday smallint not null check (weekday between 1 and 7), -- ISO: 1 - понедельник ... 7 - воскресенье
from_minute smallint not null default 0 check (from_minute between 0 and 1439), -- минут от полуночи, включительно
to_minute smallint not null default 1440 check (to_minute between 1 and 1440), -- минут от полуночи, не включительно (1440 - до конца дня)
timezone text not null default 'America/New_York',
is_active boolean not null default true,
note text,
created_at timestamptz not null default now(),
check (from_minute < to_minute)
);
alter table agent_passive_window enable row level security;
insert into agent_passive_window (weekday, from_minute, to_minute, note) values (2, 0, 1440, 'встреча менеджеров по вторникам: обсуждают статус работ');

View File

@@ -1,7 +1,7 @@
import type { FastifyInstance } from "fastify";
import type { Pool } from "khb_common";
import { loadMemory, saveMemory } from "./agents/session.js";
import { NOT_PAUSED_SQL, pauseState, resumeAll, resumeManager, setPause, setPauseAll } from "./pause.js";
import { activeWindow, loadWindows, NOT_PAUSED_SQL, pauseState, resumeAll, resumeManager, setPause, setPauseAll } from "./pause.js";
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const clampLimit = (v: unknown, def: number, max: number): number => {
@@ -94,6 +94,41 @@ export function registerAgentRoutes(app: FastifyInstance, pool: Pool): void {
app.post("/agents/resume-all", async () => ({ ok: true, managers: await resumeAll(pool) }));
/** Календарь пассивных окон по дням недели: в это время все агенты в режиме passive. */
app.get("/agents/passive-windows", async () => ({ windows: await loadWindows(pool), activeNow: await activeWindow(pool) }));
const WEEKDAYS: Record<string, number> = { mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6, sun: 7 };
const hhmm = (v: unknown, def: number): number | null => {
if (v === undefined || v === null || v === "") return def;
const m = String(v).match(/^(\d{1,2}):(\d{2})$/);
if (!m) return null;
const x = Number(m[1]) * 60 + Number(m[2]);
return x >= 0 && x <= 1440 ? x : null;
};
/** Добавить пассивное окно: weekday (1-7 или mon..sun), from/to ("HH:MM", по умолчанию весь день), timezone, note. */
app.post<{ Body: { weekday?: string | number; from?: string; to?: string; timezone?: string; note?: string } }>("/agents/passive-windows", async (req, reply) => {
const b = req.body ?? {};
const wd = typeof b.weekday === "number" ? b.weekday : (WEEKDAYS[String(b.weekday ?? "").slice(0, 3).toLowerCase()] ?? Number(b.weekday));
const from = hhmm(b.from, 0);
const to = hhmm(b.to, 1440);
if (!(wd >= 1 && wd <= 7)) return reply.code(400).send({ error: "weekday: 1-7 (1 - понедельник) или mon..sun" });
if (from === null || to === null || from >= to || from > 1439) return reply.code(400).send({ error: "from/to: время HH:MM, from меньше to (to может быть 24:00)" });
const tz = b.timezone ?? "America/New_York";
try {
new Intl.DateTimeFormat("en-US", { timeZone: tz });
} catch {
return reply.code(400).send({ error: "timezone: неизвестный часовой пояс" });
}
const { rows } = await pool.query("insert into agent_passive_window (weekday, from_minute, to_minute, timezone, note) values ($1,$2,$3,$4,$5) returning id", [wd, from, to, tz, b.note ?? null]);
return { ok: true, id: rows[0].id };
});
app.delete<{ Params: { wid: string } }>("/agents/passive-windows/:wid", async (req, reply) => {
if (!UUID.test(req.params.wid)) return reply.code(404).send({ error: "окно не найдено" });
const r = await pool.query("delete from agent_passive_window where id = $1", [req.params.wid]);
return r.rowCount ? { ok: true } : reply.code(404).send({ error: "окно не найдено" });
});
app.get<{ Params: { id: string } }>("/agents/:id/memory", async (req, reply) => {
const m = await knownManager(req.params.id);
if (!m) return reply.code(404).send({ error: "менеджер не найден" });

View File

@@ -12,6 +12,7 @@ import Fastify from "fastify";
import { registerAgentRoutes } from "./agents-api.js";
import { buildApi } from "./http-api.js";
import { listManagers } from "./managers.js";
import { pauseState } from "./pause.js";
import { handleManagerMessages } from "./slack/chat.js";
import { DriveInbox } from "./slack/drive-inbox.js";
import { SlackIntake } from "./slack/intake.js";
@@ -63,6 +64,7 @@ d("консольные агенты (временная БД, фейковый
db = await createTestDb(url!);
await db.pool.query("insert into person (id, display_name, jt_membership_id, slack_user_id) values ($1,'llmtest-Manager','m1','ULLMTEST')", [MGR]);
await db.pool.query("insert into construction_manager (person_id, slack_user_id, slack_channel_id) values ($1,'ULLMTEST','CLLMTEST')", [MGR]);
await db.pool.query("delete from agent_passive_window"); // миграция сеет вторник; результаты тестов не должны зависеть от дня недели
});
afterAll(async () => { await db?.drop(); });
@@ -299,6 +301,58 @@ d("консольные агенты (временная БД, фейковый
}
});
it("календарь пассивных окон: во вторник (по Тампе) события не идут никому, сообщения менеджеров обрабатываются как обычно", async () => {
calls = [];
const app = Fastify();
registerAgentRoutes(app, db.pool);
await db.pool.query("insert into assistant_project (jt_job_id, manager_person_id, mode, is_enabled) values ('llmtest-window',$1,'test',true)", [MGR]);
const TUE = new Date("2026-10-20T15:00:00Z"); // вторник 11:00 по Тампе
const TUE_LATE = new Date("2026-10-21T03:30:00Z"); // вторник 23:30 по Тампе (в UTC уже среда)
const MON = new Date("2026-10-19T15:00:00Z");
const WED = new Date("2026-10-21T04:30:00Z"); // среда 00:30 по Тампе
try {
const post = (url: string, payload: object) => app.inject({ method: "POST", url, payload });
expect((await post("/agents/passive-windows", { weekday: "tue", note: "встреча менеджеров" })).statusCode).toBe(200); // весь день
expect((await post("/agents/passive-windows", { weekday: 9 })).statusCode).toBe(400);
expect((await post("/agents/passive-windows", { weekday: "fri", from: "13:00", to: "12:00" })).statusCode).toBe(400);
expect((await post("/agents/passive-windows", { weekday: "fri", timezone: "Mars/Olympus" })).statusCode).toBe(400);
const ids = async (now: Date) => (await listManagers(db.pool, ["test"], { now })).map((m) => m.personId);
expect(await ids(MON)).toContain(MGR);
expect(await ids(TUE)).toEqual([]); // вторник: события не идут никому
expect(await ids(TUE_LATE)).toEqual([]); // вторник по Тампе, хотя в UTC уже среда
expect(await ids(WED)).toContain(MGR);
expect((await listManagers(db.pool, ["test"], { includePaused: true, now: TUE })).map((m) => m.personId)).toContain(MGR); // ручные запуски владельца идут
expect(await pauseState(db.pool, MGR, TUE)).toMatchObject({ paused: true, mode: "passive", by: "calendar" });
expect((await pauseState(db.pool, MGR, MON)).paused).toBe(false);
const w = (await app.inject("/agents/passive-windows")).json() as { windows: Array<{ id: string; weekday: number; fromMinute: number; toMinute: number }> };
expect(w.windows).toHaveLength(1);
expect(w.windows[0]).toMatchObject({ weekday: 2, fromMinute: 0, toMinute: 1440 });
// окно с интервалом
expect((await post("/agents/passive-windows", { weekday: "mon", from: "09:00", to: "12:00" })).statusCode).toBe(200);
expect(await ids(new Date("2026-10-19T14:00:00Z"))).toEqual([]); // понедельник 10:00
expect(await ids(new Date("2026-10-19T16:30:00Z"))).toContain(MGR); // понедельник 12:30
// удаление
expect((await app.inject({ method: "DELETE", url: "/agents/passive-windows/" + w.windows[0]!.id })).statusCode).toBe(200);
expect(await ids(TUE)).toContain(MGR);
// сообщение менеджера в пассивное окно обрабатывается как обычно
await post("/agents/passive-windows", { weekday: "tue" });
const nl = String.fromCharCode(10);
script = [ok(["## Ответ менеджеру", "ответ во вторник", "## Память", "м"].join(nl))];
const posted: string[] = [];
const deps = { ctx: ctx(), timezone: "America/New_York", slack: { postMessage: async (_c: string, x: string) => { posted.push(x); return true; }, fileInfo: async () => null, download: async () => 0 } };
const intake = new SlackIntake(deps, { channelIds: [], debounceMs: 600_000 });
await intake.onEvent({ type: "message", channel: "CLLMTEST", user: "ULLMTEST", ts: "8.1", text: "пишу во вторник" });
await intake.flush(MGR);
await intake.idle();
intake.stop();
expect(posted).toEqual(["ответ во вторник"]);
} finally {
await db.pool.query("delete from agent_passive_window");
await db.pool.query("delete from assistant_project where jt_job_id = 'llmtest-window'");
await app.close();
}
});
it("событие ассистента: напоминание пишется в историю, ответ менеджера закрывает его; через followup агент спрашивает `что-то ещё`", async () => {
calls = [];
const posted: string[] = [];

View File

@@ -1,5 +1,5 @@
import type { Pool } from "khb_common";
import { NOT_PAUSED_SQL } from "./pause.js";
import { activeWindow, NOT_PAUSED_SQL } from "./pause.js";
import { rowToManager } from "./slack/intake.js";
import type { ManagerInfo } from "./slack/chat.js";
@@ -7,7 +7,9 @@ import type { ManagerInfo } from "./slack/chat.js";
* Менеджеры с включённым проектом нужного режима. По умолчанию без отключённых (пауза на время или до команды): системные события им не идут.
* Для ручных запусков владельца (simulate/apply) отключённых можно включить в список (`includePaused`).
*/
export async function listManagers(pool: Pool, modes: string[], opts: { includePaused?: boolean } = {}): Promise<ManagerInfo[]> {
export async function listManagers(pool: Pool, modes: string[], opts: { includePaused?: boolean; now?: Date } = {}): Promise<ManagerInfo[]> {
// в пассивное окно календаря (например, вторник) системные события не идут никому
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
from construction_manager cm join person p on p.id = cm.person_id

View File

@@ -8,6 +8,39 @@ export const NOT_PAUSED_SQL = (alias = "cm"): string => `(not ${alias}.agent_pau
export type PauseMode = "passive" | "off";
/** Пассивное окно календаря: день недели (ISO, 1 - понедельник) и интервал в минутах от полуночи в часовом поясе окна. */
export interface PassiveWindow {
id?: string;
weekday: number;
fromMinute: number;
toMinute: number;
timezone: string;
note: string | null;
}
/** День недели (ISO) и минуты от полуночи момента `now` в часовом поясе. */
export function localWeekdayMinute(now: Date, timezone: string): { weekday: number; minute: number } {
const parts = new Intl.DateTimeFormat("en-US", { timeZone: timezone, weekday: "short", hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).formatToParts(now);
const get = (t: string) => parts.find((x) => x.type === t)?.value ?? "";
const weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].indexOf(get("weekday")) + 1;
return { weekday, minute: Number(get("hour")) * 60 + Number(get("minute")) };
}
export const inWindow = (w: PassiveWindow, now: Date): boolean => {
const l = localWeekdayMinute(now, w.timezone);
return l.weekday === w.weekday && l.minute >= w.fromMinute && l.minute < w.toMinute;
};
export async function loadWindows(pool: Pool): Promise<PassiveWindow[]> {
const { rows } = await pool.query("select id, weekday, from_minute, to_minute, timezone, note from agent_passive_window where is_active order by weekday, from_minute");
return rows.map((r) => ({ id: String(r.id), weekday: Number(r.weekday), fromMinute: Number(r.from_minute), toMinute: Number(r.to_minute), timezone: String(r.timezone), note: (r.note as string | null) ?? null }));
}
/** Пассивное окно календаря, действующее сейчас (null - нет). */
export async function activeWindow(pool: Pool, now: Date = new Date()): Promise<PassiveWindow | null> {
return (await loadWindows(pool)).find((w) => inWindow(w, now)) ?? null;
}
export interface PauseState {
paused: boolean;
/** passive - молчит, пока ему не пишут (на сообщения отвечает как обычно); off - ничего не делает. */
@@ -19,7 +52,7 @@ export interface PauseState {
by: string | null;
}
export async function pauseState(pool: Pool, managerId: string): Promise<PauseState> {
export async function pauseState(pool: Pool, managerId: string, now: Date = new Date()): Promise<PauseState> {
const { rows } = await pool.query(
`select (not ${NOT_PAUSED_SQL("cm")}) as paused, cm.pause_mode, cm.agent_paused, cm.paused_until, cm.pause_reason, cm.paused_by from construction_manager cm where cm.person_id = $1`,
[managerId],
@@ -27,6 +60,11 @@ export async function pauseState(pool: Pool, managerId: string): Promise<PauseSt
const r = rows[0];
if (!r) return { paused: false, mode: "passive", indefinite: false, until: null, reason: null, by: null };
const paused = r.paused === true;
if (!paused) {
// календарь пассивных окон (например, вторник): агент в режиме passive у всех менеджеров
const w = await activeWindow(pool, now);
if (w) return { paused: true, mode: "passive", indefinite: false, until: null, reason: `календарь: ${w.note ?? "пассивное окно"}`, by: "calendar" };
}
return { paused, mode: r.pause_mode === "off" ? "off" : "passive", indefinite: paused && r.agent_paused === true, until: paused && !r.agent_paused ? (r.paused_until as Date) : null, reason: paused ? (r.pause_reason as string | null) : null, by: paused ? (r.paused_by as string | null) : null };
}