import { test, expect, vi } from "vitest"; import { EventEmitter } from "node:events"; import { ThtRunner } from "../src/tht/tht-runner.js"; // Spy on child_process.spawn so we can capture the resolved argv (incl. -c config) // that ThtRunner.run() builds, without launching a real process. vi.mock("node:child_process", () => ({ spawn: vi.fn(() => { const ch: any = new EventEmitter(); ch.stdout = new EventEmitter(); ch.stderr = new EventEmitter(); queueMicrotask(() => { ch.stdout.emit("data", Buffer.from('{"id":"x"}')); ch.emit("close", 0); }); return ch; }), })); import { spawn } from "node:child_process"; test("sessionNew parses id from JSON", async () => { const r = new ThtRunner({ thtBin: "tht", harnessDir: "/h", configPath: "config/tht.yaml" }); r.run = async () => ({ code: 0, stdout: '{"id":"2026-06-27-100000-x"}', stderr: "" }); expect(await r.sessionNew({ question: "q" })).toEqual({ id: "2026-06-27-100000-x" }); }); test("run passes configured THT_DATA_ROOT and preserves the remaining environment", async () => { const previousDataRoot = process.env.THT_DATA_ROOT; const previousCa = process.env.NODE_EXTRA_CA_CERTS; process.env.THT_DATA_ROOT = "/ambient"; process.env.NODE_EXTRA_CA_CERTS = "/certs/company-ca.pem"; try { (spawn as any).mockClear(); const r = new ThtRunner({ thtBin: "/opt/venv/bin/tht", harnessDir: "/app/harness", configPath: "config/tht.yaml", dataRoot: "/configured", }); await r.run(["session", "list", "--json"]); const [bin, , options] = (spawn as any).mock.calls[0]; expect(bin).toBe("/opt/venv/bin/tht"); expect(options.env).toMatchObject({ THT_DATA_ROOT: "/configured", NODE_EXTRA_CA_CERTS: "/certs/company-ca.pem", }); } finally { if (previousDataRoot === undefined) delete process.env.THT_DATA_ROOT; else process.env.THT_DATA_ROOT = previousDataRoot; if (previousCa === undefined) delete process.env.NODE_EXTRA_CA_CERTS; else process.env.NODE_EXTRA_CA_CERTS = previousCa; } }); test("run omits ambient THT_DATA_ROOT when config does not provide one", async () => { const previousDataRoot = process.env.THT_DATA_ROOT; const previousCredential = process.env.PI_PROVIDER_API_KEY; process.env.THT_DATA_ROOT = "/ambient-must-not-leak"; process.env.PI_PROVIDER_API_KEY = "still-inherited"; try { (spawn as any).mockClear(); const r = new ThtRunner({ thtBin: "tht", harnessDir: "/h", configPath: "config/tht.yaml" }); await r.run(["session", "list", "--json"]); const options = (spawn as any).mock.calls[0][2]; expect(options.env).not.toHaveProperty("THT_DATA_ROOT"); expect(options.env.PI_PROVIDER_API_KEY).toBe("still-inherited"); } finally { if (previousDataRoot === undefined) delete process.env.THT_DATA_ROOT; else process.env.THT_DATA_ROOT = previousDataRoot; if (previousCredential === undefined) delete process.env.PI_PROVIDER_API_KEY; else process.env.PI_PROVIDER_API_KEY = previousCredential; } }); test("run with exit != 0 propagates error with stderr", async () => { const r = new ThtRunner({ thtBin: "tht", harnessDir: "/h", configPath: "config/tht.yaml" }); r.run = async () => ({ code: 1, stdout: "", stderr: "ERRORE: boom" }); await expect(r.sessionList()).rejects.toThrow(/boom/); }); test("sessionNew with missing workspace file falls back to default configPath argv", async () => { // harnessDir "/nope" has no workspaces/foo.yaml -> configArg falls back to default. (spawn as any).mockClear(); const r = new ThtRunner({ thtBin: "tht", harnessDir: "/nope", configPath: "config/tht.yaml" }); await r.sessionNew({ question: "q", workspace: "foo" }); const [bin, argv] = (spawn as any).mock.calls[0]; expect(bin).toBe("tht"); // `--config`/`-c` is a PER-COMMAND option in tht (no global -c): it MUST follow // the subcommand, never precede it. (Prepending it caused a live 500 "No such option: -c".) expect(argv).toEqual(["session", "new", "q", "--json", "-c", "config/tht.yaml"]); }); test("buildArgv appends -c AFTER the subcommand (never a global -c)", () => { const r = new ThtRunner({ thtBin: "tht", harnessDir: "/nope", configPath: "config/tht.yaml" }); expect(r.buildArgv(["session", "list", "--json"])).toEqual([ "session", "list", "--json", "-c", "config/tht.yaml", ]); }); test("sqlPreview argv has no positional file — uses --session to resolve path", async () => { // The harness preview_cmd now resolves sql_final.sql from the session workspace; // the backend must NOT pass a sessions//sql_final.sql positional arg. (spawn as any).mockClear(); const r = new ThtRunner({ thtBin: "tht", harnessDir: "/nope", configPath: "config/tht.yaml" }); // stub json() via run() — just need spawn call captured r.run = async () => ({ code: 0, stdout: '{"columns":[],"rows":[],"execution_ms":1,"truncated":false}', stderr: "" }); await r.sqlPreview("ses1", { limit: 10, offset: 5 }); // Verify via the patched run — we stub run() so spawn isn't called again. // Instead confirm directly that sqlPreview builds the right args by inspecting run calls. // We swap back to a spy on run itself. const runSpy = vi.fn().mockResolvedValue({ code: 0, stdout: '{"columns":["c"],"rows":[[1]],"execution_ms":2,"truncated":false}', stderr: "", }); const r2 = new ThtRunner({ thtBin: "tht", harnessDir: "/nope", configPath: "config/tht.yaml" }); r2.run = runSpy; await r2.sqlPreview("ses2", { limit: 20, offset: 0 }); const [calledArgs] = runSpy.mock.calls[0]; // Must NOT include any positional file path before --session expect(calledArgs).toEqual(["sql", "preview", "--session", "ses2", "--json", "--limit", "20", "--offset", "0"]); expect(calledArgs).not.toContain("sessions/ses2/sql_final.sql"); }); test("setName builds the right argv", async () => { const calls: string[][] = []; const r = new ThtRunner({ thtBin: "tht", harnessDir: "/h", configPath: "config/tht.yaml" }); r.run = async (args) => { calls.push(args); return { code: 0, stdout: "", stderr: "" }; }; await r.setName("sid", "Mio nome"); expect(calls[0]).toEqual(["session", "set-name", "sid", "--name", "Mio nome"]); }); test("setGroup / archive / unarchive / deleteSession build argv", async () => { const calls: string[][] = []; const r = new ThtRunner({ thtBin: "tht", harnessDir: "/h", configPath: "config/tht.yaml" }); r.run = async (args) => { calls.push(args); return { code: 0, stdout: "", stderr: "" }; }; await r.setGroup("sid", "G1"); await r.archive("sid"); await r.unarchive("sid"); await r.deleteSession("sid"); expect(calls).toEqual([ ["session", "set-group", "sid", "--group", "G1"], ["session", "archive", "sid"], ["session", "unarchive", "sid"], ["session", "delete", "sid"], ]); }); test("ok() throws on non-zero exit", async () => { const r = new ThtRunner({ thtBin: "tht", harnessDir: "/h", configPath: "config/tht.yaml" }); r.run = async () => ({ code: 1, stdout: "", stderr: "ERRORE: nope" }); await expect(r.archive("sid")).rejects.toThrow(/nope/); }); test("documents parses the JSON array", async () => { const r = new ThtRunner({ thtBin: "tht", harnessDir: "/h", configPath: "config/tht.yaml" }); r.run = async () => ({ code: 0, stdout: '[{"phase":"—","key":"question","title":"Domanda originale","format":"text","content":"q"}]', stderr: "", }); const docs = await r.documents("sid"); expect(docs[0].key).toBe("question"); }); test("ollamaEnsure builds argv with --json --timeout and the workspace -c", async () => { let calledArgs: string[] = []; let calledWs: string | undefined; const r = new ThtRunner({ thtBin: "tht", harnessDir: "/nope", configPath: "config/tht.yaml" }); r.run = async (args, ws) => { calledArgs = args; calledWs = ws; return { code: 0, stdout: '{"ok":true,"server":"up","model":"warmed","model_name":"m"}', stderr: "" }; }; const res = await r.ollamaEnsure("psd", 60); expect(calledArgs).toEqual(["ollama", "ensure", "--json", "--timeout", "60"]); expect(calledWs).toBe("psd"); expect(res).toEqual({ ok: true, server: "up", model: "warmed", model_name: "m" }); }); test("ollamaEnsure maps a non-zero exit to ok:false with stage/error from stdout JSON", async () => { const r = new ThtRunner({ thtBin: "tht", harnessDir: "/nope", configPath: "config/tht.yaml" }); r.run = async () => ({ code: 1, stdout: '{"ok":false,"stage":"model","error":"missing"}', stderr: "" }); expect(await r.ollamaEnsure("psd", 60)).toEqual({ ok: false, stage: "model", error: "missing" }); }); test("ollamaEnsure falls back to stderr when stdout is not JSON on failure", async () => { const r = new ThtRunner({ thtBin: "tht", harnessDir: "/nope", configPath: "config/tht.yaml" }); r.run = async () => ({ code: 1, stdout: "", stderr: "boom" }); const res = await r.ollamaEnsure("psd", 60); expect(res.ok).toBe(false); expect(res.error).toContain("boom"); });