Каркас monorepo: scheduler, data_collector, khbuild_assistant_prep, khb_common; миграции; CI/CD
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
142
packages/khbuild_assistant_prep/src/jobs.int.test.ts
Normal file
142
packages/khbuild_assistant_prep/src/jobs.int.test.ts
Normal file
@@ -0,0 +1,142 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { createLogger, createTestDb, testDatabaseUrl, type TestDb } from "khb_common";
|
||||
import { runPrepJob, type PrepDeps } from "./jobs.js";
|
||||
|
||||
const url = testDatabaseUrl();
|
||||
const d = url ? describe : describe.skip;
|
||||
|
||||
const NOW = new Date("2026-10-14T10:00:00Z"); // среда, 06:00 Tampa; неделя 12-18 октября, следующая 19-25
|
||||
const SNAP = new Date(NOW.getTime() - 20 * 60_000);
|
||||
const MGR = "llmtest-mgr";
|
||||
const VENDOR = "llmtest-vendor";
|
||||
const JOB = "llmtest-job";
|
||||
|
||||
async function seed(db: TestDb) {
|
||||
const q = (sql: string, p: unknown[] = []) => db.pool.query(sql, p);
|
||||
await q("insert into sync_snapshot (started_at, source_prefix, finished_at, requested_tables) values ($1,'jt',$1,'{}')", [SNAP]);
|
||||
for (const t of ["jt_job", "jt_membership", "jt_task", "jt_task_dependency", "jt_task_assignment"])
|
||||
await q("insert into sync_table_status (snapshot_ts, table_name, status, row_count, finished_at) values ($1,$2,'ok',0,$1)", [SNAP, t]);
|
||||
await q("insert into jt_job (id, name, snapshot_ts) values ($1,'llmtest-Project',$2), ('llmtest-other-job','llmtest-Other',$2)", [JOB, SNAP]);
|
||||
await q("insert into jt_membership (id, user_name, role, snapshot_ts) values ($1,'llmtest-Manager','Admin',$3), ($2,'llmtest-Vendor','Vendor',$3)", [MGR, VENDOR, SNAP]);
|
||||
// id, name, start, end, progress, is_todo
|
||||
const tasks: [string, string, string | null, string | null, number | null, boolean, string][] = [
|
||||
["t-overdue", "llmtest-Overdue work", "2026-10-01", "2026-10-05", null, false, JOB],
|
||||
["t-week", "llmtest-Foundation", "2026-10-13", "2026-10-17", 0.3, false, JOB],
|
||||
["t-future", "llmtest-Future work", "2026-10-28", "2026-10-30", null, false, JOB],
|
||||
["t-done", "llmtest-Done work", "2026-10-12", "2026-10-13", 1, false, JOB],
|
||||
["todo-over", "llmtest-todo overdue", "2026-10-10", "2026-10-10", null, true, JOB],
|
||||
["todo-week", "llmtest-todo this week", "2026-10-15", "2026-10-15", null, true, JOB],
|
||||
["todo-next", "llmtest-todo next week", "2026-10-21", "2026-10-21", null, true, JOB],
|
||||
["p-soon", "Purchase 1 order start", "2026-10-20", "2026-10-20", null, false, JOB],
|
||||
["p-far", "Purchase 4 Delivered", "2027-03-01", "2027-03-01", null, false, JOB],
|
||||
["v-permit", "llmtest-Permit approval", "2026-10-06", "2026-10-12", null, false, JOB],
|
||||
["o-task", "llmtest-Other project task", "2026-10-13", "2026-10-14", null, false, "llmtest-other-job"],
|
||||
];
|
||||
for (const [id, name, s, e, prog, todo, job] of tasks)
|
||||
await q("insert into jt_task (id, job_id, name, start_date, end_date, progress, is_todo, snapshot_ts) values ($1,$2,$3,$4,$5,$6,$7,$8)", [id, job, name, s, e, prog, todo, SNAP]);
|
||||
const assign: [string, string][] = [["t-overdue", MGR], ["t-week", MGR], ["t-future", MGR], ["t-done", MGR], ["todo-over", MGR], ["todo-week", MGR], ["todo-next", MGR], ["p-soon", VENDOR], ["p-far", VENDOR], ["v-permit", VENDOR], ["o-task", MGR]];
|
||||
for (const [t, m] of assign) await q("insert into jt_task_assignment (task_id, membership_id, snapshot_ts) values ($1,$2,$3)", [t, m, SNAP]);
|
||||
// зависимости: закупки зависят от Foundation (задача менеджера), Foundation зависит от согласования подрядчика
|
||||
for (const [t, dep] of [["p-soon", "t-week"], ["p-far", "t-week"], ["t-week", "v-permit"]])
|
||||
await q("insert into jt_task_dependency (task_id, depends_on_task_id, snapshot_ts) values ($1,$2,$3)", [t, dep, SNAP]);
|
||||
|
||||
await q("insert into person (id, display_name, jt_membership_id) values ('00000000-0000-0000-0000-0000000000a1','llmtest-Manager',$1)", [MGR]);
|
||||
await q("insert into construction_manager (person_id) values ('00000000-0000-0000-0000-0000000000a1')");
|
||||
await q("insert into assistant_project (id, jt_job_id, manager_person_id, mode) values ('00000000-0000-0000-0000-0000000000b1',$1,'00000000-0000-0000-0000-0000000000a1','test')", [JOB]);
|
||||
await q("insert into reminder_history (assistant_project_id, jt_task_id, reminded_at, reply_outcome, reply_summary) values ('00000000-0000-0000-0000-0000000000b1','t-week',$1,'rescheduled','llmtest-завтра')", [new Date(NOW.getTime() - 86400_000)]);
|
||||
}
|
||||
|
||||
d("подготовка данных ассистента (временная БД)", () => {
|
||||
let db: TestDb;
|
||||
let agentCalls: { url: string; body: string }[];
|
||||
const fetchFn = (async (u: string, init: RequestInit) => {
|
||||
agentCalls.push({ url: u, body: String(init.body) });
|
||||
return new Response(JSON.stringify({ claude_code_session_url: "https://claude.ai/code/session_llmtest" }), { status: 200 });
|
||||
}) as unknown as typeof fetch;
|
||||
const deps = (now = NOW, over: Partial<PrepDeps> = {}): PrepDeps => ({
|
||||
pool: db.pool, log: createLogger("test", "silent"), common: { timezone: "America/New_York" },
|
||||
requiredTables: ["jt_job", "jt_membership", "jt_task", "jt_task_dependency", "jt_task_assignment"],
|
||||
maxSnapshotAgeMinutes: 90, lookaheadWorkDays: 10, modes: ["test"], agent: { triggerUrl: "https://llmtest.invalid/trigger", triggerToken: "llmtest-token" },
|
||||
now: () => now, fetchFn, ...over,
|
||||
});
|
||||
const itemsOf = async (kind: string) =>
|
||||
(await db.pool.query(
|
||||
`select i.input_no, i.jt_task_id, i.is_overdue, i.is_purchase, i.related_task_id, i.days_until_start
|
||||
from ap_input_package_item i join ap_input_package p on p.id = i.package_id where p.kind = $1 order by i.input_no, i.jt_task_id`, [kind])).rows;
|
||||
|
||||
beforeAll(async () => { db = await createTestDb(url!); await seed(db); });
|
||||
afterAll(async () => { await db?.drop(); });
|
||||
|
||||
it("утро: собирает входы (1)-(5),(7) по правилам и вызывает агента", async () => {
|
||||
agentCalls = [];
|
||||
const r = await runPrepJob(deps(), "collect_morning");
|
||||
expect(r.status).toBe("ok");
|
||||
const items = await itemsOf("morning");
|
||||
const ids = (no: number) => items.filter((i) => i.input_no === no).map((i) => i.jt_task_id);
|
||||
|
||||
expect(ids(1)).toEqual(["t-overdue", "t-week"]); // просроченное и на этой неделе; без будущего, завершённого и чужого проекта
|
||||
expect(items.find((i) => i.jt_task_id === "t-overdue")!.is_overdue).toBe(true);
|
||||
expect(ids(2)).toEqual(["todo-over", "todo-week"]);
|
||||
expect(ids(3)).toEqual(["todo-next"]);
|
||||
expect(ids(4)).toEqual(["p-soon"]); // закупка через 4 рабочих дня; далёкая (2027) не входит
|
||||
expect(items.find((i) => i.jt_task_id === "p-soon")).toMatchObject({ is_purchase: true, related_task_id: "t-week", days_until_start: 4 });
|
||||
expect(ids(5)).toEqual(["v-permit"]); // подрядчик, от которого зависит Foundation
|
||||
expect(ids(7)).toEqual(["t-week"]); // история напоминаний
|
||||
|
||||
expect(agentCalls).toHaveLength(1);
|
||||
expect(JSON.parse(JSON.parse(agentCalls[0]!.body).text)).toMatchObject({ reason: "morning", supabaseView: "v_agent_input" });
|
||||
const inv = await db.pool.query("select status, session_ref from ap_agent_invocation");
|
||||
expect(inv.rows).toEqual([{ status: "accepted", session_ref: "https://claude.ai/code/session_llmtest" }]);
|
||||
});
|
||||
|
||||
it("представление v_agent_input отдаёт пакет агенту", async () => {
|
||||
const { rows } = await db.pool.query("select project_name, manager_name, count(*)::int n from v_agent_input group by 1,2");
|
||||
expect(rows).toEqual([{ project_name: "llmtest-Project", manager_name: "llmtest-Manager", n: 8 }]);
|
||||
});
|
||||
|
||||
it("устаревший снапшот (старше 90 минут) - задание не стартует", async () => {
|
||||
agentCalls = [];
|
||||
const r = await runPrepJob(deps(new Date(NOW.getTime() + 350 * 60_000)), "recheck_noon");
|
||||
// снапшот старше 90 минут -> задание не стартует
|
||||
expect(r.status).toBe("skipped");
|
||||
expect(agentCalls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("11:50 со свежим снапшотом и без изменений - агент не нужен; с изменением - вызывается", async () => {
|
||||
const noon = new Date(NOW.getTime() + 350 * 60_000);
|
||||
const noonSnap = new Date(noon.getTime() - 10 * 60_000);
|
||||
const refresh = async () => {
|
||||
await db.pool.query("insert into sync_snapshot (started_at, source_prefix, finished_at, requested_tables) values ($1,'jt',$1,'{}') on conflict do nothing", [noonSnap]);
|
||||
for (const t of ["jt_job", "jt_membership", "jt_task", "jt_task_dependency", "jt_task_assignment"])
|
||||
await db.pool.query("insert into sync_table_status (snapshot_ts, table_name, status, row_count, finished_at) values ($1,$2,'ok',0,$1) on conflict do nothing", [noonSnap, t]);
|
||||
};
|
||||
await refresh();
|
||||
agentCalls = [];
|
||||
const same = await runPrepJob(deps(noon), "recheck_noon");
|
||||
expect(same.projects[0]).toMatchObject({ changedSinceMorning: false, agent: "not_needed" });
|
||||
expect(agentCalls).toHaveLength(0);
|
||||
|
||||
await db.pool.query("update jt_task set end_date = '2026-10-16' where id = 'p-soon'"); // у закупки сдвинули даты - вход (4) изменился
|
||||
await db.pool.query("update jt_task set start_date = '2026-10-16' where id = 'p-soon'");
|
||||
const changed = await runPrepJob(deps(noon), "recheck_noon");
|
||||
expect(changed.projects[0]).toMatchObject({ changedSinceMorning: true, agent: "accepted" });
|
||||
expect(agentCalls).toHaveLength(1);
|
||||
expect(JSON.parse(JSON.parse(agentCalls[0]!.body).text).reason).toBe("noon_changed");
|
||||
});
|
||||
|
||||
it("сбой нужной таблицы блокирует задание, сбой чужой таблицы - нет", async () => {
|
||||
const later = new Date(NOW.getTime() + 24 * 3600_000);
|
||||
const ts = new Date(later.getTime() - 5 * 60_000);
|
||||
await db.pool.query("insert into sync_snapshot (started_at, source_prefix, finished_at, requested_tables, had_errors) values ($1,'jt',$1,'{}',true)", [ts]);
|
||||
await db.pool.query("insert into sync_table_status (snapshot_ts, table_name, status, error_message) values ($1,'llmtest_new_table','error','boom')", [ts]);
|
||||
for (const t of ["jt_job", "jt_membership", "jt_task", "jt_task_dependency", "jt_task_assignment"])
|
||||
await db.pool.query("insert into sync_table_status (snapshot_ts, table_name, status, row_count, finished_at) values ($1,$2,'ok',0,$1)", [ts, t]);
|
||||
const okRun = await runPrepJob(deps(later, { modes: ["test"] }), "collect_morning", { dryRun: true });
|
||||
expect(okRun.status).toBe("ok"); // сбой "новой" таблицы старый сервис не останавливает
|
||||
|
||||
await db.pool.query("update sync_table_status set status = 'error', error_message = 'boom' where snapshot_ts = $1 and table_name = 'jt_task'", [ts]);
|
||||
const blocked = await runPrepJob(deps(later), "collect_morning", { dryRun: true });
|
||||
expect(blocked.status).toBe("skipped");
|
||||
expect(blocked.reason).toContain("jt_task");
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user