evidence-mcp-dev 1.0.28 → 1.0.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1433 -353
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -62,6 +62,10 @@ function bool(name, def, env = process.env) {
62
62
  // src/env-load.ts
63
63
  loadDotenv();
64
64
 
65
+ // src/net-defaults.ts
66
+ import { setDefaultAutoSelectFamilyAttemptTimeout } from "net";
67
+ setDefaultAutoSelectFamilyAttemptTimeout(2e3);
68
+
65
69
  // src/index.ts
66
70
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
67
71
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
@@ -71,31 +75,31 @@ import { fetch as undiciFetch } from "undici";
71
75
 
72
76
  // src/race.ts
73
77
  var OPEN = /* @__PURE__ */ new Set();
74
- function openRequest(write, name) {
78
+ function openRequest(write2, name) {
75
79
  const ctrl = new AbortController();
76
80
  let closed = false;
77
81
  const entry = { abandon: () => {
78
82
  if (!closed) {
79
83
  closed = true;
80
- write(`abandoned ${name}: server stopped`);
84
+ write2(`abandoned ${name}: server stopped`);
81
85
  }
82
86
  } };
83
87
  OPEN.add(entry);
84
- write(`try ${name}`);
88
+ write2(`try ${name}`);
85
89
  return {
86
90
  signal: ctrl.signal,
87
91
  abort: (why) => {
88
92
  if (closed) return;
89
93
  closed = true;
90
94
  OPEN.delete(entry);
91
- write(`aborted ${name}: ${why}`);
95
+ write2(`aborted ${name}: ${why}`);
92
96
  ctrl.abort(new Error(`aborted: ${why}`));
93
97
  },
94
98
  close: (line) => {
95
99
  if (closed) return false;
96
100
  closed = true;
97
101
  OPEN.delete(entry);
98
- write(line);
102
+ write2(line);
99
103
  return true;
100
104
  }
101
105
  };
@@ -108,14 +112,14 @@ async function firstOk(tasks, decisive = () => null) {
108
112
  if (!tasks.length) return { won: null, results: [] };
109
113
  const results2 = new Array(tasks.length);
110
114
  const settled = new Array(tasks.length).fill(false);
111
- return new Promise((resolve4) => {
115
+ return new Promise((resolve5) => {
112
116
  let left = tasks.length, done = false;
113
117
  const end = (won, why) => {
114
118
  done = true;
115
119
  tasks.forEach((t, j) => {
116
120
  if (!settled[j]) t.abort(why);
117
121
  });
118
- resolve4({ won, results: results2 });
122
+ resolve5({ won, results: results2 });
119
123
  };
120
124
  tasks.forEach((task, i) => {
121
125
  task.go().then((r) => {
@@ -127,7 +131,7 @@ async function firstOk(tasks, decisive = () => null) {
127
131
  else if (gone) end(null, `${task.name} had ${gone}`);
128
132
  else if (--left === 0) {
129
133
  done = true;
130
- resolve4({ won: null, results: results2 });
134
+ resolve5({ won: null, results: results2 });
131
135
  }
132
136
  });
133
137
  });
@@ -159,7 +163,63 @@ var openalexParams = (env = process.env) => {
159
163
  import { ProxyAgent } from "undici";
160
164
 
161
165
  // src/browser.ts
166
+ import { isIP as isIP2 } from "net";
167
+
168
+ // src/hosts.ts
162
169
  import { lookup } from "dns/promises";
170
+ import { connect, isIP } from "net";
171
+ var UP_MS = 6e4;
172
+ var DOWN_MS = 5 * 6e4;
173
+ var PROBE_MS = 3e3;
174
+ var seen = /* @__PURE__ */ new Map();
175
+ var key = (host3, port) => `${host3}:${port}`;
176
+ function connectOnce(address, port, timeoutMs) {
177
+ return new Promise((resolve5) => {
178
+ const s = connect({ host: address, port });
179
+ const done = (error) => {
180
+ s.destroy();
181
+ resolve5(error);
182
+ };
183
+ s.setTimeout(timeoutMs, () => done(`no answer within ${timeoutMs / 1e3} s`));
184
+ s.once("connect", () => done(null));
185
+ s.once("error", (e) => done(e.code ?? e.message));
186
+ });
187
+ }
188
+ async function candidates(host3, lookupImpl = lookup) {
189
+ if (host3 === "localhost" || isIP(host3)) return [host3];
190
+ const all = await lookupImpl(host3, { all: true, order: "verbatim" });
191
+ const usable = all.map((a) => a.address).filter((a) => !/^fe[89ab]/i.test(a));
192
+ return usable.length ? usable : [host3];
193
+ }
194
+ async function probe(host3, port, timeoutMs = PROBE_MS) {
195
+ const t0 = Date.now();
196
+ let list5;
197
+ try {
198
+ list5 = await candidates(host3);
199
+ } catch (e) {
200
+ return { up: false, ms: Date.now() - t0, at: Date.now(), error: e.code ?? String(e) };
201
+ }
202
+ let first = null;
203
+ for (const address of list5) {
204
+ const left = timeoutMs - (Date.now() - t0);
205
+ if (left <= 0) break;
206
+ const error = await connectOnce(address, port, left);
207
+ if (!error) return { up: true, ms: Date.now() - t0, at: Date.now(), error: null, address };
208
+ first ??= error;
209
+ }
210
+ return { up: false, ms: Date.now() - t0, at: Date.now(), error: first ?? `no answer within ${timeoutMs / 1e3} s` };
211
+ }
212
+ async function hostState(host3, port, onDown) {
213
+ const k = key(host3, port), now2 = Date.now(), old = seen.get(k);
214
+ if (old && now2 - old.at < (old.up ? UP_MS : DOWN_MS)) return old;
215
+ const s = await probe(host3, port);
216
+ seen.set(k, s);
217
+ if (!s.up && (!old || old.up)) onDown?.(s);
218
+ return s;
219
+ }
220
+ var downNote = (s) => `host down (${s.error}, since ${new Date(s.at).toTimeString().slice(0, 5)})`;
221
+
222
+ // src/browser.ts
163
223
  import { existsSync as existsSync3, mkdirSync } from "fs";
164
224
  import { createRequire } from "module";
165
225
  import { join as join3 } from "path";
@@ -246,11 +306,8 @@ async function cdpUrl(endpoint) {
246
306
  const u = new URL(cdpHttp(endpoint));
247
307
  const host3 = u.hostname.replace(/^\[|\]$/g, "");
248
308
  if (host3 === "localhost" || /^[\d.]+$/.test(host3) || host3.includes(":")) return u.toString().replace(/\/$/, "");
249
- try {
250
- const { address, family } = await lookup(host3);
251
- u.hostname = family === 6 ? `[${address}]` : address;
252
- } catch {
253
- }
309
+ const h = await hostState(host3, Number(u.port) || 9222);
310
+ if (h.address) u.hostname = isIP2(h.address) === 6 ? `[${h.address}]` : h.address;
254
311
  return u.toString().replace(/\/$/, "");
255
312
  }
256
313
  var stageKind = (endpoint) => isCdp(endpoint) ? "chrome" : "playwright";
@@ -339,9 +396,9 @@ function touchIdle() {
339
396
  idleTimer.unref();
340
397
  }
341
398
  async function closeBrowsers() {
342
- const open = [...ctxs.entries()];
399
+ const open2 = [...ctxs.entries()];
343
400
  ctxs.clear();
344
- for (const [endpoint, p] of open) {
401
+ for (const [endpoint, p] of open2) {
345
402
  try {
346
403
  const { ctx, browser } = await p;
347
404
  if (isCdp(endpoint)) {
@@ -438,11 +495,11 @@ async function browserFetch(url, endpoint, cfg = browserConfig(), signal) {
438
495
  if (!r.ok()) throw new Error(`HTTP ${r.status()} (pdf request)`);
439
496
  return { bytes: Buffer.from(await r.body()), contentType: "application/pdf", url: page.url(), via: "request" };
440
497
  }
441
- const words3 = () => page.evaluate(() => (document.body?.innerText ?? "").split(/\s+/).filter(Boolean).length).catch(() => 0);
442
- if (await words3() < SETTLE_WORDS) {
498
+ const words4 = () => page.evaluate(() => (document.body?.innerText ?? "").split(/\s+/).filter(Boolean).length).catch(() => 0);
499
+ if (await words4() < SETTLE_WORDS) {
443
500
  await page.waitForLoadState("networkidle", { timeout: SETTLE_MS }).catch(() => void 0);
444
501
  const t2 = Date.now();
445
- while (Date.now() - t2 < SETTLE_MS && await words3() < SETTLE_WORDS) await new Promise((r) => setTimeout(r, 1e3));
502
+ while (Date.now() - t2 < SETTLE_MS && await words4() < SETTLE_WORDS) await new Promise((r) => setTimeout(r, 1e3));
446
503
  }
447
504
  const html = await page.content();
448
505
  return { bytes: Buffer.from(html, "utf8"), contentType: contentType || "text/html", url: page.url(), via: "page" };
@@ -511,18 +568,54 @@ async function fetchBytes(url, headers = DOWNLOAD_HEADERS, proxy, signal) {
511
568
  }
512
569
  throw Object.assign(new Error(last), finalUrl ? { url: finalUrl } : {}, lastBody ? { body: lastBody, contentType: lastType } : {});
513
570
  }
571
+ var isNcbi = (url) => {
572
+ try {
573
+ return new URL(url).hostname === "eutils.ncbi.nlm.nih.gov";
574
+ } catch {
575
+ return false;
576
+ }
577
+ };
578
+ var ncbiNext = 0;
579
+ var ncbiSlow = 1;
580
+ var ncbiBase = (env) => env.FH_NCBI_API_KEY?.trim() ? 1e3 / 9 : 400;
581
+ async function ncbiTurn(env = process.env) {
582
+ const gap = Math.min(2e3, ncbiBase(env) * ncbiSlow);
583
+ const now2 = Date.now(), at = Math.max(now2, ncbiNext);
584
+ ncbiNext = at + gap;
585
+ if (at > now2) await new Promise((r) => setTimeout(r, at - now2));
586
+ }
587
+ var ncbiRefused = () => {
588
+ ncbiSlow = Math.min(32, ncbiSlow * 2);
589
+ };
590
+ var ncbiAnswered = () => {
591
+ ncbiSlow = Math.max(1, ncbiSlow * 0.9);
592
+ };
593
+ var ncbiWait = (attempt, retryAfter) => {
594
+ const s = Number(retryAfter);
595
+ return Number.isFinite(s) && s > 0 ? Math.min(3e4, s * 1e3) : Math.min(1e4, 1500 * 2 ** attempt) * (0.75 + Math.random() / 2);
596
+ };
514
597
  async function fetchText(url, headers = {}) {
515
598
  let last = "unknown error";
516
- for (let attempt = 0; attempt < 2; attempt++) {
599
+ const ncbi = isNcbi(url);
600
+ for (let attempt = 0; attempt < (ncbi ? 6 : 2); attempt++) {
601
+ let retryAfter = null;
517
602
  try {
603
+ if (ncbi) await ncbiTurn();
518
604
  const res = await fetch(url, { headers, signal: AbortSignal.timeout(TIMEOUT_MS), redirect: "follow" });
519
- if (res.ok) return await res.text();
605
+ if (res.ok) {
606
+ if (ncbi) ncbiAnswered();
607
+ return await res.text();
608
+ }
609
+ if (ncbi && res.status === 429) {
610
+ ncbiRefused();
611
+ retryAfter = res.headers.get("retry-after");
612
+ }
520
613
  last = res.status < 500 ? httpReason(res.status, await res.text().catch(() => "")) : `HTTP ${res.status}`;
521
614
  if (res.status !== 429 && res.status < 500) break;
522
615
  } catch (e) {
523
616
  last = e instanceof Error && e.name === "TimeoutError" ? "timeout" : e instanceof Error ? e.message : String(e);
524
617
  }
525
- await new Promise((r) => setTimeout(r, 1500));
618
+ await new Promise((r) => setTimeout(r, ncbi ? ncbiWait(attempt, retryAfter) : 1500));
526
619
  }
527
620
  throw new Error(last);
528
621
  }
@@ -565,11 +658,11 @@ var headings = (md) => md.split("\n").filter((l) => /^#{1,6}\s/.test(l)).map((l)
565
658
  function proseWords(md) {
566
659
  let n = 0;
567
660
  for (const p of md.split(/\n\s*\n/).map((x) => x.trim()).filter((x) => x && !/^#{1,6}\s/.test(x))) {
568
- const words3 = p.split(/\s+/).length;
569
- if (words3 < 40 || /^(-|\*|\d+\.)\s/.test(p)) continue;
661
+ const words4 = p.split(/\s+/).length;
662
+ if (words4 < 40 || /^(-|\*|\d+\.)\s/.test(p)) continue;
570
663
  const linkChars = (p.match(/\[[^\]]*\]\([^)]*\)/g) ?? []).join("").length;
571
664
  if (linkChars / p.length > 0.3) continue;
572
- n += words3;
665
+ n += words4;
573
666
  }
574
667
  return n;
575
668
  }
@@ -578,8 +671,8 @@ function hasMethodsAndResults(md) {
578
671
  const hs = headings(md);
579
672
  const has = (re) => hs.some((h) => re.test(h));
580
673
  if (has(/method|material|procedure|design|experimental|patients? and|participants/i) && has(/result|finding|outcome/i)) return true;
581
- const words3 = md.split(/\s+/).length;
582
- if (words3 < 1200 || hs.length < 2) return false;
674
+ const words4 = md.split(/\s+/).length;
675
+ if (words4 < 1200 || hs.length < 2) return false;
583
676
  const SECTION = /^(abstract|summary|introduction|background|discussion|conclusions?|references|acknowledg|limitations|key points|funding|participants|statistical|supplementary|data availability|author contributions|competing interests|conflicts? of interest|disclosure)/i;
584
677
  return hs.filter((h) => SECTION.test(h.trim())).length >= 2;
585
678
  }
@@ -597,36 +690,6 @@ function checkFulltext(md, title, titleSource, doi, trusted = false, pdf = false
597
690
  return { ok: true };
598
691
  }
599
692
 
600
- // src/hosts.ts
601
- import { connect } from "net";
602
- var UP_MS = 6e4;
603
- var DOWN_MS = 5 * 6e4;
604
- var PROBE_MS = 3e3;
605
- var seen = /* @__PURE__ */ new Map();
606
- var key = (host3, port) => `${host3}:${port}`;
607
- function probe(host3, port, timeoutMs = PROBE_MS) {
608
- const t0 = Date.now();
609
- return new Promise((resolve4) => {
610
- const s = connect({ host: host3, port });
611
- const done = (error) => {
612
- s.destroy();
613
- resolve4({ up: !error, ms: Date.now() - t0, at: Date.now(), error });
614
- };
615
- s.setTimeout(timeoutMs, () => done(`no answer within ${timeoutMs / 1e3} s`));
616
- s.once("connect", () => done(null));
617
- s.once("error", (e) => done(e.code ?? e.message));
618
- });
619
- }
620
- async function hostState(host3, port, onDown) {
621
- const k = key(host3, port), now2 = Date.now(), old = seen.get(k);
622
- if (old && now2 - old.at < (old.up ? UP_MS : DOWN_MS)) return old;
623
- const s = await probe(host3, port);
624
- seen.set(k, s);
625
- if (!s.up && (!old || old.up)) onDown?.(s);
626
- return s;
627
- }
628
- var downNote = (s) => `host down (${s.error}, since ${new Date(s.at).toTimeString().slice(0, 5)})`;
629
-
630
693
  // src/html.ts
631
694
  import TurndownService from "turndown";
632
695
  import { gfm } from "@joplin/turndown-plugin-gfm";
@@ -1375,7 +1438,7 @@ function pageReason(error, msg) {
1375
1438
  return null;
1376
1439
  }
1377
1440
  function post(url, init) {
1378
- return new Promise((resolve4, reject) => {
1441
+ return new Promise((resolve5, reject) => {
1379
1442
  const req = httpsRequest(url, { method: "POST", headers: { ...init.headers, "Content-Length": String(Buffer.byteLength(init.body)) }, signal: init.signal }, (res) => {
1380
1443
  const chunks = [];
1381
1444
  res.on("data", (c) => chunks.push(c));
@@ -1383,7 +1446,7 @@ function post(url, init) {
1383
1446
  res.on("end", () => {
1384
1447
  const body = Buffer.concat(chunks);
1385
1448
  const status = res.statusCode ?? 0;
1386
- resolve4({
1449
+ resolve5({
1387
1450
  ok: status >= 200 && status < 300,
1388
1451
  status,
1389
1452
  headers: { get: (name) => {
@@ -2734,13 +2797,13 @@ var hostOf2 = (url) => {
2734
2797
  }
2735
2798
  };
2736
2799
  var NCBI = /^https?:\/\/([a-z0-9.-]+\.)?(ncbi\.nlm\.nih\.gov|pubmed\.gov)\//i;
2737
- function order(candidates) {
2800
+ function order(candidates2) {
2738
2801
  const rank = (c) => (c.pdf ? 0 : 2) + (c.host === "publisher" ? 1 : 0);
2739
- return [...candidates].sort((a, b) => rank(a) - rank(b));
2802
+ return [...candidates2].sort((a, b) => rank(a) - rank(b));
2740
2803
  }
2741
- async function download(tier, p, candidates, ctx) {
2742
- const usable = candidates.filter((c) => !NCBI.test(c.url));
2743
- if (!usable.length && candidates.length) return miss(tier, "only pmc copies (covered by the pmc tier)");
2804
+ async function download(tier, p, candidates2, ctx) {
2805
+ const usable = candidates2.filter((c) => !NCBI.test(c.url));
2806
+ if (!usable.length && candidates2.length) return miss(tier, "only pmc copies (covered by the pmc tier)");
2744
2807
  const ordered = order(usable.map((c) => {
2745
2808
  const u = toHttps(c.url);
2746
2809
  if (u !== c.url) ctx.onTry?.(`http upgraded: ${c.url} \u2192 ${u}`);
@@ -2796,9 +2859,9 @@ async function download(tier, p, candidates, ctx) {
2796
2859
  const UNLOCK = /^(HTTP 403|wall page)/;
2797
2860
  let browsed = false;
2798
2861
  if (!gone && !c.headers && !c.service && (climbsOn(plainReason) || climbsOn(bare(reasonOf(r))))) {
2799
- const open = browserStages().filter((b) => !skipped(target.url, stageName(b)));
2800
- const down = await Promise.all(open.map((b) => hostDown(b.host, b.port, stageName(b), target.url)));
2801
- const tasks = open.filter((_, i2) => !down[i2]).map((b) => run(target, { browser: b.endpoint, label: b.label }, stageName(b)));
2862
+ const open2 = browserStages().filter((b) => !skipped(target.url, stageName(b)));
2863
+ const down = await Promise.all(open2.map((b) => hostDown(b.host, b.port, stageName(b), target.url)));
2864
+ const tasks = open2.filter((_, i2) => !down[i2]).map((b) => run(target, { browser: b.endpoint, label: b.label }, stageName(b)));
2802
2865
  browsed = tasks.length > 0;
2803
2866
  const two = await firstOk(tasks, isGone);
2804
2867
  if (two.won) return two.won;
@@ -2869,9 +2932,9 @@ function serviceMessage(bytes, contentType = "") {
2869
2932
  return (visible || text4).slice(0, 160);
2870
2933
  }
2871
2934
  function describe(reason, format, md) {
2872
- const words3 = md.split(/\s+/).filter(Boolean).length;
2935
+ const words4 = md.split(/\s+/).filter(Boolean).length;
2873
2936
  const headings2 = md.split("\n").filter((l) => /^#{2,6}\s/.test(l)).length;
2874
- const seen2 = `${format}, ${words3} words, ${proseWords(md)} in prose, ${headings2} heading${headings2 === 1 ? "" : "s"}`;
2937
+ const seen2 = `${format}, ${words4} words, ${proseWords(md)} in prose, ${headings2} heading${headings2 === 1 ? "" : "s"}`;
2875
2938
  if (reason === "no methods/results") return `no article body (${seen2})`;
2876
2939
  if (reason === "title missing") return `neither title nor DOI in text (${seen2})`;
2877
2940
  return reason;
@@ -2993,10 +3056,10 @@ function coreTier(apiKey2) {
2993
3056
  } catch (e) {
2994
3057
  return miss(this.name, errMsg(e));
2995
3058
  }
2996
- const candidates = coreCandidates(data);
2997
- if (!candidates.length) return miss(this.name, data.results?.length ? "no full text" : "not in core");
2998
- ctx.onTry?.(`located ${candidates.length} copies`);
2999
- return download(this.name, p, candidates, ctx);
3059
+ const candidates2 = coreCandidates(data);
3060
+ if (!candidates2.length) return miss(this.name, data.results?.length ? "no full text" : "not in core");
3061
+ ctx.onTry?.(`located ${candidates2.length} copies`);
3062
+ return download(this.name, p, candidates2, ctx);
3000
3063
  }
3001
3064
  };
3002
3065
  }
@@ -3030,10 +3093,10 @@ var europepmc = {
3030
3093
  }
3031
3094
  const rec = data.resultList?.result?.[0];
3032
3095
  if (!rec) return miss(this.name, "not in europe pmc");
3033
- const candidates = europepmcCandidates(rec, p.pmcid);
3034
- if (!candidates.length) return miss(this.name, "no free copy");
3035
- ctx.onTry?.(`located ${candidates.length} copies`);
3036
- return download(this.name, p, candidates, ctx);
3096
+ const candidates2 = europepmcCandidates(rec, p.pmcid);
3097
+ if (!candidates2.length) return miss(this.name, "no free copy");
3098
+ ctx.onTry?.(`located ${candidates2.length} copies`);
3099
+ return download(this.name, p, candidates2, ctx);
3037
3100
  }
3038
3101
  };
3039
3102
  function europepmcCandidates(r, pmcid) {
@@ -3071,10 +3134,10 @@ var openalex = {
3071
3134
  } catch (e) {
3072
3135
  return miss(this.name, errMsg(e));
3073
3136
  }
3074
- const candidates = openalexCandidates(data);
3075
- if (!candidates.length) return miss(this.name, data.open_access?.is_oa === false ? "closed" : "no oa copy");
3076
- ctx.onTry?.(`located ${candidates.length} copies`);
3077
- return download(this.name, p, candidates, ctx);
3137
+ const candidates2 = openalexCandidates(data);
3138
+ if (!candidates2.length) return miss(this.name, data.open_access?.is_oa === false ? "closed" : "no oa copy");
3139
+ ctx.onTry?.(`located ${candidates2.length} copies`);
3140
+ return download(this.name, p, candidates2, ctx);
3078
3141
  }
3079
3142
  };
3080
3143
  function openalexCandidates(d) {
@@ -3137,12 +3200,12 @@ var hostOf3 = (url) => {
3137
3200
  function tdmCandidates(work, tokens2 = {}, env = process.env) {
3138
3201
  const links = (work.message?.link ?? []).filter((l) => l["intended-application"] === "text-mining" && l.URL);
3139
3202
  const seen2 = /* @__PURE__ */ new Set();
3140
- const candidates = [];
3203
+ const candidates2 = [];
3141
3204
  const missingTokens = /* @__PURE__ */ new Set();
3142
3205
  for (const l of links) {
3143
3206
  const ct = (l["content-type"] ?? "").toLowerCase();
3144
3207
  if (seen2.has(l.URL)) {
3145
- const prev = candidates.find((c) => c.url === l.URL);
3208
+ const prev = candidates2.find((c) => c.url === l.URL);
3146
3209
  if (prev && /pdf/.test(ct)) prev.pdf = true;
3147
3210
  continue;
3148
3211
  }
@@ -3158,11 +3221,11 @@ function tdmCandidates(work, tokens2 = {}, env = process.env) {
3158
3221
  headers = { [rule.header]: token };
3159
3222
  }
3160
3223
  if (/text\/plain/.test(ct)) continue;
3161
- candidates.push({ url: l.URL, version: "published", source: "tdm", host: work.message?.publisher ?? hostOf3(l.URL), pdf: /pdf/.test(ct) || /\.pdf(\?|$)/i.test(l.URL), headers });
3224
+ candidates2.push({ url: l.URL, version: "published", source: "tdm", host: work.message?.publisher ?? hostOf3(l.URL), pdf: /pdf/.test(ct) || /\.pdf(\?|$)/i.test(l.URL), headers });
3162
3225
  }
3163
3226
  const rank = (c) => /\/xml|text\/xml/.test(c.url) ? 0 : c.pdf ? 1 : 2;
3164
- candidates.sort((a, b) => rank(a) - rank(b));
3165
- return { candidates, missingTokens: [...missingTokens] };
3227
+ candidates2.sort((a, b) => rank(a) - rank(b));
3228
+ return { candidates: candidates2, missingTokens: [...missingTokens] };
3166
3229
  }
3167
3230
  function tdmTier(tokens2 = {}) {
3168
3231
  return {
@@ -3176,10 +3239,10 @@ function tdmTier(tokens2 = {}) {
3176
3239
  } catch (e) {
3177
3240
  return miss(this.name, errMsg(e));
3178
3241
  }
3179
- const { candidates, missingTokens } = tdmCandidates(work, tokens2);
3180
- if (!candidates.length) return missingTokens.length ? { ...miss(this.name, `needs ${missingTokens.join("/")} token`), skipped: true } : miss(this.name, "no text-mining links");
3181
- ctx.onTry?.(`${candidates.length} text-mining links${missingTokens.length ? ` (skipped hosts needing ${missingTokens.join("/")} token)` : ""}`);
3182
- return download(this.name, p, candidates, ctx);
3242
+ const { candidates: candidates2, missingTokens } = tdmCandidates(work, tokens2);
3243
+ if (!candidates2.length) return missingTokens.length ? { ...miss(this.name, `needs ${missingTokens.join("/")} token`), skipped: true } : miss(this.name, "no text-mining links");
3244
+ ctx.onTry?.(`${candidates2.length} text-mining links${missingTokens.length ? ` (skipped hosts needing ${missingTokens.join("/")} token)` : ""}`);
3245
+ return download(this.name, p, candidates2, ctx);
3183
3246
  }
3184
3247
  };
3185
3248
  }
@@ -3197,10 +3260,10 @@ var unpaywall = {
3197
3260
  } catch (e) {
3198
3261
  return miss(this.name, errMsg(e));
3199
3262
  }
3200
- const candidates = unpaywallCandidates(data);
3201
- if (!candidates.length) return miss(this.name, data.is_oa === false ? "closed" : "no oa copy");
3202
- ctx.onTry?.(`located ${candidates.length} copies`);
3203
- return download(this.name, p, candidates, ctx);
3263
+ const candidates2 = unpaywallCandidates(data);
3264
+ if (!candidates2.length) return miss(this.name, data.is_oa === false ? "closed" : "no oa copy");
3265
+ ctx.onTry?.(`located ${candidates2.length} copies`);
3266
+ return download(this.name, p, candidates2, ctx);
3204
3267
  }
3205
3268
  };
3206
3269
  function unpaywallCandidates(d) {
@@ -3285,13 +3348,11 @@ var VARIABLES = [
3285
3348
  "FH_REFRESH_AFTER_DAYS",
3286
3349
  "FH_SEARCH_CACHE_DAYS",
3287
3350
  "FH_NCBI_API_KEY",
3288
- "FH_WEB_SEARCH_ENABLED",
3289
3351
  "FH_WEB_SEARCH_EXA_API_KEY",
3290
3352
  "FH_WEB_SEARCH_SERPER_API_KEY",
3291
3353
  "FH_WEB_SEARCH_BRAVE_API_KEY",
3292
3354
  "FH_WEB_SEARCH_SNIPPETS",
3293
3355
  "FH_WEB_SEARCH_TIMEOUT_SECS",
3294
- "FH_CITATIONS_ENABLED",
3295
3356
  "FH_OPENALEX_API_KEY",
3296
3357
  "FH_ZENROWS_API_KEY",
3297
3358
  "FH_FIRECRAWL_API_KEY",
@@ -3305,13 +3366,17 @@ var VARIABLES = [
3305
3366
  "FH_EVMAP_MAX_RESULTS_PER_QUERY",
3306
3367
  "FH_EVMAP_CITATION_REVIEWS",
3307
3368
  "FH_EVMAP_CITATION_MAX_ADDED",
3308
- "FH_EVMAP_RANK_PROVIDER",
3309
- "FH_EVMAP_RANK_API_KEY",
3310
- "FH_EVMAP_RANK_MODEL",
3311
- "FH_EVMAP_RANK_URL",
3312
- "FH_EVMAP_RANK_CANDIDATES",
3313
- "FH_EVMAP_RANK_PICKS",
3314
- "FH_EVMAP_SCREEN_PROVIDER",
3369
+ "FH_EVMAP_RANKING_PROVIDER",
3370
+ "FH_EVMAP_RANKING_API_KEY",
3371
+ "FH_EVMAP_RANKING_MODEL",
3372
+ "FH_EVMAP_RANKING_URL",
3373
+ "FH_EVMAP_RANKING_CANDIDATES",
3374
+ "FH_EVMAP_RANKING_DIRECT",
3375
+ "FH_EVMAP_RANKING_PICKS",
3376
+ "FH_EVMAP_RANKING_ITEM_CANDIDATES",
3377
+ "FH_EVMAP_RANKING_ITEM_PICKS",
3378
+ "FH_EVMAP_RANKING_ASSIGN_ARTICLES",
3379
+ "FH_EVMAP_SCREENING_PROVIDER",
3315
3380
  "FH_EVMAP_ANTHROPIC_API_KEY",
3316
3381
  "FH_EVMAP_ANTHROPIC_MODEL",
3317
3382
  "FH_EVMAP_ANTHROPIC_URL",
@@ -3321,13 +3386,34 @@ var VARIABLES = [
3321
3386
  "FH_EVMAP_OPENAI_API_KEY",
3322
3387
  "FH_EVMAP_OPENAI_MODEL",
3323
3388
  "FH_EVMAP_OPENAI_URL",
3324
- "FH_EVMAP_SCREEN_URL",
3325
- "FH_EVMAP_SCREEN_API_KEY",
3326
- "FH_EVMAP_SCREEN_MODEL",
3327
- "FH_EVMAP_SCREEN_PARALLEL"
3389
+ "FH_EVMAP_OPENROUTER_API_KEY",
3390
+ "FH_EVMAP_OPENROUTER_MODEL",
3391
+ "FH_EVMAP_OPENROUTER_URL",
3392
+ "FH_EVMAP_SCREENING_URL",
3393
+ "FH_EVMAP_SCREENING_API_KEY",
3394
+ "FH_EVMAP_SCREENING_MODEL",
3395
+ "FH_EVMAP_SCREENING_PARALLEL",
3396
+ "FH_EVMAP_PROMPTS",
3397
+ "FH_EVMAP_WAIT_SECS",
3398
+ "FH_EVMAP_DISCOVERY_PROVIDER",
3399
+ "FH_EVMAP_DISCOVERY_API_KEY",
3400
+ "FH_EVMAP_DISCOVERY_MODEL",
3401
+ "FH_EVMAP_DISCOVERY_URL",
3402
+ "FH_EVMAP_DISCOVERY_ITERATIONS",
3403
+ "FH_EVMAP_DISCOVERY_MAX_BENEFITS",
3404
+ "FH_EVMAP_DISCOVERY_MAX_RISKS",
3405
+ "FH_EVMAP_DISCOVERY_MAX_INTERACTIONS",
3406
+ "FH_EVMAP_DISCOVERY_MAX_PROTOCOL",
3407
+ "FH_EVMAP_RANKING_REVIEW_PICKS",
3408
+ "FH_EVMAP_DISCOVERY_ITEM_RESULTS",
3409
+ "FH_EVMAP_DISCOVERY_SURVEY_RESULTS",
3410
+ "FH_EVMAP_DISCOVERY_TITLES",
3411
+ "FH_EVMAP_XAI_API_KEY",
3412
+ "FH_EVMAP_XAI_MODEL",
3413
+ "FH_EVMAP_XAI_URL"
3328
3414
  ];
3329
3415
  var on = (v) => /^(true|1|yes|on)$/i.test(v?.trim() ?? "");
3330
- var hidden = (v, env) => v.startsWith("FH_WEB_SEARCH_") && !on(env.FH_WEB_SEARCH_ENABLED) || v === "FH_CITATIONS_ENABLED" && !on(env.FH_CITATIONS_ENABLED) || v.startsWith("FH_EVID_") && !on(env.FH_EVID_ENABLED) || v.startsWith("FH_EVMAP_") && !on(env.FH_EVMAP_ENABLED);
3416
+ var hidden = (v, env) => v.startsWith("FH_EVID_") && !on(env.FH_EVID_ENABLED) || v.startsWith("FH_EVMAP_") && !on(env.FH_EVMAP_ENABLED);
3331
3417
  var sources = (env = process.env) => Object.fromEntries(VARIABLES.filter((v) => !hidden(v, env)).map((v) => [v, sourceOf(v, env)]));
3332
3418
  function settings(env = process.env) {
3333
3419
  return {
@@ -3592,7 +3678,7 @@ function sections(md) {
3592
3678
  }
3593
3679
  var countWords = (s) => (s.replace(/^#{1,6}\s+/gm, "").match(/\S+/g) ?? []).length;
3594
3680
  function outline(md, text4) {
3595
- return { text: text4, words: countWords(md), sections: sections(md).filter((s) => s.level > 1).map(({ level, label, words: words3 }) => ({ level, heading: label, words: words3 })) };
3681
+ return { text: text4, words: countWords(md), sections: sections(md).filter((s) => s.level > 1).map(({ level, label, words: words4 }) => ({ level, heading: label, words: words4 })) };
3596
3682
  }
3597
3683
  function findSections(md, name) {
3598
3684
  let q = name.trim().toLowerCase().replace(/^#+\s*/, "");
@@ -4525,40 +4611,291 @@ async function searchArticles(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = liv
4525
4611
  // src/evidencemap.ts
4526
4612
  import { mkdirSync as mkdirSync11 } from "fs";
4527
4613
  import { dirname as dirname6 } from "path";
4528
- import { existsSync as existsSync13, readFileSync as readFileSync9 } from "fs";
4614
+ import { existsSync as existsSync14, readFileSync as readFileSync10 } from "fs";
4615
+
4616
+ // src/prompts.ts
4617
+ import { existsSync as existsSync10, readFileSync as readFileSync8, statSync as statSync2 } from "fs";
4618
+ import { join as join9, resolve as resolve4 } from "path";
4619
+
4620
+ // src/prompts.generated.ts
4621
+ var BUILTIN_PROMPTS = {
4622
+ screening: "# Evidence Map \u2014 Screening Prompt\n\nHow the screening model judges each abstract found for an evidence map. The server sends it once per article: {{topic}} filled in with the EVID's topic, {{article}} with the article's PMID, title, year, publication types and abstract. With it goes the answer's form, a JSON schema the model must fill \u2014 the map's columns, fixed by the server:\n\n- relevance \u2014 direct (the topic's intervention itself, any outcome) / indirect (a broader category, a related intervention, or pooled with others) / background (animal, in vitro, mechanism, epidemiology) / off-topic (out of the map)\n- population \u2014 humans / animals / in vitro / none\n- design \u2014 the study design, e.g. meta-analysis, RCT, cohort, case report, animal study\n- n \u2014 participants, if the abstract states it\n- outcome \u2014 hard (death, incidence, clinical events) / surrogate (biomarker, imaging) / none\n- finding \u2014 benefit / no effect / harm / mixed / none: the intervention's effect\n- aspect \u2014 efficacy / safety / mechanism / dosing / interaction / other\n- reason \u2014 one sentence: what the paper adds to the topic\n\nThis prompt says how to judge; the fields say what to answer. Everything above the line is for people and is not sent.\n\n---\n\nScreen this article for the topic: {{topic}}\n\nRead the abstract and fill every field from it; where the abstract says nothing, answer none.\n\n{{article}}\n",
4623
+ ranking: `# Evidence Map \u2014 Ranking Prompt
4624
+
4625
+ How the ranking model picks the articles that matter most. Three steps, one section each: **Map** \u2014 the picks over the whole map; **Assign** \u2014 for a map built by the server's own discovery, which of the map's best articles belong to which item, whatever query found them: {{topic}}, {{items}} (the numbered items) and {{articles}} (the numbered articles, each with its finding); **Items** \u2014 for a map built by the server's own discovery, the picks for each item (a benefit, a risk, an interaction): {{topic}}, {{picks}} (how many per item) and {{groups}} \u2014 one group per item, its name and its candidates. A file without sections is the Map step alone.
4626
+
4627
+ The Map step: The server sends it once per map, after the screening: {{topic}} filled in with the EVID's topic, {{count}} with the number of candidates (the 200 best-scored articles and up to 100 more direct ones by default), {{picks}} with how many to pick (100), and {{candidates}} with one row per candidate \u2014 number, title, year, design, n, relevance, aspect, and its signals (in how many queries and reviews, citations per year). The answer's form is fixed by the server: the picked numbers, most important first. The picks lead the map in that order; the other articles follow by score.
4628
+
4629
+ Everything above the line is for people and is not sent.
4630
+
4631
+ ---
4632
+
4633
+ ## Map
4634
+
4635
+ Below are {{count}} candidate articles on the topic "{{topic}}". Pick the {{picks}} that matter most \u2014 the key trials and meta-analyses for each important question, including safety and the null results; only articles that study the topic's intervention itself. Answer with their numbers, most important first.
4636
+
4637
+ {{candidates}}
4638
+
4639
+ ## Assign
4640
+
4641
+ A review of the topic "{{topic}}" is about to be written. Below are its items \u2014 each a benefit, a risk, an interaction or a protocol question of the intervention \u2014 and a list of articles found for the topic.
4642
+
4643
+ For each article name the items a review could cite it for:
4644
+ - an article belongs to an item when it reports on that item for the topic's intervention: a result, a rate, a dose \u2014 also as one outcome among several, as a broad meta-analysis or a large trial does
4645
+ - most articles belong to one to three items; an article that fits no item is left out of the answer
4646
+ - not by a shared word alone: the article must say something about the item
4647
+
4648
+ Answer with each article's number and the numbers of its items.
4649
+
4650
+ Items:
4651
+ {{items}}
4652
+
4653
+ Articles:
4654
+ {{articles}}
4655
+
4656
+ ## Items
4657
+
4658
+ A review of the topic "{{topic}}" is about to be written. Below are groups of candidate articles; each group answers one question about the intervention, named in its heading (a benefit, a risk, an interaction, a protocol question, or the intervention's systematic reviews).
4659
+
4660
+ The topic names its goal ("\u2026 for Health & Longevity": prevention and long-term outcomes in people who use the intervention for that). Where a group's candidates allow a choice, the articles that serve that goal come first.
4661
+
4662
+ For each group pick the articles the review needs for that question, the most important first \u2014 up to {{picks}}, or the number its heading names:
4663
+ - for a benefit: the best systematic review or meta-analysis (the newest or largest), then the contrary or null evidence, then the key trial
4664
+ - for a risk or an interaction: the human studies that document it \u2014 the review, the trial, the pharmacokinetic study, the case report where nothing else exists
4665
+ - for a group named "overall" (safety, interactions, pharmacokinetics): the broad reviews and the largest studies of that side of the intervention as a whole
4666
+ - for a protocol question: the study or guideline a dose or a pharmacokinetic figure can be cited to, for the use the topic's goal means \u2014 for health and longevity the long-term use by people who take it for that (for a supplement: oral, at the usual doses), not the dosing of acute or intensive care
4667
+ - for the group of the intervention's systematic reviews: only systematic reviews and meta-analyses (no single trial, no cohort or Mendelian randomization study, no narrative review) \u2014 the major ones for the goal the topic names, by citations, size and recency, spread over its main questions rather than several on one; a topic on health and longevity is about prevention and long-term outcomes in people who use the intervention for that \u2014 not about its use in acute or intensive care, which gets at most one pick; where the intervention involves a trade-off, at least one on the claimed effect and one on the principal risk
4668
+ - only articles that are about the group's question and study the topic's intervention itself; a group whose candidates do not answer its question gets no pick
4669
+
4670
+ Answer with each group's number and the numbers of its picked candidates.
4671
+
4672
+ {{groups}}
4673
+ `,
4674
+ discovery: `# Evidence Map \u2014 Discovery Prompt
4675
+
4676
+ How the discovery model finds the articles for a map. The server sends one section per step. **Survey** \u2014 the queries for a first look at what the intervention has been studied for. Then four lists, each from the titles the survey found, each item with its own query: **Benefits**, **Risks**, **Interactions**, **Protocol** \u2014 the tables an evidence review has (its fifth, the major systematic reviews, comes from the survey itself). **Iteration** \u2014 a survey query with more hits than are read is split or narrowed (only when the survey is read whole). **Hints** is put into each step in place of {{hints}}. Slots: {{topic}}; {{titles}} and {{max}} (the lists: at most this many items); {{queries}} and {{limit}} (Iteration). The answers' form is fixed by the server.
4677
+
4678
+ Everything above the line is never sent.
4679
+
4680
+ ---
4681
+
4682
+ ## Survey
4683
+
4684
+ Write the PubMed queries for a first survey of this topic: {{topic}}
4685
+
4686
+ The survey is to show what the intervention has been studied for \u2014 every benefit, every risk, every interaction \u2014 so that a second round can ask about each one by name. It reads the reviews, not the single studies. Queries that usually serve:
4687
+ - systematic reviews and meta-analyses of the intervention
4688
+ - narrative reviews of its effects and uses
4689
+ - its safety: reviews of adverse effects and toxicity, case reports of rare harms
4690
+ - its interactions with drugs, supplements and foods
4691
+ - its pharmacokinetics
4692
+ - guidelines and position statements
4693
+ - for a drug, safety across its class; for a combination, each part on its own
4694
+
4695
+ About 6 to 10 queries, each with its kind and a short label. Only the first results of each are read, so one query per question, the names in the title. The interactions query is read whole, so it must hold the human interaction and pharmacokinetic studies and little else \u2014 a few hundred results, not thousands: the names in the title, the words of such a study (pharmacokinetics, bioavailability, absorption, interaction), humans, and a study design. E.g. (centrophenoxine[ti] OR meclofenoxate[ti]) AND (pharmacokinetic*[tiab] OR bioavailability[tiab] OR absorption[tiab] OR "drug interactions"[mh] OR interaction*[ti]) AND humans[mh] AND (clinical trial[pt] OR randomized controlled trial[pt] OR crossover[tiab] OR volunteers[tiab])
4696
+
4697
+ {{hints}}
4698
+
4699
+ ## Benefits
4700
+
4701
+ Topic: {{topic}}
4702
+
4703
+ A review of this topic has a table of benefits: every benefit the intervention has been studied for, each backed by its evidence. Below are the titles of the articles a survey found. List the benefits, one item each:
4704
+ - every distinct outcome or condition the intervention has been studied for, whatever the result \u2014 also where it did not help
4705
+ - the goal's own outcomes (for longevity, e.g. mortality, frailty, physical function) and the intervention's main medical use, also when the titles lack them
4706
+
4707
+ Keep distinct outcomes apart \u2014 cataract and macular degeneration are two items, blood glucose and metabolic syndrome are two. At most {{max}} items: only if there are more, merge the closest ones.
4708
+
4709
+ {{item_query}}
4710
+
4711
+ {{hints}}
4712
+
4713
+ Titles:
4714
+
4715
+ {{titles}}
4716
+
4717
+ ## Risks
4718
+
4719
+ Topic: {{topic}}
4720
+
4721
+ A review of this topic has a table of risks: every harm the intervention can do, each backed by its evidence. Below are the titles of the articles a survey found. List the risks, one item each:
4722
+ - every adverse effect reported, the common and the rare ones \u2014 a rare harm known from case reports is an item too
4723
+ - every group at risk: pregnancy, children, older people, a disease or a genetic trait that makes the intervention dangerous
4724
+ - toxicity and overdose; effects on laboratory tests
4725
+ - a known adverse effect of the intervention or of its class that the titles lack belongs in the list too
4726
+
4727
+ Keep distinct harms apart. At most {{max}} items.
4728
+
4729
+ {{item_query}}
4730
+
4731
+ {{hints}}
4732
+
4733
+ Titles:
4734
+
4735
+ {{titles}}
4736
+
4737
+ ## Interactions
4738
+
4739
+ Topic: {{topic}}
4740
+
4741
+ A review of this topic has a table of interactions: every drug, supplement or food the intervention interacts with, each backed by its evidence. Below are the titles of the articles a survey found. List the interactions, one item each:
4742
+ - each drug, supplement or food on its own \u2014 one item per substance, never several in one item; a single human study of one substance with the intervention is enough to make it an item
4743
+ - a drug class as an item where the interaction is known for the class (e.g. diuretics, proton pump inhibitors)
4744
+ - a known interaction of the intervention that the titles lack belongs in the list too
4745
+
4746
+ At most {{max}} items.
4747
+
4748
+ {{item_query}}
4749
+
4750
+ {{hints}}
4751
+
4752
+ Titles:
4753
+
4754
+ {{titles}}
4755
+
4756
+ ## Protocol
4757
+
4758
+ Topic: {{topic}}
4759
+
4760
+ A review of this topic describes how the intervention is used \u2014 its therapeutic protocol \u2014 and cites each dose to a source. Below are the titles of the articles a survey found. List what the protocol needs, one item each:
4761
+ - the doses and regimens used in trials and named in guidelines; dose-response
4762
+ - pharmacokinetics: half-life, bioavailability, absorption, a single dose against split doses, the time of day
4763
+ - the forms and routes that differ in effect (e.g. oral against intravenous, one salt or formulation against another)
4764
+ - genetic variants that change the dose or the response
4765
+ - stopping: withdrawal, rebound, cycling
4766
+
4767
+ The protocol is for the goal the topic names: for health and longevity the long-term use by people who take the intervention for that \u2014 not the dosing of acute or intensive care, which is at most one item (the routes compared).
4768
+
4769
+ Only what has been studied for this intervention. At most {{max}} items.
4770
+
4771
+ {{item_query}}
4772
+
4773
+ {{hints}}
4774
+
4775
+ Titles:
4776
+
4777
+ {{titles}}
4778
+
4779
+ ## Item query
4780
+
4781
+ For each item write one PubMed query that finds the studies of the intervention on that item. Only the first results of each query are read, so it has to be narrow: the intervention's names in the title ([ti]) and the item's own words in the title too, with their synonyms. One item per query.
4782
+
4783
+ ## Iteration
4784
+
4785
+ Topic: {{topic}}
4786
+
4787
+ Each of these PubMed queries has more than {{limit}} hits; only the first {{limit}} of a query are read, so the rest would be lost. Replace each one by one or more queries that each stay under {{limit}} hits and together keep what the query was for:
4788
+ - the intervention's names in the title ([ti])
4789
+ - split by outcome, by study design (reviews; trials; observational studies) or by population
4790
+ - the question's words in the title where title and abstract give too many
4791
+
4792
+ Not by publication date. A query that cannot be narrowed without losing its purpose: give it back unchanged.
4793
+
4794
+ {{hints}}
4795
+
4796
+ Queries (number, hits, query):
4797
+
4798
+ {{queries}}
4799
+
4800
+ ## Hints
4801
+
4802
+ Hints for writing the queries:
4803
+ - every name the intervention goes by: the generic name, brand and trade names (also former and foreign ones), chemical names, common abbreviations
4804
+ - names untagged let PubMed also find them by their MeSH term; in the title ([ti]) they keep the articles that are about the intervention, where untagged names bring thousands that only mention it
4805
+ - reviews and meta-analyses of the intervention name it in their title
4806
+ - tags fit the question words: [tiab] for title and abstract, [pt] for publication types, * for word endings
4807
+ - filters on MeSH terms or publication types miss articles not yet indexed, often the newest; title words beside them keep those
4808
+ - e.g. (centrophenoxine[ti] OR meclofenoxate[ti] OR lucidril[ti]) AND (systematic review[pt] OR meta-analysis[pt] OR systematic review[ti] OR meta-analy*[ti])
4809
+ - e.g. (centrophenoxine OR meclofenoxate OR lucidril) AND (interaction*[tiab] OR coadministration[tiab] OR concomitant[tiab])
4810
+ `
4811
+ };
4812
+
4813
+ // src/prompts.ts
4814
+ var BUILTIN2 = { screening: promptBody(BUILTIN_PROMPTS.screening), ranking: promptBody(BUILTIN_PROMPTS.ranking), discovery: promptBody(BUILTIN_PROMPTS.discovery) };
4815
+ var FILES = {
4816
+ screening: { file: "screening.md", slots: ["{{topic}}", "{{article}}"] },
4817
+ ranking: { file: "ranking.md", slots: ["{{candidates}}"] },
4818
+ // the discovery prompt: one section per step (## Survey; ## Benefits, ## Risks, ## Interactions; ## Iteration; ## Item query and ## Hints go into the steps)
4819
+ discovery: { file: "discovery.md", slots: ["## Survey", "## Benefits", "## Risks", "## Interactions", "## Protocol", "## Item query", "## Iteration", "{{titles}}", "{{queries}}"] }
4820
+ };
4821
+ var builtinPrompt = (kind) => BUILTIN2[kind];
4822
+ function promptBody(text4) {
4823
+ let t = text4.replace(/<!--[\s\S]*?-->[ \t]*\r?\n?/g, "");
4824
+ const fm = /^---[ \t]*\r?\n[\s\S]*?\r?\n---[ \t]*(\r?\n|$)/.exec(t);
4825
+ if (fm) t = t.slice(fm[0].length);
4826
+ else {
4827
+ const m = /^---[ \t]*\r?\n/m.exec(t);
4828
+ if (m) t = t.slice(m.index + m[0].length);
4829
+ }
4830
+ return t.replace(/^\s*\n/, "");
4831
+ }
4832
+ var PROMPTS_SETTING = "FH_EVMAP_PROMPTS";
4833
+ function activePrompt(kind, env = process.env) {
4834
+ const { slots, file: file3 } = FILES[kind];
4835
+ const dir = str(PROMPTS_SETTING, env);
4836
+ const builtin = (note = "", problem) => ({ text: BUILTIN2[kind], source: `built-in (evmap/${file3})${note}`, ...problem ? { problem } : {} });
4837
+ if (!dir) return builtin();
4838
+ const folder = resolve4(dir);
4839
+ if (!existsSync10(folder) || !statSync2(folder).isDirectory()) return builtin("", `${PROMPTS_SETTING}=${dir}: no such folder`);
4840
+ const full = join9(folder, file3);
4841
+ if (!existsSync10(full)) return builtin(` \u2014 no ${file3} in ${dir}`);
4842
+ const text4 = promptBody(readFileSync8(full, "utf8"));
4843
+ const missing = slots.filter((x) => !text4.includes(x));
4844
+ if (missing.length) return builtin("", `${PROMPTS_SETTING}=${dir}: ${file3} needs ${missing.join(" and ")}`);
4845
+ return { text: text4, source: join9(dir, file3) };
4846
+ }
4847
+ function promptSections(text4) {
4848
+ const out = {};
4849
+ const parts = text4.split(/^## +(.+?)[ \t]*$/m);
4850
+ for (let i = 1; i < parts.length; i += 2) out[parts[i].trim().toLowerCase()] = parts[i + 1].trim();
4851
+ return out;
4852
+ }
4853
+ function promptStep(text4, step, first) {
4854
+ const s = promptSections(text4);
4855
+ if (!Object.keys(s).length) return step === first ? text4 : null;
4856
+ return s[step] ?? null;
4857
+ }
4529
4858
 
4530
4859
  // src/screen.ts
4531
4860
  import Anthropic from "@anthropic-ai/sdk";
4532
4861
  import { createHash as createHash5 } from "crypto";
4533
- import { existsSync as existsSync10, mkdirSync as mkdirSync8, readFileSync as readFileSync8 } from "fs";
4534
- import { dirname as dirname4, join as join9 } from "path";
4535
- var screenParallel = (env = process.env) => num("FH_EVMAP_SCREEN_PARALLEL", 100, env, (n) => n >= 1 && n <= 400 && Number.isInteger(n));
4862
+ import { existsSync as existsSync11, mkdirSync as mkdirSync8, readFileSync as readFileSync9 } from "fs";
4863
+ import { dirname as dirname4, join as join10 } from "path";
4864
+ var screenParallel = (env = process.env) => num("FH_EVMAP_SCREENING_PARALLEL", 400, env, (n) => n >= 1 && n <= 400 && Number.isInteger(n));
4536
4865
  var SCREEN_PROVIDERS = {
4537
- anthropic: { api: "anthropic", url: "https://api.anthropic.com", model: "claude-haiku-5-5", keyPrefix: "sk-ant-" },
4538
- openai: { api: "openai", url: "https://api.openai.com/v1", model: "gpt-5.4-mini", keyPrefix: "sk-" },
4866
+ anthropic: { api: "anthropic", url: "https://api.anthropic.com", keyPrefix: "sk-ant-" },
4867
+ openai: { api: "openai", url: "https://api.openai.com/v1", keyPrefix: "sk-" },
4539
4868
  // Gemini through Google's OpenAI-compatible endpoint (speed test 2026-11-19: flash-lite 82 papers/s, Haiku 35)
4540
- google: { api: "openai", url: "https://generativelanguage.googleapis.com/v1beta/openai", model: "gemini-3.5-flash-lite", keyPrefix: "AIza" }
4869
+ google: { api: "openai", url: "https://generativelanguage.googleapis.com/v1beta/openai", keyPrefix: "AIza" },
4870
+ // OpenRouter: one key for many providers' models (the open ones too), OpenAI-compatible; the
4871
+ // model by its OpenRouter name. Reasoning off: a screening answer needs none, and a reasoning
4872
+ // model left on can spend its whole budget thinking (Liquid's, 2026-11-21).
4873
+ openrouter: { api: "openai", url: "https://openrouter.ai/api/v1", keyPrefix: "sk-or-", body: { reasoning: { enabled: false } } },
4874
+ // xAI (Grok), OpenAI-compatible (2026-11-22; models from its /v1/models list)
4875
+ xai: { api: "openai", url: "https://api.x.ai/v1", keyPrefix: "xai-" }
4541
4876
  };
4542
4877
  function screenConfig(env = process.env, forProvider) {
4543
- const field2 = (p2, f) => p2 && str(`FH_EVMAP_${p2.toUpperCase()}_${f}`, env) || str(`FH_EVMAP_SCREEN_${f}`, env);
4544
- const named = forProvider ?? str("FH_EVMAP_SCREEN_PROVIDER", env).toLowerCase();
4545
- if (named && !(named in SCREEN_PROVIDERS)) return { ok: false, reason: `FH_EVMAP_SCREEN_PROVIDER: ${named}, not one of ${Object.keys(SCREEN_PROVIDERS).join(", ")}` };
4878
+ const field2 = (p2, f) => p2 && str(`FH_EVMAP_${p2.toUpperCase()}_${f}`, env) || str(`FH_EVMAP_SCREENING_${f}`, env);
4879
+ const named = forProvider ?? str("FH_EVMAP_SCREENING_PROVIDER", env).toLowerCase();
4880
+ if (named && !(named in SCREEN_PROVIDERS)) return { ok: false, reason: `FH_EVMAP_SCREENING_PROVIDER: ${named}, not one of ${Object.keys(SCREEN_PROVIDERS).join(", ")}` };
4546
4881
  let provider = named ? named : null;
4547
4882
  const url = field2(provider, "URL").replace(/\/+$/, "");
4548
- const key2 = field2(provider, "API_KEY");
4883
+ const shared = (p2) => (p2 && !forProvider ? ["DISCOVERY", "RANKING"].filter((o) => str(`FH_EVMAP_${o}_PROVIDER`, env).toLowerCase() === p2).map((o) => str(`FH_EVMAP_${o}_API_KEY`, env)).find(Boolean) : "") || "";
4884
+ const key2 = field2(provider, "API_KEY") || shared(provider);
4549
4885
  if (!provider && url) provider = "openai";
4550
4886
  const anyKey = key2 || Object.keys(SCREEN_PROVIDERS).some((p2) => str(`FH_EVMAP_${p2.toUpperCase()}_API_KEY`, env));
4551
- if (!provider) return { ok: false, reason: anyKey ? "FH_EVMAP_SCREEN_PROVIDER: not set \u2014 anthropic, google or openai" : "no screening model (FH_EVMAP_SCREEN_PROVIDER, FH_EVMAP_SCREEN_API_KEY)" };
4887
+ if (!provider) return { ok: false, reason: anyKey ? `FH_EVMAP_SCREENING_PROVIDER: not set \u2014 ${Object.keys(SCREEN_PROVIDERS).join(", ")}` : "no screening model (FH_EVMAP_SCREENING_PROVIDER, FH_EVMAP_SCREENING_API_KEY)" };
4552
4888
  const p = SCREEN_PROVIDERS[provider];
4553
- const model = field2(provider, "MODEL") || p.model;
4554
- if (!key2 && !url) return { ok: false, reason: `FH_EVMAP_SCREEN_API_KEY: needed for ${provider}'s hosted API` };
4889
+ const model = field2(provider, "MODEL");
4890
+ if (!model) return { ok: false, reason: `FH_EVMAP_SCREENING_MODEL: not set \u2014 the screening model for ${provider}, e.g. a fast one` };
4891
+ if (!key2 && !url) return { ok: false, reason: `FH_EVMAP_SCREENING_API_KEY: needed for ${provider}'s hosted API` };
4555
4892
  const from = (f) => {
4556
4893
  const own = `FH_EVMAP_${provider.toUpperCase()}_${f}`;
4557
- return str(own, env) || !str(`FH_EVMAP_SCREEN_${f}`, env) ? own : `FH_EVMAP_SCREEN_${f}`;
4894
+ return str(own, env) || !str(`FH_EVMAP_SCREENING_${f}`, env) ? own : `FH_EVMAP_SCREENING_${f}`;
4558
4895
  };
4559
4896
  return { ok: true, provider, api: p.api, url: url || p.url, model, key: key2, vars: { key: from("API_KEY"), model: from("MODEL"), url: from("URL") } };
4560
4897
  }
4561
- var DEFAULT_SCREENING = "Screen this article for the topic: {{topic}}\n\nRead the abstract and fill every field from it; where the abstract says nothing, answer none.\n\n{{article}}\n";
4898
+ var DEFAULT_SCREENING = builtinPrompt("screening");
4562
4899
  var FIELDS2 = ["relevance", "population", "design", "n", "outcome", "finding", "aspect", "reason"];
4563
4900
  var SCHEMA = {
4564
4901
  type: "object",
@@ -4590,12 +4927,12 @@ var Refusal = class extends Error {
4590
4927
  super("refusal");
4591
4928
  }
4592
4929
  };
4593
- var PLAIN = { key: "FH_EVMAP_SCREEN_API_KEY", model: "FH_EVMAP_SCREEN_MODEL", url: "FH_EVMAP_SCREEN_URL" };
4930
+ var PLAIN = { key: "FH_EVMAP_SCREENING_API_KEY", model: "FH_EVMAP_SCREENING_MODEL", url: "FH_EVMAP_SCREENING_URL" };
4594
4931
  function hint(status, message, v = PLAIN) {
4595
4932
  if (status === 401 || status === 403 || /api key|api_key|x-api-key|unauthori[sz]ed|permission/i.test(message)) return `the API key is missing, wrong or has no access to the model \u2014 ${v.key} in the server's .env`;
4596
4933
  if (status === 404 || /model.*(not found|does not exist)|not_found/i.test(message)) return `the model or the endpoint does not exist \u2014 ${v.model}, ${v.url} in the server's .env`;
4597
4934
  if (/quota|spend|billing|credit balance|insufficient/i.test(message)) return `the provider account's quota or spending limit is used up \u2014 raise it in the provider's console, or use another key (${v.key})`;
4598
- if (status === 429) return "rate limit still hit after retries \u2014 lower FH_EVMAP_SCREEN_PARALLEL or try again later";
4935
+ if (status === 429) return "rate limit still hit after retries \u2014 lower FH_EVMAP_SCREENING_PARALLEL or try again later";
4599
4936
  if (status === 400) return `the provider refused the request; the model may not support structured output (a JSON schema) \u2014 ${v.model}`;
4600
4937
  if (status && status >= 500) return "the provider's service is failing \u2014 try again later";
4601
4938
  if (/timed? ?out|timeout/i.test(message)) return `no answer in time \u2014 the provider is slow or overloaded: try again later, or another model (${v.model})`;
@@ -4618,7 +4955,7 @@ var describe2 = (e, where2, v = PLAIN) => {
4618
4955
  };
4619
4956
  var where = (c) => `${c.provider} ${c.model} at ${c.url}`;
4620
4957
  function askFor(c) {
4621
- const ask = c.api === "anthropic" ? anthropicAsk(c.key, c.model, c.url) : openaiAsk(c.url, c.key, c.model);
4958
+ const ask = c.api === "anthropic" ? anthropicAsk(c.key, c.model, c.url) : openaiAsk(c.url, c.key, c.model, fetch, SCREEN_PROVIDERS[c.provider].body);
4622
4959
  return async (text4) => {
4623
4960
  try {
4624
4961
  return await ask(text4);
@@ -4643,15 +4980,17 @@ function anthropicAsk(apiKey2, model, baseURL) {
4643
4980
  return parseAnswer(block.text);
4644
4981
  };
4645
4982
  }
4646
- function openaiAsk(baseUrl, apiKey2, model, fetchImpl = fetch) {
4983
+ function openaiAsk(baseUrl, apiKey2, model, fetchImpl = fetch, extra = {}) {
4984
+ let fields = extra;
4647
4985
  return async (text4) => {
4648
4986
  for (let attempt = 0; ; attempt++) {
4649
4987
  let r;
4988
+ const sent = fields;
4650
4989
  try {
4651
4990
  r = await fetchImpl(`${baseUrl}/chat/completions`, {
4652
4991
  method: "POST",
4653
4992
  headers: { "content-type": "application/json", ...apiKey2 ? { authorization: `Bearer ${apiKey2}` } : {} },
4654
- body: JSON.stringify({ model, messages: [{ role: "user", content: text4 }], response_format: { type: "json_schema", json_schema: { name: "screening", strict: true, schema: SCHEMA } } }),
4993
+ body: JSON.stringify({ ...sent, model, messages: [{ role: "user", content: text4 }], response_format: { type: "json_schema", json_schema: { name: "screening", strict: true, schema: SCHEMA } } }),
4655
4994
  signal: AbortSignal.timeout(SCREEN_TIMEOUT_MS)
4656
4995
  });
4657
4996
  } catch (e) {
@@ -4661,7 +5000,15 @@ function openaiAsk(baseUrl, apiKey2, model, fetchImpl = fetch) {
4661
5000
  await new Promise((ok) => setTimeout(ok, Math.min(3e4, 1e3 * 2 ** attempt)));
4662
5001
  continue;
4663
5002
  }
4664
- if (!r.ok) throw new ScreenError(`HTTP ${r.status} ${(await r.text()).replace(/\s+/g, " ").slice(0, 2e3)}`, r.status);
5003
+ if (!r.ok) {
5004
+ const why = (await r.text()).replace(/\s+/g, " ").slice(0, 2e3);
5005
+ if (r.status === 400 && sent.reasoning && /reasoning is mandatory/i.test(why) && sent.reasoning.effort !== "minimal") {
5006
+ fields = { ...sent, reasoning: { effort: "minimal" } };
5007
+ attempt--;
5008
+ continue;
5009
+ }
5010
+ throw new ScreenError(`HTTP ${r.status} ${why}`, r.status);
5011
+ }
4665
5012
  const body = await r.json();
4666
5013
  const choice = body?.choices?.[0];
4667
5014
  if (choice?.finish_reason === "length") throw new Error("max_tokens: the answer was cut off");
@@ -4683,19 +5030,21 @@ function parseAnswer(text4) {
4683
5030
  return a;
4684
5031
  }
4685
5032
  async function screenAll(lib, pmids, prompt, topic, paper, ask, model, parallel, note = () => {
5033
+ }, done = () => {
4686
5034
  }) {
4687
- const dir = join9(lib, "screen", cacheKey(model, prompt, topic));
5035
+ const dir = join10(lib, "screen", cacheKey(model, prompt, topic));
4688
5036
  const out = new Array(pmids.length);
4689
5037
  let next = 0;
4690
5038
  const worker = async () => {
4691
5039
  while (next < pmids.length) {
4692
5040
  const i = next++;
4693
5041
  const pmid = pmids[i];
4694
- const file3 = join9(dir, `${pmid}.json`);
4695
- if (existsSync10(file3)) {
5042
+ const file3 = join10(dir, `${pmid}.json`);
5043
+ if (existsSync11(file3)) {
4696
5044
  try {
4697
- const c = JSON.parse(readFileSync8(file3, "utf8"));
5045
+ const c = JSON.parse(readFileSync9(file3, "utf8"));
4698
5046
  out[i] = c?.refused === true ? { pmid, refused: true, cached: true } : { pmid, screened: c, cached: true };
5047
+ done(out[i]);
4699
5048
  continue;
4700
5049
  } catch {
4701
5050
  }
@@ -4704,6 +5053,7 @@ async function screenAll(lib, pmids, prompt, topic, paper, ask, model, parallel,
4704
5053
  if (!text4) {
4705
5054
  out[i] = { pmid, error: "no abstract", cached: false };
4706
5055
  note(out[i], 0);
5056
+ done(out[i]);
4707
5057
  continue;
4708
5058
  }
4709
5059
  const t = Date.now();
@@ -4720,6 +5070,7 @@ async function screenAll(lib, pmids, prompt, topic, paper, ask, model, parallel,
4720
5070
  } else out[i] = { pmid, error: e instanceof Error ? e.message : String(e), cached: false };
4721
5071
  }
4722
5072
  note(out[i], Date.now() - t);
5073
+ done(out[i]);
4723
5074
  }
4724
5075
  };
4725
5076
  await Promise.all(Array.from({ length: Math.min(parallel, pmids.length) }, worker));
@@ -4736,20 +5087,20 @@ function score(s, types, queries, citesPerYear = 0, inReviews = 0) {
4736
5087
  return Math.round(level + rel + hard + size + Math.min(10, 2 * queries) + 20 * Math.log10(1 + citesPerYear) + 4 * Math.log2(1 + inReviews));
4737
5088
  }
4738
5089
  function screenLine(r, ms, model) {
4739
- const secs = `${(ms / 1e3).toFixed(1)}s`;
4740
- if (r.refused) return `refused screen ${model} ${secs}`;
4741
- if (!r.screened) return `failed screen ${model} ${secs}: ${r.error}`;
5090
+ const secs = `${(ms / 1e3).toFixed(1).padStart(4, "0")}s`;
5091
+ if (r.refused) return `refused ${secs} \xB7 ${model}`;
5092
+ if (!r.screened) return `screen failed ${secs} \xB7 ${model} \xB7 ${r.error}`;
4742
5093
  const f = r.screened;
4743
- return `screened ${f.relevance} \xB7 ${f.population} \xB7 ${f.design} \xB7 n=${f.n ?? "-"} \xB7 ${f.outcome} \xB7 ${f.finding} \xB7 ${f.aspect} \xB7 ${model} ${secs} \xB7 ${f.reason}`;
5094
+ return `screened ${secs} ${f.relevance} \xB7 ${f.population} \xB7 ${f.design} \xB7 n=${f.n ?? "-"} \xB7 ${f.outcome} \xB7 ${f.finding} \xB7 ${f.aspect} \xB7 ${model} \xB7 ${f.reason}`;
4744
5095
  }
4745
5096
 
4746
5097
  // src/log.ts
4747
- import { appendFileSync, existsSync as existsSync11, mkdirSync as mkdirSync9, readdirSync as readdirSync3, renameSync as renameSync4, statSync as statSync2, unlinkSync as unlinkSync2 } from "fs";
5098
+ import { appendFileSync, existsSync as existsSync12, mkdirSync as mkdirSync9, readdirSync as readdirSync3, renameSync as renameSync4, statSync as statSync3, unlinkSync as unlinkSync2 } from "fs";
4748
5099
  import { hostname } from "os";
4749
- import { basename as basename2, dirname as dirname5, join as join10 } from "path";
5100
+ import { basename as basename2, dirname as dirname5, join as join11 } from "path";
4750
5101
  var HOST = hostname();
4751
- var LOG_DIR = join10(FH_EVIDENCE_DIR, "logs");
4752
- var LOG_FILE = join10(LOG_DIR, "evidence.log");
5102
+ var LOG_DIR = join11(FH_EVIDENCE_DIR, "logs");
5103
+ var LOG_FILE = join11(LOG_DIR, "evidence.log");
4753
5104
  function stamp() {
4754
5105
  const d = /* @__PURE__ */ new Date();
4755
5106
  const p = (n) => String(n).padStart(2, "0");
@@ -4762,15 +5113,15 @@ var stampOf = (t) => {
4762
5113
  return `${t.getFullYear()}-${p(t.getMonth() + 1)}-${p(t.getDate())}-${p(t.getHours())}${p(t.getMinutes())}${p(t.getSeconds())}`;
4763
5114
  };
4764
5115
  function datedName(file3, when) {
4765
- const base = join10(dirname5(file3), `${basename2(file3, ".log")}-${stampOf(when)}`);
5116
+ const base = join11(dirname5(file3), `${basename2(file3, ".log")}-${stampOf(when)}`);
4766
5117
  let name = `${base}.log`;
4767
- for (let n = 2; existsSync11(name); n++) name = `${base}-${n}.log`;
5118
+ for (let n = 2; existsSync12(name); n++) name = `${base}-${n}.log`;
4768
5119
  return name;
4769
5120
  }
4770
5121
  function rotateIfLarge(file3, max = LOG_MAX_BYTES, keepDays = num("FH_LOG_KEEP_DAYS", 7)) {
4771
5122
  let size = 0;
4772
5123
  try {
4773
- size = statSync2(file3).size;
5124
+ size = statSync3(file3).size;
4774
5125
  } catch {
4775
5126
  return false;
4776
5127
  }
@@ -4788,20 +5139,20 @@ function pruneLogs(file3, keepDays, now2 = Date.now()) {
4788
5139
  const dir = dirname5(file3), stem2 = basename2(file3, ".log");
4789
5140
  try {
4790
5141
  const old1 = `${file3}.1`;
4791
- if (existsSync11(old1)) renameSync4(old1, datedName(file3, statSync2(old1).mtime));
5142
+ if (existsSync12(old1)) renameSync4(old1, datedName(file3, statSync3(old1).mtime));
4792
5143
  for (const f of readdirSync3(dir)) {
4793
5144
  if (!f.startsWith(`${stem2}-`) || !f.endsWith(".log")) continue;
4794
- const path = join10(dir, f);
4795
- if (now2 - statSync2(path).mtimeMs > keepDays * DAY_MS) unlinkSync2(path);
5145
+ const path = join11(dir, f);
5146
+ if (now2 - statSync3(path).mtimeMs > keepDays * DAY_MS) unlinkSync2(path);
4796
5147
  }
4797
5148
  } catch {
4798
5149
  }
4799
5150
  }
4800
5151
  function migrateLogName(dir = FH_EVIDENCE_DIR) {
4801
- const logs = join10(dir, "logs");
5152
+ const logs = join11(dir, "logs");
4802
5153
  for (const [from, to] of [["evidence.log", "evidence.log"], ["evidence.log.1", "evidence.log.1"], ["library.log", "evidence.log"], ["library.log.1", "evidence.log.1"]]) {
4803
- const a = join10(dir, from), b = join10(logs, to);
4804
- if (existsSync11(a) && !existsSync11(b)) {
5154
+ const a = join11(dir, from), b = join11(logs, to);
5155
+ if (existsSync12(a) && !existsSync12(b)) {
4805
5156
  try {
4806
5157
  mkdirSync9(logs, { recursive: true });
4807
5158
  renameSync4(a, b);
@@ -4811,8 +5162,8 @@ function migrateLogName(dir = FH_EVIDENCE_DIR) {
4811
5162
  }
4812
5163
  }
4813
5164
  function log(tool, id, message) {
4814
- const clean2 = message.replace(/\x1b\[[0-9;]*m/g, "").replace(/\s*\n\s*/g, " | ").replace(/https:\/\//g, "");
4815
- const line = `${stamp()} ${HOST} ${tool} ${(id ?? "-").replace(/https:\/\//g, "")} ${clean2}
5165
+ const clean3 = message.replace(/\x1b\[[0-9;]*m/g, "").replace(/\s*\n\s*/g, " | ").replace(/https:\/\//g, "");
5166
+ const line = `${stamp()} ${HOST} ${tool} ${(id ?? "-").replace(/https:\/\//g, "")} ${clean3}
4816
5167
  `;
4817
5168
  try {
4818
5169
  mkdirSync9(LOG_DIR, { recursive: true });
@@ -4905,16 +5256,16 @@ function inclusionCounts(refs) {
4905
5256
  }
4906
5257
 
4907
5258
  // src/evmapdb.ts
4908
- import { existsSync as existsSync12, mkdirSync as mkdirSync10 } from "fs";
5259
+ import { existsSync as existsSync13, mkdirSync as mkdirSync10 } from "fs";
4909
5260
  import { createRequire as createRequire2 } from "module";
4910
- import { join as join11 } from "path";
4911
- var LAYOUT = 3;
5261
+ import { join as join12 } from "path";
5262
+ var LAYOUT = 7;
4912
5263
  var DB_DIR = "evmap";
4913
5264
  var DB_NAME = "evmap.db";
4914
5265
  var require2 = createRequire2(import.meta.url);
4915
5266
  var SCHEMA_SQL = `
4916
5267
  CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT);
4917
- CREATE TABLE IF NOT EXISTS queries (id INTEGER PRIMARY KEY, query TEXT UNIQUE NOT NULL, total INTEGER, kept INTEGER, error TEXT, searched TEXT);
5268
+ CREATE TABLE IF NOT EXISTS queries (id INTEGER PRIMARY KEY, query TEXT UNIQUE NOT NULL, total INTEGER, kept INTEGER, error TEXT, searched TEXT, round INTEGER, max_results INTEGER);
4918
5269
  CREATE TABLE IF NOT EXISTS query_hits (query_id INTEGER NOT NULL REFERENCES queries(id), pmid TEXT NOT NULL, rank INTEGER, PRIMARY KEY (query_id, pmid));
4919
5270
  CREATE INDEX IF NOT EXISTS query_hits_pmid ON query_hits (pmid);
4920
5271
  CREATE TABLE IF NOT EXISTS articles (
@@ -4922,6 +5273,9 @@ var SCHEMA_SQL = `
4922
5273
  found_by TEXT, added TEXT, queries INTEGER, reviews INTEGER, citations INTEGER,
4923
5274
  relevance TEXT, population TEXT, design TEXT, n INTEGER, outcome TEXT, finding TEXT, aspect TEXT, reason TEXT, error TEXT,
4924
5275
  score INTEGER, pick INTEGER);
5276
+ CREATE TABLE IF NOT EXISTS query_items (query TEXT PRIMARY KEY, kind TEXT NOT NULL, item TEXT NOT NULL);
5277
+ CREATE TABLE IF NOT EXISTS item_picks (kind TEXT NOT NULL, item TEXT NOT NULL, pmid TEXT NOT NULL, pick INTEGER NOT NULL, PRIMARY KEY (kind, item, pmid));
5278
+ CREATE TABLE IF NOT EXISTS item_articles (kind TEXT NOT NULL, item TEXT NOT NULL, pmid TEXT NOT NULL, PRIMARY KEY (kind, item, pmid));
4925
5279
  CREATE TABLE IF NOT EXISTS runs (id INTEGER PRIMARY KEY, started TEXT, finished TEXT, state TEXT, error TEXT, report TEXT);
4926
5280
  CREATE VIEW IF NOT EXISTS evidence_map AS
4927
5281
  SELECT pmid, title, first_author, year, journal, types, score, pick, found_by, added, queries, reviews, citations,
@@ -4930,15 +5284,20 @@ var SCHEMA_SQL = `
4930
5284
  `;
4931
5285
  function openDb(dir, readonly = false) {
4932
5286
  const { DatabaseSync } = require2("node:sqlite");
4933
- const file3 = join11(dir, DB_DIR, DB_NAME);
5287
+ const file3 = join12(dir, DB_DIR, DB_NAME);
4934
5288
  if (readonly) {
4935
- if (!existsSync12(file3)) return null;
5289
+ if (!existsSync13(file3)) return null;
4936
5290
  return new DatabaseSync(file3, { readOnly: true });
4937
5291
  }
4938
- mkdirSync10(join11(dir, DB_DIR), { recursive: true });
5292
+ mkdirSync10(join12(dir, DB_DIR), { recursive: true });
4939
5293
  const db = new DatabaseSync(file3);
4940
5294
  db.exec("PRAGMA journal_mode = WAL;");
4941
5295
  db.exec(SCHEMA_SQL);
5296
+ if (!db.prepare("PRAGMA table_info(queries)").all().some((c) => c.name === "round")) {
5297
+ db.exec("ALTER TABLE queries ADD COLUMN round INTEGER");
5298
+ db.exec("UPDATE queries SET round = 1");
5299
+ }
5300
+ if (!db.prepare("PRAGMA table_info(queries)").all().some((c) => c.name === "max_results")) db.exec("ALTER TABLE queries ADD COLUMN max_results INTEGER");
4942
5301
  db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES ('layout', ?)").run(String(LAYOUT));
4943
5302
  return db;
4944
5303
  }
@@ -4963,15 +5322,15 @@ function lastRun(db) {
4963
5322
 
4964
5323
  // src/rank.ts
4965
5324
  import Anthropic2 from "@anthropic-ai/sdk";
4966
- var rankCandidates = (env = process.env) => num("FH_EVMAP_RANK_CANDIDATES", 200, env, (n) => n >= 10 && n <= 1e3 && Number.isInteger(n));
4967
- var rankPicks = (env = process.env) => num("FH_EVMAP_RANK_PICKS", 50, env, (n) => n >= 5 && n <= 200 && Number.isInteger(n));
4968
- var RANK_MODELS = { anthropic: "claude-opus-5-5", openai: "gpt-5.5", google: "gemini-pro-latest" };
5325
+ var rankCandidates = (env = process.env) => num("FH_EVMAP_RANKING_CANDIDATES", 200, env, (n) => n >= 10 && n <= 1e3 && Number.isInteger(n));
5326
+ var rankDirect = (env = process.env) => num("FH_EVMAP_RANKING_DIRECT", 100, env, (n) => n >= 0 && n <= 1e3 && Number.isInteger(n));
5327
+ var rankPicks = (env = process.env) => num("FH_EVMAP_RANKING_PICKS", 100, env, (n) => n >= 5 && n <= 200 && Number.isInteger(n));
4969
5328
  var RANK_TIMEOUT_MS = 18e4;
4970
- function rankPrompt(topic, rows, picks) {
5329
+ var DEFAULT_RANKING = promptStep(builtinPrompt("ranking"), "map", "map");
5330
+ var RANK_SLOT = "{{candidates}}";
5331
+ function rankPrompt(topic, rows, picks, template = DEFAULT_RANKING) {
4971
5332
  const list5 = rows.map((x, i) => `${i + 1}. ${x.title ?? "(no title)"} (${x.year ?? "-"}; ${x.design || "-"}; n=${x.n ?? "-"}; ${x.relevance}; ${x.aspect}; ${x.signals})`).join("\n");
4972
- return `Below are ${rows.length} candidate articles on the topic "${topic}". Pick the ${picks} that matter most \u2014 the key trials and meta-analyses for each important question, including safety and the null results; only articles that study the topic's intervention itself. Answer with their numbers, most important first.
4973
-
4974
- ${list5}`;
5333
+ return template.split("{{topic}}").join(topic).split("{{count}}").join(String(rows.length)).split("{{picks}}").join(String(picks)).split(RANK_SLOT).join(list5);
4975
5334
  }
4976
5335
  var SCHEMA2 = { type: "object", properties: { picks: { type: "array", items: { type: "integer" } } }, required: ["picks"], additionalProperties: false };
4977
5336
  function parsePicks(text4, count) {
@@ -4986,8 +5345,8 @@ function parsePicks(text4, count) {
4986
5345
  }
4987
5346
  function rankFor(c, model, fetchImpl = fetch) {
4988
5347
  const at = where({ ...c, model });
4989
- return async (topic, rows, picks) => {
4990
- const prompt = rankPrompt(topic, rows, picks);
5348
+ return async (topic, rows, picks, template) => {
5349
+ const prompt = rankPrompt(topic, rows, picks, template);
4991
5350
  try {
4992
5351
  if (c.api === "anthropic") {
4993
5352
  const client = new Anthropic2({ apiKey: c.key, baseURL: c.url, maxRetries: 2, timeout: RANK_TIMEOUT_MS });
@@ -5009,101 +5368,137 @@ function rankFor(c, model, fetchImpl = fetch) {
5009
5368
  if (typeof content !== "string") throw new Error("no answer");
5010
5369
  return parsePicks(content, rows.length);
5011
5370
  } catch (e) {
5012
- throw new Error(describe2(e, at, { key: c.vars?.key ?? "FH_EVMAP_RANK_API_KEY", model: "FH_EVMAP_RANK_MODEL", url: c.vars?.url ?? "FH_EVMAP_RANK_URL" }));
5371
+ throw new Error(describe2(e, at, { key: c.vars?.key ?? "FH_EVMAP_RANKING_API_KEY", model: "FH_EVMAP_RANKING_MODEL", url: c.vars?.url ?? "FH_EVMAP_RANKING_URL" }));
5013
5372
  }
5014
5373
  };
5015
5374
  }
5016
- function rankConfig(env = process.env) {
5017
- const m = str("FH_EVMAP_RANK_MODEL", env);
5018
- if (/^(off|none|0|false)$/i.test(m)) return { ok: false, off: "FH_EVMAP_RANK_MODEL=off" };
5019
- const p = str("FH_EVMAP_RANK_PROVIDER", env).toLowerCase() || str("FH_EVMAP_SCREEN_PROVIDER", env).toLowerCase();
5020
- if (!p) return { ok: false, off: "no provider", problem: "the re-ranking has no provider (FH_EVMAP_RANK_PROVIDER, or FH_EVMAP_SCREEN_PROVIDER) \u2014 the map stays in score order" };
5021
- if (!(p in SCREEN_PROVIDERS)) return { ok: false, off: `unknown provider ${p}`, problem: `FH_EVMAP_RANK_PROVIDER=${p}, not one of ${Object.keys(SCREEN_PROVIDERS).join(", ")} \u2014 the map stays in score order` };
5022
- const same = (str("FH_EVMAP_SCREEN_PROVIDER", env).toLowerCase() || "") === p;
5375
+ function rankConfig(env = process.env, part = "RANKING") {
5376
+ const what = part === "RANKING" ? "ranking" : "discovery";
5377
+ const p = str(`FH_EVMAP_${part}_PROVIDER`, env).toLowerCase();
5378
+ if (!p) return { ok: false, problem: `FH_EVMAP_${part}_PROVIDER: not set \u2014 the ${what} model's provider (${Object.keys(SCREEN_PROVIDERS).join(", ")})` };
5379
+ if (!(p in SCREEN_PROVIDERS)) return { ok: false, problem: `FH_EVMAP_${part}_PROVIDER: ${p}, not one of ${Object.keys(SCREEN_PROVIDERS).join(", ")}` };
5380
+ const model = str(`FH_EVMAP_${part}_MODEL`, env);
5381
+ if (!model) return { ok: false, problem: `FH_EVMAP_${part}_MODEL: not set \u2014 the ${what} model for ${p}, a strong one` };
5382
+ const others = ["DISCOVERY", "SCREENING", "RANKING"].filter((o) => o !== part && str(`FH_EVMAP_${o}_PROVIDER`, env).toLowerCase() === p);
5023
5383
  const pick = (f) => {
5024
- for (const v of [`FH_EVMAP_RANK_${f}`, `FH_EVMAP_${p.toUpperCase()}_${f}`, ...same ? [`FH_EVMAP_SCREEN_${f}`] : []]) if (str(v, env)) return [str(v, env), v];
5025
- return ["", `FH_EVMAP_RANK_${f}`];
5384
+ for (const v of [`FH_EVMAP_${part}_${f}`, `FH_EVMAP_${p.toUpperCase()}_${f}`, ...others.map((o) => `FH_EVMAP_${o}_${f}`)]) if (str(v, env)) return [str(v, env), v];
5385
+ return ["", `FH_EVMAP_${part}_${f}`];
5026
5386
  };
5027
5387
  const [key2, keyVar] = pick("API_KEY");
5028
5388
  const [url, urlVar] = pick("URL");
5029
- if (!key2 && !url) return { ok: false, off: `no key for ${p}`, problem: `no key for the re-ranking's provider ${p} (FH_EVMAP_RANK_API_KEY or FH_EVMAP_${p.toUpperCase()}_API_KEY) \u2014 the map stays in score order` };
5389
+ if (!key2 && !url) return { ok: false, problem: `FH_EVMAP_${part}_API_KEY: no key for the ${what} model's provider ${p} (or FH_EVMAP_${p.toUpperCase()}_API_KEY, or another part's key for ${p})` };
5030
5390
  const P = SCREEN_PROVIDERS[p];
5031
- const config = { ok: true, provider: p, api: P.api, url: url.replace(/\/+$/, "") || P.url, model: "", key: key2, vars: { key: keyVar, model: "FH_EVMAP_RANK_MODEL", url: urlVar } };
5032
- const model = m || RANK_MODELS[p];
5033
- return model ? { ok: true, config: { ...config, model }, model } : { ok: false, off: `FH_EVMAP_RANK_MODEL needed for ${p}` };
5391
+ return { ok: true, config: { ok: true, provider: p, api: P.api, url: url.replace(/\/+$/, "") || P.url, model, key: key2, vars: { key: keyVar, model: `FH_EVMAP_${part}_MODEL`, url: urlVar } }, model };
5392
+ }
5393
+ async function askJson(c, model, prompt, schema, name, fetchImpl = fetch) {
5394
+ const at = where({ ...c, model });
5395
+ try {
5396
+ let text4;
5397
+ if (c.api === "anthropic") {
5398
+ const client = new Anthropic2({ apiKey: c.key, baseURL: c.url, maxRetries: 2, timeout: RANK_TIMEOUT_MS });
5399
+ const r = await client.messages.create({ model, max_tokens: 32e3, output_config: { format: { type: "json_schema", schema } }, messages: [{ role: "user", content: prompt }] });
5400
+ if (r.stop_reason === "refusal") throw new Error("refusal");
5401
+ if (r.stop_reason === "max_tokens") throw new Error("the answer was cut off at its maximum length");
5402
+ text4 = r.content.find((b) => b.type === "text")?.text;
5403
+ } else {
5404
+ const r = await fetchImpl(`${c.url}/chat/completions`, {
5405
+ method: "POST",
5406
+ headers: { "content-type": "application/json", ...c.key ? { authorization: `Bearer ${c.key}` } : {} },
5407
+ body: JSON.stringify({ model, messages: [{ role: "user", content: prompt }], response_format: { type: "json_schema", json_schema: { name, strict: true, schema } } }),
5408
+ signal: AbortSignal.timeout(RANK_TIMEOUT_MS)
5409
+ });
5410
+ if (!r.ok) throw new ScreenError(`HTTP ${r.status} ${(await r.text()).replace(/\s+/g, " ").slice(0, 2e3)}`, r.status);
5411
+ const body = await r.json();
5412
+ text4 = body?.choices?.[0]?.message?.content;
5413
+ }
5414
+ if (typeof text4 !== "string") throw new Error("no answer");
5415
+ try {
5416
+ return JSON.parse(text4);
5417
+ } catch {
5418
+ throw new Error(`the answer is not JSON: ${text4.slice(0, 80)}`);
5419
+ }
5420
+ } catch (e) {
5421
+ throw new Error(describe2(e, at, { key: c.vars?.key ?? "FH_EVMAP_DISCOVERY_API_KEY", model: "FH_EVMAP_DISCOVERY_MODEL", url: c.vars?.url ?? "FH_EVMAP_DISCOVERY_URL" }));
5422
+ }
5034
5423
  }
5035
5424
  function evmapModels(env = process.env) {
5036
5425
  const problems = [];
5037
5426
  const s = screenConfig(env);
5038
- if (!s.ok) problems.push(`evidence map screening: ${s.reason} \u2014 fh_create_evidence_map will refuse to run`);
5039
- const key2 = (p) => str(`FH_EVMAP_${p.toUpperCase()}_API_KEY`, env) || str("FH_EVMAP_SCREEN_API_KEY", env);
5427
+ if (!s.ok) problems.push(`evidence map screening: ${s.reason} \u2014 fh_evmap_create_map will refuse to run`);
5040
5428
  if (s.ok) {
5041
5429
  const k = s.key;
5042
- const looks = k.startsWith("sk-ant-") ? "anthropic" : k.startsWith("AIza") || k.startsWith("AQ.") ? "google" : k.startsWith("sk-") ? "openai" : null;
5043
- if (looks && looks !== s.provider) problems.push(`evidence map screening: the key for ${s.provider} looks like a ${looks} key (FH_EVMAP_${s.provider.toUpperCase()}_API_KEY or FH_EVMAP_SCREEN_API_KEY)`);
5044
- }
5045
- let ranking;
5046
- const r = rankConfig(env);
5047
- if (r.ok) ranking = { provider: r.config.provider, model: r.model, url: r.config.url };
5048
- else {
5049
- ranking = { off: r.off };
5050
- if (r.problem) problems.push(`evidence map ranking: ${r.problem}`);
5430
+ const looks = k.startsWith("sk-ant-") ? "anthropic" : k.startsWith("sk-or-") ? "openrouter" : k.startsWith("xai-") ? "xai" : k.startsWith("AIza") || k.startsWith("AQ.") ? "google" : k.startsWith("sk-") ? "openai" : null;
5431
+ if (looks && looks !== s.provider) problems.push(`evidence map screening: the key for ${s.provider} looks like a ${looks} key (FH_EVMAP_${s.provider.toUpperCase()}_API_KEY or FH_EVMAP_SCREENING_API_KEY)`);
5051
5432
  }
5052
- return { models: { screening: s.ok ? { provider: s.provider, model: s.model, url: s.url } : null, ranking }, problems };
5433
+ const part = (name) => {
5434
+ const r = rankConfig(env, name);
5435
+ if (r.ok) return { provider: r.config.provider, model: r.model, url: r.config.url };
5436
+ problems.push(`evidence map ${name.toLowerCase()}: ${r.problem}${name === "RANKING" ? " \u2014 fh_evmap_create_map will refuse to run" : ""}`);
5437
+ return null;
5438
+ };
5439
+ const discovery = part("DISCOVERY"), ranking = part("RANKING");
5440
+ const pd = activePrompt("discovery", env), ps = activePrompt("screening", env), pr = activePrompt("ranking", env);
5441
+ for (const x of [pd, ps, pr]) if (x.problem && !problems.some((p) => p.includes(x.problem))) problems.push(`evidence map prompts: ${x.problem} \u2014 fh_evmap_create_map will refuse to run`);
5442
+ return { models: { discovery, screening: s.ok ? { provider: s.provider, model: s.model, url: s.url } : null, ranking, prompts: { discovery: pd.source, screening: ps.source, ranking: pr.source } }, problems };
5053
5443
  }
5054
5444
 
5055
5445
  // src/evidencemap.ts
5056
5446
  var evidenceMapEnabled = (env = process.env) => /^(true|1|yes|on)$/i.test(env.FH_EVMAP_ENABLED?.trim() ?? "");
5057
- var maxQueries = (env = process.env) => num("FH_EVMAP_MAX_QUERIES", 15, env, (n) => n >= 1 && Number.isInteger(n));
5447
+ var PREFILL_PARALLEL = 4;
5448
+ var searchParallel = (env = process.env) => env.FH_NCBI_API_KEY?.trim() ? 10 : 2;
5449
+ var maxQueries = (env = process.env) => num("FH_EVMAP_MAX_QUERIES", 40, env, (n) => n >= 1 && Number.isInteger(n));
5058
5450
  var maxResultsPerQuery = (env = process.env) => num("FH_EVMAP_MAX_RESULTS_PER_QUERY", 500, env, (n) => n >= 1 && n <= 1e3 && Number.isInteger(n));
5059
5451
  var SLOTS = ["{{topic}}", "{{article}}"];
5060
- var SETTINGS = "FH_EVMAP_SCREEN_PROVIDER, FH_EVMAP_SCREEN_API_KEY, FH_EVMAP_SCREEN_MODEL, FH_EVMAP_SCREEN_URL";
5452
+ var SETTINGS = "FH_EVMAP_SCREENING_PROVIDER, FH_EVMAP_SCREENING_API_KEY, FH_EVMAP_SCREENING_MODEL, FH_EVMAP_SCREENING_URL";
5061
5453
  var live4 = (lib) => ({
5062
5454
  search: async (query2, max) => {
5063
- if (max > 200) return bigSearch(lib, query2, max);
5064
- const r = await searchArticles({ query: query2, max_results: max }, lib, void 0, max);
5065
- return r.ok ? { ok: true, total: r.result.total, rows: r.result.rows } : { ok: false, error: r.error };
5455
+ return bigSearch(lib, query2, max);
5066
5456
  },
5067
- prefill: async (pmids) => (await fetchArticles(pmids, lib)).rows.map((r) => ({ pmid: r[0], retracted: r[5], level: r[6], title: r[1], first_author: r[2], year: r[3], types: r[4] })),
5457
+ prefill: async (pmids) => (await fetchArticles(pmids, lib)).rows.map((r) => ({ pmid: r[0], retracted: r[5], level: r[6], title: r[1], first_author: r[2], year: r[3], journal: journalOf(lib, r[0]), types: r[4] })),
5068
5458
  screener: (() => {
5069
5459
  const c = screenConfig();
5070
5460
  return c.ok ? { ok: true, ask: askFor(c), model: c.model, where: where(c) } : { ok: false, reason: c.reason };
5071
5461
  })(),
5072
5462
  paper: (pmid) => {
5073
5463
  const f = entryPaths(lib, "pmid", pmid).md;
5074
- return existsSync13(f) ? readFileSync9(f, "utf8") : null;
5464
+ return existsSync14(f) ? readFileSync10(f, "utf8") : null;
5075
5465
  },
5076
5466
  cites: (pmids) => citationCounts(pmids),
5077
5467
  refs: (reviews) => referencedPmids(reviews),
5078
- rank: (() => {
5468
+ ...(() => {
5079
5469
  const r = rankConfig();
5080
- return r.ok ? { rank: rankFor(r.config, r.model), model: r.model } : null;
5470
+ return r.ok ? { rank: { rank: rankFor(r.config, r.model), model: r.model } } : { rank: null, rankProblem: r.problem };
5081
5471
  })(),
5082
5472
  log: (id, message) => log("evmap", id, message)
5083
5473
  });
5474
+ var unesc = (t) => t.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&amp;/g, "&");
5475
+ function journalOf(lib, pmid) {
5476
+ try {
5477
+ const xml = readFileSync10(entryPaths(lib, "pmid", pmid).xml, "utf8");
5478
+ const m = /<ISOAbbreviation>([^<]+)<\/ISOAbbreviation>/.exec(xml) ?? /<MedlineTA>([^<]+)<\/MedlineTA>/.exec(xml) ?? /<Journal>[\s\S]*?<Title>([^<]+)<\/Title>/.exec(xml);
5479
+ return m ? unesc(m[1]).trim() || null : null;
5480
+ } catch {
5481
+ return null;
5482
+ }
5483
+ }
5084
5484
  async function bigSearch(lib, query2, max) {
5085
5485
  const q = normalizeQuery2({ query: query2, max_results: max }, max);
5086
5486
  if ("error" in q) return { ok: false, error: q.error };
5087
5487
  const file3 = searchFile(lib, searchKey2(q));
5088
- if (existsSync13(file3)) {
5488
+ if (existsSync14(file3)) {
5089
5489
  try {
5090
- const r = JSON.parse(readFileSync9(file3, "utf8"));
5091
- if (daysSince(r.searched) < searchCacheDays()) return { ok: true, total: r.total, rows: r.rows };
5490
+ const r = JSON.parse(readFileSync10(file3, "utf8"));
5491
+ if (daysSince(r.searched) < searchCacheDays()) return { ok: true, total: r.total, rows: r.rows, cached: true };
5092
5492
  } catch {
5093
5493
  }
5094
5494
  }
5095
- const get5 = (url) => fetchText(url, { "User-Agent": "evidence-mcp", Accept: "application/json" });
5096
5495
  try {
5097
- const { total, ids } = parseEsearch(await get5(esearchUrl(q)));
5098
- const rows = [];
5099
- for (let i = 0; i < ids.length; i += 200) {
5100
- const chunk = ids.slice(i, i + 200);
5101
- rows.push(...parseEsummary(await get5(esummaryUrl(chunk)), chunk, lib));
5102
- }
5103
- const result = { source: "pubmed", query: q, total, columns: ["pmid", "title", "first_author", "year", "journal", "publication_types", "pmcid", "level"], rows, searched: today() };
5496
+ const { total, ids } = parseEsearch(await fetchText(esearchUrl(q), { "User-Agent": "evidence-mcp", Accept: "application/json" }));
5497
+ const rows = ids.map((id) => [id]);
5498
+ const result = { source: "pubmed", query: q, total, columns: ["pmid"], rows, searched: today() };
5104
5499
  try {
5105
5500
  mkdirSync11(dirname6(file3), { recursive: true });
5106
- writeAtomic(file3, JSON.stringify(result, null, 2) + "\n");
5501
+ writeAtomic(file3, JSON.stringify(result) + "\n");
5107
5502
  } catch {
5108
5503
  }
5109
5504
  return { ok: true, total, rows };
@@ -5118,36 +5513,63 @@ function csvCell(v) {
5118
5513
  var reviewCount = (env = process.env) => num("FH_EVMAP_CITATION_REVIEWS", 10, env, (n) => n >= 0 && n <= 50 && Number.isInteger(n));
5119
5514
  var maxFromReviews = (env = process.env) => num("FH_EVMAP_CITATION_MAX_ADDED", 300, env, (n) => n >= 0 && n <= 2e3 && Number.isInteger(n));
5120
5515
  var REVIEW = /meta-analy|systematic review/i;
5121
- async function doResearch(lib, evid, queries, screeningArg, env = process.env, now2 = /* @__PURE__ */ new Date(), deps = live4(lib)) {
5516
+ async function doResearch(lib, evid, queries, screeningArg, env = process.env, now2 = /* @__PURE__ */ new Date(), deps = live4(lib), rankingArg, limits) {
5122
5517
  const o = openEvid(lib, evid);
5123
5518
  if (!o.ok) return o;
5124
- const screening = screeningArg?.trim() ? screeningArg : DEFAULT_SCREENING;
5519
+ const ps = activePrompt("screening", env), pr = activePrompt("ranking", env);
5520
+ for (const x of [...screeningArg?.trim() ? [] : [ps], ...rankingArg?.trim() ? [] : [pr]]) if (x.problem) return { ok: false, failed: true, error: `prompts: ${x.problem}. Nothing ran. It is set in the server's .env by whoever runs the server.` };
5521
+ const screening = screeningArg?.trim() ? screeningArg : ps.text;
5125
5522
  const missing = SLOTS.filter((p) => !screening.includes(p));
5126
- if (missing.length) return { ok: false, error: `screening: the prompt needs ${missing.join(" and ")} (sample: prompts/screening.md)` };
5523
+ if (missing.length) return { ok: false, error: `screening: the prompt needs ${missing.join(" and ")} (sample: evmap/screening.md)` };
5524
+ const ranking = rankingArg?.trim() ? rankingArg : promptStep(pr.text, "map", "map") ?? DEFAULT_RANKING;
5525
+ if (!ranking.includes(RANK_SLOT)) return { ok: false, error: `ranking: the prompt needs ${RANK_SLOT} (sample: evmap/ranking.md)` };
5127
5526
  const topic = o.metadata.topic;
5128
5527
  if (typeof topic !== "string" || !topic.trim()) return { ok: false, error: `${o.evid}: the metadata has no topic for {{topic}}` };
5129
5528
  const fresh = [...new Set(queries.map((q) => q.trim()).filter(Boolean))];
5130
5529
  if (!fresh.length) return { ok: false, error: "queries: at least one PubMed query" };
5131
- const max = maxQueries(env);
5132
- if (fresh.length > max) return { ok: false, error: `queries: ${fresh.length}, at most ${max} per call (FH_EVMAP_MAX_QUERIES); nothing ran` };
5133
5530
  const db = openDb(o.dir);
5134
5531
  const stored = storedQueries(db);
5135
- const qs = [...stored, ...fresh.filter((q) => !stored.includes(q))];
5532
+ const ownMax = new Map(db.prepare("SELECT query, max_results FROM queries WHERE max_results IS NOT NULL").all().map((x) => [x.query, x.max_results]));
5533
+ for (const [q, n2] of Object.entries(limits ?? {})) ownMax.set(q.replace(/\s+/g, " ").trim(), n2);
5534
+ const added = fresh.filter((q) => !stored.includes(q));
5535
+ const alreadyRun = fresh.length - added.length;
5536
+ const max = maxQueries(env);
5537
+ if (added.length > max) {
5538
+ db.close();
5539
+ return { ok: false, error: `queries: ${added.length} new, at most ${max} per call (FH_EVMAP_MAX_QUERIES); nothing ran` };
5540
+ }
5541
+ const qs = [...stored, ...added];
5542
+ const round = db.prepare("SELECT COUNT(*) AS c FROM runs WHERE state != 'failed'").get().c + 1;
5136
5543
  const screener = deps.screener;
5137
5544
  if (!screener.ok) return { ok: false, failed: true, error: `screening model: ${screener.reason}. Nothing ran. It is set in the server's .env (${SETTINGS}) by whoever runs the server; calling again will not help until then.` };
5545
+ if (deps.rankProblem) return { ok: false, failed: true, error: `ranking model: ${deps.rankProblem}. Nothing ran. It is set in the server's .env by whoever runs the server; calling again will not help until then.` };
5138
5546
  const perQuery = maxResultsPerQuery(env);
5139
5547
  const started = now2.toISOString();
5548
+ const found = new Array(qs.length);
5549
+ const tS = Date.now();
5550
+ deps.log(o.evid, `round ${round}, ${added.length} new queries${stored.length ? `, ${stored.length} from earlier rounds` : ""}${alreadyRun ? `, ${alreadyRun} sent again` : ""}`);
5551
+ deps.log(o.evid, `searching ${qs.length} queries, ${added.length} new, ${stored.length} from earlier calls`);
5552
+ let nextQ = 0;
5553
+ await Promise.all(Array.from({ length: Math.min(searchParallel(env), qs.length) }, async () => {
5554
+ while (nextQ < qs.length) {
5555
+ const k = nextQ++;
5556
+ const tq = Date.now();
5557
+ const r = found[k] = await deps.search(qs[k], ownMax.get(qs[k]) ?? perQuery);
5558
+ const secs = `${((Date.now() - tq) / 1e3).toFixed(1).padStart(4, "0")}s`;
5559
+ deps.log(o.evid, r.ok ? `query ${r.cached ? "cached" : secs} ${k + 1}/${qs.length}, ${r.total} hits, ${r.rows.length} used \xB7 ${qs[k]}` : `query failed ${secs} ${k + 1}/${qs.length} \xB7 ${r.error} \xB7 ${qs[k]}`);
5560
+ }
5561
+ }));
5140
5562
  const papers = /* @__PURE__ */ new Map();
5141
5563
  const runs = [];
5564
+ let cachedCount = 0;
5142
5565
  for (const [i, query2] of qs.entries()) {
5143
- const r = await deps.search(query2, perQuery);
5566
+ const r = found[i];
5144
5567
  if (!r.ok) {
5145
5568
  runs.push({ query: query2, total: null, kept: 0, error: r.error });
5146
- deps.log(o.evid, `failed query ${i + 1}/${qs.length}: ${r.error} \xB7 ${query2}`);
5147
5569
  continue;
5148
5570
  }
5571
+ if (r.cached) cachedCount++;
5149
5572
  runs.push({ query: query2, total: r.total, kept: r.rows.length, hits: r.rows.map((row4) => String(row4[0])) });
5150
- deps.log(o.evid, `query ${i + 1}/${qs.length} total=${r.total} kept=${r.rows.length} \xB7 ${query2}`);
5151
5573
  for (const row4 of r.rows) {
5152
5574
  const pmid = String(row4[0]);
5153
5575
  const p = papers.get(pmid);
@@ -5155,28 +5577,50 @@ async function doResearch(lib, evid, queries, screeningArg, env = process.env, n
5155
5577
  if (!p.queries.includes(i)) p.queries.push(i);
5156
5578
  continue;
5157
5579
  }
5158
- papers.set(pmid, { pmid, title: row4[1], first_author: row4[2], year: row4[3], journal: row4[4], types: row4[5], queries: [i] });
5580
+ papers.set(pmid, { pmid, title: row4[1] ?? null, first_author: row4[2] ?? null, year: row4[3] ?? null, journal: row4[4] ?? null, types: row4[5] ?? null, queries: [i] });
5159
5581
  }
5160
5582
  }
5583
+ deps.log(o.evid, `searched ${((Date.now() - tS) / 1e3).toFixed(1).padStart(4, "0")}s ${added.length} new, ${cachedCount} cached`);
5161
5584
  if (runs.every((r) => r.error)) return { ok: false, failed: true, error: `pubmed: every query failed (${runs[0].error}). Nothing was stored; try again later, or check the queries' syntax with fh_pubmed_search_articles.` };
5162
5585
  const storedArticles = db.prepare("SELECT pmid, title, first_author, year, journal, types, found_by, reviews FROM articles").all();
5163
5586
  for (const a of storedArticles) if (!papers.has(a.pmid)) papers.set(a.pmid, { pmid: a.pmid, title: a.title, first_author: a.first_author, year: a.year ? String(a.year) : null, journal: a.journal, types: a.types, queries: [], ...a.found_by === "references" && a.reviews ? { reviews: a.reviews } : {} });
5164
5587
  const ids = [...papers.keys()];
5165
5588
  const retracted = /* @__PURE__ */ new Set();
5166
5589
  let notFound = 0;
5167
- for (let k = 0; k < ids.length; k += MAX_PMIDS) {
5168
- for (const r of await deps.prefill(ids.slice(k, k + MAX_PMIDS))) {
5169
- if (r.retracted) retracted.add(r.pmid);
5170
- if (r.level === "not found") notFound++;
5590
+ const batches = [];
5591
+ for (let k = 0; k < ids.length; k += MAX_PMIDS) batches.push(ids.slice(k, k + MAX_PMIDS));
5592
+ deps.log(o.evid, `fetching abstracts for ${ids.length} papers`);
5593
+ const tP = Date.now();
5594
+ let nextB = 0, doneP = 0, lastP = Date.now();
5595
+ await Promise.all(Array.from({ length: Math.min(PREFILL_PARALLEL, batches.length) }, async () => {
5596
+ while (nextB < batches.length) {
5597
+ const b = batches[nextB++];
5598
+ for (const r of await deps.prefill(b)) {
5599
+ if (r.retracted) retracted.add(r.pmid);
5600
+ if (r.level === "not found") notFound++;
5601
+ const p = papers.get(r.pmid);
5602
+ if (p) {
5603
+ p.title ??= r.title ?? null;
5604
+ p.first_author ??= r.first_author ?? null;
5605
+ p.year ??= r.year ?? null;
5606
+ p.journal ??= r.journal ?? null;
5607
+ p.types ??= r.types ?? null;
5608
+ }
5609
+ }
5610
+ doneP += b.length;
5611
+ if (doneP < ids.length && Date.now() - lastP >= 5e3) {
5612
+ lastP = Date.now();
5613
+ deps.log(o.evid, `fetching abstracts, ${doneP} of ${ids.length} done`);
5614
+ }
5171
5615
  }
5172
- }
5616
+ }));
5173
5617
  const kept = ids.filter((id) => !retracted.has(id)).map((id) => papers.get(id));
5174
- deps.log(o.evid, `prefilled found=${ids.length} retracted=${retracted.size} not_found=${notFound} papers=${kept.length}`);
5618
+ deps.log(o.evid, `prefilled ${((Date.now() - tP) / 1e3).toFixed(1).padStart(4, "0")}s ${kept.length} papers, ${ids.length} found, ${retracted.size} retracted, ${notFound} not found`);
5175
5619
  const unique = (i) => kept.filter((p) => p.queries.length === 1 && p.queries[0] === i).length;
5176
5620
  const n = qs.length;
5177
5621
  const row3 = (p, sc, pick2, sig, f) => [p.pmid, p.title, p.first_author, p.year, p.journal, p.types, sc, pick2, sig, ...FIELDS2.map((k) => f?.[k] ?? "")].map(csvCell).join(",");
5178
5622
  const citesP = deps.cites(kept.map((p) => p.pmid)).then((c) => {
5179
- deps.log(o.evid, `citations counted=${c.counts.size} failed=${c.failed}${c.error ? ` \xB7 ${c.error}` : ""}`);
5623
+ deps.log(o.evid, `citations${c.failed ? " failed" : ""} ${c.counts.size} counted, ${c.failed} failed${c.error ? ` \xB7 ${c.error}` : ""}`);
5180
5624
  return c;
5181
5625
  }, (e) => ({ counts: /* @__PURE__ */ new Map(), failed: kept.length, error: String(e) }));
5182
5626
  let cites = /* @__PURE__ */ new Map();
@@ -5194,6 +5638,26 @@ async function doResearch(lib, evid, queries, screeningArg, env = process.env, n
5194
5638
  Publication types: ${papers.get(pmid).types ?? "none listed"}`;
5195
5639
  };
5196
5640
  const note = (r, ms) => deps.log(`pmid:${r.pmid}`, screenLine(r, ms, model));
5641
+ const progress = (what, total) => {
5642
+ let n2 = 0, fresh2 = 0, cached = 0, failed = 0, refused2 = 0, last = Date.now();
5643
+ const t0 = last;
5644
+ const counts = () => `${fresh2} new, ${cached} cached${failed ? `, ${failed} failed` : ""}${refused2 ? `, ${refused2} refused` : ""}`;
5645
+ deps.log(o.evid, `screening ${total} ${what}`);
5646
+ return {
5647
+ done: (r) => {
5648
+ n2++;
5649
+ if (r.refused) refused2++;
5650
+ else if (r.error) failed++;
5651
+ else if (r.cached) cached++;
5652
+ else fresh2++;
5653
+ if (n2 < total && Date.now() - last >= 5e3) {
5654
+ last = Date.now();
5655
+ deps.log(o.evid, `screening ${n2}/${total}, ${counts()}`);
5656
+ }
5657
+ },
5658
+ end: () => deps.log(o.evid, `screened ${((Date.now() - t0) / 1e3).toFixed(1).padStart(4, "0")}s ${total} ${what}, ${counts()}`)
5659
+ };
5660
+ };
5197
5661
  const order2 = kept.map((p) => p.pmid);
5198
5662
  const probe2 = order2.find((pmid) => deps.paper(pmid) !== null);
5199
5663
  const results2 = probe2 ? await screenAll(lib, [probe2], screening, topic, text4, screener.ask, model, 1, note) : [];
@@ -5203,7 +5667,9 @@ Publication types: ${papers.get(pmid).types ?? "none listed"}`;
5203
5667
  db.close();
5204
5668
  return { ok: false, failed: true, error: `screening failed on the first paper (pmid:${probe2}): ${error}. The searches ran: ${kept.length} papers found and stored in the library with their abstracts; nothing was screened, no map yet. Call again once the cause is fixed (the searches answer from the cache).` };
5205
5669
  }
5206
- results2.push(...await screenAll(lib, order2.filter((pmid) => pmid !== probe2), screening, topic, text4, screener.ask, model, screenParallel(env), note));
5670
+ const rest = order2.filter((pmid) => pmid !== probe2), p1 = progress("abstracts", rest.length);
5671
+ results2.push(...await screenAll(lib, rest, screening, topic, text4, screener.ask, model, screenParallel(env), note, p1.done));
5672
+ p1.end();
5207
5673
  const by = new Map(results2.map((r) => [r.pmid, r]));
5208
5674
  const counted = await citesP;
5209
5675
  cites = counted.counts;
@@ -5225,7 +5691,7 @@ Publication types: ${papers.get(pmid).types ?? "none listed"}`;
5225
5691
  for (let k = 0; k < fresh2.length; k += MAX_PMIDS) {
5226
5692
  for (const x of await deps.prefill(fresh2.slice(k, k + MAX_PMIDS))) {
5227
5693
  if (x.retracted || x.level === "not found" || papers.has(x.pmid)) continue;
5228
- const p = { pmid: x.pmid, title: x.title ?? null, first_author: x.first_author ?? null, year: x.year ?? null, journal: null, types: x.types ?? null, queries: [] };
5694
+ const p = { pmid: x.pmid, title: x.title ?? null, first_author: x.first_author ?? null, year: x.year ?? null, journal: x.journal ?? null, types: x.types ?? null, queries: [] };
5229
5695
  papers.set(x.pmid, p);
5230
5696
  kept.push(p);
5231
5697
  fromReviews++;
@@ -5235,12 +5701,14 @@ Publication types: ${papers.get(pmid).types ?? "none listed"}`;
5235
5701
  const c = inc.get(p.pmid);
5236
5702
  if (c) p.reviews = c;
5237
5703
  }
5238
- const added = kept.slice(kept.length - fromReviews).map((p) => p.pmid);
5239
- deps.log(o.evid, `references reviews=${K} failed=${refsFailed} new=${fromReviews}`);
5240
- if (added.length) {
5241
- results2.push(...await screenAll(lib, added, screening, topic, text4, screener.ask, model, screenParallel(env), note));
5704
+ const added2 = kept.slice(kept.length - fromReviews).map((p) => p.pmid);
5705
+ deps.log(o.evid, `references${refsFailed ? " failed" : ""} ${K} reviews, ${refsFailed} failed, ${fromReviews} new papers`);
5706
+ if (added2.length) {
5707
+ const p2 = progress("abstracts from the reviews' references", added2.length);
5708
+ results2.push(...await screenAll(lib, added2, screening, topic, text4, screener.ask, model, screenParallel(env), note, p2.done));
5709
+ p2.end();
5242
5710
  for (const r2 of results2) by.set(r2.pmid, r2);
5243
- const more = await deps.cites(added).catch(() => ({ counts: /* @__PURE__ */ new Map(), failed: added.length }));
5711
+ const more = await deps.cites(added2).catch(() => ({ counts: /* @__PURE__ */ new Map(), failed: added2.length }));
5244
5712
  for (const [k2, v] of more.counts) cites.set(k2, v);
5245
5713
  }
5246
5714
  scored = kept.map(scoreOf);
@@ -5251,17 +5719,20 @@ Publication types: ${papers.get(pmid).types ?? "none listed"}`;
5251
5719
  let rankRun = { off: true };
5252
5720
  if (deps.rank) {
5253
5721
  const t2 = Date.now();
5254
- const top = ranked.filter(({ sc }) => sc !== null).slice(0, rankCandidates(env));
5722
+ const scoredRows = ranked.filter(({ sc }) => sc !== null);
5723
+ const best = scoredRows.slice(0, rankCandidates(env));
5724
+ const extra = scoredRows.slice(best.length).filter(({ f }) => f?.relevance === "direct").slice(0, rankDirect(env));
5725
+ const top = [...best, ...extra];
5255
5726
  try {
5256
- const idx = await deps.rank.rank(topic, top.map(({ p, f }) => ({ title: p.title, year: p.year, design: f?.design ?? "", n: f?.n ?? null, relevance: f?.relevance ?? "", aspect: f?.aspect ?? "", signals: signals(p) })), rankPicks(env));
5727
+ const idx = await deps.rank.rank(topic, top.map(({ p, f }) => ({ title: p.title, year: p.year, design: f?.design ?? "", n: f?.n ?? null, relevance: f?.relevance ?? "", aspect: f?.aspect ?? "", signals: signals(p) })), rankPicks(env), ranking);
5257
5728
  idx.slice(0, rankPicks(env)).forEach((i, k) => pick.set(top[i].p.pmid, k + 1));
5258
5729
  ranked = [...ranked.filter(({ p }) => pick.has(p.pmid)).sort((a, b) => pick.get(a.p.pmid) - pick.get(b.p.pmid)), ...ranked.filter(({ p }) => !pick.has(p.pmid))];
5259
5730
  rankRun = { model: deps.rank.model, candidates: top.length, picks: pick.size, seconds: Math.round((Date.now() - t2) / 1e3) };
5260
- deps.log(o.evid, `ranked ${deps.rank.model} candidates=${top.length} picks=${pick.size} ${((Date.now() - t2) / 1e3).toFixed(1)}s`);
5731
+ deps.log(o.evid, `ranked ${((Date.now() - t2) / 1e3).toFixed(1).padStart(4, "0")}s ${top.length} candidates, ${pick.size} picks \xB7 ${deps.rank.model}`);
5261
5732
  } catch (e) {
5262
5733
  const error = e instanceof Error ? e.message : String(e);
5263
5734
  rankRun = { model: deps.rank.model, error };
5264
- deps.log(o.evid, `failed rank: ${error} \u2014 the map keeps the score order`);
5735
+ deps.log(o.evid, `ranked failed \xB7 ${error} \u2014 the map keeps the score order`);
5265
5736
  }
5266
5737
  }
5267
5738
  const lines = ranked.map(({ p, f, sc }) => row3(p, sc ?? "", pick.get(p.pmid) ?? "", signals(p), f));
@@ -5275,11 +5746,11 @@ Publication types: ${papers.get(pmid).types ?? "none listed"}`;
5275
5746
  db.exec("BEGIN");
5276
5747
  try {
5277
5748
  if (metaOf(db, "hash") !== hash) db.exec("UPDATE articles SET relevance = NULL, population = NULL, design = NULL, n = NULL, outcome = NULL, finding = NULL, aspect = NULL, reason = NULL, error = NULL, score = NULL, pick = NULL");
5278
- const qUp = db.prepare("INSERT INTO queries (query, total, kept, error, searched) VALUES (?, ?, ?, ?, ?) ON CONFLICT(query) DO UPDATE SET total = excluded.total, kept = excluded.kept, error = excluded.error, searched = excluded.searched RETURNING id");
5749
+ const qUp = db.prepare("INSERT INTO queries (query, total, kept, error, searched, round, max_results) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(query) DO UPDATE SET total = excluded.total, kept = excluded.kept, error = excluded.error, searched = excluded.searched, max_results = excluded.max_results RETURNING id");
5279
5750
  const hDel = db.prepare("DELETE FROM query_hits WHERE query_id = ?");
5280
5751
  const hIns = db.prepare("INSERT OR IGNORE INTO query_hits (query_id, pmid, rank) VALUES (?, ?, ?)");
5281
5752
  for (const r of runs) {
5282
- const id = qUp.get(r.query, r.total, r.kept, r.error ?? null, started).id;
5753
+ const id = qUp.get(r.query, r.total, r.kept, r.error ?? null, started, round, ownMax.get(r.query) ?? null).id;
5283
5754
  if (r.hits) {
5284
5755
  hDel.run(id);
5285
5756
  r.hits.forEach((pmid, k) => hIns.run(id, pmid, k + 1));
@@ -5302,6 +5773,7 @@ Publication types: ${papers.get(pmid).types ?? "none listed"}`;
5302
5773
  meta.run("hash", hash);
5303
5774
  meta.run("model", model);
5304
5775
  meta.run("prompt", screening);
5776
+ meta.run("ranking", ranking);
5305
5777
  meta.run("topic", topic);
5306
5778
  meta.run("updated", finished);
5307
5779
  db.prepare("INSERT INTO runs (started, finished, state, error, report) VALUES (?, ?, ?, NULL, ?)").run(started, finished, state, JSON.stringify({ ...base, queries: qs.length, new_queries: qs.length - stored.length, ...screenRun, included: lines.length }));
@@ -5317,16 +5789,16 @@ Publication types: ${papers.get(pmid).types ?? "none listed"}`;
5317
5789
  const citesFailed = counted.failed || refsFailed ? { citations_error: `citation counts failed for ${counted.failed} of ${kept.length} articles, reference lists for ${refsFailed} of ${reviewIds.length} reviews${counted.error ? ` (${counted.error})` : ""}: the order is weaker. Call again later with the evid and the same queries: searches and screening answer from the cache.` } : {};
5318
5790
  const failedQueries = runs.filter((r) => r.error).map((r) => ({ query: r.query, error: r.error }));
5319
5791
  const emptyQueries = runs.filter((r) => !r.error && r.total === 0).map((r) => r.query);
5320
- return { ok: true, evid: o.evid, included: lines.length, ...failedQueries.length ? { failed_queries: failedQueries } : {}, ...emptyQueries.length ? { empty_queries: emptyQueries } : {}, ...partial, ...rankFailed, ...citesFailed };
5792
+ return { ok: true, evid: o.evid, included: lines.length, ...failedQueries.length ? { failed_queries: failedQueries } : {}, ...emptyQueries.length ? { empty_queries: emptyQueries } : {}, ...partial, ...rankFailed, ...citesFailed, ...alreadyRun ? { already_run: alreadyRun } : {} };
5321
5793
  }
5322
5794
  var MAX_ROWS = 500;
5323
5795
  function getMap(lib, evid, opts = {}) {
5324
5796
  const o = openEvid(lib, evid);
5325
5797
  if (!o.ok) return o;
5326
5798
  const db = openDb(o.dir, true);
5327
- if (!db) return { ok: false, error: `${o.evid}: no evidence map yet \u2014 fh_create_evidence_map first` };
5799
+ if (!db) return { ok: false, error: `${o.evid}: no evidence map yet \u2014 fh_evmap_create_map first` };
5328
5800
  try {
5329
- if (!db.prepare("SELECT value FROM meta WHERE key = 'updated'").get()) return { ok: false, error: `${o.evid}: no evidence map yet \u2014 the last fh_create_evidence_map did not finish: ${lastRun(db)?.error ?? "no run recorded"}` };
5801
+ if (!db.prepare("SELECT value FROM meta WHERE key = 'updated'").get()) return { ok: false, error: `${o.evid}: no evidence map yet \u2014 the last fh_evmap_create_map did not finish: ${lastRun(db)?.error ?? "no run recorded"}` };
5330
5802
  const top = Math.min(MAX_ROWS, Math.max(1, Math.floor(opts.top ?? 50)));
5331
5803
  const rows = query(db, DEFAULT_SELECT, [], 0, top);
5332
5804
  return { ok: true, evid: o.evid, ...rows };
@@ -5334,18 +5806,41 @@ function getMap(lib, evid, opts = {}) {
5334
5806
  db.close();
5335
5807
  }
5336
5808
  }
5809
+ var QUERY_PERFORMANCE_SELECT = `
5810
+ WITH kept AS (SELECT pmid FROM articles WHERE relevance IS NOT NULL AND relevance != 'off-topic'),
5811
+ top AS (SELECT pmid FROM evidence_map ORDER BY pick IS NULL, pick, score DESC LIMIT 50),
5812
+ n AS (SELECT pmid, COUNT(*) AS c FROM query_hits GROUP BY pmid)
5813
+ SELECT q.round AS round, q.query AS query, q.total AS hits, q.kept AS used,
5814
+ COALESCE(SUM(h.pmid IN kept), 0) AS kept,
5815
+ COALESCE(SUM(h.pmid IN kept AND n.c = 1), 0) AS "unique",
5816
+ COALESCE(SUM(h.pmid IN top), 0) AS in_top_50
5817
+ FROM queries q LEFT JOIN query_hits h ON h.query_id = q.id LEFT JOIN n ON n.pmid = h.pmid
5818
+ GROUP BY q.id ORDER BY q.round, q.id`;
5819
+ function getQueryPerformance(lib, evid) {
5820
+ const o = openEvid(lib, evid);
5821
+ if (!o.ok) return o;
5822
+ const db = openDb(o.dir, true);
5823
+ if (!db) return { ok: false, error: `${o.evid}: no evidence map yet \u2014 fh_evmap_create_map first` };
5824
+ try {
5825
+ if (!db.prepare("SELECT value FROM meta WHERE key = 'updated'").get()) return { ok: false, error: `${o.evid}: no evidence map yet \u2014 the last fh_evmap_create_map did not finish: ${lastRun(db)?.error ?? "no run recorded"}` };
5826
+ const hasRound = db.prepare("PRAGMA table_info(queries)").all().some((c) => c.name === "round");
5827
+ return { ok: true, evid: o.evid, ...query(db, hasRound ? QUERY_PERFORMANCE_SELECT : QUERY_PERFORMANCE_SELECT.replace("q.round AS round", "1 AS round").replace("ORDER BY q.round, q.id", "ORDER BY q.id"), [], 0, 1e4) };
5828
+ } finally {
5829
+ db.close();
5830
+ }
5831
+ }
5337
5832
 
5338
5833
  // src/stats.ts
5339
- import { mkdirSync as mkdirSync12, readdirSync as readdirSync4, readFileSync as readFileSync10, statSync as statSync3, unlinkSync as unlinkSync3 } from "fs";
5340
- import { join as join12 } from "path";
5834
+ import { mkdirSync as mkdirSync12, readdirSync as readdirSync4, readFileSync as readFileSync11, statSync as statSync4, unlinkSync as unlinkSync3 } from "fs";
5835
+ import { join as join13 } from "path";
5341
5836
  var HEARTBEAT_MS = 5 * 6e4;
5342
5837
  var STALE_MS = 20 * 6e4;
5343
5838
  var stats = null;
5344
5839
  var file2 = null;
5345
5840
  function startStats(pkg2, libraryDir = FH_EVIDENCE_DIR) {
5346
5841
  stats = { host: HOST, pid: process.pid, package: pkg2.name, version: pkg2.version, started: (/* @__PURE__ */ new Date()).toISOString(), verify: { hits: 0, misses: 0 }, fetch: { hits: 0, misses: 0 }, search: { hits: 0, misses: 0 }, pubmed: { hits: 0, misses: 0 } };
5347
- file2 = join12(libraryDir, ".servers", `${HOST}-${process.pid}.json`);
5348
- sweep(join12(libraryDir, ".servers"));
5842
+ file2 = join13(libraryDir, ".servers", `${HOST}-${process.pid}.json`);
5843
+ sweep(join13(libraryDir, ".servers"));
5349
5844
  publish();
5350
5845
  setInterval(publish, HEARTBEAT_MS).unref();
5351
5846
  const stop = () => {
@@ -5368,9 +5863,9 @@ function sweep(dir, staleMs = STALE_MS) {
5368
5863
  }
5369
5864
  for (const name of names2) {
5370
5865
  if (!name.endsWith(".json")) continue;
5371
- const p = join12(dir, name);
5866
+ const p = join13(dir, name);
5372
5867
  try {
5373
- if (Date.now() - statSync3(p).mtimeMs > staleMs) {
5868
+ if (Date.now() - statSync4(p).mtimeMs > staleMs) {
5374
5869
  unlinkSync3(p);
5375
5870
  n++;
5376
5871
  }
@@ -5388,14 +5883,14 @@ var currentStats = () => stats;
5388
5883
  function publish() {
5389
5884
  if (!stats || !file2) return;
5390
5885
  try {
5391
- mkdirSync12(join12(file2, ".."), { recursive: true });
5886
+ mkdirSync12(join13(file2, ".."), { recursive: true });
5392
5887
  writeAtomic(file2, JSON.stringify(stats, null, 2) + "\n");
5393
5888
  } catch {
5394
5889
  }
5395
5890
  }
5396
5891
 
5397
5892
  // src/tools.ts
5398
- import { existsSync as existsSync21, readFileSync as readFileSync18 } from "fs";
5893
+ import { existsSync as existsSync24, readFileSync as readFileSync20 } from "fs";
5399
5894
  import { z } from "zod";
5400
5895
 
5401
5896
  // src/cascade.ts
@@ -5449,7 +5944,7 @@ async function fulltextCascade(p, attempts, onEvent, tiers = resolveTiers().tier
5449
5944
 
5450
5945
  // src/websearch.ts
5451
5946
  import { createHash as createHash6 } from "crypto";
5452
- import { existsSync as existsSync14, mkdirSync as mkdirSync13, readFileSync as readFileSync11 } from "fs";
5947
+ import { existsSync as existsSync15, mkdirSync as mkdirSync13, readFileSync as readFileSync12 } from "fs";
5453
5948
  import { dirname as dirname7 } from "path";
5454
5949
  var COLUMNS4 = ["title", "url", "published", "author", "snippet"];
5455
5950
  var snippetsOn = (env = process.env) => !/^(off|false|no|0)$/i.test((env.FH_WEB_SEARCH_SNIPPETS ?? "").trim());
@@ -5464,9 +5959,7 @@ function cleanSnippet(t) {
5464
5959
  return cut.slice(0, Math.max(cut.lastIndexOf(" "), SNIPPET_CHARS - 40)).replace(/[,;:\s]+$/, "") + " \u2026";
5465
5960
  }
5466
5961
  var SEARCH_PROVIDERS = ["exa", "serper", "brave"];
5467
- var webSearchEnabled = (env = process.env) => /^(true|1|yes|on)$/i.test(env.FH_WEB_SEARCH_ENABLED?.trim() ?? "");
5468
5962
  function webSearchConfig(env = process.env) {
5469
- if (!webSearchEnabled(env)) return [];
5470
5963
  return SEARCH_PROVIDERS.flatMap((provider) => {
5471
5964
  const key2 = env[`FH_WEB_SEARCH_${provider.toUpperCase()}_API_KEY`]?.trim();
5472
5965
  return key2 ? [{ provider, key: key2 }] : [];
@@ -5565,17 +6058,17 @@ var SEARCH = {
5565
6058
  var inFlight = /* @__PURE__ */ new Map();
5566
6059
  function oneProvider(q, cfg, libraryDir, post2, onEvent) {
5567
6060
  const file3 = searchFile(libraryDir, searchKey3(q, cfg.provider));
5568
- const running = inFlight.get(file3);
5569
- if (running) return running;
6061
+ const running2 = inFlight.get(file3);
6062
+ if (running2) return running2;
5570
6063
  const p = askProvider(q, cfg, libraryDir, post2, onEvent).finally(() => inFlight.delete(file3));
5571
6064
  inFlight.set(file3, p);
5572
6065
  return p;
5573
6066
  }
5574
6067
  async function askProvider(q, cfg, libraryDir, post2, onEvent) {
5575
6068
  const file3 = searchFile(libraryDir, searchKey3(q, cfg.provider));
5576
- if (existsSync14(file3)) {
6069
+ if (existsSync15(file3)) {
5577
6070
  try {
5578
- const r = JSON.parse(readFileSync11(file3, "utf8"));
6071
+ const r = JSON.parse(readFileSync12(file3, "utf8"));
5579
6072
  if (daysSince(r.searched) < searchCacheDays()) return { rows: r.rows, cached: true };
5580
6073
  } catch {
5581
6074
  }
@@ -5636,13 +6129,13 @@ async function webSearch(raw, libraryDir = FH_EVIDENCE_DIR, post2 = live5, cfgs
5636
6129
  }
5637
6130
 
5638
6131
  // src/info.ts
5639
- import { existsSync as existsSync15, readdirSync as readdirSync5, readFileSync as readFileSync12, statSync as statSync4 } from "fs";
5640
- import { dirname as dirname8, join as join13 } from "path";
6132
+ import { existsSync as existsSync16, readdirSync as readdirSync5, readFileSync as readFileSync13, statSync as statSync5 } from "fs";
6133
+ import { dirname as dirname8, join as join14 } from "path";
5641
6134
  function* metaFiles(dir) {
5642
- if (!existsSync15(dir)) return;
6135
+ if (!existsSync16(dir)) return;
5643
6136
  for (const name of readdirSync5(dir)) {
5644
- const p = join13(dir, name);
5645
- if (statSync4(p).isDirectory()) yield* metaFiles(p);
6137
+ const p = join14(dir, name);
6138
+ if (statSync5(p).isDirectory()) yield* metaFiles(p);
5646
6139
  else if (name.endsWith("-meta.md")) yield p;
5647
6140
  }
5648
6141
  }
@@ -5659,6 +6152,17 @@ function field(md, key2) {
5659
6152
  const m = new RegExp(`^${key2}:\\s*(.*)$`, "m").exec(md);
5660
6153
  return m ? m[1].trim() : "";
5661
6154
  }
6155
+ function evidCounts(lib) {
6156
+ const dirs = (p) => {
6157
+ try {
6158
+ return readdirSync5(p, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => join14(p, d.name));
6159
+ } catch {
6160
+ return [];
6161
+ }
6162
+ };
6163
+ const all = dirs(join14(lib, "evid")).flatMap(dirs).flatMap(dirs);
6164
+ return { entries: all.length, evidence_maps: all.filter((d) => existsSync16(join14(d, "evmap", "evmap.db"))).length };
6165
+ }
5662
6166
  function libraryInfo(libraryDir, host3, tiers = resolveTiers()) {
5663
6167
  const info = {
5664
6168
  evidence_dir: libraryDir,
@@ -5667,6 +6171,7 @@ function libraryInfo(libraryDir, host3, tiers = resolveTiers()) {
5667
6171
  config: { ...settings(), problems: [...tiers.problems, ...verifyProblems(), ...evidenceMapEnabled() ? evmapModels().problems : []], sources: sources() },
5668
6172
  download: downloadInfo(),
5669
6173
  verify: verifyInfo(),
6174
+ ...evidEnabled() ? { evid: evidCounts(libraryDir) } : {},
5670
6175
  ...evidenceMapEnabled() ? { evidence_map: evmapModels().models } : {},
5671
6176
  ...webSearchConfigured() ? { web_search: webSearchConfig().map((c) => c.provider) } : {},
5672
6177
  unlockers: unlockers().map((provider) => ({ provider })),
@@ -5683,11 +6188,11 @@ function libraryInfo(libraryDir, host3, tiers = resolveTiers()) {
5683
6188
  concerns: 0,
5684
6189
  updates: 0
5685
6190
  };
5686
- for (const type of existsSync15(libraryDir) ? readdirSync5(libraryDir) : []) {
5687
- const typeDir = join13(libraryDir, type);
5688
- if (!statSync4(typeDir).isDirectory()) continue;
6191
+ for (const type of existsSync16(libraryDir) ? readdirSync5(libraryDir) : []) {
6192
+ const typeDir = join14(libraryDir, type);
6193
+ if (!statSync5(typeDir).isDirectory()) continue;
5689
6194
  for (const meta of metaFiles(typeDir)) {
5690
- const md = readFileSync12(meta, "utf8");
6195
+ const md = readFileSync13(meta, "utf8");
5691
6196
  const raw = field(md, "level") || "unknown";
5692
6197
  const level = raw === "abstract" && field(md, "has_abstract") === "no" ? "title" : raw;
5693
6198
  info.entries++;
@@ -5700,7 +6205,7 @@ function libraryInfo(libraryDir, host3, tiers = resolveTiers()) {
5700
6205
  const dir = dirname8(meta);
5701
6206
  for (const f of readdirSync5(dir)) {
5702
6207
  try {
5703
- const st = statSync4(join13(dir, f));
6208
+ const st = statSync5(join14(dir, f));
5704
6209
  if (st.isFile()) info.size_bytes += st.size;
5705
6210
  } catch {
5706
6211
  }
@@ -5727,7 +6232,7 @@ function noticeTypes(md, metaPath) {
5727
6232
  return out;
5728
6233
  }
5729
6234
  try {
5730
- const xml = readFileSync12(metaPath.replace(/-meta\.md$/, "-abstract.xml"), "utf8");
6235
+ const xml = readFileSync13(metaPath.replace(/-meta\.md$/, "-abstract.xml"), "utf8");
5731
6236
  for (const m of xml.matchAll(/<CommentsCorrections RefType="([A-Za-z]+)"/g)) if (XML_TYPES[m[1]]) out.add(XML_TYPES[m[1]]);
5732
6237
  } catch {
5733
6238
  }
@@ -5890,9 +6395,9 @@ function parseCrossref(json2) {
5890
6395
  }
5891
6396
  function fromInvertedIndex(index) {
5892
6397
  if (!index) return "";
5893
- const words3 = [];
5894
- for (const [w, ps] of Object.entries(index)) for (const p of ps) words3[p] = w;
5895
- return words3.filter((w) => w !== void 0).join(" ").replace(/\s+([.,;:!?)])/g, "$1").replace(/\(\s+/g, "(").trim();
6398
+ const words4 = [];
6399
+ for (const [w, ps] of Object.entries(index)) for (const p of ps) words4[p] = w;
6400
+ return words4.filter((w) => w !== void 0).join(" ").replace(/\s+([.,;:!?)])/g, "$1").replace(/\(\s+/g, "(").trim();
5896
6401
  }
5897
6402
  async function openAlexAbstract(doi) {
5898
6403
  try {
@@ -5944,8 +6449,8 @@ function parseCsl(json2) {
5944
6449
 
5945
6450
  // src/urlfetch.ts
5946
6451
  import { createHash as createHash7 } from "crypto";
5947
- import { existsSync as existsSync16, mkdirSync as mkdirSync14, readFileSync as readFileSync13 } from "fs";
5948
- import { join as join14 } from "path";
6452
+ import { existsSync as existsSync17, mkdirSync as mkdirSync14, readFileSync as readFileSync14 } from "fs";
6453
+ import { join as join15 } from "path";
5949
6454
 
5950
6455
  // src/pagemeta.ts
5951
6456
  var CONTENT = /^(Article|NewsArticle|BlogPosting|ScholarlyArticle|MedicalScholarlyArticle|Report|MedicalWebPage|FAQPage|QAPage|Product|Drug|DietarySupplement|MedicalCondition|MedicalStudy|Dataset|Guideline|MedicalGuideline|HowTo|Recipe|PodcastEpisode|VideoObject|SearchResultsPage|CollectionPage|ProfilePage|WebPage)$/;
@@ -6085,8 +6590,8 @@ var urlHash = (normalized2) => createHash7("sha1").update(normalized2).digest("h
6085
6590
  function urlPaths(libraryDir, normalized2) {
6086
6591
  const hash = urlHash(normalized2);
6087
6592
  const entry = `url-${hash}`;
6088
- const entryDir = join14(libraryDir, "url", hash.slice(0, 2), hash.slice(0, 4), hash);
6089
- return { hash, entry, entryDir, meta: join14(entryDir, `${entry}-meta.md`), md: join14(entryDir, `${entry}-page.md`), raw: (ext) => join14(entryDir, `${entry}-page.${ext}`) };
6593
+ const entryDir = join15(libraryDir, "url", hash.slice(0, 2), hash.slice(0, 4), hash);
6594
+ return { hash, entry, entryDir, meta: join15(entryDir, `${entry}-meta.md`), md: join15(entryDir, `${entry}-page.md`), raw: (ext) => join15(entryDir, `${entry}-page.${ext}`) };
6090
6595
  }
6091
6596
  function renderUrlMeta(m) {
6092
6597
  const lines = [
@@ -6108,8 +6613,8 @@ function renderUrlMeta(m) {
6108
6613
  return lines.map(([k, v]) => `${k}: ${v}`).join("\n") + "\n";
6109
6614
  }
6110
6615
  function readUrlMeta(p) {
6111
- if (!existsSync16(p.meta)) return null;
6112
- const md = readFileSync13(p.meta, "utf8");
6616
+ if (!existsSync17(p.meta)) return null;
6617
+ const md = readFileSync14(p.meta, "utf8");
6113
6618
  const f = (k) => {
6114
6619
  const m = new RegExp(`^${k}:[ \\t]*(.*)$`, "m").exec(md);
6115
6620
  return m ? m[1].trim() : "";
@@ -6152,8 +6657,8 @@ var EMPTY_WORDS = 10;
6152
6657
  var SHELL_PHRASE = /\bloading\b|javascript|enable it|connecting to|please wait|redirecting/i;
6153
6658
  function isScriptShell(markdownOrHtml) {
6154
6659
  const text4 = markdownOrHtml.replace(/<script[\s\S]*?<\/script>|<style[\s\S]*?<\/style>|<noscript[\s\S]*?<\/noscript>/gi, " ").replace(/<[^>]+>/g, " ").replace(/&[a-z#0-9]+;/gi, " ").replace(/\]\([^)]*\)/g, ")");
6155
- const words3 = text4.split(/\s+/).filter((w) => /[\p{L}\p{N}]/u.test(w)).length;
6156
- return { shell: words3 < EMPTY_WORDS || words3 < SHELL_WORDS && SHELL_PHRASE.test(text4), words: words3 };
6660
+ const words4 = text4.split(/\s+/).filter((w) => /[\p{L}\p{N}]/u.test(w)).length;
6661
+ return { shell: words4 < EMPTY_WORDS || words4 < SHELL_WORDS && SHELL_PHRASE.test(text4), words: words4 };
6157
6662
  }
6158
6663
  var viaName = (via) => typeof via === "object" ? "unlocker" in via ? via.unlocker : "proxy" in via ? fetchProxyName(via) : stageName({ kind: stageKind(via.browser), label: via.label }) : via;
6159
6664
  async function stage(url, via, signal) {
@@ -6193,14 +6698,14 @@ var climb = async (given, onTry, onAlert) => {
6193
6698
  }
6194
6699
  return g;
6195
6700
  };
6196
- const write = (line) => onTry?.(line);
6701
+ const write2 = (line) => onTry?.(line);
6197
6702
  const run = (target2, via, name, after) => {
6198
6703
  let req = null;
6199
6704
  return {
6200
6705
  name,
6201
6706
  abort: (why) => req?.abort(why),
6202
6707
  go: async () => {
6203
- req = openRequest(write, name);
6708
+ req = openRequest(write2, name);
6204
6709
  const g = await stage(target2, via, req.signal);
6205
6710
  if (req.signal.aborted) return { ok: false, reason: "aborted", via: name };
6206
6711
  seen2(g);
@@ -6241,9 +6746,9 @@ var climb = async (given, onTry, onAlert) => {
6241
6746
  const notThere = () => gone ? { ...r, ok: false, reason: gone, via: r.via } : null;
6242
6747
  if (gone) return { ...notThere(), first: gone };
6243
6748
  if (escalates(r)) {
6244
- const open = browserStages().filter((b) => !skipped(target, stageName(b)));
6245
- const down = await Promise.all(open.map((b) => hostDown(b.host, b.port, stageName(b))));
6246
- const tasks = open.filter((_, i) => !down[i]).map((b) => run(target, { browser: b.endpoint, label: b.label }, stageName(b)));
6749
+ const open2 = browserStages().filter((b) => !skipped(target, stageName(b)));
6750
+ const down = await Promise.all(open2.map((b) => hostDown(b.host, b.port, stageName(b))));
6751
+ const tasks = open2.filter((_, i) => !down[i]).map((b) => run(target, { browser: b.endpoint, label: b.label }, stageName(b)));
6247
6752
  const two = await firstOk(tasks, isGone);
6248
6753
  if (two.won) return two.won;
6249
6754
  if (two.results.length) r = two.results.filter(Boolean).pop();
@@ -6279,8 +6784,8 @@ var decode2 = (s) => s.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (m, e) => {
6279
6784
  });
6280
6785
  var visibleText = (html) => decode2(html.replace(/<[^>]+>/g, " ")).replace(/\s+/g, " ").replace(/¶\s*$/, "").trim();
6281
6786
  var normalized = (text4) => {
6282
- const words3 = text4.toLowerCase().match(/[\p{L}\p{N}]+/gu);
6283
- return words3 ? ` ${words3.join(" ")} ` : "";
6787
+ const words4 = text4.toLowerCase().match(/[\p{L}\p{N}]+/gu);
6788
+ return words4 ? ` ${words4.join(" ")} ` : "";
6284
6789
  };
6285
6790
  function pageTitle(html) {
6286
6791
  const head = html.slice(0, 2e5);
@@ -6423,14 +6928,14 @@ function titleLine(m, md) {
6423
6928
  }
6424
6929
  function serve(requested, p, m, args, cached) {
6425
6930
  const maxLength = args.max_length ?? 5e3, startIndex = args.start_index ?? 0;
6426
- const read2 = (file3) => existsSync16(file3) ? readFileSync13(file3, "utf8") : "";
6931
+ const read2 = (file3) => existsSync17(file3) ? readFileSync14(file3, "utf8") : "";
6427
6932
  if (args.title_only) return { ok: true, text: `Contents of ${requested}:
6428
6933
  ${titleLine(m, read2(p.md))}`, cached, meta: m };
6429
6934
  const rawFile = m.files.find((f) => !f.endsWith("-meta.md") && !f.endsWith("-page.md"));
6430
6935
  let body, prefix = "";
6431
6936
  if (m.format === "markdown") body = read2(p.md);
6432
6937
  else if (m.format === "text" || args.raw) {
6433
- body = rawFile ? read2(join14(p.entryDir, rawFile)) : read2(p.md);
6938
+ body = rawFile ? read2(join15(p.entryDir, rawFile)) : read2(p.md);
6434
6939
  prefix = `Content type ${m.content_type || "(not declared)"} cannot be simplified to markdown, but here is the raw content:
6435
6940
  `;
6436
6941
  } else body = read2(p.md);
@@ -6448,9 +6953,9 @@ async function libraryFetch(libraryDir, requested, args, converter, logs = {}, f
6448
6953
  let stored = readUrlMeta(p);
6449
6954
  if (stored && fresh(stored) && stored.format === "html" && olderConverter(stored.converted_by, converter)) {
6450
6955
  const html = stored.files.find((f) => f.endsWith("-page.html"));
6451
- if (html && existsSync16(join14(p.entryDir, html))) {
6956
+ if (html && existsSync17(join15(p.entryDir, html))) {
6452
6957
  try {
6453
- const page = await convert(readFileSync13(join14(p.entryDir, html)), stored.content_type || "text/html", stored.final_url || stored.url);
6958
+ const page = await convert(readFileSync14(join15(p.entryDir, html)), stored.content_type || "text/html", stored.final_url || stored.url);
6454
6959
  if (page.md !== null) {
6455
6960
  writeAtomic(p.md, page.md);
6456
6961
  writeUrlMeta(p, { ...stored, title: page.title, converted_by: converter, ...sourceFields(page) });
@@ -6494,11 +6999,11 @@ async function libraryFetch(libraryDir, requested, args, converter, logs = {}, f
6494
6999
 
6495
7000
  // src/verify/cache.ts
6496
7001
  import { createHash as createHash8 } from "crypto";
6497
- import { existsSync as existsSync18, mkdirSync as mkdirSync15, readFileSync as readFileSync15 } from "fs";
6498
- import { dirname as dirname9, join as join15 } from "path";
7002
+ import { existsSync as existsSync19, mkdirSync as mkdirSync15, readFileSync as readFileSync16 } from "fs";
7003
+ import { dirname as dirname9, join as join16 } from "path";
6499
7004
 
6500
7005
  // src/verify/verify.ts
6501
- import { existsSync as existsSync17, readFileSync as readFileSync14 } from "fs";
7006
+ import { existsSync as existsSync18, readFileSync as readFileSync15 } from "fs";
6502
7007
  var QUESTION = "Does the paper state this, in substance? Ignore section labels and definitions of terms in parentheses. Every fact and number of the statement must be stated in the paper or follow from its numbers; a rounded number counts. If any part of the statement is absent from the paper or contradicted by it, answer false.";
6503
7008
  function cleanMarkdown(md) {
6504
7009
  return paperYearOnly(dropReferences(md)).replace(/!\[[^\]]*\]\([^)]*\)/g, "").replace(/\]\([^)]*\)/g, "]").replace(/^\s*#+\s*(see more about|more for you|back to top)\b.*$/gim, "").replace(/\n{3,}/g, "\n\n");
@@ -6602,16 +7107,16 @@ async function readPaper(raw, libraryDir = FH_EVIDENCE_DIR) {
6602
7107
  if (p.error) return { id: p.requested, error: p.error };
6603
7108
  const paths = entryPaths(libraryDir, p.type, p.id);
6604
7109
  if (!entryExists(paths)) return { id: p.requested, error: "not in library" };
6605
- const full = existsSync17(paths.fulltextMd);
6606
- if (full) return { id: p.requested, basis: "full_text", text: readFileSync14(paths.fulltextMd, "utf8") };
7110
+ const full = existsSync18(paths.fulltextMd);
7111
+ if (full) return { id: p.requested, basis: "full_text", text: readFileSync15(paths.fulltextMd, "utf8") };
6607
7112
  const meta = readMeta(paths);
6608
- return { id: p.requested, basis: meta.has_abstract ? "abstract" : "title", text: readFileSync14(paths.md, "utf8") };
7113
+ return { id: p.requested, basis: meta.has_abstract ? "abstract" : "title", text: readFileSync15(paths.md, "utf8") };
6609
7114
  }
6610
7115
  async function verifyClaim(claim, id, cfg, decide, read2 = readPaper) {
6611
7116
  const out = { claim, id, verdict: "error", reason: null, score: null, basis: null, windows: 0, glyphs_unresolved: 0, superseded: null, model: cfg?.model ?? null };
6612
- const words3 = claim.trim().split(/\s+/).filter(Boolean).length;
6613
- if (!words3) return { ...out, error: "claim empty" };
6614
- if (words3 < 3) return { ...out, error: "claim too short to be a finding" };
7117
+ const words4 = claim.trim().split(/\s+/).filter(Boolean).length;
7118
+ if (!words4) return { ...out, error: "claim empty" };
7119
+ if (words4 < 3) return { ...out, error: "claim too short to be a finding" };
6615
7120
  const frag = fragment(claim);
6616
7121
  if (frag) return { ...out, error: frag };
6617
7122
  const groups = citationGroups(claim);
@@ -6657,11 +7162,11 @@ ${id}
6657
7162
  ${model}
6658
7163
  ${threshold}
6659
7164
  ${text4}`).slice(0, 16);
6660
- var verdictFile = (libraryDir, key2) => join15(libraryDir, "verify", key2.slice(0, 2), key2.slice(0, 4), `${key2}.json`);
7165
+ var verdictFile = (libraryDir, key2) => join16(libraryDir, "verify", key2.slice(0, 2), key2.slice(0, 4), `${key2}.json`);
6661
7166
  function readVerdict(file3) {
6662
- if (!existsSync18(file3)) return null;
7167
+ if (!existsSync19(file3)) return null;
6663
7168
  try {
6664
- return JSON.parse(readFileSync15(file3, "utf8"));
7169
+ return JSON.parse(readFileSync16(file3, "utf8"));
6665
7170
  } catch {
6666
7171
  return null;
6667
7172
  }
@@ -6693,7 +7198,7 @@ async function verifyCached(claim, id, cfg, decide, libraryDir = FH_EVIDENCE_DIR
6693
7198
 
6694
7199
  // src/dailymedsearch.ts
6695
7200
  import { createHash as createHash9 } from "crypto";
6696
- import { existsSync as existsSync19, mkdirSync as mkdirSync16, readFileSync as readFileSync16 } from "fs";
7201
+ import { existsSync as existsSync20, mkdirSync as mkdirSync16, readFileSync as readFileSync17 } from "fs";
6697
7202
  import { dirname as dirname10 } from "path";
6698
7203
  var MAX_RESULTS3 = 100;
6699
7204
  var DEFAULT_RESULTS3 = 20;
@@ -6743,9 +7248,9 @@ async function searchLabels(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = live6
6743
7248
  const q = normalizeQuery4(raw);
6744
7249
  if ("error" in q) return { ok: false, error: q.error, input: true };
6745
7250
  const file3 = searchFile(libraryDir, searchKey4(q));
6746
- if (existsSync19(file3)) {
7251
+ if (existsSync20(file3)) {
6747
7252
  try {
6748
- const r = JSON.parse(readFileSync16(file3, "utf8"));
7253
+ const r = JSON.parse(readFileSync17(file3, "utf8"));
6749
7254
  if (daysSince(r.searched) < searchCacheDays()) return { ok: true, result: { ...r, rows: r.rows.map((row3) => {
6750
7255
  const c = [...row3];
6751
7256
  c[5] = levelOf2(row3[0], libraryDir);
@@ -6771,13 +7276,12 @@ async function searchLabels(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = live6
6771
7276
 
6772
7277
  // src/citations.ts
6773
7278
  import { createHash as createHash10 } from "crypto";
6774
- import { existsSync as existsSync20, mkdirSync as mkdirSync17, readFileSync as readFileSync17 } from "fs";
7279
+ import { existsSync as existsSync21, mkdirSync as mkdirSync17, readFileSync as readFileSync18 } from "fs";
6775
7280
  import { dirname as dirname11 } from "path";
6776
7281
  var MAX_RESULTS4 = 100;
6777
7282
  var DEFAULT_RESULTS4 = 20;
6778
7283
  var PAGE = 200;
6779
7284
  var MAX_PAGES = 50;
6780
- var citationsEnabled = (env = process.env) => /^(true|1|yes|on)$/i.test(env.FH_CITATIONS_ENABLED?.trim() ?? "");
6781
7285
  var ALIAS = { rct: "randomized controlled trial", "systematic-review": "systematic review" };
6782
7286
  var norm2 = (t) => {
6783
7287
  const s = t.toLowerCase().replace(/[-_\s]+/g, " ").trim();
@@ -6829,9 +7333,9 @@ async function citingArticles(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = liv
6829
7333
  const q = normalizeQuery5(raw);
6830
7334
  if ("error" in q) return { ok: false, error: q.error, input: true };
6831
7335
  const file3 = searchFile(libraryDir, searchKey5(q));
6832
- if (existsSync20(file3)) {
7336
+ if (existsSync21(file3)) {
6833
7337
  try {
6834
- const r = JSON.parse(readFileSync17(file3, "utf8"));
7338
+ const r = JSON.parse(readFileSync18(file3, "utf8"));
6835
7339
  if (daysSince(r.searched) < searchCacheDays()) return { ok: true, result: r, cached: true };
6836
7340
  } catch {
6837
7341
  }
@@ -7005,10 +7509,491 @@ function resultsText(nct, md, maxChars) {
7005
7509
  return { nct, has_results: true, text: truncated ? part.slice(0, maxChars).trimEnd() + "\n\n[truncated]" : part, truncated, outcomes, note: truncated ? "cut at max_chars; fh_library_read(id, section: <an outcome title>) returns one measure whole" : null };
7006
7510
  }
7007
7511
 
7512
+ // src/items.ts
7513
+ var KINDS = ["review", "benefit", "risk", "interaction", "protocol", "other"];
7514
+ var ORDER2 = `CASE kind ${["review", "benefit", "risk", "interaction", "protocol"].map((k, i) => `WHEN '${k}' THEN ${i}`).join(" ")} ELSE 9 END, MIN(rowid)`;
7515
+ var itemCandidates = (env = process.env) => num("FH_EVMAP_RANKING_ITEM_CANDIDATES", 20, env, (n) => n >= 3 && n <= 100 && Number.isInteger(n));
7516
+ var reviewPicks = (env = process.env) => num("FH_EVMAP_RANKING_REVIEW_PICKS", 5, env, (n) => n >= 1 && n <= 20 && Number.isInteger(n));
7517
+ var itemPicks = (env = process.env) => num("FH_EVMAP_RANKING_ITEM_PICKS", 3, env, (n) => n >= 1 && n <= 10 && Number.isInteger(n));
7518
+ var assignArticles = (env = process.env) => num("FH_EVMAP_RANKING_ASSIGN_ARTICLES", 300, env, (n) => n >= 0 && n <= 2e3 && Number.isInteger(n));
7519
+ var PER_CALL = 10;
7520
+ var CALLS_AT_ONCE = 3;
7521
+ var ASSIGN_PER_CALL = 50;
7522
+ var ASSIGNED = /* @__PURE__ */ new Set(["benefit", "risk", "interaction", "protocol", "other"]);
7523
+ var ITEMS_PROMPT = promptStep(builtinPrompt("ranking"), "items", "map");
7524
+ var ASSIGN_PROMPT = promptStep(builtinPrompt("ranking"), "assign", "map");
7525
+ var ASSIGN_SCHEMA = { type: "object", properties: { articles: { type: "array", items: { type: "object", properties: { article: { type: "integer" }, items: { type: "array", items: { type: "integer" } } }, required: ["article", "items"], additionalProperties: false } } }, required: ["articles"], additionalProperties: false };
7526
+ var SCHEMA3 = { type: "object", properties: { groups: { type: "array", items: { type: "object", properties: { group: { type: "integer" }, picks: { type: "array", items: { type: "integer" } } }, required: ["group", "picks"], additionalProperties: false } } }, required: ["groups"], additionalProperties: false };
7527
+ function setItems(lib, evid, items) {
7528
+ const db = openDb(evidDir(lib, evid.replace(/^evid:/, "")));
7529
+ try {
7530
+ const up = db.prepare("INSERT INTO query_items (query, kind, item) VALUES (?, ?, ?) ON CONFLICT(query) DO NOTHING");
7531
+ for (const q of items) up.run(q.query.replace(/\s+/g, " ").trim(), KINDS.includes(q.kind) ? q.kind : "other", q.item.trim() || "(unnamed)");
7532
+ } finally {
7533
+ db.close();
7534
+ }
7535
+ }
7536
+ async function pickItems(lib, evid, env = process.env, ask) {
7537
+ const t0 = Date.now();
7538
+ const rc = ask ? null : rankConfig(env);
7539
+ if (rc && !rc.ok) return { ok: false, error: `ranking model: ${rc.problem}` };
7540
+ const call = ask ?? ((prompt, schema, name) => askJson(rc.config, rc.model, prompt, schema, name));
7541
+ const pr = activePrompt("ranking", env);
7542
+ if (pr.problem) return { ok: false, error: `prompts: ${pr.problem}` };
7543
+ const template = promptStep(pr.text, "items", "map") ?? ITEMS_PROMPT;
7544
+ const N = itemCandidates(env), K = itemPicks(env), KR = reviewPicks(env);
7545
+ const picksOf = (g) => g.kind === "review" ? KR : K;
7546
+ const db = openDb(evidDir(lib, evid.replace(/^evid:/, "")));
7547
+ try {
7548
+ const topic = metaOf(db, "topic") ?? "";
7549
+ const LINE = "a.pmid, a.title, a.year, a.design, a.n, a.relevance, a.aspect, a.citations";
7550
+ const line = (x) => ({ pmid: String(x[0]), line: `${x[1] ?? "(no title)"} (${x[2] ?? "-"}; ${x[3] || "-"}; n=${x[4] ?? "-"}; ${x[5]}; ${x[6]}${x[7] != null ? `; cited ${x[7]} times` : ""})` });
7551
+ const all = query(db, `SELECT kind, item FROM query_items GROUP BY kind, item ORDER BY ${ORDER2}`, [], 0, 1e4).rows;
7552
+ let failed = "", calls2 = 0;
7553
+ const targets = all.filter(([kind]) => ASSIGNED.has(kind));
7554
+ const best = targets.length ? query(db, "SELECT pmid, title, year, design, n, finding FROM evidence_map WHERE score IS NOT NULL ORDER BY score DESC, pmid", [], 0, assignArticles(env)).rows : [];
7555
+ const pairs = [];
7556
+ if (best.length) {
7557
+ const assign = promptStep(pr.text, "assign", "map") ?? ASSIGN_PROMPT;
7558
+ const list5 = targets.map(([kind, item], i) => `${i + 1}. ${kind}: ${item}`).join("\n");
7559
+ const parts = [];
7560
+ for (let i = 0; i < best.length; i += ASSIGN_PER_CALL) parts.push(best.slice(i, i + ASSIGN_PER_CALL));
7561
+ let at = 0;
7562
+ await Promise.all(Array.from({ length: Math.min(CALLS_AT_ONCE, parts.length) }, async () => {
7563
+ while (at < parts.length && !failed) {
7564
+ const part = parts[at++];
7565
+ calls2++;
7566
+ const text4 = part.map((x, j) => `${j + 1}. ${x[1] ?? "(no title)"} (${x[2] ?? "-"}; ${x[3] || "-"}; n=${x[4] ?? "-"})${x[5] ? ` \u2014 ${x[5]}` : ""}`).join("\n");
7567
+ try {
7568
+ const a = await call(assign.split("{{topic}}").join(topic).split("{{items}}").join(list5).split("{{articles}}").join(text4), ASSIGN_SCHEMA, "item_articles");
7569
+ for (const x of a.articles ?? []) {
7570
+ const art = part[x.article - 1];
7571
+ if (!art || !Array.isArray(x.items)) continue;
7572
+ for (const n of new Set(x.items)) {
7573
+ const t = targets[n - 1];
7574
+ if (t) pairs.push([t[0], t[1], String(art[0])]);
7575
+ }
7576
+ }
7577
+ } catch (e) {
7578
+ failed = e instanceof Error ? e.message : String(e);
7579
+ }
7580
+ }
7581
+ }));
7582
+ if (failed) return { ok: false, error: failed };
7583
+ }
7584
+ db.exec("BEGIN");
7585
+ db.exec("DELETE FROM item_articles");
7586
+ const put = db.prepare("INSERT OR IGNORE INTO item_articles (kind, item, pmid) VALUES (?, ?, ?)");
7587
+ for (const x of pairs) put.run(...x);
7588
+ db.exec("COMMIT");
7589
+ const groups = [];
7590
+ for (const [kind, item] of all) {
7591
+ const own = query(db, `SELECT ${LINE}, MAX(a.score) AS s
7592
+ FROM query_items i JOIN queries q ON q.query = i.query JOIN query_hits h ON h.query_id = q.id JOIN evidence_map a ON a.pmid = h.pmid
7593
+ WHERE i.kind = ? AND i.item = ? AND a.score IS NOT NULL GROUP BY a.pmid ORDER BY s DESC`, [kind, item], 0, kind === "review" ? N * 3 : N).rows.map(line);
7594
+ const has = new Set(own.map((a) => a.pmid));
7595
+ const more = query(db, `SELECT ${LINE} FROM item_articles x JOIN evidence_map a ON a.pmid = x.pmid WHERE x.kind = ? AND x.item = ? AND a.score IS NOT NULL ORDER BY a.score DESC`, [kind, item], 0, 1e3).rows.map(line).filter((a) => !has.has(a.pmid)).slice(0, N);
7596
+ if (own.length + more.length) groups.push({ kind, item, arts: [...own, ...more] });
7597
+ }
7598
+ const picks = groups.map(() => []);
7599
+ const batches = [];
7600
+ for (let i = 0; i < groups.length; i += PER_CALL) batches.push(groups.slice(i, i + PER_CALL).map((_, k) => i + k));
7601
+ let next = 0;
7602
+ await Promise.all(Array.from({ length: Math.min(CALLS_AT_ONCE, batches.length) }, async () => {
7603
+ while (next < batches.length && !failed) {
7604
+ const b = batches[next++];
7605
+ const text4 = b.map((gi, k) => `Group ${k + 1} \u2014 ${groups[gi].kind}: ${groups[gi].item}${picksOf(groups[gi]) !== K ? ` (up to ${picksOf(groups[gi])})` : ""}
7606
+ ${groups[gi].arts.map((a, j) => `${j + 1}. ${a.line}`).join("\n")}`).join("\n\n");
7607
+ try {
7608
+ const a = await call(template.split("{{topic}}").join(topic).split("{{picks}}").join(String(K)).split("{{groups}}").join(text4), SCHEMA3, "item_picks");
7609
+ for (const g of a.groups ?? []) {
7610
+ const gi = b[g.group - 1];
7611
+ if (gi === void 0 || !Array.isArray(g.picks)) continue;
7612
+ picks[gi] = [...new Set(g.picks)].filter((j) => Number.isInteger(j) && j >= 1 && j <= groups[gi].arts.length).slice(0, picksOf(groups[gi])).map((j) => groups[gi].arts[j - 1].pmid);
7613
+ }
7614
+ } catch (e) {
7615
+ failed = e instanceof Error ? e.message : String(e);
7616
+ }
7617
+ }
7618
+ }));
7619
+ if (failed) return { ok: false, error: failed };
7620
+ db.exec("BEGIN");
7621
+ db.exec("DELETE FROM item_picks");
7622
+ const ins = db.prepare("INSERT OR IGNORE INTO item_picks (kind, item, pmid, pick) VALUES (?, ?, ?, ?)");
7623
+ groups.forEach((g, i) => picks[i].forEach((p, k) => ins.run(g.kind, g.item, p, k + 1)));
7624
+ db.exec("COMMIT");
7625
+ return { ok: true, items: groups.length, picked: picks.filter((p) => p.length).length, papers: new Set(picks.flat()).size, assigned: pairs.length, calls: calls2 + batches.length, seconds: Math.round((Date.now() - t0) / 1e3) };
7626
+ } finally {
7627
+ db.close();
7628
+ }
7629
+ }
7630
+ var ITEM_COLUMNS = ["pmid", "title", "first_author", "year", "design", "n", "finding"];
7631
+ function getItems(lib, evid, kind) {
7632
+ const db = openDb(evidDir(lib, evid.replace(/^evid:/, "")), true);
7633
+ if (!db) return null;
7634
+ try {
7635
+ if (!db.prepare("SELECT name FROM sqlite_master WHERE name = 'item_picks'").get()) return null;
7636
+ const all = query(db, `SELECT kind, item FROM query_items GROUP BY kind, item ORDER BY ${ORDER2}`, [], 0, 1e4).rows;
7637
+ if (!all.length) return null;
7638
+ const counts = {};
7639
+ for (const [k] of all) counts[k] = (counts[k] ?? 0) + 1;
7640
+ const items = all.filter(([k]) => !kind || k === kind).map(([k, item]) => ({ kind: k, item, articles: query(db, `SELECT ${ITEM_COLUMNS.map((c) => `a.${c}`).join(", ")} FROM item_picks p JOIN articles a ON a.pmid = p.pmid WHERE p.kind = ? AND p.item = ? ORDER BY p.pick`, [k, item], 0, 100).rows }));
7641
+ return { counts, columns: ITEM_COLUMNS, items };
7642
+ } finally {
7643
+ db.close();
7644
+ }
7645
+ }
7646
+
7647
+ // src/mapjob.ts
7648
+ import { existsSync as existsSync22, mkdirSync as mkdirSync18, readFileSync as readFileSync19 } from "fs";
7649
+ import { join as join17 } from "path";
7650
+ var JOB_FILE = "job.json";
7651
+ var HEARTBEAT_SECS = 10;
7652
+ var STALE_SECS = 60;
7653
+ var waitSecs = (env = process.env) => num("FH_EVMAP_WAIT_SECS", 5, env, (n) => n >= 0 && n <= 600);
7654
+ var fileOf = (lib, evid) => {
7655
+ const o = openEvid(lib, evid);
7656
+ return o.ok ? join17(o.dir, DB_DIR, JOB_FILE) : null;
7657
+ };
7658
+ var write = (file3, j) => {
7659
+ try {
7660
+ mkdirSync18(join17(file3, ".."), { recursive: true });
7661
+ writeAtomic(file3, JSON.stringify(j) + "\n");
7662
+ } catch {
7663
+ }
7664
+ };
7665
+ function readJob(lib, evid, now2 = /* @__PURE__ */ new Date()) {
7666
+ const file3 = fileOf(lib, evid);
7667
+ if (!file3 || !existsSync22(file3)) return null;
7668
+ let j;
7669
+ try {
7670
+ j = JSON.parse(readFileSync19(file3, "utf8"));
7671
+ } catch {
7672
+ return null;
7673
+ }
7674
+ const end = j.finished ? Date.parse(j.finished) : now2.getTime();
7675
+ const stale = j.state === "running" && now2.getTime() - Date.parse(j.updated) > STALE_SECS * 1e3;
7676
+ return { ...j, state: stale ? "interrupted" : j.state, seconds: Math.max(0, Math.round((end - Date.parse(j.started)) / 1e3)) };
7677
+ }
7678
+ var running = /* @__PURE__ */ new Map();
7679
+ var jobRunning = (evid) => running.has(evid);
7680
+ function startJob(lib, evid, run) {
7681
+ const file3 = fileOf(lib, evid);
7682
+ const job = { state: "running", stage: "starting", started: (/* @__PURE__ */ new Date()).toISOString(), updated: (/* @__PURE__ */ new Date()).toISOString(), host: HOST, pid: process.pid };
7683
+ const save = () => {
7684
+ job.updated = (/* @__PURE__ */ new Date()).toISOString();
7685
+ if (file3) write(file3, job);
7686
+ };
7687
+ save();
7688
+ const beat = setInterval(save, HEARTBEAT_SECS * 1e3);
7689
+ beat.unref?.();
7690
+ const p = (async () => {
7691
+ let r;
7692
+ try {
7693
+ r = await run((m) => {
7694
+ job.stage = m;
7695
+ save();
7696
+ });
7697
+ } catch (e) {
7698
+ r = { ok: false, error: e instanceof Error ? e.message : String(e) };
7699
+ }
7700
+ clearInterval(beat);
7701
+ job.state = r.ok ? "done" : "failed";
7702
+ job.finished = (/* @__PURE__ */ new Date()).toISOString();
7703
+ if (!r.ok) job.error = r.error ?? "failed";
7704
+ save();
7705
+ running.delete(evid);
7706
+ return r;
7707
+ })();
7708
+ running.set(evid, p);
7709
+ return p;
7710
+ }
7711
+ var jobAnswer = (evid, j) => ({
7712
+ evid,
7713
+ state: j.state,
7714
+ stage: j.stage,
7715
+ seconds: j.seconds,
7716
+ ...j.state === "running" ? { next: "the map is being built; read it with fh_evmap_get_map \u2014 it answers this state until the map is done (several minutes)" } : {},
7717
+ ...j.state === "interrupted" ? { next: "the server that was building this map stopped; call fh_evmap_create_map again with this evid to go on (what was searched and screened is kept)" } : {},
7718
+ ...j.state === "failed" ? { error: j.error } : {}
7719
+ });
7720
+
7721
+ // src/gaps.ts
7722
+ import { createRequire as createRequire3 } from "module";
7723
+ import { existsSync as existsSync23, mkdirSync as mkdirSync19 } from "fs";
7724
+ import { join as join18 } from "path";
7725
+ var require3 = createRequire3(import.meta.url);
7726
+ var GAPS_DIR = "evmap";
7727
+ var GAPS_DB = "gaps.db";
7728
+ var GAP_COLUMNS = ["id", "reported", "host", "evid", "topic", "pmid", "item", "kind", "reason", "class", "detail"];
7729
+ function open(lib, readonly = false) {
7730
+ const { DatabaseSync } = require3("node:sqlite");
7731
+ const file3 = join18(lib, GAPS_DIR, GAPS_DB);
7732
+ if (readonly) return existsSync23(file3) ? new DatabaseSync(file3, { readOnly: true }) : null;
7733
+ mkdirSync19(join18(lib, GAPS_DIR), { recursive: true });
7734
+ const db = new DatabaseSync(file3);
7735
+ db.exec("PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;");
7736
+ db.exec("CREATE TABLE IF NOT EXISTS gaps (id INTEGER PRIMARY KEY, reported TEXT NOT NULL, host TEXT, evid TEXT NOT NULL, topic TEXT, pmid TEXT, item TEXT, kind TEXT, reason TEXT, class TEXT NOT NULL, detail TEXT)");
7737
+ return db;
7738
+ }
7739
+ function classify(map, pmid) {
7740
+ const a = map.prepare("SELECT relevance, reason, title FROM articles WHERE pmid = ?").get(pmid);
7741
+ if (!a) return { class: "not found", detail: "no query of the map found this article" };
7742
+ const by = map.prepare("SELECT q.query FROM query_hits h JOIN queries q ON q.id = h.query_id WHERE h.pmid = ? ORDER BY q.id").all(pmid).map((x) => x.query);
7743
+ const hasItems = !!map.prepare("SELECT name FROM sqlite_master WHERE name = 'item_picks'").get();
7744
+ const itemsOf = hasItems ? map.prepare("SELECT DISTINCT i.kind || ': ' || i.item AS it FROM query_hits h JOIN queries q ON q.id = h.query_id JOIN query_items i ON i.query = q.query WHERE h.pmid = ?").all(pmid).map((x) => x.it) : [];
7745
+ if (a.relevance === "off-topic") return { class: "screened off-topic", detail: `found by ${by.length} quer${by.length === 1 ? "y" : "ies"}${itemsOf.length ? ` (${itemsOf.join("; ")})` : ""}; the screening: ${a.reason ?? "no reason stored"}` };
7746
+ const picked = hasItems ? map.prepare("SELECT kind || ': ' || item AS it, pick FROM item_picks WHERE pmid = ? ORDER BY pick").all(pmid) : [];
7747
+ if (picked.length) return { class: "picked", detail: `the map has it: ${picked.map((p) => `${p.it} (pick ${p.pick})`).join("; ")}` };
7748
+ const rank = map.prepare("SELECT COUNT(*) + 1 AS r FROM evidence_map e, (SELECT pick, score FROM evidence_map WHERE pmid = ?) me WHERE (e.pick IS NOT NULL AND me.pick IS NULL) OR (e.pick IS NOT NULL AND me.pick IS NOT NULL AND e.pick < me.pick) OR (e.pick IS NULL AND me.pick IS NULL AND e.score > me.score)").get(pmid).r;
7749
+ return { class: "not picked", detail: `in the map at ${rank} of the one table, relevance ${a.relevance ?? "not screened"}${itemsOf.length ? `; found for ${itemsOf.join("; ")}, in no item's top` : by.length ? `; found by ${by.length} quer${by.length === 1 ? "y" : "ies"}` : "; from a review's reference list"}` };
7750
+ }
7751
+ var STOP = /* @__PURE__ */ new Set(["with", "from", "risk", "risks", "benefit", "interaction", "effect", "effects", "lower", "higher", "fewer", "more", "less", "other", "increased", "reduced", "improved", "possible", "group"]);
7752
+ var words3 = (t) => [...new Set((t.toLowerCase().match(/[a-z0-9]{4,}/g) ?? []).filter((w) => !STOP.has(w)).map((w) => w.slice(0, 5)))];
7753
+ function instead(map, pmid, item, kind) {
7754
+ if (!map.prepare("SELECT name FROM sqlite_master WHERE name = 'item_picks'").get()) return [];
7755
+ const score2 = /* @__PURE__ */ new Map();
7756
+ const all = map.prepare("SELECT kind, item FROM query_items GROUP BY kind, item ORDER BY MIN(rowid)").all();
7757
+ const key2 = (x) => `${x.kind}\0${x.item}`;
7758
+ if (item) {
7759
+ const w = words3(item);
7760
+ for (const x of all) {
7761
+ if (kind && x.kind !== kind) continue;
7762
+ const n = words3(x.item).filter((y) => w.includes(y)).length;
7763
+ if (n) score2.set(key2(x), n * 10);
7764
+ }
7765
+ }
7766
+ if (pmid) {
7767
+ const of = map.prepare("SELECT DISTINCT i.kind, i.item FROM query_hits h JOIN queries q ON q.id = h.query_id JOIN query_items i ON i.query = q.query WHERE h.pmid = ?").all(pmid);
7768
+ if (map.prepare("SELECT name FROM sqlite_master WHERE name = 'item_articles'").get()) of.push(...map.prepare("SELECT kind, item FROM item_articles WHERE pmid = ?").all(pmid));
7769
+ for (const x of of) if (x.kind !== "review") score2.set(key2(x), (score2.get(key2(x)) ?? 0) + 5);
7770
+ }
7771
+ const out = [];
7772
+ for (const [k] of [...score2].sort((a, b) => b[1] - a[1])) {
7773
+ const [kd, it] = k.split("\0");
7774
+ const articles = map.prepare("SELECT a.pmid, a.title, a.year, a.design FROM item_picks p JOIN articles a ON a.pmid = p.pmid WHERE p.kind = ? AND p.item = ? ORDER BY p.pick").all(kd, it).filter((a) => a.pmid !== pmid).map((a) => ({ ...a }));
7775
+ if (articles.length) out.push({ item: `${kd}: ${it}`, articles });
7776
+ if (out.length === 3) break;
7777
+ }
7778
+ return out;
7779
+ }
7780
+ function reportGap(lib, r, now2 = /* @__PURE__ */ new Date()) {
7781
+ const o = openEvid(lib, r.evid);
7782
+ if (!o.ok) return o;
7783
+ const pmid = r.pmid?.replace(/^pmid:/i, "").trim() || void 0, item = r.item?.trim() || void 0;
7784
+ if (!pmid && !item) return { ok: false, error: "give pmid (a paper the map lacks) or item (a benefit, risk or interaction it lacks), or both" };
7785
+ if (pmid && !/^\d{1,8}$/.test(pmid)) return { ok: false, error: `invalid pmid '${r.pmid}'` };
7786
+ const map = openDb(o.dir, true);
7787
+ if (!map) return { ok: false, error: `${o.evid}: no evidence map yet` };
7788
+ let c, items, topic = "", alt = [];
7789
+ try {
7790
+ topic = map.prepare("SELECT value FROM meta WHERE key = 'topic'").get()?.value ?? "";
7791
+ if (pmid) c = classify(map, pmid);
7792
+ else {
7793
+ const has = !!map.prepare("SELECT name FROM sqlite_master WHERE name = 'query_items'").get();
7794
+ items = has ? query(map, `SELECT kind || ': ' || item FROM query_items ${r.kind ? "WHERE kind = ?" : ""} GROUP BY kind, item ORDER BY MIN(rowid)`, r.kind ? [r.kind] : [], 0, 500).rows.map((x) => String(x[0])) : [];
7795
+ c = { class: "item", detail: has ? `the map has ${items.length} item${items.length === 1 ? "" : "s"}${r.kind ? ` of kind ${r.kind}` : ""}; whether one covers "${item}" under another name is in the list` : "this map has no items (it was built from a caller's own queries)" };
7796
+ }
7797
+ if (c.class !== "picked") alt = instead(map, pmid, item, r.kind);
7798
+ } finally {
7799
+ map.close();
7800
+ }
7801
+ const db = open(lib);
7802
+ try {
7803
+ const id = Number(db.prepare("INSERT INTO gaps (reported, host, evid, topic, pmid, item, kind, reason, class, detail) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id").get(now2.toISOString(), HOST, o.evid, topic, pmid ?? null, item ?? null, r.kind ?? null, r.reason?.trim() || null, c.class, c.detail).id);
7804
+ return { ok: true, id, class: c.class, detail: c.detail, ...items ? { items } : {}, ...alt.length ? { instead: alt } : {} };
7805
+ } finally {
7806
+ db.close();
7807
+ }
7808
+ }
7809
+ function getGaps(lib, f = {}) {
7810
+ const db = open(lib, true);
7811
+ if (!db) return { counts: {}, columns: GAP_COLUMNS, rows: [], total: 0 };
7812
+ try {
7813
+ const where2 = [], params = [];
7814
+ if (f.since) {
7815
+ where2.push("reported >= ?");
7816
+ params.push(f.since);
7817
+ }
7818
+ if (f.evid) {
7819
+ where2.push("evid = ?");
7820
+ params.push(f.evid.startsWith("evid:") ? f.evid : `evid:${f.evid}`);
7821
+ }
7822
+ const w = where2.length ? `WHERE ${where2.join(" AND ")}` : "";
7823
+ const counts = Object.fromEntries(db.prepare(`SELECT class, COUNT(*) AS n FROM gaps ${w} GROUP BY class ORDER BY n DESC`).all(...params).map((x) => [x.class, x.n]));
7824
+ const w2 = f.class ? `${w ? `${w} AND` : "WHERE"} class = ?` : w;
7825
+ const r = query(db, `SELECT ${GAP_COLUMNS.join(", ")} FROM gaps ${w2} ORDER BY id DESC`, f.class ? [...params, f.class] : params, 0, Math.min(1e3, Math.max(1, f.limit ?? 100)));
7826
+ return { counts, columns: GAP_COLUMNS, rows: r.rows, total: r.total };
7827
+ } finally {
7828
+ db.close();
7829
+ }
7830
+ }
7831
+
7832
+ // src/discovery.ts
7833
+ var REVIEWS_ITEM = "Systematic reviews and meta-analyses of the intervention";
7834
+ var OVERALL = {
7835
+ reviews: { kind: "review", item: REVIEWS_ITEM },
7836
+ safety: { kind: "risk", item: "Safety overall" },
7837
+ interactions: { kind: "interaction", item: "Interactions overall" },
7838
+ pharmacokinetics: { kind: "protocol", item: "Pharmacokinetics overall" },
7839
+ guidelines: { kind: "protocol", item: "Guidelines" }
7840
+ };
7841
+ var discoveryIterations = (env = process.env) => num("FH_EVMAP_DISCOVERY_ITERATIONS", 3, env, (n) => n >= 1 && n <= 6 && Number.isInteger(n));
7842
+ var discoveryMax = (list5, env = process.env) => num(`FH_EVMAP_DISCOVERY_MAX_${list5.toUpperCase()}`, { benefits: 80, risks: 40, interactions: 40, protocol: 15 }[list5], env, (n) => n >= 0 && n <= 200 && Number.isInteger(n));
7843
+ var discoveryItemResults = (env = process.env) => num("FH_EVMAP_DISCOVERY_ITEM_RESULTS", 50, env, (n) => n >= 5 && n <= 500 && Number.isInteger(n));
7844
+ var discoverySurveyResults = (env = process.env) => num("FH_EVMAP_DISCOVERY_SURVEY_RESULTS", 200, env, (n) => n >= 20 && n <= 1e3 && Number.isInteger(n));
7845
+ var discoveryTitles = (env = process.env) => num("FH_EVMAP_DISCOVERY_TITLES", 800, env, (n) => n >= 50 && n <= 3e3 && Number.isInteger(n));
7846
+ var Q = { type: "object", properties: { label: { type: "string" }, query: { type: "string" } }, required: ["label", "query"], additionalProperties: false };
7847
+ var SURVEY = { type: "object", properties: { queries: { type: "array", items: { type: "object", properties: { kind: { type: "string", enum: ["reviews", "safety", "interactions", "pharmacokinetics", "guidelines", "other"] }, label: { type: "string" }, query: { type: "string" } }, required: ["kind", "label", "query"], additionalProperties: false } } }, required: ["queries"], additionalProperties: false };
7848
+ var ITEMS = { type: "object", properties: { items: { type: "array", items: Q } }, required: ["items"], additionalProperties: false };
7849
+ var ITERATION = { type: "object", properties: { replacements: { type: "array", items: { type: "object", properties: { number: { type: "integer" }, queries: { type: "array", items: Q } }, required: ["number", "queries"], additionalProperties: false } } }, required: ["replacements"], additionalProperties: false };
7850
+ var PER_ITERATION_CALL = 12;
7851
+ var fill2 = (text4, slots) => Object.entries(slots).reduce((t, [k, v]) => t.split(`{{${k}}}`).join(v), text4);
7852
+ var clean2 = (qs) => {
7853
+ const seen2 = /* @__PURE__ */ new Set();
7854
+ return qs.map((q) => ({ ...q, query: q.query.replace(/\s+/g, " ").trim() })).filter((q) => q.query && !seen2.has(q.query) && seen2.add(q.query));
7855
+ };
7856
+ var LISTS = [["benefits", "benefit"], ["risks", "risk"], ["interactions", "interaction"], ["protocol", "protocol"]];
7857
+ function discoverySteps(env = process.env) {
7858
+ const s = promptSections(activePrompt("discovery", env).text);
7859
+ const put = (t) => fill2(t ?? "", { item_query: s["item query"] ?? "", hints: s.hints ?? "" });
7860
+ return { survey: put(s.survey), iteration: put(s.iteration), lists: { benefits: put(s.benefits), risks: put(s.risks), interactions: put(s.interactions), protocol: put(s.protocol) } };
7861
+ }
7862
+ async function fit(topic, queries, limit, iterations, iterationPrompt, deps) {
7863
+ let qs = clean2(queries), iterated = 0;
7864
+ const count = async (list5) => {
7865
+ let k = 0;
7866
+ await Promise.all(Array.from({ length: Math.min(10, list5.length) }, async () => {
7867
+ while (k < list5.length) {
7868
+ const q = list5[k++];
7869
+ if (q.hits === void 0) q.hits = await deps.hits(q.query).catch(() => null);
7870
+ }
7871
+ }));
7872
+ };
7873
+ for (let pass = 0; ; pass++) {
7874
+ await count(qs);
7875
+ const over = qs.filter((q) => (q.hits ?? 0) > limit);
7876
+ if (!over.length || pass + 1 >= iterations) return { queries: qs, iterated, over: over.length };
7877
+ deps.log(`iteration ${pass + 2}: ${over.length} of ${qs.length} queries over ${limit} hits`);
7878
+ const by = /* @__PURE__ */ new Map();
7879
+ const chunks = [];
7880
+ for (let i = 0; i < over.length; i += PER_ITERATION_CALL) chunks.push(over.slice(i, i + PER_ITERATION_CALL));
7881
+ let nextChunk = 0;
7882
+ await Promise.all(Array.from({ length: Math.min(3, chunks.length) }, async () => {
7883
+ while (nextChunk < chunks.length) {
7884
+ const c = chunks[nextChunk++];
7885
+ try {
7886
+ const a = await deps.ask(fill2(iterationPrompt, { topic, limit: String(limit), queries: c.map((q, i) => `${i + 1}. ${q.hits} hits: ${q.query}`).join("\n") }), ITERATION, "iteration");
7887
+ for (const r of a.replacements ?? []) if (c[r.number - 1] && Array.isArray(r.queries)) by.set(c[r.number - 1], r.queries);
7888
+ } catch (e) {
7889
+ deps.log(`iteration ${pass + 2}: a call failed, ${c.length} queries stay as they are \xB7 ${e instanceof Error ? e.message.slice(0, 200) : String(e)}`);
7890
+ }
7891
+ }
7892
+ }));
7893
+ const next = [];
7894
+ for (const q of qs) {
7895
+ const rep = by.get(q);
7896
+ if (!rep?.length) {
7897
+ next.push(q);
7898
+ continue;
7899
+ }
7900
+ iterated++;
7901
+ for (const r of rep) next.push(r.query.replace(/\s+/g, " ").trim() === q.query ? q : { label: q.label, query: r.query, kind: q.kind });
7902
+ }
7903
+ qs = clean2(next);
7904
+ }
7905
+ }
7906
+ async function discoverMap(lib, evid, topic, env = process.env, deps = liveDeps(env, (m) => log("evmap", evid, `discovery ${m}`))) {
7907
+ const t0 = Date.now();
7908
+ const dc = rankConfig(env, "DISCOVERY");
7909
+ if (!dc.ok && deps.configured !== true) return { ok: false, failed: true, error: `discovery model: ${dc.problem}. Nothing ran. It is set in the server's .env by whoever runs the server.` };
7910
+ const pd = activePrompt("discovery", env);
7911
+ if (pd.problem) return { ok: false, failed: true, error: `prompts: ${pd.problem}. Nothing ran. It is set in the server's .env by whoever runs the server.` };
7912
+ const steps = discoverySteps(env), limit = maxResultsPerQuery(env), iterations = discoveryIterations(env);
7913
+ const many = { ...env, FH_EVMAP_MAX_QUERIES: "400" };
7914
+ const s0 = await deps.ask(fill2(steps.survey, { topic }), SURVEY, "survey");
7915
+ const surveyResults = Math.min(discoverySurveyResults(env), limit);
7916
+ const survey = surveyResults >= limit ? await fit(topic, s0.queries ?? [], limit, iterations, steps.iteration, deps) : { queries: clean2(s0.queries ?? []), iterated: 0, over: 0 };
7917
+ if (!survey.queries.length) return { ok: false, failed: true, error: "discovery: the model wrote no survey queries" };
7918
+ deps.log(`survey: ${survey.queries.length} queries, the first ${surveyResults} results of each`);
7919
+ const r1 = await doResearch(lib, evid, survey.queries.map((q) => q.query), void 0, many, /* @__PURE__ */ new Date(), { ...live4(lib), rank: null }, void 0, Object.fromEntries(survey.queries.map((q) => [q.query, q.kind === "interactions" ? limit : surveyResults])));
7920
+ if (!r1.ok) return { ok: false, error: `survey: ${r1.error}`, ...r1.failed ? { failed: true } : {} };
7921
+ const db = openDb(evidDir(lib, evid.replace(/^evid:/, "")), true);
7922
+ const line = (x) => `- ${x[0]} (${x[1] ?? "-"}; ${x[2] || "-"}; ${x[3] || "-"})`;
7923
+ const OWN = {
7924
+ benefits: { survey: ["reviews"], aspect: "efficacy", head: "From the search for reviews of the intervention" },
7925
+ risks: { survey: ["safety"], aspect: "safety", head: "From the search for its safety (every adverse effect and every group at risk named in one of these is a risk item)" },
7926
+ protocol: { survey: ["pharmacokinetics", "guidelines"], aspect: "dosing", head: "From the searches for its pharmacokinetics and for guidelines" },
7927
+ interactions: { survey: ["interactions"], aspect: "interaction", head: "From the search for interaction and pharmacokinetic studies (every drug, supplement or food studied with the intervention in one of these is an interaction item)" }
7928
+ };
7929
+ const titlesFor = (list5) => {
7930
+ const own = survey.queries.filter((q) => OWN[list5].survey.includes(q.kind ?? "")).map((q) => q.query);
7931
+ const first = own.length ? query(db, `SELECT a.title, a.year, a.design, a.aspect, MIN(h.rank) AS r FROM queries q JOIN query_hits h ON h.query_id = q.id JOIN articles a ON a.pmid = h.pmid WHERE a.title IS NOT NULL AND q.query IN (${own.map(() => "?").join(", ")}) GROUP BY a.pmid ORDER BY r`, own, 0, discoveryTitles(env)).rows : [];
7932
+ const seen2 = new Set(first.map((x) => String(x[0])));
7933
+ const rest = query(db, "SELECT title, year, design, aspect FROM evidence_map WHERE title IS NOT NULL ORDER BY (aspect = ? AND population = 'humans') DESC, score DESC", [OWN[list5].aspect], 0, discoveryTitles(env)).rows.filter((x) => !seen2.has(String(x[0]))).slice(0, Math.max(0, discoveryTitles(env) - first.length));
7934
+ return { text: (first.length ? `${OWN[list5].head}:
7935
+ ${first.map(line).join("\n")}
7936
+
7937
+ The other titles:
7938
+ ` : "") + rest.map(line).join("\n"), n: first.length + rest.length };
7939
+ };
7940
+ const have = new Set(survey.queries.map((q) => q.query));
7941
+ const listed = [];
7942
+ let titleCount = 0;
7943
+ const counts = [];
7944
+ const answers = await Promise.all(LISTS.map(async ([list5, kind]) => {
7945
+ const max = discoveryMax(list5, env);
7946
+ if (!max || !steps.lists[list5]) return { list: list5, kind, items: [], n: 0 };
7947
+ const t = titlesFor(list5);
7948
+ const a = await deps.ask(fill2(steps.lists[list5], { topic, titles: t.text, max: String(max) }), ITEMS, list5);
7949
+ return { list: list5, kind, items: (a.items ?? []).slice(0, max), n: t.n };
7950
+ }));
7951
+ db.close();
7952
+ for (const a of answers) {
7953
+ titleCount = Math.max(titleCount, a.n);
7954
+ counts.push(`${a.items.length} ${a.list}`);
7955
+ for (const q of a.items) listed.push({ ...q, kind: a.kind });
7956
+ }
7957
+ const items = { queries: clean2(listed).filter((q) => !have.has(q.query)), iterated: 0, over: 0 };
7958
+ const rows = { length: titleCount };
7959
+ const itemResults = discoveryItemResults(env);
7960
+ deps.log(`items: ${counts.join(", ")} \u2014 ${items.queries.length} queries, the first ${itemResults} results of each`);
7961
+ const report = { survey: survey.queries, items: items.queries, iterated: survey.iterated + items.iterated, over: survey.over + items.over, titles: rows.length, seconds: 0 };
7962
+ if (!items.queries.length) {
7963
+ const r = await doResearch(lib, evid, survey.queries.map((q) => q.query), void 0, many);
7964
+ return r.ok ? { ok: true, evid: r.evid, included: r.included, discovery: { ...report, seconds: Math.round((Date.now() - t0) / 1e3) } } : { ok: false, error: r.error };
7965
+ }
7966
+ const r2 = await doResearch(lib, evid, items.queries.map((q) => q.query), void 0, many, /* @__PURE__ */ new Date(), live4(lib), void 0, Object.fromEntries(items.queries.map((q) => [q.query, itemResults])));
7967
+ if (!r2.ok) return { ok: false, error: `items: ${r2.error}`, ...r2.failed ? { failed: true } : {} };
7968
+ setItems(lib, evid, [...survey.queries.flatMap((q) => {
7969
+ const o = OVERALL[q.kind ?? ""];
7970
+ return o ? [{ query: q.query, ...o }] : [];
7971
+ }), ...items.queries.map((q) => ({ query: q.query, kind: q.kind ?? "other", item: q.label }))]);
7972
+ const p = await pickItems(lib, evid, env, deps.pick);
7973
+ deps.log(p.ok ? `picked ${p.papers} articles for ${p.picked} of ${p.items} items (${p.assigned} assignments from the whole map), ${p.calls} calls, ${p.seconds} s` : `picking per item failed: ${p.error}`);
7974
+ return { ok: true, evid: r2.evid, included: r2.included, discovery: { ...report, picks: p.ok ? { items: p.items, picked: p.picked, papers: p.papers, assigned: p.assigned, calls: p.calls, seconds: p.seconds } : { error: p.error }, seconds: Math.round((Date.now() - t0) / 1e3) } };
7975
+ }
7976
+ function liveDeps(env = process.env, log2 = () => {
7977
+ }) {
7978
+ const rc = rankConfig(env, "DISCOVERY");
7979
+ return {
7980
+ ask: async (prompt, schema, name) => {
7981
+ if (!rc.ok) throw new Error(`discovery model: ${rc.problem}`);
7982
+ return askJson(rc.config, rc.model, prompt, schema, name);
7983
+ },
7984
+ hits: async (q) => {
7985
+ const n = normalizeQuery2({ query: q, max_results: 1 }, 1);
7986
+ if ("error" in n) return null;
7987
+ return parseEsearch(await fetchText(esearchUrl(n), { "User-Agent": "evidence-mcp", Accept: "application/json" })).total;
7988
+ },
7989
+ log: log2
7990
+ };
7991
+ }
7992
+
7008
7993
  // src/tools.ts
7009
7994
  var pkg = (() => {
7010
7995
  try {
7011
- return JSON.parse(readFileSync18(new URL("../package.json", import.meta.url), "utf8"));
7996
+ return JSON.parse(readFileSync20(new URL("../package.json", import.meta.url), "utf8"));
7012
7997
  } catch {
7013
7998
  return { name: "evidence-mcp", version: "0.0.0" };
7014
7999
  }
@@ -7024,10 +8009,10 @@ A URL is no ID: send the ID of a PubMed, doi.org, ClinicalTrials.gov or DailyMed
7024
8009
 
7025
8010
  Tools
7026
8011
  - Library: fh_library_add, fh_library_status, fh_library_read (outline, one section, or the passages for a query), fh_verify_claim (does this one source state this one finding?).
7027
- - Search: fh_pubmed_search_articles, fh_pubmed_fetch_articles${citationsEnabled() ? ", fh_pubmed_citing_articles" : ""}, fh_clinicaltrials_search_studies, fh_dailymed_search_labels${webSearchConfigured() ? ", fh_web_search (instead of the built-in web search)" : ""}.
8012
+ - Search: fh_pubmed_search_articles, fh_pubmed_fetch_articles, fh_citing_articles, fh_clinicaltrials_search_studies, fh_dailymed_search_labels${webSearchConfigured() ? ", fh_web_search (instead of the built-in web search)" : ""}.
7028
8013
  - Trials: fh_clinicaltrials_get_study_record, fh_clinicaltrials_get_study_results.
7029
8014
  - Web: fh_fetch_url, for every URL that is not an article, label or trial record.
7030
- ${evidEnabled() ? "- EVID: fh_evid_create, fh_evid_find, fh_evid_list_objects, fh_evid_put, fh_evid_get \u2014 a store that outlives the session.\n" : ""}${evidenceMapEnabled() ? "- Evidence map: fh_create_evidence_map, fh_get_evidence_map.\n" : ""}- fh_info: this server's version and the library.
8015
+ ${evidEnabled() ? "- EVID: fh_evid_create, fh_evid_find, fh_evid_list_objects, fh_evid_put, fh_evid_get \u2014 a store that outlives the session.\n" : ""}${evidenceMapEnabled() ? "- Evidence map \u2014 the articles a review of a topic needs, by table (systematic reviews, benefits, risks, interactions, protocol): fh_evmap_create_map (topic in, EVID out; takes minutes), fh_evmap_get_map (the state, then the map), fh_evmap_report_gap (the map seems to lack a paper or item: what it has instead). Not needed to use a map: fh_evmap_get_query_performance, fh_evmap_get_gaps.\n" : ""}- fh_info: this server's version and the library.
7031
8016
 
7032
8017
  Rules
7033
8018
  - fh_library_read and fh_verify_claim store a missing record themselves (added: true); no fh_library_add first.
@@ -7395,13 +8380,13 @@ function registerTools(server2) {
7395
8380
  }
7396
8381
  added = true;
7397
8382
  }
7398
- const stored = existsSync21(paths.fulltextMd);
7399
- if (abstractOnly && !existsSync21(paths.md)) {
8383
+ const stored = existsSync24(paths.fulltextMd);
8384
+ if (abstractOnly && !existsSync24(paths.md)) {
7400
8385
  log("read", parsed.requested, "error abstract only: no abstract stored");
7401
8386
  return out({ requested: parsed.requested, entry: paths.entry, error: `no abstract stored for ${parsed.requested}${stored ? "; a full text is: read again without abstract_only" : ""}` });
7402
8387
  }
7403
8388
  const full = stored && !abstractOnly;
7404
- const md = readFileSync18(full ? paths.fulltextMd : paths.md, "utf8");
8389
+ const md = readFileSync20(full ? paths.fulltextMd : paths.md, "utf8");
7405
8390
  const text4 = full ? "full_text" : "abstract";
7406
8391
  const more = abstractOnly ? stored ? { fulltext: "stored" } : untried(paths) ? { fulltext: "not tried" } : {} : {};
7407
8392
  const base = { requested: parsed.requested, entry: paths.entry, text: text4, ...more, ...added ? { added: true } : {} };
@@ -7422,8 +8407,8 @@ function registerTools(server2) {
7422
8407
  const cap = max_chars ?? 6e3;
7423
8408
  let sec = readSection(md, section2, cap);
7424
8409
  let via = "";
7425
- if (!sec && /abstract/i.test(section2) && full && existsSync21(paths.md)) {
7426
- sec = readSection(readFileSync18(paths.md, "utf8"), "abstract", cap);
8410
+ if (!sec && /abstract/i.test(section2) && full && existsSync24(paths.md)) {
8411
+ sec = readSection(readFileSync20(paths.md, "utf8"), "abstract", cap);
7427
8412
  via = " (from the abstract file)";
7428
8413
  }
7429
8414
  if (!sec && /declaration/i.test(section2)) {
@@ -7494,7 +8479,7 @@ ${st.funding.map((f) => `- ${f}`).join("\n")}` : ""].filter(Boolean).join("\n\n"
7494
8479
  );
7495
8480
  server2.tool(
7496
8481
  "fh_info",
7497
- `The server and the whole library as JSON: this server's package name and version (which build is loaded), its log file; evidence directory (evidence_dir) and host; entry count and size on disk, by type and by level (by_type, by_level); per type (pmid, doi, dailymed, nct, url \u2014 pages stored by fh_fetch_url) the entries by level (full_text, abstract, title), retractions and fulltext_not_tried (articles stored from PubMed alone) (types); counts of retracted and not-citable entries and of errata, expressions of concern and updates (retracted, not_citable, errata, concerns, updates); the retrieval sources in run order and which are off (tiers); the multi-stage download (download): the Playwright servers with the version they must run, the Chrome stages, whether an unlocker is configured; the configuration and where each value came from \u2014 environment, .env or default, never the value (config); the decision model behind fh_verify_claim and whether it answers right now (verify);${evidenceMapEnabled() ? " the screening and re-ranking models of fh_create_evidence_map (evidence_map);" : ""}${webSearchConfigured() ? " the providers behind fh_web_search (web_search);" : ""} the unlockers and whether each answers right now (unlockers); our own stage hosts \u2014 fetch proxy, Playwright servers, Chrome \u2014 and whether each is reachable right now (stages); this server's cache hits and misses since it started (cache): verify (fh_verify_claim), fetch (fh_fetch_url), search (the search tools), pubmed (fh_pubmed_fetch_articles, per PMID).`,
8482
+ `The server and the whole library as JSON: this server's package name and version (which build is loaded), its log file; evidence directory (evidence_dir) and host; entry count and size on disk, by type and by level (by_type, by_level); per type (pmid, doi, dailymed, nct, url \u2014 pages stored by fh_fetch_url) the entries by level (full_text, abstract, title), retractions and fulltext_not_tried (articles stored from PubMed alone) (types); counts of retracted and not-citable entries and of errata, expressions of concern and updates (retracted, not_citable, errata, concerns, updates); the retrieval sources in run order and which are off (tiers); the multi-stage download (download): the Playwright servers with the version they must run, the Chrome stages, whether an unlocker is configured; the configuration and where each value came from \u2014 environment, .env or default, never the value (config); the decision model behind fh_verify_claim and whether it answers right now (verify);${evidEnabled() ? " the EVIDs and how many hold an evidence map (evid);" : ""}${evidenceMapEnabled() ? " the screening and re-ranking models of fh_evmap_create_map (evidence_map);" : ""}${webSearchConfigured() ? " the providers behind fh_web_search (web_search);" : ""} the unlockers and whether each answers right now (unlockers); our own stage hosts \u2014 fetch proxy, Playwright servers, Chrome \u2014 and whether each is reachable right now (stages); this server's cache hits and misses since it started (cache): verify (fh_verify_claim), fetch (fh_fetch_url), search (the search tools), pubmed (fh_pubmed_fetch_articles, per PMID).`,
7498
8483
  {},
7499
8484
  async () => {
7500
8485
  const info = libraryInfo(FH_EVIDENCE_DIR, HOST);
@@ -7558,8 +8543,8 @@ ${st.funding.map((f) => `- ${f}`).join("\n")}` : ""].filter(Boolean).join("\n\n"
7558
8543
  return { content: [{ type: "text", text: `Failed to fetch ${url}: ${added.error}` }], isError: true };
7559
8544
  }
7560
8545
  }
7561
- const file3 = pid.type === "pmid" ? paths.md : existsSync21(paths.fulltextMd) ? paths.fulltextMd : paths.md;
7562
- const md = existsSync21(file3) ? readFileSync18(file3, "utf8") : "";
8546
+ const file3 = pid.type === "pmid" ? paths.md : existsSync24(paths.fulltextMd) ? paths.fulltextMd : paths.md;
8547
+ const md = existsSync24(file3) ? readFileSync20(file3, "utf8") : "";
7563
8548
  const text4 = title_only ? `Contents of ${url}:
7564
8549
  ${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "", max_length, start_index);
7565
8550
  bump("fetch", had);
@@ -7618,8 +8603,8 @@ ${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "
7618
8603
  return { content: [{ type: "text", text: searchAnswer(r.result) }] };
7619
8604
  }
7620
8605
  );
7621
- if (citationsEnabled()) server2.tool(
7622
- "fh_pubmed_citing_articles",
8606
+ server2.tool(
8607
+ "fh_citing_articles",
7623
8608
  `The articles that cite an article, as rows in fh_pubmed_search_articles' columns: PMID, title, first author, year, journal, publication types, PMCID, library level. Use it for a trial's follow-ups, later meta-analyses that include it, guidelines (sort: cited) and comments on it.
7624
8609
  - types: PubMed publication types, any of them; an article without one (many plain articles, some guidelines) never matches.
7625
8610
  - Comments: with comment, letter or editorial in types, the comments PubMed links to the article come first, of any year and type, and comments_on lists their PMIDs. The other rows only cite the article and are mostly about something else.
@@ -7721,46 +8706,144 @@ Citations from OpenAlex. Cached ${searchCacheDays()} days.`,
7721
8706
  );
7722
8707
  }
7723
8708
  if (evidenceMapEnabled()) server2.tool(
7724
- "fh_create_evidence_map",
7725
- "Builds the evidence map for a topic: the PubMed articles that matter, most important first. topic: creates a new EVID; or evid: an existing one. Answers evid and included (how many articles are in the map). Every article found is stored: fh_library_read(id, abstract_only: true) reads its abstract at once. A repeat call with the evid adds queries. Up to ~4 minutes. Read the map: fh_get_evidence_map.",
8709
+ "fh_evmap_create_map",
8710
+ `Builds the evidence map of a topic: the PubMed articles a review needs, picked per item of five tables \u2014 systematic reviews, benefits, risks, interactions, protocol. topic: a new EVID; or evid. The server writes the queries. Takes minutes: answers evid and state "running"; fh_evmap_get_map answers the state, then the map. Built once per EVID; failed or interrupted: call again.`,
7726
8711
  {
7727
8712
  topic: z.string().optional().describe('A topic, e.g. "Telmisartan for Health & Longevity".'),
7728
- evid: z.string().optional().describe('Instead of topic: an existing EVID with "topic" in its metadata.'),
7729
- queries: z.array(z.string()).min(1).describe(`PubMed queries, up to ${maxQueries()} per call, covering the topic's names and synonyms, reviews and meta-analyses, trials, outcomes, safety. E.g. "telmisartan[tiab] AND (systematic review[pt] OR meta-analysis[pt])", "(telmisartan OR micardis) AND randomized controlled trial[pt]", "telmisartan AND (adverse effects[sh] OR hyperkalemia[tiab])".`),
7730
- screening: z.string().optional().describe(`Optional screening prompt with {{topic}} and {{article}}; the fields it fills are fixed (the map's columns). Default: "${DEFAULT_SCREENING.trim().replace(/\n+/g, " / ")}"`)
8713
+ evid: z.string().optional().describe('Instead of topic: an existing EVID with "topic" in its metadata.')
7731
8714
  },
7732
- async ({ topic, evid: evidArg, queries, screening }) => {
8715
+ async ({ topic, evid: evidArg }) => {
8716
+ const answer = (o, isError = false) => ({ content: [{ type: "text", text: compact2(o) }], ...isError ? { isError: true } : {} });
7733
8717
  if (!topic === !evidArg) {
7734
8718
  log("evmap", evidArg ?? null, "error topic or evid, one of them");
7735
- return { content: [{ type: "text", text: compact2({ error: "give either topic (a new EVID) or evid, not both, not neither" }) }], isError: true };
8719
+ return answer({ error: "give either topic (a new EVID) or evid, not both, not neither" }, true);
7736
8720
  }
7737
- let evid = evidArg ?? "";
8721
+ let evid = evidArg ?? "", name = topic?.trim() ?? "";
7738
8722
  if (topic) {
7739
- const c = createEvid(FH_EVIDENCE_DIR, { topic: topic.trim() });
7740
- if (!c.ok) return { content: [{ type: "text", text: compact2({ error: c.error }) }], isError: true };
8723
+ const c = createEvid(FH_EVIDENCE_DIR, { topic: name });
8724
+ if (!c.ok) return answer({ error: c.error }, true);
7741
8725
  evid = c.evid;
7742
- log("evid", evid, `create topic=${topic.trim()}`);
8726
+ log("evid", evid, `create topic=${name}`);
8727
+ } else {
8728
+ const o = openEvid(FH_EVIDENCE_DIR, evid);
8729
+ if (!o.ok) {
8730
+ log("evmap", evid, `error ${o.error}`);
8731
+ return answer({ error: o.error }, true);
8732
+ }
8733
+ evid = o.evid;
8734
+ name = typeof o.metadata.topic === "string" ? o.metadata.topic.trim() : "";
8735
+ if (!name) {
8736
+ log("evmap", evid, "error no topic in the metadata");
8737
+ return answer({ error: `${evid} has no "topic" in its metadata` }, true);
8738
+ }
8739
+ }
8740
+ if (jobRunning(evid)) {
8741
+ const j = readJob(FH_EVIDENCE_DIR, evid);
8742
+ return answer(j ? jobAnswer(evid, j) : { evid, state: "running" });
8743
+ }
8744
+ const have = getItems(FH_EVIDENCE_DIR, evid, "none")?.counts;
8745
+ if (have && readJob(FH_EVIDENCE_DIR, evid)?.state === "done") {
8746
+ log("evmap", evid, "exists already");
8747
+ return answer({ evid, state: "done", items: have, note: "this EVID's map is built: fh_evmap_get_map" });
8748
+ }
8749
+ const job = startJob(FH_EVIDENCE_DIR, evid, async (stage2) => {
8750
+ const r2 = await discoverMap(FH_EVIDENCE_DIR, evid, name, process.env, liveDeps(process.env, (m) => {
8751
+ log("evmap", evid, `discovery ${m}`);
8752
+ stage2(m);
8753
+ }));
8754
+ log("evmap", evid, r2.ok ? `created ${r2.discovery.survey.length + r2.discovery.items.length} queries, ${r2.included} articles, ${r2.discovery.seconds} s` : `${r2.failed ? "failed" : "error"} ${r2.error}`);
8755
+ if (!r2.ok) return r2;
8756
+ const p = r2.discovery.picks;
8757
+ return { ok: true, evid: r2.evid, included: r2.included, items: getItems(FH_EVIDENCE_DIR, evid, "none")?.counts, ...p && "error" in p ? { picking_error: p.error } : {}, seconds: r2.discovery.seconds };
8758
+ });
8759
+ const r = await Promise.race([job, new Promise((res) => setTimeout(() => res(null), waitSecs() * 1e3))]);
8760
+ if (!r) {
8761
+ const j = readJob(FH_EVIDENCE_DIR, evid);
8762
+ return answer(j ? jobAnswer(evid, j) : { evid, state: "running" });
7743
8763
  }
7744
- const r = await doResearch(FH_EVIDENCE_DIR, evid, queries, screening);
7745
- log("evmap", evid, r.ok ? `created queries=${queries.length} articles=${r.included}${r.failed_queries ? ` failed_queries=${r.failed_queries.length}` : ""}${r.empty_queries ? ` empty_queries=${r.empty_queries.length}` : ""}${r.screening_errors ? ` screening_errors=${r.screening_errors}` : ""}${r.citations_error ? " citations_failed" : ""}` : `${r.failed ? "failed" : "error"} ${r.error}`);
8764
+ const { ok, ...rest } = r;
8765
+ return answer(rest, !ok);
8766
+ }
8767
+ );
8768
+ if (evidenceMapEnabled()) server2.tool(
8769
+ "fh_evmap_get_query_performance",
8770
+ "Not needed to use a map. How each query of an EVID's evidence map did, as rows in columns order: round, hits (PubMed), used (fewer than hits: cut off), kept (screening positive), unique (kept, found by no other query), in_top_50.",
8771
+ { evid: z.string().describe("The EVID.") },
8772
+ async ({ evid }) => {
8773
+ const r = getQueryPerformance(FH_EVIDENCE_DIR, evid);
8774
+ log("evmap", evid, r.ok ? `performance reported ${r.rows.length} queries` : `error ${r.error}`);
7746
8775
  const { ok, ...rest } = r;
7747
8776
  return { content: [{ type: "text", text: compact2(rest) }], ...ok ? {} : { isError: true } };
7748
8777
  }
7749
8778
  );
7750
8779
  if (evidenceMapEnabled()) server2.tool(
7751
- "fh_get_evidence_map",
7752
- "An EVID's evidence map: articles as rows in columns order, most important first. relevance: direct, indirect or background; reason: what the article adds.",
8780
+ "fh_evmap_report_gap",
8781
+ "The map seems to lack a paper or an item: ask here before adding one. pmid (the paper you would add), or item with kind, or both; reason: one sentence. Answers instead: the map's items that cover it, with their picked articles \u2014 one of them may back the claim. class: what the map knows of the paper \u2014 picked (it has it, under the item named), not picked, screened off-topic, not found.",
7753
8782
  {
7754
8783
  evid: z.string().describe("The EVID."),
7755
- top: z.number().int().positive().optional().describe("How many (default 50, at most 500).")
8784
+ pmid: z.string().optional().describe("The paper you would add."),
8785
+ item: z.string().optional().describe('The benefit, risk or interaction the map lacks, e.g. "interaction with levothyroxine".'),
8786
+ kind: z.enum(["review", "benefit", "risk", "interaction", "protocol", "other"]).optional().describe("The item's kind."),
8787
+ reason: z.string().optional().describe("What claim it is to back.")
7756
8788
  },
7757
- async ({ evid, top }) => {
7758
- const r = getMap(FH_EVIDENCE_DIR, evid, { top });
7759
- log("evmap", evid, r.ok ? `get rows=${r.rows.length} total=${r.total}` : `error ${r.error}`);
8789
+ async (a) => {
8790
+ const r = reportGap(FH_EVIDENCE_DIR, a);
8791
+ log("evmap", a.evid, r.ok ? `gap ${r.class}${a.pmid ? ` pmid:${a.pmid.replace(/^pmid:/i, "")}` : ""}${a.item ? ` item "${a.item}"` : ""}${a.reason ? ` \xB7 ${a.reason}` : ""}` : `error ${r.error}`);
7760
8792
  const { ok, ...rest } = r;
7761
8793
  return { content: [{ type: "text", text: compact2(rest) }], ...ok ? {} : { isError: true } };
7762
8794
  }
7763
8795
  );
8796
+ if (evidenceMapEnabled()) server2.tool(
8797
+ "fh_evmap_get_gaps",
8798
+ "Not needed to use a map. What was reported with fh_evmap_report_gap in this library, newest first, as rows in columns order, and counts per class. Filters: since (YYYY-MM-DD), evid, class.",
8799
+ {
8800
+ since: z.string().optional().describe("Only reports from this date on, YYYY-MM-DD."),
8801
+ evid: z.string().optional().describe("Only this EVID's."),
8802
+ class: z.enum(["not found", "screened off-topic", "not picked", "picked", "item"]).optional().describe("Only this class."),
8803
+ limit: z.number().int().positive().optional().describe("How many rows (default 100, at most 1000).")
8804
+ },
8805
+ async (a) => {
8806
+ const r = getGaps(FH_EVIDENCE_DIR, a);
8807
+ log("evmap", a.evid ?? null, `gaps reported ${r.rows.length} of ${r.total}`);
8808
+ return { content: [{ type: "text", text: compact2(r) }] };
8809
+ }
8810
+ );
8811
+ if (evidenceMapEnabled()) server2.tool(
8812
+ "fh_evmap_get_map",
8813
+ `An EVID's evidence map. While it is built: state (running, failed, interrupted) \u2014 ask again later.
8814
+ items: one table or "all" \u2014 each item with its few picked articles; any one of them backs the item:
8815
+ - review: the major systematic reviews
8816
+ - benefit: one item per outcome
8817
+ - risk: one per adverse effect or group at risk
8818
+ - interaction: one per drug, supplement or food
8819
+ - protocol: dose, pharmacokinetics, forms, stopping
8820
+ An "overall" item leads a table with its broad articles.
8821
+ Without items: all articles as one table, most important first; relevance: direct, indirect or background; reason: what the article adds.
8822
+ An article's abstract: fh_library_read(id, abstract_only: true).`,
8823
+ {
8824
+ evid: z.string().describe("The EVID."),
8825
+ top: z.number().int().positive().optional().describe("Without items: how many articles (default 50, at most 500)."),
8826
+ items: z.enum(["review", "benefit", "risk", "interaction", "protocol", "all"]).optional().describe("One table, or all five.")
8827
+ },
8828
+ async ({ evid, top, items }) => {
8829
+ const j = readJob(FH_EVIDENCE_DIR, evid);
8830
+ if (j && j.state !== "done") {
8831
+ log("evmap", evid, `map ${j.state} \xB7 ${j.stage}`);
8832
+ return { content: [{ type: "text", text: compact2(jobAnswer(evid, j)) }], ...j.state === "failed" ? { isError: true } : {} };
8833
+ }
8834
+ if (items) {
8835
+ const it = getItems(FH_EVIDENCE_DIR, evid, items === "all" ? void 0 : items);
8836
+ log("evmap", evid, it ? `items reported ${it.items.length} ${items}` : "error no items");
8837
+ if (!it) return { content: [{ type: "text", text: compact2({ error: "this map has no items \u2014 read it without items" }) }], isError: true };
8838
+ return { content: [{ type: "text", text: compact2({ evid, item_counts: it.counts, columns: it.columns, items: it.items }) }] };
8839
+ }
8840
+ const r = getMap(FH_EVIDENCE_DIR, evid, { top });
8841
+ log("evmap", evid, r.ok ? `map reported ${r.rows.length} of ${r.total} articles` : `error ${r.error}`);
8842
+ const { ok, ...rest } = r;
8843
+ const counts = ok ? getItems(FH_EVIDENCE_DIR, evid, "none")?.counts : void 0;
8844
+ return { content: [{ type: "text", text: compact2({ ...rest, ...counts ? { item_counts: counts } : {} }) }], ...ok ? {} : { isError: true } };
8845
+ }
8846
+ );
7764
8847
  server2.tool(
7765
8848
  "fh_clinicaltrials_search_studies",
7766
8849
  `Search ClinicalTrials.gov by free text, intervention or condition \u2014 at least one of them; status ongoing | completed | all; sort relevance | newest | largest | completion. Returns the total and up to ${MAX_RESULTS} rows as arrays in columns order: NCT ID, title, status, phase, enrollment ("~100" estimated), start, primary completion, primary outcome, conditions, interventions, has_results. Link: https://clinicaltrials.gov/study/<NCT ID>. Cached ${searchCacheDays()} days. One trial in detail: fh_clinicaltrials_get_study_record.`,
@@ -7855,7 +8938,7 @@ Citations from OpenAlex. Cached ${searchCacheDays()} days.`,
7855
8938
  return { content: [{ type: "text", text: compact2({ error: e.error }) }], isError: true };
7856
8939
  }
7857
8940
  const raw = e.paths.fulltextRaw("json");
7858
- const r = existsSync21(raw) ? recordSummary(readFileSync18(raw, "utf8")) : null;
8941
+ const r = existsSync24(raw) ? recordSummary(readFileSync20(raw, "utf8")) : null;
7859
8942
  if (!r) {
7860
8943
  log("trials", e.requested, "record error: no stored record");
7861
8944
  return { content: [{ type: "text", text: compact2({ error: "no stored record" }) }], isError: true };
@@ -7874,7 +8957,7 @@ Citations from OpenAlex. Cached ${searchCacheDays()} days.`,
7874
8957
  log("trials", nct, `results error: ${e.error}`);
7875
8958
  return { content: [{ type: "text", text: compact2({ error: e.error }) }], isError: true };
7876
8959
  }
7877
- const md = existsSync21(e.paths.fulltextMd) ? readFileSync18(e.paths.fulltextMd, "utf8") : "";
8960
+ const md = existsSync24(e.paths.fulltextMd) ? readFileSync20(e.paths.fulltextMd, "utf8") : "";
7878
8961
  const r = resultsText(e.requested.replace(/^nct:/, "NCT"), md, max_chars);
7879
8962
  log("trials", e.requested, `results ${r.has_results ? `${r.outcomes.length} outcomes${r.truncated ? " truncated" : ""}` : "none"}`);
7880
8963
  return { content: [{ type: "text", text: leanJson(r) }] };
@@ -7885,9 +8968,6 @@ Citations from OpenAlex. Cached ${searchCacheDays()} days.`,
7885
8968
  // src/devfeatures.ts
7886
8969
  function devFeatures(env = process.env) {
7887
8970
  const out = [];
7888
- const web = webSearchConfig(env);
7889
- if (web.length) out.push("FH_WEB_SEARCH_ENABLED");
7890
- if (citationsEnabled(env)) out.push("FH_CITATIONS_ENABLED");
7891
8971
  if (evidEnabled(env)) out.push("FH_EVID_ENABLED");
7892
8972
  if (evidenceMapEnabled(env)) out.push("FH_EVMAP_ENABLED");
7893
8973
  return out;