Каркас 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:
60
packages/khbuild_assistant_prep/src/agent-trigger.ts
Normal file
60
packages/khbuild_assistant_prep/src/agent-trigger.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import type { Pool } from "khb_common";
|
||||
|
||||
export interface AgentTriggerPayload {
|
||||
packageId: string;
|
||||
assistantProjectId: string;
|
||||
reason: "morning" | "noon_changed";
|
||||
supabaseView: "v_agent_input";
|
||||
}
|
||||
|
||||
export interface TriggerConfig {
|
||||
triggerUrl: string;
|
||||
triggerToken: string;
|
||||
}
|
||||
|
||||
/** Запускает рутину Claude через API-триггер (поле text - JSON-строка payload), пишет результат в ap_agent_invocation. С повторами. */
|
||||
export async function triggerAgent(
|
||||
pool: Pool,
|
||||
cfg: TriggerConfig,
|
||||
payload: AgentTriggerPayload,
|
||||
opts: { attempts?: number; fetchFn?: typeof fetch; sleep?: (ms: number) => Promise<void> } = {},
|
||||
): Promise<{ status: "accepted" | "failed"; invocationId: string }> {
|
||||
const attempts = opts.attempts ?? 3;
|
||||
const fetchFn = opts.fetchFn ?? fetch;
|
||||
const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
||||
let last: { status: number; session?: string; error?: string } = { status: 0 };
|
||||
for (let attempt = 1; attempt <= attempts; attempt++) {
|
||||
const { rows } = await pool.query(
|
||||
"insert into ap_agent_invocation (package_id, reason, status, attempt) values ($1,$2,'requested',$3) returning id",
|
||||
[payload.packageId, payload.reason, attempt],
|
||||
);
|
||||
const id = rows[0].id as string;
|
||||
try {
|
||||
const res = await fetchFn(cfg.triggerUrl, {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${cfg.triggerToken}`, "content-type": "application/json" },
|
||||
body: JSON.stringify({ text: JSON.stringify(payload) }),
|
||||
signal: AbortSignal.timeout(30_000),
|
||||
});
|
||||
const text = await res.text();
|
||||
let session: string | undefined;
|
||||
try {
|
||||
const j = JSON.parse(text) as { claude_code_session_url?: string; claude_code_session_id?: string };
|
||||
session = j.claude_code_session_url ?? j.claude_code_session_id;
|
||||
} catch {
|
||||
/* не JSON */
|
||||
}
|
||||
last = { status: res.status, session, error: res.ok ? undefined : text.slice(0, 300) };
|
||||
} catch (e) {
|
||||
last = { status: 0, error: e instanceof Error ? e.message : String(e) };
|
||||
}
|
||||
const ok = last.status >= 200 && last.status < 300;
|
||||
await pool.query("update ap_agent_invocation set status = $2, http_status = $3, session_ref = $4, error = $5 where id = $1", [
|
||||
id, ok ? "accepted" : "failed", last.status || null, last.session ?? null, last.error ?? null,
|
||||
]);
|
||||
if (ok) return { status: "accepted", invocationId: id };
|
||||
if (attempt < attempts) await sleep(1000 * 2 ** (attempt - 1));
|
||||
else return { status: "failed", invocationId: id };
|
||||
}
|
||||
return { status: "failed", invocationId: "" };
|
||||
}
|
||||
56
packages/khbuild_assistant_prep/src/http-api.ts
Normal file
56
packages/khbuild_assistant_prep/src/http-api.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import Fastify, { type FastifyInstance } from "fastify";
|
||||
import type { Pool } from "khb_common";
|
||||
import type { PrepJob, PrepResult } from "./jobs.js";
|
||||
|
||||
export interface PrepApiDeps {
|
||||
pool: Pool;
|
||||
token: string;
|
||||
run(job: PrepJob, opts: { projectId?: string; dryRun?: boolean }): Promise<PrepResult>;
|
||||
}
|
||||
|
||||
interface RunState {
|
||||
id: string;
|
||||
job: PrepJob;
|
||||
status: "running" | "ok" | "skipped" | "error";
|
||||
startedAt: string;
|
||||
finishedAt?: string;
|
||||
result?: PrepResult;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export function buildApi(deps: PrepApiDeps): FastifyInstance {
|
||||
const app = Fastify();
|
||||
const runs = new Map<string, RunState>(); // состояние последних запусков в памяти; постоянный след - ap_*, sched_run
|
||||
app.addHook("onRequest", async (req, reply) => {
|
||||
if (req.url === "/healthz") return;
|
||||
if (req.headers.authorization !== `Bearer ${deps.token}`) return reply.code(401).send({ error: "unauthorized" });
|
||||
});
|
||||
|
||||
app.get("/healthz", async () => {
|
||||
let db = false;
|
||||
try {
|
||||
await deps.pool.query("select 1");
|
||||
db = true;
|
||||
} catch {
|
||||
/* db=false */
|
||||
}
|
||||
return { ok: db, db, time: new Date().toISOString() };
|
||||
});
|
||||
|
||||
app.post<{ Body: { job: PrepJob; projectId?: string; dryRun?: boolean } }>("/runs", async (req, reply) => {
|
||||
const { job, projectId, dryRun } = req.body ?? ({} as never);
|
||||
if (job !== "collect_morning" && job !== "recheck_noon") return reply.code(400).send({ error: "job должен быть collect_morning или recheck_noon" });
|
||||
const st: RunState = { id: randomUUID(), job, status: "running", startedAt: new Date().toISOString() };
|
||||
runs.set(st.id, st);
|
||||
if (runs.size > 50) runs.delete(runs.keys().next().value as string);
|
||||
deps.run(job, { projectId, dryRun }).then(
|
||||
(r) => Object.assign(st, { status: r.status, result: r, finishedAt: new Date().toISOString() }),
|
||||
(e) => Object.assign(st, { status: "error", error: e instanceof Error ? e.message : String(e), finishedAt: new Date().toISOString() }),
|
||||
);
|
||||
return reply.code(202).send({ runId: st.id, status: "running" });
|
||||
});
|
||||
|
||||
app.get<{ Params: { id: string } }>("/runs/:id", async (req, reply) => runs.get(req.params.id) ?? reply.code(404).send({ error: "not found" }));
|
||||
return app;
|
||||
}
|
||||
70
packages/khbuild_assistant_prep/src/inputs/build.ts
Normal file
70
packages/khbuild_assistant_prep/src/inputs/build.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
import { addDays, addWorkDays, weekBounds, workDaysBetween, type Queryable } from "khb_common";
|
||||
import { input1, input2, input3, input4, input5, input7, type InputParams, type TaskRow } from "./queries.js";
|
||||
|
||||
export interface PackageItem {
|
||||
input_no: 1 | 2 | 3 | 4 | 5 | 7;
|
||||
jt_task_id: string | null;
|
||||
name: string;
|
||||
start_date: string | null;
|
||||
end_date: string | null;
|
||||
is_overdue: boolean;
|
||||
is_purchase: boolean;
|
||||
assignees: string[];
|
||||
related_task_id: string | null;
|
||||
days_until_start: number | null;
|
||||
payload: unknown | null;
|
||||
}
|
||||
|
||||
export function paramsFor(
|
||||
jtJobId: string,
|
||||
managerMembershipId: string,
|
||||
today: string,
|
||||
nonWorkdays: ReadonlySet<string>,
|
||||
lookaheadWorkDays: number,
|
||||
): InputParams {
|
||||
const wk = weekBounds(today);
|
||||
const next = weekBounds(addDays(wk.start, 7));
|
||||
return {
|
||||
jtJobId, managerMembershipId, today,
|
||||
weekStart: wk.start, weekEnd: wk.end, nextWeekStart: next.start, nextWeekEnd: next.end,
|
||||
horizon: addWorkDays(today, lookaheadWorkDays, nonWorkdays),
|
||||
};
|
||||
}
|
||||
|
||||
const effectiveEnd = (t: TaskRow) => t.end_date ?? t.start_date;
|
||||
|
||||
function toItem(no: PackageItem["input_no"], t: TaskRow, today: string, nonWorkdays: ReadonlySet<string>): PackageItem {
|
||||
const start = t.start_date ?? t.end_date;
|
||||
return {
|
||||
input_no: no, jt_task_id: t.jt_task_id, name: t.name, start_date: t.start_date, end_date: t.end_date,
|
||||
is_overdue: !!effectiveEnd(t) && effectiveEnd(t)! < today,
|
||||
is_purchase: t.is_purchase, assignees: t.assignees, related_task_id: t.related_task_id,
|
||||
days_until_start: no === 4 && start ? workDaysBetween(today, start, nonWorkdays) : null,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Собирает все входы (1)-(5), (7) для одного проекта по зеркалам и native-таблицам. */
|
||||
export async function buildItems(
|
||||
db: Queryable,
|
||||
p: InputParams,
|
||||
assistantProjectId: string,
|
||||
nonWorkdays: ReadonlySet<string>,
|
||||
historyDays = 14,
|
||||
now = new Date(),
|
||||
): Promise<PackageItem[]> {
|
||||
const [i1, i2, i3] = [await input1(db, p), await input2(db, p), await input3(db, p)];
|
||||
const managerIds = [...new Set([...i1, ...i2].map((t) => t.jt_task_id))];
|
||||
const [i4, i5] = [await input4(db, p, managerIds), await input5(db, p, managerIds)];
|
||||
const history = await input7(db, assistantProjectId, new Date(now.getTime() - historyDays * 86400_000));
|
||||
|
||||
const items: PackageItem[] = [];
|
||||
for (const [no, rows] of [[1, i1], [2, i2], [3, i3], [4, i4], [5, i5]] as const)
|
||||
for (const t of rows) items.push(toItem(no, t, p.today, nonWorkdays));
|
||||
for (const h of history)
|
||||
items.push({
|
||||
input_no: 7, jt_task_id: h.jt_task_id, name: h.jt_task_id ?? "(без задачи)", start_date: null, end_date: null,
|
||||
is_overdue: false, is_purchase: false, assignees: [], related_task_id: null, days_until_start: null, payload: h,
|
||||
});
|
||||
return items;
|
||||
}
|
||||
57
packages/khbuild_assistant_prep/src/inputs/package-writer.ts
Normal file
57
packages/khbuild_assistant_prep/src/inputs/package-writer.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { withTx, type Pool } from "khb_common";
|
||||
import type { PackageItem } from "./build.js";
|
||||
|
||||
/**
|
||||
* Хэш содержимого пакета. Вход (7) (история напоминаний) в хэш не входит: за полдня в 11:50 он может измениться
|
||||
* только из-за самих напоминаний ассистента, а не из-за изменения данных стройки.
|
||||
*/
|
||||
export function contentHash(items: PackageItem[]): string {
|
||||
const stable = items
|
||||
.filter((i) => i.input_no !== 7)
|
||||
.map((i) => [i.input_no, i.jt_task_id, i.name, i.start_date, i.end_date, i.is_overdue, i.is_purchase, i.assignees, i.related_task_id, i.days_until_start])
|
||||
.sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));
|
||||
return createHash("sha256").update(JSON.stringify(stable)).digest("hex");
|
||||
}
|
||||
|
||||
export type PackageKind = "morning" | "noon";
|
||||
|
||||
export interface WrittenPackage {
|
||||
id: string;
|
||||
hash: string;
|
||||
changedSinceMorning: boolean | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Пишет пакет входных данных проекта на день (повторная запись за ту же дату и вид заменяет прежний).
|
||||
* Для noon сравнивает хэш с утренним пакетом: нет утреннего -> changed = true.
|
||||
*/
|
||||
export async function writePackage(
|
||||
pool: Pool,
|
||||
opts: { assistantProjectId: string; date: string; kind: PackageKind; sourceSnapshotTs: Date | null; items: PackageItem[] },
|
||||
): Promise<WrittenPackage> {
|
||||
const hash = contentHash(opts.items);
|
||||
let changed: boolean | null = null;
|
||||
if (opts.kind === "noon") {
|
||||
const m = await pool.query("select content_hash from ap_input_package where assistant_project_id = $1 and package_date = $2 and kind = 'morning'", [opts.assistantProjectId, opts.date]);
|
||||
changed = m.rows[0] ? m.rows[0].content_hash !== hash : true;
|
||||
}
|
||||
const id = await withTx(pool, async (c) => {
|
||||
await c.query("delete from ap_input_package where assistant_project_id = $1 and package_date = $2 and kind = $3", [opts.assistantProjectId, opts.date, opts.kind]);
|
||||
const { rows } = await c.query(
|
||||
`insert into ap_input_package (assistant_project_id, package_date, kind, source_snapshot_ts, content_hash, item_count, changed_since_morning)
|
||||
values ($1,$2,$3,$4,$5,$6,$7) returning id`,
|
||||
[opts.assistantProjectId, opts.date, opts.kind, opts.sourceSnapshotTs, hash, opts.items.length, changed],
|
||||
);
|
||||
const pkgId = rows[0].id as string;
|
||||
for (const it of opts.items) {
|
||||
await c.query(
|
||||
`insert into ap_input_package_item (package_id, input_no, jt_task_id, name, start_date, end_date, is_overdue, is_purchase, assignees, related_task_id, days_until_start, payload)
|
||||
values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)`,
|
||||
[pkgId, it.input_no, it.jt_task_id, it.name, it.start_date, it.end_date, it.is_overdue, it.is_purchase, it.assignees, it.related_task_id, it.days_until_start, it.payload ? JSON.stringify(it.payload) : null],
|
||||
);
|
||||
}
|
||||
return pkgId;
|
||||
});
|
||||
return { id, hash, changedSinceMorning: changed };
|
||||
}
|
||||
134
packages/khbuild_assistant_prep/src/inputs/queries.ts
Normal file
134
packages/khbuild_assistant_prep/src/inputs/queries.ts
Normal file
@@ -0,0 +1,134 @@
|
||||
import type { Queryable } from "khb_common";
|
||||
|
||||
/** Параметры сбора по одному проекту. Даты - yyyy-mm-dd по Tampa. */
|
||||
export interface InputParams {
|
||||
jtJobId: string;
|
||||
managerMembershipId: string;
|
||||
today: string;
|
||||
weekStart: string;
|
||||
weekEnd: string;
|
||||
nextWeekStart: string;
|
||||
nextWeekEnd: string;
|
||||
/** Граница "ближайших N рабочих дней" для входа (4). */
|
||||
horizon: string;
|
||||
}
|
||||
|
||||
export interface TaskRow {
|
||||
jt_task_id: string;
|
||||
name: string;
|
||||
start_date: string | null;
|
||||
end_date: string | null;
|
||||
is_todo: boolean;
|
||||
is_purchase: boolean;
|
||||
assignees: string[];
|
||||
related_task_id: string | null;
|
||||
}
|
||||
|
||||
const COLS = `
|
||||
t.id as jt_task_id, t.name, t.is_todo,
|
||||
to_char(t.start_date, 'YYYY-MM-DD') as start_date, to_char(t.end_date, 'YYYY-MM-DD') as end_date,
|
||||
exists (select 1 from purchase_task_ref p where lower(p.task_name) = lower(t.name)) as is_purchase,
|
||||
coalesce((select array_agg(m.user_name order by m.user_name) from jt_task_assignment a
|
||||
join jt_membership m on m.id = a.membership_id where a.task_id = t.id), '{}') as assignees`;
|
||||
|
||||
const MANAGER_TASKS = `
|
||||
from jt_task t
|
||||
join jt_task_assignment ma on ma.task_id = t.id and ma.membership_id = $2
|
||||
where t.job_id = $1 and not t.is_deleted and not t.is_group and coalesce(t.progress, 0) < 1`;
|
||||
|
||||
/** Вход (1): не завершённые работы менеджера на этой неделе и просроченные. */
|
||||
export async function input1(db: Queryable, p: InputParams): Promise<TaskRow[]> {
|
||||
const { rows } = await db.query(
|
||||
`select ${COLS}, null::text as related_task_id ${MANAGER_TASKS} and not t.is_todo
|
||||
and t.end_date is not null and (t.end_date < $3 or (coalesce(t.start_date, t.end_date) <= $5 and t.end_date >= $4))
|
||||
order by t.end_date, t.name`,
|
||||
[p.jtJobId, p.managerMembershipId, p.today, p.weekStart, p.weekEnd],
|
||||
);
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** Вход (2): todo менеджера на этой неделе и просроченные. */
|
||||
export async function input2(db: Queryable, p: InputParams): Promise<TaskRow[]> {
|
||||
const { rows } = await db.query(
|
||||
`select ${COLS}, null::text as related_task_id ${MANAGER_TASKS} and t.is_todo
|
||||
and coalesce(t.end_date, t.start_date) is not null
|
||||
and (coalesce(t.end_date, t.start_date) < $3 or coalesce(t.end_date, t.start_date) between $4 and $5)
|
||||
order by coalesce(t.end_date, t.start_date), t.name`,
|
||||
[p.jtJobId, p.managerMembershipId, p.today, p.weekStart, p.weekEnd],
|
||||
);
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** Вход (3): todo менеджера на следующую неделю. */
|
||||
export async function input3(db: Queryable, p: InputParams): Promise<TaskRow[]> {
|
||||
const { rows } = await db.query(
|
||||
`select ${COLS}, null::text as related_task_id ${MANAGER_TASKS} and t.is_todo
|
||||
and coalesce(t.end_date, t.start_date) between $3 and $4
|
||||
order by coalesce(t.end_date, t.start_date), t.name`,
|
||||
[p.jtJobId, p.managerMembershipId, p.nextWeekStart, p.nextWeekEnd],
|
||||
);
|
||||
return rows;
|
||||
}
|
||||
|
||||
const OTHERS = `
|
||||
where t.job_id = $1 and not t.is_deleted and not t.is_group and coalesce(t.progress, 0) < 1
|
||||
and not exists (select 1 from jt_task_assignment a where a.task_id = t.id and a.membership_id = $2)`;
|
||||
|
||||
/**
|
||||
* Вход (4): работы других исполнителей (особенно закупки), зависящие (прямо или через цепочку до 5 звеньев)
|
||||
* от задач менеджера из (1) или (2) и стартующие не позже горизонта (включая просроченные).
|
||||
*/
|
||||
export async function input4(db: Queryable, p: InputParams, managerTaskIds: string[]): Promise<TaskRow[]> {
|
||||
if (!managerTaskIds.length) return [];
|
||||
const { rows } = await db.query(
|
||||
`with recursive dep(root, id, depth) as (
|
||||
select s, d.task_id, 1 from unnest($3::text[]) s join jt_task_dependency d on d.depends_on_task_id = s
|
||||
union all
|
||||
select dep.root, d.task_id, dep.depth + 1 from dep join jt_task_dependency d on d.depends_on_task_id = dep.id where dep.depth < 5
|
||||
)
|
||||
select distinct on (t.id) ${COLS}, dep.root as related_task_id
|
||||
from dep join jt_task t on t.id = dep.id ${OTHERS}
|
||||
and coalesce(t.start_date, t.end_date) is not null and coalesce(t.start_date, t.end_date) <= $4
|
||||
order by t.id, dep.depth`,
|
||||
[p.jtJobId, p.managerMembershipId, managerTaskIds, p.horizon],
|
||||
);
|
||||
return rows.sort((a, b) => String(a.start_date ?? a.end_date).localeCompare(String(b.start_date ?? b.end_date)) || a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
/** Вход (5): не завершённые работы других исполнителей, от которых зависят работы менеджера из (1) или (2). */
|
||||
export async function input5(db: Queryable, p: InputParams, managerTaskIds: string[]): Promise<TaskRow[]> {
|
||||
if (!managerTaskIds.length) return [];
|
||||
const { rows } = await db.query(
|
||||
`with recursive dep(root, id, depth) as (
|
||||
select s, d.depends_on_task_id, 1 from unnest($3::text[]) s join jt_task_dependency d on d.task_id = s
|
||||
union all
|
||||
select dep.root, d.depends_on_task_id, dep.depth + 1 from dep join jt_task_dependency d on d.task_id = dep.id where dep.depth < 5
|
||||
)
|
||||
select distinct on (t.id) ${COLS}, dep.root as related_task_id
|
||||
from dep join jt_task t on t.id = dep.id ${OTHERS}
|
||||
order by t.id, dep.depth`,
|
||||
[p.jtJobId, p.managerMembershipId, managerTaskIds],
|
||||
);
|
||||
return rows.sort((a, b) => String(a.end_date ?? a.start_date).localeCompare(String(b.end_date ?? b.start_date)) || a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
export interface ReminderSummary {
|
||||
jt_task_id: string | null;
|
||||
reminders: number;
|
||||
last_reminded_at: string;
|
||||
last_reply_outcome: string | null;
|
||||
last_reply_summary: string | null;
|
||||
}
|
||||
|
||||
/** Вход (7): компактная история напоминаний за последние days дней: по задаче - сколько раз напоминали и чем ответил менеджер. */
|
||||
export async function input7(db: Queryable, assistantProjectId: string, since: Date): Promise<ReminderSummary[]> {
|
||||
const { rows } = await db.query(
|
||||
`select jt_task_id, count(*)::int as reminders, max(reminded_at) as last_reminded_at,
|
||||
(array_agg(reply_outcome order by reminded_at desc))[1] as last_reply_outcome,
|
||||
(array_agg(reply_summary order by reminded_at desc))[1] as last_reply_summary
|
||||
from reminder_history where assistant_project_id = $1 and reminded_at >= $2
|
||||
group by jt_task_id order by max(reminded_at) desc`,
|
||||
[assistantProjectId, since],
|
||||
);
|
||||
return rows.map((r) => ({ ...r, last_reminded_at: (r.last_reminded_at as Date).toISOString() }));
|
||||
}
|
||||
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");
|
||||
});
|
||||
});
|
||||
104
packages/khbuild_assistant_prep/src/jobs.ts
Normal file
104
packages/khbuild_assistant_prep/src/jobs.ts
Normal file
@@ -0,0 +1,104 @@
|
||||
import { itNotify, localDate, MirrorNotReadyError, requireFreshTables, type CommonSettings, type Logger, type Pool } from "khb_common";
|
||||
import { triggerAgent, type TriggerConfig } from "./agent-trigger.js";
|
||||
import { buildItems, paramsFor } from "./inputs/build.js";
|
||||
import { writePackage } from "./inputs/package-writer.js";
|
||||
|
||||
export type PrepJob = "collect_morning" | "recheck_noon";
|
||||
|
||||
export interface PrepDeps {
|
||||
pool: Pool;
|
||||
log: Logger;
|
||||
common: Pick<CommonSettings, "timezone" | "itAlerts">;
|
||||
requiredTables: string[];
|
||||
maxSnapshotAgeMinutes: number;
|
||||
lookaheadWorkDays: number;
|
||||
modes: string[];
|
||||
agent: TriggerConfig;
|
||||
now?: () => Date;
|
||||
fetchFn?: typeof fetch;
|
||||
}
|
||||
|
||||
export interface ProjectOutcome {
|
||||
assistantProjectId: string;
|
||||
jtJobId: string;
|
||||
packageId?: string;
|
||||
items?: number;
|
||||
changedSinceMorning?: boolean | null;
|
||||
agent?: "accepted" | "failed" | "not_needed" | "dry_run";
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface PrepResult {
|
||||
status: "ok" | "skipped" | "error";
|
||||
reason?: string;
|
||||
projects: ProjectOutcome[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Задание подготовки данных (06:00 collect_morning / 11:50 recheck_noon).
|
||||
* Если нужные таблицы-зеркала сбойные или устарели - не стартует: skipped и уведомление ИТ (docs/mirroring.md).
|
||||
*/
|
||||
export async function runPrepJob(deps: PrepDeps, job: PrepJob, opts: { projectId?: string; dryRun?: boolean } = {}): Promise<PrepResult> {
|
||||
const now = (deps.now ?? (() => new Date()))();
|
||||
const today = localDate(now, deps.common.timezone);
|
||||
|
||||
let snapshotTs: Date | null = null;
|
||||
try {
|
||||
const states = await requireFreshTables(deps.pool, deps.requiredTables, deps.maxSnapshotAgeMinutes, now);
|
||||
snapshotTs = states.map((s) => s.snapshotTs!).reduce((a, b) => (b < a ? b : a));
|
||||
} catch (e) {
|
||||
if (!(e instanceof MirrorNotReadyError)) throw e;
|
||||
const text = `:warning: khbuild_assistant_prep: задание ${job} не запущено - данные зеркал не готовы. ${e.message}`;
|
||||
deps.log.error({ job, failing: e.failing }, "зеркала не готовы, задание пропущено");
|
||||
const sent = await itNotify(deps.common, text).catch((err) => {
|
||||
deps.log.error({ err: String(err) }, "не удалось отправить уведомление ИТ");
|
||||
return false;
|
||||
});
|
||||
if (!sent) deps.log.warn("уведомление ИТ не отправлено (itAlerts не настроен или Slack вернул ошибку)");
|
||||
return { status: "skipped", reason: e.message, projects: [] };
|
||||
}
|
||||
|
||||
const nonWork = new Set<string>(
|
||||
(await deps.pool.query("select to_char(day, 'YYYY-MM-DD') as d from calendar_day where not is_workday")).rows.map((r) => r.d as string),
|
||||
);
|
||||
|
||||
const { rows: projects } = await deps.pool.query(
|
||||
`select ap.id, ap.jt_job_id, per.jt_membership_id
|
||||
from assistant_project ap
|
||||
join construction_manager cm on cm.person_id = ap.manager_person_id
|
||||
join person per on per.id = cm.person_id
|
||||
where ap.is_enabled and ap.mode = any($1) and cm.is_active and per.is_active and per.jt_membership_id is not null
|
||||
and (cm.paused_until is null or cm.paused_until < $2::date)
|
||||
and ($3::uuid is null or ap.id = $3)
|
||||
order by ap.created_at`,
|
||||
[deps.modes, today, opts.projectId ?? null],
|
||||
);
|
||||
|
||||
const outcomes: ProjectOutcome[] = [];
|
||||
for (const pr of projects as { id: string; jt_job_id: string; jt_membership_id: string }[]) {
|
||||
const out: ProjectOutcome = { assistantProjectId: pr.id, jtJobId: pr.jt_job_id };
|
||||
try {
|
||||
const params = paramsFor(pr.jt_job_id, pr.jt_membership_id, today, nonWork, deps.lookaheadWorkDays);
|
||||
const items = await buildItems(deps.pool, params, pr.id, nonWork, 14, now);
|
||||
const pkg = await writePackage(deps.pool, {
|
||||
assistantProjectId: pr.id, date: today, kind: job === "collect_morning" ? "morning" : "noon", sourceSnapshotTs: snapshotTs, items,
|
||||
});
|
||||
Object.assign(out, { packageId: pkg.id, items: items.length, changedSinceMorning: pkg.changedSinceMorning });
|
||||
const needAgent = job === "collect_morning" || pkg.changedSinceMorning === true;
|
||||
if (!needAgent) out.agent = "not_needed";
|
||||
else if (opts.dryRun) out.agent = "dry_run";
|
||||
else {
|
||||
const r = await triggerAgent(deps.pool, deps.agent, {
|
||||
packageId: pkg.id, assistantProjectId: pr.id, reason: job === "collect_morning" ? "morning" : "noon_changed", supabaseView: "v_agent_input",
|
||||
}, { fetchFn: deps.fetchFn });
|
||||
out.agent = r.status;
|
||||
}
|
||||
} catch (e) {
|
||||
out.error = e instanceof Error ? e.message : String(e);
|
||||
deps.log.error({ project: pr.id, err: out.error }, "ошибка подготовки данных проекта");
|
||||
}
|
||||
outcomes.push(out);
|
||||
}
|
||||
const failed = outcomes.some((o) => o.error || o.agent === "failed");
|
||||
return { status: failed ? "error" : "ok", projects: outcomes };
|
||||
}
|
||||
24
packages/khbuild_assistant_prep/src/main.ts
Normal file
24
packages/khbuild_assistant_prep/src/main.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { createLogger, createPool, loadServiceSettings } from "khb_common";
|
||||
import { buildApi } from "./http-api.js";
|
||||
import { runPrepJob } from "./jobs.js";
|
||||
import { assistantPrepSchema } from "./settings.js";
|
||||
|
||||
const { common, service } = loadServiceSettings("khbuild_assistant_prep", assistantPrepSchema);
|
||||
const log = createLogger("khbuild_assistant_prep", common.logLevel);
|
||||
const pool = createPool(common.database.url);
|
||||
|
||||
const app = buildApi({
|
||||
pool,
|
||||
token: service.http.token,
|
||||
run: (job, opts) =>
|
||||
runPrepJob(
|
||||
{
|
||||
pool, log, common, requiredTables: service.requiredTables, maxSnapshotAgeMinutes: service.maxSnapshotAgeMinutes,
|
||||
lookaheadWorkDays: service.lookaheadWorkDays, modes: service.modes, agent: service.agent,
|
||||
},
|
||||
job,
|
||||
opts,
|
||||
),
|
||||
});
|
||||
await app.listen({ host: service.http.host, port: service.http.port });
|
||||
log.info({ port: service.http.port }, "khbuild_assistant_prep запущен");
|
||||
11
packages/khbuild_assistant_prep/src/settings.ts
Normal file
11
packages/khbuild_assistant_prep/src/settings.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const assistantPrepSchema = z.object({
|
||||
http: z.object({ host: z.string().default("127.0.0.1"), port: z.number(), token: z.string().min(1) }),
|
||||
lookaheadWorkDays: z.number().default(10),
|
||||
modes: z.array(z.string()).default(["test"]),
|
||||
requiredTables: z.array(z.string()).default(["jt_job", "jt_membership", "jt_task", "jt_task_dependency", "jt_task_assignment"]),
|
||||
maxSnapshotAgeMinutes: z.number().default(90),
|
||||
agent: z.object({ triggerUrl: z.string(), triggerToken: z.string() }),
|
||||
});
|
||||
export type AssistantPrepSettings = z.infer<typeof assistantPrepSchema>;
|
||||
Reference in New Issue
Block a user