import test from "node:test"; import assert from "node:assert/strict"; import { execFile } from "node:child_process"; import { promisify } from "node:util"; import { mkdtemp, rm, stat, readFile } from "node:fs/promises"; import { join } from "node:path"; import { tmpdir } from "node:os"; import { Workspace } from "../dist/workspace/index.js"; import { investigate } from "../dist/core/engine.js"; import { researchWithAI, validateSections, prioritizeResearchQueries, isContactBrokerURL } from "../dist/ai/deepseek.js"; import { saveCredential, readCredential, forgetCredential, } from "../dist/ai/credentials.js"; import { validateInvestigation } from "../dist/core/schema.js"; import { renderReport, renderDashboard } from "../dist/reports/html.js"; async function base(t) { const root = await mkdtemp(join(tmpdir(), "phomber-ai-")); t.after(() => rm(root, { recursive: true, force: true })); const w = new Workspace(root); await w.init(); return { w, inv: await investigate( { schema_version: "1.0", subject: { name: "Example Researcher" }, research: { depth: "quick", offline: true }, }, w, ), }; } test("AI query budgets prioritize supplied handles and college context over broad names", () => { const subject={name:'Casey Researcher',socials:[{platform:'instagram',username:'casey_public'}],education:[{institution:'EXAMPLE College'}]}; const queries=prioritizeResearchQueries(subject,['"Casey Researcher"','"Casey Researcher" EXAMPLE theatre','"casey_public"']); assert.equal(queries[0],'"casey_public"'); assert.equal(queries[1],'"Casey Researcher" "EXAMPLE College"'); assert.ok(queries.indexOf('"Casey Researcher" EXAMPLE theatre')query==='"casey_public"').length,1); assert.deepEqual(prioritizeResearchQueries(subject,[],false),[]); }); test("AI excludes known contact brokers before fetch and before consuming the page budget", async t => { const {inv}=await base(t), fetched=[]; const brokers=['signalhire.com','zoominfo.com','radaris.in','rocketreach.co','allpeople.biz','contactout.com']; assert.equal(isContactBrokerURL('https://sub.signalhire.com/profile'),true); assert.equal(isContactBrokerURL('https://signalhire.com.example.org/profile'),false); await researchWithAI(inv,async(path,body)=>{ if(path==='/models')return {data:[{id:'deepseek-flash'}]}; if(path==='/v1/tools/search')return {results:[...brokers.map(host=>({url:'https://'+host+'/profile'})),{url:'https://example.edu/research'}]}; if(path==='/v1/tools/fetch'){fetched.push(body.url);return {content:'An official institution publishes public research information.'};} const plan=body.messages[1].content.startsWith('Plan'); return {choices:[{message:{content:JSON.stringify(plan?{queries:['"Example Researcher" college']}:{claims:[],queries:[],limitations:[]})}}]}; }); assert.deepEqual(fetched,['https://example.edu/research']); assert.ok(inv.ai.limitations.some(note=>note.includes('excluded before fetching'))); assert.ok(inv.sources.every(source=>!isContactBrokerURL(source.url))); }); test("AI runs search/fetch, follows evidence and writes source-cited sections", async (t) => { const { inv } = await base(t); const calls = []; const transport = async (path, body) => { calls.push(path); if (path === "/models") return { data: [{ id: "deepseek-flash" }] }; if (path === "/v1/tools/search") return { results: [{ url: "https://example.org/researcher" }] }; if (path === "/v1/tools/fetch") return { content: "Example Researcher created the public Example Project in 2020.", }; const prompt = body.messages[1].content; if (prompt.startsWith("Plan")) return { choices: [ { message: { content: JSON.stringify({ queries: ['"Example Researcher" project'], }), }, }, ], }; if (prompt.startsWith("Extract")) return { choices: [ { message: { content: JSON.stringify({ claims: [ { url: "https://example.org/researcher", category: "projects", field: "Project", value: "Example Project", quote: "created the public Example Project in 2020.", }, { url: "https://example.org/researcher", category: "identity", field: "Bad", value: "Invented", quote: "Not actually on page", }, ], queries: [], }), }, }, ], }; return { choices: [ { message: { content: JSON.stringify({ sections: [ { title: "Projects", blocks: [ {type:'paragraph',text:'The collected page credits Example Project to this candidate.',evidence_ids:['E1']}, {type:'table',caption:'Public project evidence',columns:['Project'],rows:[{cells:['Example Project'],evidence_ids:['E1']}]} ], }, ], }), }, }, ], }; }; await researchWithAI(inv, transport); assert.ok(calls.includes("/v1/tools/search")); assert.ok(calls.includes("/v1/tools/fetch")); assert.ok(!inv.findings.some((f) => f.value === "Invented")); assert.equal(inv.ai.sections.length, 1); assert.equal( inv.findings.find((f) => f.value === "Example Project").status, "lead", ); validateInvestigation(inv); assert.equal(inv.ai.sections[0].blocks[1].rows[0].evidence_ids[0],inv.evidence[0].id); assert.match(renderReport(inv), /Public project evidence/); }); test("unsupported evidence citations fail; unknown models fail before paid searches", async (t) => { const { inv } = await base(t); assert.throws(() => validateSections( { sections: [ { title: "x", paragraphs: [{ text: "invented", evidence_ids: ["unknown"] }], }, ], }, inv, ), ); await assert.rejects( () => researchWithAI(inv, async () => ({ data: [{ id: "available" }] }), { model: "missing", }), /model unavailable/, ); }); test("installed and NPX runs share saved credentials; session-only storage is explicit", async (t) => { const { w, inv } = await base(t); await saveCredential(w, "fixture-not-a-real-key"); assert.equal(await readCredential(w), "fixture-not-a-real-key"); if (process.platform !== "win32") assert.equal( (await stat(join(w.root, "credentials.json"))).mode & 0o777, 0o600, ); assert.ok(!JSON.stringify(inv).includes("fixture-not-a-real-key")); const credentialsURL = new URL("../dist/ai/credentials.js", import.meta.url).href; const workspaceURL = new URL("../dist/workspace/index.js", import.meta.url).href; const code = `import {getKey} from ${JSON.stringify(credentialsURL)}; import {Workspace} from ${JSON.stringify(workspaceURL)}; console.log(await getKey(new Workspace()));`; const run = (npmCommand, ephemeral = "") => promisify(execFile)(process.execPath, ["--input-type=module", "--eval", code], { env: { ...process.env, PHOMBER_HOME: w.root, DEEPSEEK_API_KEY: "", npm_command: npmCommand, PHOMBER_EPHEMERAL_KEY: ephemeral }, }); for (const command of ["", "exec", "run-script"]) assert.equal((await run(command)).stdout.trim(), "fixture-not-a-real-key"); for (const command of ["", "exec"]) await assert.rejects(() => run(command, "1"), e => /DeepSeek key required/.test(e.stderr)); await forgetCredential(w); assert.equal(await readCredential(w), undefined); }); test("home features newest person, without a fixed archived individual, and logo includes W", () => { const v = { id: "test-profile", name: "Most Recent Person", type: "person", created_at: "2026-01-01", updated_at: "2026-01-02", status: "complete", source_count: 0, verified_count: 0, depth: "quick", formats: ["html", "json"], }; const html = renderDashboard([v]); assert.ok(!html.includes("Most recent profile")); assert.match(html, />Most Recent Person<\/a>/); assert.match(html, /Most recently researched/); assert.match(html, />W<\/text>/); }); test("DeepSeek records provider usage without recording the API key", async () => { const { DeepSeek } = await import("../dist/ai/deepseek.js"); const previous = globalThis.fetch; globalThis.fetch = async () => new Response( JSON.stringify({ model: "deepseek-flash", usage: { prompt_tokens: 100, prompt_cache_hit_tokens: 10, prompt_cache_miss_tokens: 90, completion_tokens: 20, }, choices: [], }), { status: 200 }, ); try { const client = new DeepSeek("fixture-private-key"); await client.request("/chat/completions", { model: "deepseek-flash" }); const usage = client.usage(); assert.equal(usage.totals.prompt_tokens, 100); assert.equal(usage.totals.completion_tokens, 20); assert.ok(!JSON.stringify(usage).includes("fixture-private-key")); } finally { globalThis.fetch = previous; } }); test("evidence-only synthesis repairs citation identifiers without repeating searches", async (t) => { const { inv } = await base(t); inv.sources.push({ id: "source-fixture", adapter: "fixture", url: "https://example.org", retrieved_at: "2026-11-11T00:00:00Z", status: "ok", }); inv.findings.push({ id: "finding-fixture", category: "projects", field: "Project", value: "Example Project", status: "lead", source_ids: ["source-fixture"], identity: "candidate", confidence: { score: null, explanation: "Candidate" }, }); inv.evidence.push({ id: "evidence-fixture", finding_id: "finding-fixture", source_id: "source-fixture", excerpt: "The candidate maintains Example Project.", retrieved_at: "2026-11-11T00:00:00Z", }); let attempts = 0; const paths = []; await researchWithAI( inv, async (path) => { paths.push(path); if (path === "/models") return { data: [{ id: "deepseek-flash" }] }; attempts++; return { choices: [ { message: { content: JSON.stringify({ sections: [ { title: "Projects", paragraphs: [ { text: "The collected page mentions Example Project.", evidence_ids: [attempts === 1 ? "E999" : "E1"], }, ], }, ], }), }, }, ], }; }, { synthesisOnly: true }, ); assert.equal(attempts, 2); assert.ok(!paths.includes("/v1/tools/search")); assert.equal( inv.ai.sections[0].paragraphs[0].evidence_ids[0], "evidence-fixture", ); }); test("AI synthesis receives finding identity and conflict status with every excerpt", async (t) => { const { inv }=await base(t); const { addFinding }=await import('../dist/core/engine.js'); const source={id:'source',adapter:'fixture',url:'https://example.org/profile',status:'ok',retrieved_at:new Date().toISOString()}; inv.sources.push(source); addFinding(inv,{category:'identity',field:'name',value:'Candidate Name',identity:'candidate'},source); let received; await researchWithAI(inv,async(path,body)=>{ if(path==='/models')return {data:[{id:'deepseek-flash'}]}; const prompt=body.messages[1].content; received=JSON.parse(prompt.split('\nUNTRUSTED RESEARCH DATA:\n')[1]); return {choices:[{message:{content:JSON.stringify({sections:[{title:'Overview',paragraphs:[{text:'A candidate profile lists Candidate Name.',evidence_ids:['E1']}]}]})}}]}; },{synthesisOnly:true}); assert.equal(received.evidence[0].identity,'candidate'); assert.equal(received.evidence[0].status,'lead'); assert.equal(inv.ai.status,'complete'); assert.throws(()=>validateSections({},inv),/must be an array/); }); test("DeepSeek abort during a retry does not issue another billed attempt", async (t) => { const { DeepSeek }=await import('../dist/ai/deepseek.js'); const controller=new AbortController();let calls=0; t.mock.method(globalThis,'fetch',async()=>{ calls++;queueMicrotask(()=>controller.abort()); return new Response('{}',{status:429}); }); const provider=new DeepSeek('fixture',controller.signal); await assert.rejects(()=>provider.request('/models'),{name:'AbortError'}); assert.equal(calls,1); });