import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; import { createLogger, createTestDb, testDatabaseUrl, type TestDb } from "khb_common"; import type { ClaudeRunner } from "./claude-runner.js"; import { buildAgentPrompt, extractAgentJson, runCategorization } from "./categorize.js"; const log = createLogger("test", "silent"); describe("разбор ответа агента", () => { it("берёт последний json-блок", () => { const out = 'текст\n```json\n{"results":[]}\n```\nещё\n```json\n{"run_id":"r1","results":[{"feed_txn_id":"a"}]}\n```'; expect(extractAgentJson(out)).toEqual({ run_id: "r1", results: [{ feed_txn_id: "a" }] }); }); it("без блока - объект из текста", () => { expect(extractAgentJson('итог {"results":[]}')).toEqual({ results: [] }); }); it("нет JSON - ошибка", () => { expect(() => extractAgentJson("ничего")).toThrow(); }); it("промпт содержит контекст и формат", () => { const p = buildAgentPrompt("ПРОМПТ", { realmId: "123", runStartedAt: new Date("2026-11-17T10:00:00Z") }); expect(p).toContain("ПРОМПТ"); expect(p).toContain(":realm_id = 123"); expect(p).toContain("khb-sql"); expect(p).toContain('"results"'); }); }); const url = testDatabaseUrl(); const d = url ? describe : describe.skip; d("категоризация (временная БД)", () => { let db: TestDb; const claudeOk = (json: unknown): ClaudeRunner => async () => ({ ok: true, stdout: "рассуждения\n```json\n" + JSON.stringify(json) + "\n```", stderr: "", exitCode: 0, timedOut: false }); const mk = (claude: ClaudeRunner) => ({ pool: db.pool, claude, loadPrompt: async () => "ПРОМПТ", realmId: "9341", now: () => new Date("2026-11-17T12:00:00Z"), log }); beforeAll(async () => { db = await createTestDb(url!); }); afterAll(async () => { await db?.drop(); }); beforeEach(async () => { await db.pool.query("truncate acc_categorization_review, acc_categorization_review_original, acc_manual_review cascade"); }); it("записывает результаты, триггеры создают original и задачи", async () => { const r = await runCategorization(mk(claudeOk({ run_id: "run-1", results: [ { feed_txn_id: "t1", suggestion: { account: "55", project_customer_id: "7", splits: [] }, confidence: 91, problem_highlight: null }, { feed_txn_id: "t2", suggestion: null, confidence: null, problem_highlight: "ждёт документ" }, { feed_txn_id: "t3", suggestion: null }, ], }))); expect(r).toMatchObject({ status: "ok", runId: "run-1", parsed: 3, inserted: 3, skipped: 0 }); const rows = (await db.pool.query("select feed_txn_id, run_id, confidence, problem_highlight, suggestion from acc_categorization_review order by 1")).rows; expect(rows[0]).toMatchObject({ feed_txn_id: "t1", run_id: "run-1", confidence: 91, problem_highlight: null }); expect(rows[0].suggestion.account).toBe("55"); expect(rows[1].problem_highlight).toBe("ждёт документ"); expect(rows[2].problem_highlight).toContain("нужен человек"); expect((await db.pool.query("select count(*)::int n from acc_categorization_review_original")).rows[0].n).toBe(3); const q = (await db.pool.query("select kind, ref_id, assignee_role, problem_highlight from acc_manual_review order by ref_id")).rows; expect(q).toHaveLength(3); expect(q[0]).toMatchObject({ kind: "categorization", ref_id: "t1", assignee_role: "accountant", problem_highlight: null }); expect(q[1].problem_highlight).toBe("ждёт документ"); }); it("повторный прогон не дублирует уже стоящие операции", async () => { const out = { run_id: "r", results: [{ feed_txn_id: "t1", suggestion: { account: "1" }, confidence: 50 }] }; await runCategorization(mk(claudeOk(out))); const r2 = await runCategorization(mk(claudeOk(out))); expect(r2).toMatchObject({ status: "ok", inserted: 0, skipped: 1 }); expect((await db.pool.query("select count(*)::int n from acc_categorization_review")).rows[0].n).toBe(1); }); it("ошибка агента и неверный вывод не пишут ничего", async () => { const fail: ClaudeRunner = async () => ({ ok: false, stdout: "", stderr: "boom", exitCode: 1, timedOut: false }); expect((await runCategorization(mk(fail))).status).toBe("agent_failed"); const timeout: ClaudeRunner = async () => ({ ok: false, stdout: "", stderr: "", exitCode: null, timedOut: true }); expect((await runCategorization(mk(timeout))).message).toContain("таймаут"); const junk: ClaudeRunner = async () => ({ ok: true, stdout: "не json", stderr: "", exitCode: 0, timedOut: false }); expect((await runCategorization(mk(junk))).status).toBe("bad_output"); const badShape = claudeOk({ results: [{ feed_txn_id: "t1", confidence: 150 }] }); expect((await runCategorization(mk(badShape))).status).toBe("bad_output"); expect((await db.pool.query("select count(*)::int n from acc_categorization_review")).rows[0].n).toBe(0); }); it("одновременный второй запуск получает busy", async () => { let release!: () => void; const gate = new Promise((res) => (release = res)); const slow: ClaudeRunner = async () => { await gate; return { ok: true, stdout: '```json\n{"results":[]}\n```', stderr: "", exitCode: 0, timedOut: false }; }; const first = runCategorization(mk(slow)); await new Promise((r) => setTimeout(r, 300)); const second = await runCategorization(mk(claudeOk({ results: [] }))); expect(second.status).toBe("busy"); release(); expect((await first).status).toBe("ok"); }); });