evidence-mcp-dev 1.0.29 → 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 +1347 -290
  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
  });
@@ -170,11 +174,11 @@ var PROBE_MS = 3e3;
170
174
  var seen = /* @__PURE__ */ new Map();
171
175
  var key = (host3, port) => `${host3}:${port}`;
172
176
  function connectOnce(address, port, timeoutMs) {
173
- return new Promise((resolve4) => {
177
+ return new Promise((resolve5) => {
174
178
  const s = connect({ host: address, port });
175
179
  const done = (error) => {
176
180
  s.destroy();
177
- resolve4(error);
181
+ resolve5(error);
178
182
  };
179
183
  s.setTimeout(timeoutMs, () => done(`no answer within ${timeoutMs / 1e3} s`));
180
184
  s.once("connect", () => done(null));
@@ -392,9 +396,9 @@ function touchIdle() {
392
396
  idleTimer.unref();
393
397
  }
394
398
  async function closeBrowsers() {
395
- const open = [...ctxs.entries()];
399
+ const open2 = [...ctxs.entries()];
396
400
  ctxs.clear();
397
- for (const [endpoint, p] of open) {
401
+ for (const [endpoint, p] of open2) {
398
402
  try {
399
403
  const { ctx, browser } = await p;
400
404
  if (isCdp(endpoint)) {
@@ -491,11 +495,11 @@ async function browserFetch(url, endpoint, cfg = browserConfig(), signal) {
491
495
  if (!r.ok()) throw new Error(`HTTP ${r.status()} (pdf request)`);
492
496
  return { bytes: Buffer.from(await r.body()), contentType: "application/pdf", url: page.url(), via: "request" };
493
497
  }
494
- const words3 = () => page.evaluate(() => (document.body?.innerText ?? "").split(/\s+/).filter(Boolean).length).catch(() => 0);
495
- 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) {
496
500
  await page.waitForLoadState("networkidle", { timeout: SETTLE_MS }).catch(() => void 0);
497
501
  const t2 = Date.now();
498
- 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));
499
503
  }
500
504
  const html = await page.content();
501
505
  return { bytes: Buffer.from(html, "utf8"), contentType: contentType || "text/html", url: page.url(), via: "page" };
@@ -564,18 +568,54 @@ async function fetchBytes(url, headers = DOWNLOAD_HEADERS, proxy, signal) {
564
568
  }
565
569
  throw Object.assign(new Error(last), finalUrl ? { url: finalUrl } : {}, lastBody ? { body: lastBody, contentType: lastType } : {});
566
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
+ };
567
597
  async function fetchText(url, headers = {}) {
568
598
  let last = "unknown error";
569
- 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;
570
602
  try {
603
+ if (ncbi) await ncbiTurn();
571
604
  const res = await fetch(url, { headers, signal: AbortSignal.timeout(TIMEOUT_MS), redirect: "follow" });
572
- 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
+ }
573
613
  last = res.status < 500 ? httpReason(res.status, await res.text().catch(() => "")) : `HTTP ${res.status}`;
574
614
  if (res.status !== 429 && res.status < 500) break;
575
615
  } catch (e) {
576
616
  last = e instanceof Error && e.name === "TimeoutError" ? "timeout" : e instanceof Error ? e.message : String(e);
577
617
  }
578
- await new Promise((r) => setTimeout(r, 1500));
618
+ await new Promise((r) => setTimeout(r, ncbi ? ncbiWait(attempt, retryAfter) : 1500));
579
619
  }
580
620
  throw new Error(last);
581
621
  }
@@ -618,11 +658,11 @@ var headings = (md) => md.split("\n").filter((l) => /^#{1,6}\s/.test(l)).map((l)
618
658
  function proseWords(md) {
619
659
  let n = 0;
620
660
  for (const p of md.split(/\n\s*\n/).map((x) => x.trim()).filter((x) => x && !/^#{1,6}\s/.test(x))) {
621
- const words3 = p.split(/\s+/).length;
622
- if (words3 < 40 || /^(-|\*|\d+\.)\s/.test(p)) continue;
661
+ const words4 = p.split(/\s+/).length;
662
+ if (words4 < 40 || /^(-|\*|\d+\.)\s/.test(p)) continue;
623
663
  const linkChars = (p.match(/\[[^\]]*\]\([^)]*\)/g) ?? []).join("").length;
624
664
  if (linkChars / p.length > 0.3) continue;
625
- n += words3;
665
+ n += words4;
626
666
  }
627
667
  return n;
628
668
  }
@@ -631,8 +671,8 @@ function hasMethodsAndResults(md) {
631
671
  const hs = headings(md);
632
672
  const has = (re) => hs.some((h) => re.test(h));
633
673
  if (has(/method|material|procedure|design|experimental|patients? and|participants/i) && has(/result|finding|outcome/i)) return true;
634
- const words3 = md.split(/\s+/).length;
635
- if (words3 < 1200 || hs.length < 2) return false;
674
+ const words4 = md.split(/\s+/).length;
675
+ if (words4 < 1200 || hs.length < 2) return false;
636
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;
637
677
  return hs.filter((h) => SECTION.test(h.trim())).length >= 2;
638
678
  }
@@ -1398,7 +1438,7 @@ function pageReason(error, msg) {
1398
1438
  return null;
1399
1439
  }
1400
1440
  function post(url, init) {
1401
- return new Promise((resolve4, reject) => {
1441
+ return new Promise((resolve5, reject) => {
1402
1442
  const req = httpsRequest(url, { method: "POST", headers: { ...init.headers, "Content-Length": String(Buffer.byteLength(init.body)) }, signal: init.signal }, (res) => {
1403
1443
  const chunks = [];
1404
1444
  res.on("data", (c) => chunks.push(c));
@@ -1406,7 +1446,7 @@ function post(url, init) {
1406
1446
  res.on("end", () => {
1407
1447
  const body = Buffer.concat(chunks);
1408
1448
  const status = res.statusCode ?? 0;
1409
- resolve4({
1449
+ resolve5({
1410
1450
  ok: status >= 200 && status < 300,
1411
1451
  status,
1412
1452
  headers: { get: (name) => {
@@ -2819,9 +2859,9 @@ async function download(tier, p, candidates2, ctx) {
2819
2859
  const UNLOCK = /^(HTTP 403|wall page)/;
2820
2860
  let browsed = false;
2821
2861
  if (!gone && !c.headers && !c.service && (climbsOn(plainReason) || climbsOn(bare(reasonOf(r))))) {
2822
- const open = browserStages().filter((b) => !skipped(target.url, stageName(b)));
2823
- const down = await Promise.all(open.map((b) => hostDown(b.host, b.port, stageName(b), target.url)));
2824
- 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)));
2825
2865
  browsed = tasks.length > 0;
2826
2866
  const two = await firstOk(tasks, isGone);
2827
2867
  if (two.won) return two.won;
@@ -2892,9 +2932,9 @@ function serviceMessage(bytes, contentType = "") {
2892
2932
  return (visible || text4).slice(0, 160);
2893
2933
  }
2894
2934
  function describe(reason, format, md) {
2895
- const words3 = md.split(/\s+/).filter(Boolean).length;
2935
+ const words4 = md.split(/\s+/).filter(Boolean).length;
2896
2936
  const headings2 = md.split("\n").filter((l) => /^#{2,6}\s/.test(l)).length;
2897
- 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"}`;
2898
2938
  if (reason === "no methods/results") return `no article body (${seen2})`;
2899
2939
  if (reason === "title missing") return `neither title nor DOI in text (${seen2})`;
2900
2940
  return reason;
@@ -3308,13 +3348,11 @@ var VARIABLES = [
3308
3348
  "FH_REFRESH_AFTER_DAYS",
3309
3349
  "FH_SEARCH_CACHE_DAYS",
3310
3350
  "FH_NCBI_API_KEY",
3311
- "FH_WEB_SEARCH_ENABLED",
3312
3351
  "FH_WEB_SEARCH_EXA_API_KEY",
3313
3352
  "FH_WEB_SEARCH_SERPER_API_KEY",
3314
3353
  "FH_WEB_SEARCH_BRAVE_API_KEY",
3315
3354
  "FH_WEB_SEARCH_SNIPPETS",
3316
3355
  "FH_WEB_SEARCH_TIMEOUT_SECS",
3317
- "FH_CITATIONS_ENABLED",
3318
3356
  "FH_OPENALEX_API_KEY",
3319
3357
  "FH_ZENROWS_API_KEY",
3320
3358
  "FH_FIRECRAWL_API_KEY",
@@ -3328,13 +3366,17 @@ var VARIABLES = [
3328
3366
  "FH_EVMAP_MAX_RESULTS_PER_QUERY",
3329
3367
  "FH_EVMAP_CITATION_REVIEWS",
3330
3368
  "FH_EVMAP_CITATION_MAX_ADDED",
3331
- "FH_EVMAP_RANK_PROVIDER",
3332
- "FH_EVMAP_RANK_API_KEY",
3333
- "FH_EVMAP_RANK_MODEL",
3334
- "FH_EVMAP_RANK_URL",
3335
- "FH_EVMAP_RANK_CANDIDATES",
3336
- "FH_EVMAP_RANK_PICKS",
3337
- "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",
3338
3380
  "FH_EVMAP_ANTHROPIC_API_KEY",
3339
3381
  "FH_EVMAP_ANTHROPIC_MODEL",
3340
3382
  "FH_EVMAP_ANTHROPIC_URL",
@@ -3344,13 +3386,34 @@ var VARIABLES = [
3344
3386
  "FH_EVMAP_OPENAI_API_KEY",
3345
3387
  "FH_EVMAP_OPENAI_MODEL",
3346
3388
  "FH_EVMAP_OPENAI_URL",
3347
- "FH_EVMAP_SCREEN_URL",
3348
- "FH_EVMAP_SCREEN_API_KEY",
3349
- "FH_EVMAP_SCREEN_MODEL",
3350
- "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"
3351
3414
  ];
3352
3415
  var on = (v) => /^(true|1|yes|on)$/i.test(v?.trim() ?? "");
3353
- 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);
3354
3417
  var sources = (env = process.env) => Object.fromEntries(VARIABLES.filter((v) => !hidden(v, env)).map((v) => [v, sourceOf(v, env)]));
3355
3418
  function settings(env = process.env) {
3356
3419
  return {
@@ -3615,7 +3678,7 @@ function sections(md) {
3615
3678
  }
3616
3679
  var countWords = (s) => (s.replace(/^#{1,6}\s+/gm, "").match(/\S+/g) ?? []).length;
3617
3680
  function outline(md, text4) {
3618
- 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 })) };
3619
3682
  }
3620
3683
  function findSections(md, name) {
3621
3684
  let q = name.trim().toLowerCase().replace(/^#+\s*/, "");
@@ -4548,40 +4611,291 @@ async function searchArticles(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = liv
4548
4611
  // src/evidencemap.ts
4549
4612
  import { mkdirSync as mkdirSync11 } from "fs";
4550
4613
  import { dirname as dirname6 } from "path";
4551
- 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
+ }
4552
4858
 
4553
4859
  // src/screen.ts
4554
4860
  import Anthropic from "@anthropic-ai/sdk";
4555
4861
  import { createHash as createHash5 } from "crypto";
4556
- import { existsSync as existsSync10, mkdirSync as mkdirSync8, readFileSync as readFileSync8 } from "fs";
4557
- import { dirname as dirname4, join as join9 } from "path";
4558
- 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));
4559
4865
  var SCREEN_PROVIDERS = {
4560
- anthropic: { api: "anthropic", url: "https://api.anthropic.com", model: "claude-haiku-5-5", keyPrefix: "sk-ant-" },
4561
- 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-" },
4562
4868
  // Gemini through Google's OpenAI-compatible endpoint (speed test 2026-11-19: flash-lite 82 papers/s, Haiku 35)
4563
- 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-" }
4564
4876
  };
4565
4877
  function screenConfig(env = process.env, forProvider) {
4566
- const field2 = (p2, f) => p2 && str(`FH_EVMAP_${p2.toUpperCase()}_${f}`, env) || str(`FH_EVMAP_SCREEN_${f}`, env);
4567
- const named = forProvider ?? str("FH_EVMAP_SCREEN_PROVIDER", env).toLowerCase();
4568
- 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(", ")}` };
4569
4881
  let provider = named ? named : null;
4570
4882
  const url = field2(provider, "URL").replace(/\/+$/, "");
4571
- 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);
4572
4885
  if (!provider && url) provider = "openai";
4573
4886
  const anyKey = key2 || Object.keys(SCREEN_PROVIDERS).some((p2) => str(`FH_EVMAP_${p2.toUpperCase()}_API_KEY`, env));
4574
- 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)" };
4575
4888
  const p = SCREEN_PROVIDERS[provider];
4576
- const model = field2(provider, "MODEL") || p.model;
4577
- 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` };
4578
4892
  const from = (f) => {
4579
4893
  const own = `FH_EVMAP_${provider.toUpperCase()}_${f}`;
4580
- 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}`;
4581
4895
  };
4582
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") } };
4583
4897
  }
4584
- 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");
4585
4899
  var FIELDS2 = ["relevance", "population", "design", "n", "outcome", "finding", "aspect", "reason"];
4586
4900
  var SCHEMA = {
4587
4901
  type: "object",
@@ -4613,12 +4927,12 @@ var Refusal = class extends Error {
4613
4927
  super("refusal");
4614
4928
  }
4615
4929
  };
4616
- 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" };
4617
4931
  function hint(status, message, v = PLAIN) {
4618
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`;
4619
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`;
4620
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})`;
4621
- 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";
4622
4936
  if (status === 400) return `the provider refused the request; the model may not support structured output (a JSON schema) \u2014 ${v.model}`;
4623
4937
  if (status && status >= 500) return "the provider's service is failing \u2014 try again later";
4624
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})`;
@@ -4641,7 +4955,7 @@ var describe2 = (e, where2, v = PLAIN) => {
4641
4955
  };
4642
4956
  var where = (c) => `${c.provider} ${c.model} at ${c.url}`;
4643
4957
  function askFor(c) {
4644
- 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);
4645
4959
  return async (text4) => {
4646
4960
  try {
4647
4961
  return await ask(text4);
@@ -4666,15 +4980,17 @@ function anthropicAsk(apiKey2, model, baseURL) {
4666
4980
  return parseAnswer(block.text);
4667
4981
  };
4668
4982
  }
4669
- function openaiAsk(baseUrl, apiKey2, model, fetchImpl = fetch) {
4983
+ function openaiAsk(baseUrl, apiKey2, model, fetchImpl = fetch, extra = {}) {
4984
+ let fields = extra;
4670
4985
  return async (text4) => {
4671
4986
  for (let attempt = 0; ; attempt++) {
4672
4987
  let r;
4988
+ const sent = fields;
4673
4989
  try {
4674
4990
  r = await fetchImpl(`${baseUrl}/chat/completions`, {
4675
4991
  method: "POST",
4676
4992
  headers: { "content-type": "application/json", ...apiKey2 ? { authorization: `Bearer ${apiKey2}` } : {} },
4677
- 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 } } }),
4678
4994
  signal: AbortSignal.timeout(SCREEN_TIMEOUT_MS)
4679
4995
  });
4680
4996
  } catch (e) {
@@ -4684,7 +5000,15 @@ function openaiAsk(baseUrl, apiKey2, model, fetchImpl = fetch) {
4684
5000
  await new Promise((ok) => setTimeout(ok, Math.min(3e4, 1e3 * 2 ** attempt)));
4685
5001
  continue;
4686
5002
  }
4687
- 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
+ }
4688
5012
  const body = await r.json();
4689
5013
  const choice = body?.choices?.[0];
4690
5014
  if (choice?.finish_reason === "length") throw new Error("max_tokens: the answer was cut off");
@@ -4706,19 +5030,21 @@ function parseAnswer(text4) {
4706
5030
  return a;
4707
5031
  }
4708
5032
  async function screenAll(lib, pmids, prompt, topic, paper, ask, model, parallel, note = () => {
5033
+ }, done = () => {
4709
5034
  }) {
4710
- const dir = join9(lib, "screen", cacheKey(model, prompt, topic));
5035
+ const dir = join10(lib, "screen", cacheKey(model, prompt, topic));
4711
5036
  const out = new Array(pmids.length);
4712
5037
  let next = 0;
4713
5038
  const worker = async () => {
4714
5039
  while (next < pmids.length) {
4715
5040
  const i = next++;
4716
5041
  const pmid = pmids[i];
4717
- const file3 = join9(dir, `${pmid}.json`);
4718
- if (existsSync10(file3)) {
5042
+ const file3 = join10(dir, `${pmid}.json`);
5043
+ if (existsSync11(file3)) {
4719
5044
  try {
4720
- const c = JSON.parse(readFileSync8(file3, "utf8"));
5045
+ const c = JSON.parse(readFileSync9(file3, "utf8"));
4721
5046
  out[i] = c?.refused === true ? { pmid, refused: true, cached: true } : { pmid, screened: c, cached: true };
5047
+ done(out[i]);
4722
5048
  continue;
4723
5049
  } catch {
4724
5050
  }
@@ -4727,6 +5053,7 @@ async function screenAll(lib, pmids, prompt, topic, paper, ask, model, parallel,
4727
5053
  if (!text4) {
4728
5054
  out[i] = { pmid, error: "no abstract", cached: false };
4729
5055
  note(out[i], 0);
5056
+ done(out[i]);
4730
5057
  continue;
4731
5058
  }
4732
5059
  const t = Date.now();
@@ -4743,6 +5070,7 @@ async function screenAll(lib, pmids, prompt, topic, paper, ask, model, parallel,
4743
5070
  } else out[i] = { pmid, error: e instanceof Error ? e.message : String(e), cached: false };
4744
5071
  }
4745
5072
  note(out[i], Date.now() - t);
5073
+ done(out[i]);
4746
5074
  }
4747
5075
  };
4748
5076
  await Promise.all(Array.from({ length: Math.min(parallel, pmids.length) }, worker));
@@ -4759,20 +5087,20 @@ function score(s, types, queries, citesPerYear = 0, inReviews = 0) {
4759
5087
  return Math.round(level + rel + hard + size + Math.min(10, 2 * queries) + 20 * Math.log10(1 + citesPerYear) + 4 * Math.log2(1 + inReviews));
4760
5088
  }
4761
5089
  function screenLine(r, ms, model) {
4762
- const secs = `${(ms / 1e3).toFixed(1)}s`;
4763
- if (r.refused) return `refused screen ${model} ${secs}`;
4764
- 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}`;
4765
5093
  const f = r.screened;
4766
- 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}`;
4767
5095
  }
4768
5096
 
4769
5097
  // src/log.ts
4770
- 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";
4771
5099
  import { hostname } from "os";
4772
- 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";
4773
5101
  var HOST = hostname();
4774
- var LOG_DIR = join10(FH_EVIDENCE_DIR, "logs");
4775
- 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");
4776
5104
  function stamp() {
4777
5105
  const d = /* @__PURE__ */ new Date();
4778
5106
  const p = (n) => String(n).padStart(2, "0");
@@ -4785,15 +5113,15 @@ var stampOf = (t) => {
4785
5113
  return `${t.getFullYear()}-${p(t.getMonth() + 1)}-${p(t.getDate())}-${p(t.getHours())}${p(t.getMinutes())}${p(t.getSeconds())}`;
4786
5114
  };
4787
5115
  function datedName(file3, when) {
4788
- const base = join10(dirname5(file3), `${basename2(file3, ".log")}-${stampOf(when)}`);
5116
+ const base = join11(dirname5(file3), `${basename2(file3, ".log")}-${stampOf(when)}`);
4789
5117
  let name = `${base}.log`;
4790
- for (let n = 2; existsSync11(name); n++) name = `${base}-${n}.log`;
5118
+ for (let n = 2; existsSync12(name); n++) name = `${base}-${n}.log`;
4791
5119
  return name;
4792
5120
  }
4793
5121
  function rotateIfLarge(file3, max = LOG_MAX_BYTES, keepDays = num("FH_LOG_KEEP_DAYS", 7)) {
4794
5122
  let size = 0;
4795
5123
  try {
4796
- size = statSync2(file3).size;
5124
+ size = statSync3(file3).size;
4797
5125
  } catch {
4798
5126
  return false;
4799
5127
  }
@@ -4811,20 +5139,20 @@ function pruneLogs(file3, keepDays, now2 = Date.now()) {
4811
5139
  const dir = dirname5(file3), stem2 = basename2(file3, ".log");
4812
5140
  try {
4813
5141
  const old1 = `${file3}.1`;
4814
- if (existsSync11(old1)) renameSync4(old1, datedName(file3, statSync2(old1).mtime));
5142
+ if (existsSync12(old1)) renameSync4(old1, datedName(file3, statSync3(old1).mtime));
4815
5143
  for (const f of readdirSync3(dir)) {
4816
5144
  if (!f.startsWith(`${stem2}-`) || !f.endsWith(".log")) continue;
4817
- const path = join10(dir, f);
4818
- 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);
4819
5147
  }
4820
5148
  } catch {
4821
5149
  }
4822
5150
  }
4823
5151
  function migrateLogName(dir = FH_EVIDENCE_DIR) {
4824
- const logs = join10(dir, "logs");
5152
+ const logs = join11(dir, "logs");
4825
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"]]) {
4826
- const a = join10(dir, from), b = join10(logs, to);
4827
- if (existsSync11(a) && !existsSync11(b)) {
5154
+ const a = join11(dir, from), b = join11(logs, to);
5155
+ if (existsSync12(a) && !existsSync12(b)) {
4828
5156
  try {
4829
5157
  mkdirSync9(logs, { recursive: true });
4830
5158
  renameSync4(a, b);
@@ -4834,8 +5162,8 @@ function migrateLogName(dir = FH_EVIDENCE_DIR) {
4834
5162
  }
4835
5163
  }
4836
5164
  function log(tool, id, message) {
4837
- const clean2 = message.replace(/\x1b\[[0-9;]*m/g, "").replace(/\s*\n\s*/g, " | ").replace(/https:\/\//g, "");
4838
- 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}
4839
5167
  `;
4840
5168
  try {
4841
5169
  mkdirSync9(LOG_DIR, { recursive: true });
@@ -4928,16 +5256,16 @@ function inclusionCounts(refs) {
4928
5256
  }
4929
5257
 
4930
5258
  // src/evmapdb.ts
4931
- import { existsSync as existsSync12, mkdirSync as mkdirSync10 } from "fs";
5259
+ import { existsSync as existsSync13, mkdirSync as mkdirSync10 } from "fs";
4932
5260
  import { createRequire as createRequire2 } from "module";
4933
- import { join as join11 } from "path";
4934
- var LAYOUT = 3;
5261
+ import { join as join12 } from "path";
5262
+ var LAYOUT = 7;
4935
5263
  var DB_DIR = "evmap";
4936
5264
  var DB_NAME = "evmap.db";
4937
5265
  var require2 = createRequire2(import.meta.url);
4938
5266
  var SCHEMA_SQL = `
4939
5267
  CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT);
4940
- 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);
4941
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));
4942
5270
  CREATE INDEX IF NOT EXISTS query_hits_pmid ON query_hits (pmid);
4943
5271
  CREATE TABLE IF NOT EXISTS articles (
@@ -4945,6 +5273,9 @@ var SCHEMA_SQL = `
4945
5273
  found_by TEXT, added TEXT, queries INTEGER, reviews INTEGER, citations INTEGER,
4946
5274
  relevance TEXT, population TEXT, design TEXT, n INTEGER, outcome TEXT, finding TEXT, aspect TEXT, reason TEXT, error TEXT,
4947
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));
4948
5279
  CREATE TABLE IF NOT EXISTS runs (id INTEGER PRIMARY KEY, started TEXT, finished TEXT, state TEXT, error TEXT, report TEXT);
4949
5280
  CREATE VIEW IF NOT EXISTS evidence_map AS
4950
5281
  SELECT pmid, title, first_author, year, journal, types, score, pick, found_by, added, queries, reviews, citations,
@@ -4953,15 +5284,20 @@ var SCHEMA_SQL = `
4953
5284
  `;
4954
5285
  function openDb(dir, readonly = false) {
4955
5286
  const { DatabaseSync } = require2("node:sqlite");
4956
- const file3 = join11(dir, DB_DIR, DB_NAME);
5287
+ const file3 = join12(dir, DB_DIR, DB_NAME);
4957
5288
  if (readonly) {
4958
- if (!existsSync12(file3)) return null;
5289
+ if (!existsSync13(file3)) return null;
4959
5290
  return new DatabaseSync(file3, { readOnly: true });
4960
5291
  }
4961
- mkdirSync10(join11(dir, DB_DIR), { recursive: true });
5292
+ mkdirSync10(join12(dir, DB_DIR), { recursive: true });
4962
5293
  const db = new DatabaseSync(file3);
4963
5294
  db.exec("PRAGMA journal_mode = WAL;");
4964
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");
4965
5301
  db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES ('layout', ?)").run(String(LAYOUT));
4966
5302
  return db;
4967
5303
  }
@@ -4986,15 +5322,15 @@ function lastRun(db) {
4986
5322
 
4987
5323
  // src/rank.ts
4988
5324
  import Anthropic2 from "@anthropic-ai/sdk";
4989
- var rankCandidates = (env = process.env) => num("FH_EVMAP_RANK_CANDIDATES", 200, env, (n) => n >= 10 && n <= 1e3 && Number.isInteger(n));
4990
- var rankPicks = (env = process.env) => num("FH_EVMAP_RANK_PICKS", 50, env, (n) => n >= 5 && n <= 200 && Number.isInteger(n));
4991
- 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));
4992
5328
  var RANK_TIMEOUT_MS = 18e4;
4993
- 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) {
4994
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");
4995
- 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.
4996
-
4997
- ${list5}`;
5333
+ return template.split("{{topic}}").join(topic).split("{{count}}").join(String(rows.length)).split("{{picks}}").join(String(picks)).split(RANK_SLOT).join(list5);
4998
5334
  }
4999
5335
  var SCHEMA2 = { type: "object", properties: { picks: { type: "array", items: { type: "integer" } } }, required: ["picks"], additionalProperties: false };
5000
5336
  function parsePicks(text4, count) {
@@ -5009,8 +5345,8 @@ function parsePicks(text4, count) {
5009
5345
  }
5010
5346
  function rankFor(c, model, fetchImpl = fetch) {
5011
5347
  const at = where({ ...c, model });
5012
- return async (topic, rows, picks) => {
5013
- const prompt = rankPrompt(topic, rows, picks);
5348
+ return async (topic, rows, picks, template) => {
5349
+ const prompt = rankPrompt(topic, rows, picks, template);
5014
5350
  try {
5015
5351
  if (c.api === "anthropic") {
5016
5352
  const client = new Anthropic2({ apiKey: c.key, baseURL: c.url, maxRetries: 2, timeout: RANK_TIMEOUT_MS });
@@ -5032,101 +5368,137 @@ function rankFor(c, model, fetchImpl = fetch) {
5032
5368
  if (typeof content !== "string") throw new Error("no answer");
5033
5369
  return parsePicks(content, rows.length);
5034
5370
  } catch (e) {
5035
- 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" }));
5036
5372
  }
5037
5373
  };
5038
5374
  }
5039
- function rankConfig(env = process.env) {
5040
- const m = str("FH_EVMAP_RANK_MODEL", env);
5041
- if (/^(off|none|0|false)$/i.test(m)) return { ok: false, off: "FH_EVMAP_RANK_MODEL=off" };
5042
- const p = str("FH_EVMAP_RANK_PROVIDER", env).toLowerCase() || str("FH_EVMAP_SCREEN_PROVIDER", env).toLowerCase();
5043
- 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" };
5044
- 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` };
5045
- 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);
5046
5383
  const pick = (f) => {
5047
- 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];
5048
- 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}`];
5049
5386
  };
5050
5387
  const [key2, keyVar] = pick("API_KEY");
5051
5388
  const [url, urlVar] = pick("URL");
5052
- 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})` };
5053
5390
  const P = SCREEN_PROVIDERS[p];
5054
- 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 } };
5055
- const model = m || RANK_MODELS[p];
5056
- 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
+ }
5057
5423
  }
5058
5424
  function evmapModels(env = process.env) {
5059
5425
  const problems = [];
5060
5426
  const s = screenConfig(env);
5061
- if (!s.ok) problems.push(`evidence map screening: ${s.reason} \u2014 fh_create_evidence_map will refuse to run`);
5062
- 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`);
5063
5428
  if (s.ok) {
5064
5429
  const k = s.key;
5065
- const looks = k.startsWith("sk-ant-") ? "anthropic" : k.startsWith("AIza") || k.startsWith("AQ.") ? "google" : k.startsWith("sk-") ? "openai" : null;
5066
- 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)`);
5067
- }
5068
- let ranking;
5069
- const r = rankConfig(env);
5070
- if (r.ok) ranking = { provider: r.config.provider, model: r.model, url: r.config.url };
5071
- else {
5072
- ranking = { off: r.off };
5073
- 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)`);
5074
5432
  }
5075
- 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 };
5076
5443
  }
5077
5444
 
5078
5445
  // src/evidencemap.ts
5079
5446
  var evidenceMapEnabled = (env = process.env) => /^(true|1|yes|on)$/i.test(env.FH_EVMAP_ENABLED?.trim() ?? "");
5080
- 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));
5081
5450
  var maxResultsPerQuery = (env = process.env) => num("FH_EVMAP_MAX_RESULTS_PER_QUERY", 500, env, (n) => n >= 1 && n <= 1e3 && Number.isInteger(n));
5082
5451
  var SLOTS = ["{{topic}}", "{{article}}"];
5083
- 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";
5084
5453
  var live4 = (lib) => ({
5085
5454
  search: async (query2, max) => {
5086
- if (max > 200) return bigSearch(lib, query2, max);
5087
- const r = await searchArticles({ query: query2, max_results: max }, lib, void 0, max);
5088
- return r.ok ? { ok: true, total: r.result.total, rows: r.result.rows } : { ok: false, error: r.error };
5455
+ return bigSearch(lib, query2, max);
5089
5456
  },
5090
- 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] })),
5091
5458
  screener: (() => {
5092
5459
  const c = screenConfig();
5093
5460
  return c.ok ? { ok: true, ask: askFor(c), model: c.model, where: where(c) } : { ok: false, reason: c.reason };
5094
5461
  })(),
5095
5462
  paper: (pmid) => {
5096
5463
  const f = entryPaths(lib, "pmid", pmid).md;
5097
- return existsSync13(f) ? readFileSync9(f, "utf8") : null;
5464
+ return existsSync14(f) ? readFileSync10(f, "utf8") : null;
5098
5465
  },
5099
5466
  cites: (pmids) => citationCounts(pmids),
5100
5467
  refs: (reviews) => referencedPmids(reviews),
5101
- rank: (() => {
5468
+ ...(() => {
5102
5469
  const r = rankConfig();
5103
- 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 };
5104
5471
  })(),
5105
5472
  log: (id, message) => log("evmap", id, message)
5106
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
+ }
5107
5484
  async function bigSearch(lib, query2, max) {
5108
5485
  const q = normalizeQuery2({ query: query2, max_results: max }, max);
5109
5486
  if ("error" in q) return { ok: false, error: q.error };
5110
5487
  const file3 = searchFile(lib, searchKey2(q));
5111
- if (existsSync13(file3)) {
5488
+ if (existsSync14(file3)) {
5112
5489
  try {
5113
- const r = JSON.parse(readFileSync9(file3, "utf8"));
5114
- 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 };
5115
5492
  } catch {
5116
5493
  }
5117
5494
  }
5118
- const get5 = (url) => fetchText(url, { "User-Agent": "evidence-mcp", Accept: "application/json" });
5119
5495
  try {
5120
- const { total, ids } = parseEsearch(await get5(esearchUrl(q)));
5121
- const rows = [];
5122
- for (let i = 0; i < ids.length; i += 200) {
5123
- const chunk = ids.slice(i, i + 200);
5124
- rows.push(...parseEsummary(await get5(esummaryUrl(chunk)), chunk, lib));
5125
- }
5126
- 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() };
5127
5499
  try {
5128
5500
  mkdirSync11(dirname6(file3), { recursive: true });
5129
- writeAtomic(file3, JSON.stringify(result, null, 2) + "\n");
5501
+ writeAtomic(file3, JSON.stringify(result) + "\n");
5130
5502
  } catch {
5131
5503
  }
5132
5504
  return { ok: true, total, rows };
@@ -5141,36 +5513,63 @@ function csvCell(v) {
5141
5513
  var reviewCount = (env = process.env) => num("FH_EVMAP_CITATION_REVIEWS", 10, env, (n) => n >= 0 && n <= 50 && Number.isInteger(n));
5142
5514
  var maxFromReviews = (env = process.env) => num("FH_EVMAP_CITATION_MAX_ADDED", 300, env, (n) => n >= 0 && n <= 2e3 && Number.isInteger(n));
5143
5515
  var REVIEW = /meta-analy|systematic review/i;
5144
- 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) {
5145
5517
  const o = openEvid(lib, evid);
5146
5518
  if (!o.ok) return o;
5147
- 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;
5148
5522
  const missing = SLOTS.filter((p) => !screening.includes(p));
5149
- 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)` };
5150
5526
  const topic = o.metadata.topic;
5151
5527
  if (typeof topic !== "string" || !topic.trim()) return { ok: false, error: `${o.evid}: the metadata has no topic for {{topic}}` };
5152
5528
  const fresh = [...new Set(queries.map((q) => q.trim()).filter(Boolean))];
5153
5529
  if (!fresh.length) return { ok: false, error: "queries: at least one PubMed query" };
5154
- const max = maxQueries(env);
5155
- if (fresh.length > max) return { ok: false, error: `queries: ${fresh.length}, at most ${max} per call (FH_EVMAP_MAX_QUERIES); nothing ran` };
5156
5530
  const db = openDb(o.dir);
5157
5531
  const stored = storedQueries(db);
5158
- 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;
5159
5543
  const screener = deps.screener;
5160
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.` };
5161
5546
  const perQuery = maxResultsPerQuery(env);
5162
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
+ }));
5163
5562
  const papers = /* @__PURE__ */ new Map();
5164
5563
  const runs = [];
5564
+ let cachedCount = 0;
5165
5565
  for (const [i, query2] of qs.entries()) {
5166
- const r = await deps.search(query2, perQuery);
5566
+ const r = found[i];
5167
5567
  if (!r.ok) {
5168
5568
  runs.push({ query: query2, total: null, kept: 0, error: r.error });
5169
- deps.log(o.evid, `failed query ${i + 1}/${qs.length}: ${r.error} \xB7 ${query2}`);
5170
5569
  continue;
5171
5570
  }
5571
+ if (r.cached) cachedCount++;
5172
5572
  runs.push({ query: query2, total: r.total, kept: r.rows.length, hits: r.rows.map((row4) => String(row4[0])) });
5173
- deps.log(o.evid, `query ${i + 1}/${qs.length} total=${r.total} kept=${r.rows.length} \xB7 ${query2}`);
5174
5573
  for (const row4 of r.rows) {
5175
5574
  const pmid = String(row4[0]);
5176
5575
  const p = papers.get(pmid);
@@ -5178,28 +5577,50 @@ async function doResearch(lib, evid, queries, screeningArg, env = process.env, n
5178
5577
  if (!p.queries.includes(i)) p.queries.push(i);
5179
5578
  continue;
5180
5579
  }
5181
- 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] });
5182
5581
  }
5183
5582
  }
5583
+ deps.log(o.evid, `searched ${((Date.now() - tS) / 1e3).toFixed(1).padStart(4, "0")}s ${added.length} new, ${cachedCount} cached`);
5184
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.` };
5185
5585
  const storedArticles = db.prepare("SELECT pmid, title, first_author, year, journal, types, found_by, reviews FROM articles").all();
5186
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 } : {} });
5187
5587
  const ids = [...papers.keys()];
5188
5588
  const retracted = /* @__PURE__ */ new Set();
5189
5589
  let notFound = 0;
5190
- for (let k = 0; k < ids.length; k += MAX_PMIDS) {
5191
- for (const r of await deps.prefill(ids.slice(k, k + MAX_PMIDS))) {
5192
- if (r.retracted) retracted.add(r.pmid);
5193
- 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
+ }
5194
5615
  }
5195
- }
5616
+ }));
5196
5617
  const kept = ids.filter((id) => !retracted.has(id)).map((id) => papers.get(id));
5197
- 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`);
5198
5619
  const unique = (i) => kept.filter((p) => p.queries.length === 1 && p.queries[0] === i).length;
5199
5620
  const n = qs.length;
5200
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(",");
5201
5622
  const citesP = deps.cites(kept.map((p) => p.pmid)).then((c) => {
5202
- 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}` : ""}`);
5203
5624
  return c;
5204
5625
  }, (e) => ({ counts: /* @__PURE__ */ new Map(), failed: kept.length, error: String(e) }));
5205
5626
  let cites = /* @__PURE__ */ new Map();
@@ -5217,6 +5638,26 @@ async function doResearch(lib, evid, queries, screeningArg, env = process.env, n
5217
5638
  Publication types: ${papers.get(pmid).types ?? "none listed"}`;
5218
5639
  };
5219
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
+ };
5220
5661
  const order2 = kept.map((p) => p.pmid);
5221
5662
  const probe2 = order2.find((pmid) => deps.paper(pmid) !== null);
5222
5663
  const results2 = probe2 ? await screenAll(lib, [probe2], screening, topic, text4, screener.ask, model, 1, note) : [];
@@ -5226,7 +5667,9 @@ Publication types: ${papers.get(pmid).types ?? "none listed"}`;
5226
5667
  db.close();
5227
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).` };
5228
5669
  }
5229
- 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();
5230
5673
  const by = new Map(results2.map((r) => [r.pmid, r]));
5231
5674
  const counted = await citesP;
5232
5675
  cites = counted.counts;
@@ -5248,7 +5691,7 @@ Publication types: ${papers.get(pmid).types ?? "none listed"}`;
5248
5691
  for (let k = 0; k < fresh2.length; k += MAX_PMIDS) {
5249
5692
  for (const x of await deps.prefill(fresh2.slice(k, k + MAX_PMIDS))) {
5250
5693
  if (x.retracted || x.level === "not found" || papers.has(x.pmid)) continue;
5251
- 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: [] };
5252
5695
  papers.set(x.pmid, p);
5253
5696
  kept.push(p);
5254
5697
  fromReviews++;
@@ -5258,12 +5701,14 @@ Publication types: ${papers.get(pmid).types ?? "none listed"}`;
5258
5701
  const c = inc.get(p.pmid);
5259
5702
  if (c) p.reviews = c;
5260
5703
  }
5261
- const added = kept.slice(kept.length - fromReviews).map((p) => p.pmid);
5262
- deps.log(o.evid, `references reviews=${K} failed=${refsFailed} new=${fromReviews}`);
5263
- if (added.length) {
5264
- 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();
5265
5710
  for (const r2 of results2) by.set(r2.pmid, r2);
5266
- 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 }));
5267
5712
  for (const [k2, v] of more.counts) cites.set(k2, v);
5268
5713
  }
5269
5714
  scored = kept.map(scoreOf);
@@ -5274,17 +5719,20 @@ Publication types: ${papers.get(pmid).types ?? "none listed"}`;
5274
5719
  let rankRun = { off: true };
5275
5720
  if (deps.rank) {
5276
5721
  const t2 = Date.now();
5277
- 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];
5278
5726
  try {
5279
- 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);
5280
5728
  idx.slice(0, rankPicks(env)).forEach((i, k) => pick.set(top[i].p.pmid, k + 1));
5281
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))];
5282
5730
  rankRun = { model: deps.rank.model, candidates: top.length, picks: pick.size, seconds: Math.round((Date.now() - t2) / 1e3) };
5283
- 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}`);
5284
5732
  } catch (e) {
5285
5733
  const error = e instanceof Error ? e.message : String(e);
5286
5734
  rankRun = { model: deps.rank.model, error };
5287
- 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`);
5288
5736
  }
5289
5737
  }
5290
5738
  const lines = ranked.map(({ p, f, sc }) => row3(p, sc ?? "", pick.get(p.pmid) ?? "", signals(p), f));
@@ -5298,11 +5746,11 @@ Publication types: ${papers.get(pmid).types ?? "none listed"}`;
5298
5746
  db.exec("BEGIN");
5299
5747
  try {
5300
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");
5301
- 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");
5302
5750
  const hDel = db.prepare("DELETE FROM query_hits WHERE query_id = ?");
5303
5751
  const hIns = db.prepare("INSERT OR IGNORE INTO query_hits (query_id, pmid, rank) VALUES (?, ?, ?)");
5304
5752
  for (const r of runs) {
5305
- 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;
5306
5754
  if (r.hits) {
5307
5755
  hDel.run(id);
5308
5756
  r.hits.forEach((pmid, k) => hIns.run(id, pmid, k + 1));
@@ -5325,6 +5773,7 @@ Publication types: ${papers.get(pmid).types ?? "none listed"}`;
5325
5773
  meta.run("hash", hash);
5326
5774
  meta.run("model", model);
5327
5775
  meta.run("prompt", screening);
5776
+ meta.run("ranking", ranking);
5328
5777
  meta.run("topic", topic);
5329
5778
  meta.run("updated", finished);
5330
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 }));
@@ -5340,16 +5789,16 @@ Publication types: ${papers.get(pmid).types ?? "none listed"}`;
5340
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.` } : {};
5341
5790
  const failedQueries = runs.filter((r) => r.error).map((r) => ({ query: r.query, error: r.error }));
5342
5791
  const emptyQueries = runs.filter((r) => !r.error && r.total === 0).map((r) => r.query);
5343
- 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 } : {} };
5344
5793
  }
5345
5794
  var MAX_ROWS = 500;
5346
5795
  function getMap(lib, evid, opts = {}) {
5347
5796
  const o = openEvid(lib, evid);
5348
5797
  if (!o.ok) return o;
5349
5798
  const db = openDb(o.dir, true);
5350
- 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` };
5351
5800
  try {
5352
- 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"}` };
5353
5802
  const top = Math.min(MAX_ROWS, Math.max(1, Math.floor(opts.top ?? 50)));
5354
5803
  const rows = query(db, DEFAULT_SELECT, [], 0, top);
5355
5804
  return { ok: true, evid: o.evid, ...rows };
@@ -5357,18 +5806,41 @@ function getMap(lib, evid, opts = {}) {
5357
5806
  db.close();
5358
5807
  }
5359
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
+ }
5360
5832
 
5361
5833
  // src/stats.ts
5362
- import { mkdirSync as mkdirSync12, readdirSync as readdirSync4, readFileSync as readFileSync10, statSync as statSync3, unlinkSync as unlinkSync3 } from "fs";
5363
- 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";
5364
5836
  var HEARTBEAT_MS = 5 * 6e4;
5365
5837
  var STALE_MS = 20 * 6e4;
5366
5838
  var stats = null;
5367
5839
  var file2 = null;
5368
5840
  function startStats(pkg2, libraryDir = FH_EVIDENCE_DIR) {
5369
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 } };
5370
- file2 = join12(libraryDir, ".servers", `${HOST}-${process.pid}.json`);
5371
- sweep(join12(libraryDir, ".servers"));
5842
+ file2 = join13(libraryDir, ".servers", `${HOST}-${process.pid}.json`);
5843
+ sweep(join13(libraryDir, ".servers"));
5372
5844
  publish();
5373
5845
  setInterval(publish, HEARTBEAT_MS).unref();
5374
5846
  const stop = () => {
@@ -5391,9 +5863,9 @@ function sweep(dir, staleMs = STALE_MS) {
5391
5863
  }
5392
5864
  for (const name of names2) {
5393
5865
  if (!name.endsWith(".json")) continue;
5394
- const p = join12(dir, name);
5866
+ const p = join13(dir, name);
5395
5867
  try {
5396
- if (Date.now() - statSync3(p).mtimeMs > staleMs) {
5868
+ if (Date.now() - statSync4(p).mtimeMs > staleMs) {
5397
5869
  unlinkSync3(p);
5398
5870
  n++;
5399
5871
  }
@@ -5411,14 +5883,14 @@ var currentStats = () => stats;
5411
5883
  function publish() {
5412
5884
  if (!stats || !file2) return;
5413
5885
  try {
5414
- mkdirSync12(join12(file2, ".."), { recursive: true });
5886
+ mkdirSync12(join13(file2, ".."), { recursive: true });
5415
5887
  writeAtomic(file2, JSON.stringify(stats, null, 2) + "\n");
5416
5888
  } catch {
5417
5889
  }
5418
5890
  }
5419
5891
 
5420
5892
  // src/tools.ts
5421
- import { existsSync as existsSync21, readFileSync as readFileSync18 } from "fs";
5893
+ import { existsSync as existsSync24, readFileSync as readFileSync20 } from "fs";
5422
5894
  import { z } from "zod";
5423
5895
 
5424
5896
  // src/cascade.ts
@@ -5472,7 +5944,7 @@ async function fulltextCascade(p, attempts, onEvent, tiers = resolveTiers().tier
5472
5944
 
5473
5945
  // src/websearch.ts
5474
5946
  import { createHash as createHash6 } from "crypto";
5475
- 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";
5476
5948
  import { dirname as dirname7 } from "path";
5477
5949
  var COLUMNS4 = ["title", "url", "published", "author", "snippet"];
5478
5950
  var snippetsOn = (env = process.env) => !/^(off|false|no|0)$/i.test((env.FH_WEB_SEARCH_SNIPPETS ?? "").trim());
@@ -5487,9 +5959,7 @@ function cleanSnippet(t) {
5487
5959
  return cut.slice(0, Math.max(cut.lastIndexOf(" "), SNIPPET_CHARS - 40)).replace(/[,;:\s]+$/, "") + " \u2026";
5488
5960
  }
5489
5961
  var SEARCH_PROVIDERS = ["exa", "serper", "brave"];
5490
- var webSearchEnabled = (env = process.env) => /^(true|1|yes|on)$/i.test(env.FH_WEB_SEARCH_ENABLED?.trim() ?? "");
5491
5962
  function webSearchConfig(env = process.env) {
5492
- if (!webSearchEnabled(env)) return [];
5493
5963
  return SEARCH_PROVIDERS.flatMap((provider) => {
5494
5964
  const key2 = env[`FH_WEB_SEARCH_${provider.toUpperCase()}_API_KEY`]?.trim();
5495
5965
  return key2 ? [{ provider, key: key2 }] : [];
@@ -5588,17 +6058,17 @@ var SEARCH = {
5588
6058
  var inFlight = /* @__PURE__ */ new Map();
5589
6059
  function oneProvider(q, cfg, libraryDir, post2, onEvent) {
5590
6060
  const file3 = searchFile(libraryDir, searchKey3(q, cfg.provider));
5591
- const running = inFlight.get(file3);
5592
- if (running) return running;
6061
+ const running2 = inFlight.get(file3);
6062
+ if (running2) return running2;
5593
6063
  const p = askProvider(q, cfg, libraryDir, post2, onEvent).finally(() => inFlight.delete(file3));
5594
6064
  inFlight.set(file3, p);
5595
6065
  return p;
5596
6066
  }
5597
6067
  async function askProvider(q, cfg, libraryDir, post2, onEvent) {
5598
6068
  const file3 = searchFile(libraryDir, searchKey3(q, cfg.provider));
5599
- if (existsSync14(file3)) {
6069
+ if (existsSync15(file3)) {
5600
6070
  try {
5601
- const r = JSON.parse(readFileSync11(file3, "utf8"));
6071
+ const r = JSON.parse(readFileSync12(file3, "utf8"));
5602
6072
  if (daysSince(r.searched) < searchCacheDays()) return { rows: r.rows, cached: true };
5603
6073
  } catch {
5604
6074
  }
@@ -5659,13 +6129,13 @@ async function webSearch(raw, libraryDir = FH_EVIDENCE_DIR, post2 = live5, cfgs
5659
6129
  }
5660
6130
 
5661
6131
  // src/info.ts
5662
- import { existsSync as existsSync15, readdirSync as readdirSync5, readFileSync as readFileSync12, statSync as statSync4 } from "fs";
5663
- 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";
5664
6134
  function* metaFiles(dir) {
5665
- if (!existsSync15(dir)) return;
6135
+ if (!existsSync16(dir)) return;
5666
6136
  for (const name of readdirSync5(dir)) {
5667
- const p = join13(dir, name);
5668
- if (statSync4(p).isDirectory()) yield* metaFiles(p);
6137
+ const p = join14(dir, name);
6138
+ if (statSync5(p).isDirectory()) yield* metaFiles(p);
5669
6139
  else if (name.endsWith("-meta.md")) yield p;
5670
6140
  }
5671
6141
  }
@@ -5682,6 +6152,17 @@ function field(md, key2) {
5682
6152
  const m = new RegExp(`^${key2}:\\s*(.*)$`, "m").exec(md);
5683
6153
  return m ? m[1].trim() : "";
5684
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
+ }
5685
6166
  function libraryInfo(libraryDir, host3, tiers = resolveTiers()) {
5686
6167
  const info = {
5687
6168
  evidence_dir: libraryDir,
@@ -5690,6 +6171,7 @@ function libraryInfo(libraryDir, host3, tiers = resolveTiers()) {
5690
6171
  config: { ...settings(), problems: [...tiers.problems, ...verifyProblems(), ...evidenceMapEnabled() ? evmapModels().problems : []], sources: sources() },
5691
6172
  download: downloadInfo(),
5692
6173
  verify: verifyInfo(),
6174
+ ...evidEnabled() ? { evid: evidCounts(libraryDir) } : {},
5693
6175
  ...evidenceMapEnabled() ? { evidence_map: evmapModels().models } : {},
5694
6176
  ...webSearchConfigured() ? { web_search: webSearchConfig().map((c) => c.provider) } : {},
5695
6177
  unlockers: unlockers().map((provider) => ({ provider })),
@@ -5706,11 +6188,11 @@ function libraryInfo(libraryDir, host3, tiers = resolveTiers()) {
5706
6188
  concerns: 0,
5707
6189
  updates: 0
5708
6190
  };
5709
- for (const type of existsSync15(libraryDir) ? readdirSync5(libraryDir) : []) {
5710
- const typeDir = join13(libraryDir, type);
5711
- 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;
5712
6194
  for (const meta of metaFiles(typeDir)) {
5713
- const md = readFileSync12(meta, "utf8");
6195
+ const md = readFileSync13(meta, "utf8");
5714
6196
  const raw = field(md, "level") || "unknown";
5715
6197
  const level = raw === "abstract" && field(md, "has_abstract") === "no" ? "title" : raw;
5716
6198
  info.entries++;
@@ -5723,7 +6205,7 @@ function libraryInfo(libraryDir, host3, tiers = resolveTiers()) {
5723
6205
  const dir = dirname8(meta);
5724
6206
  for (const f of readdirSync5(dir)) {
5725
6207
  try {
5726
- const st = statSync4(join13(dir, f));
6208
+ const st = statSync5(join14(dir, f));
5727
6209
  if (st.isFile()) info.size_bytes += st.size;
5728
6210
  } catch {
5729
6211
  }
@@ -5750,7 +6232,7 @@ function noticeTypes(md, metaPath) {
5750
6232
  return out;
5751
6233
  }
5752
6234
  try {
5753
- const xml = readFileSync12(metaPath.replace(/-meta\.md$/, "-abstract.xml"), "utf8");
6235
+ const xml = readFileSync13(metaPath.replace(/-meta\.md$/, "-abstract.xml"), "utf8");
5754
6236
  for (const m of xml.matchAll(/<CommentsCorrections RefType="([A-Za-z]+)"/g)) if (XML_TYPES[m[1]]) out.add(XML_TYPES[m[1]]);
5755
6237
  } catch {
5756
6238
  }
@@ -5913,9 +6395,9 @@ function parseCrossref(json2) {
5913
6395
  }
5914
6396
  function fromInvertedIndex(index) {
5915
6397
  if (!index) return "";
5916
- const words3 = [];
5917
- for (const [w, ps] of Object.entries(index)) for (const p of ps) words3[p] = w;
5918
- 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();
5919
6401
  }
5920
6402
  async function openAlexAbstract(doi) {
5921
6403
  try {
@@ -5967,8 +6449,8 @@ function parseCsl(json2) {
5967
6449
 
5968
6450
  // src/urlfetch.ts
5969
6451
  import { createHash as createHash7 } from "crypto";
5970
- import { existsSync as existsSync16, mkdirSync as mkdirSync14, readFileSync as readFileSync13 } from "fs";
5971
- 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";
5972
6454
 
5973
6455
  // src/pagemeta.ts
5974
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)$/;
@@ -6108,8 +6590,8 @@ var urlHash = (normalized2) => createHash7("sha1").update(normalized2).digest("h
6108
6590
  function urlPaths(libraryDir, normalized2) {
6109
6591
  const hash = urlHash(normalized2);
6110
6592
  const entry = `url-${hash}`;
6111
- const entryDir = join14(libraryDir, "url", hash.slice(0, 2), hash.slice(0, 4), hash);
6112
- 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}`) };
6113
6595
  }
6114
6596
  function renderUrlMeta(m) {
6115
6597
  const lines = [
@@ -6131,8 +6613,8 @@ function renderUrlMeta(m) {
6131
6613
  return lines.map(([k, v]) => `${k}: ${v}`).join("\n") + "\n";
6132
6614
  }
6133
6615
  function readUrlMeta(p) {
6134
- if (!existsSync16(p.meta)) return null;
6135
- const md = readFileSync13(p.meta, "utf8");
6616
+ if (!existsSync17(p.meta)) return null;
6617
+ const md = readFileSync14(p.meta, "utf8");
6136
6618
  const f = (k) => {
6137
6619
  const m = new RegExp(`^${k}:[ \\t]*(.*)$`, "m").exec(md);
6138
6620
  return m ? m[1].trim() : "";
@@ -6175,8 +6657,8 @@ var EMPTY_WORDS = 10;
6175
6657
  var SHELL_PHRASE = /\bloading\b|javascript|enable it|connecting to|please wait|redirecting/i;
6176
6658
  function isScriptShell(markdownOrHtml) {
6177
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, ")");
6178
- const words3 = text4.split(/\s+/).filter((w) => /[\p{L}\p{N}]/u.test(w)).length;
6179
- 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 };
6180
6662
  }
6181
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;
6182
6664
  async function stage(url, via, signal) {
@@ -6216,14 +6698,14 @@ var climb = async (given, onTry, onAlert) => {
6216
6698
  }
6217
6699
  return g;
6218
6700
  };
6219
- const write = (line) => onTry?.(line);
6701
+ const write2 = (line) => onTry?.(line);
6220
6702
  const run = (target2, via, name, after) => {
6221
6703
  let req = null;
6222
6704
  return {
6223
6705
  name,
6224
6706
  abort: (why) => req?.abort(why),
6225
6707
  go: async () => {
6226
- req = openRequest(write, name);
6708
+ req = openRequest(write2, name);
6227
6709
  const g = await stage(target2, via, req.signal);
6228
6710
  if (req.signal.aborted) return { ok: false, reason: "aborted", via: name };
6229
6711
  seen2(g);
@@ -6264,9 +6746,9 @@ var climb = async (given, onTry, onAlert) => {
6264
6746
  const notThere = () => gone ? { ...r, ok: false, reason: gone, via: r.via } : null;
6265
6747
  if (gone) return { ...notThere(), first: gone };
6266
6748
  if (escalates(r)) {
6267
- const open = browserStages().filter((b) => !skipped(target, stageName(b)));
6268
- const down = await Promise.all(open.map((b) => hostDown(b.host, b.port, stageName(b))));
6269
- 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)));
6270
6752
  const two = await firstOk(tasks, isGone);
6271
6753
  if (two.won) return two.won;
6272
6754
  if (two.results.length) r = two.results.filter(Boolean).pop();
@@ -6302,8 +6784,8 @@ var decode2 = (s) => s.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (m, e) => {
6302
6784
  });
6303
6785
  var visibleText = (html) => decode2(html.replace(/<[^>]+>/g, " ")).replace(/\s+/g, " ").replace(/¶\s*$/, "").trim();
6304
6786
  var normalized = (text4) => {
6305
- const words3 = text4.toLowerCase().match(/[\p{L}\p{N}]+/gu);
6306
- return words3 ? ` ${words3.join(" ")} ` : "";
6787
+ const words4 = text4.toLowerCase().match(/[\p{L}\p{N}]+/gu);
6788
+ return words4 ? ` ${words4.join(" ")} ` : "";
6307
6789
  };
6308
6790
  function pageTitle(html) {
6309
6791
  const head = html.slice(0, 2e5);
@@ -6446,14 +6928,14 @@ function titleLine(m, md) {
6446
6928
  }
6447
6929
  function serve(requested, p, m, args, cached) {
6448
6930
  const maxLength = args.max_length ?? 5e3, startIndex = args.start_index ?? 0;
6449
- const read2 = (file3) => existsSync16(file3) ? readFileSync13(file3, "utf8") : "";
6931
+ const read2 = (file3) => existsSync17(file3) ? readFileSync14(file3, "utf8") : "";
6450
6932
  if (args.title_only) return { ok: true, text: `Contents of ${requested}:
6451
6933
  ${titleLine(m, read2(p.md))}`, cached, meta: m };
6452
6934
  const rawFile = m.files.find((f) => !f.endsWith("-meta.md") && !f.endsWith("-page.md"));
6453
6935
  let body, prefix = "";
6454
6936
  if (m.format === "markdown") body = read2(p.md);
6455
6937
  else if (m.format === "text" || args.raw) {
6456
- body = rawFile ? read2(join14(p.entryDir, rawFile)) : read2(p.md);
6938
+ body = rawFile ? read2(join15(p.entryDir, rawFile)) : read2(p.md);
6457
6939
  prefix = `Content type ${m.content_type || "(not declared)"} cannot be simplified to markdown, but here is the raw content:
6458
6940
  `;
6459
6941
  } else body = read2(p.md);
@@ -6471,9 +6953,9 @@ async function libraryFetch(libraryDir, requested, args, converter, logs = {}, f
6471
6953
  let stored = readUrlMeta(p);
6472
6954
  if (stored && fresh(stored) && stored.format === "html" && olderConverter(stored.converted_by, converter)) {
6473
6955
  const html = stored.files.find((f) => f.endsWith("-page.html"));
6474
- if (html && existsSync16(join14(p.entryDir, html))) {
6956
+ if (html && existsSync17(join15(p.entryDir, html))) {
6475
6957
  try {
6476
- 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);
6477
6959
  if (page.md !== null) {
6478
6960
  writeAtomic(p.md, page.md);
6479
6961
  writeUrlMeta(p, { ...stored, title: page.title, converted_by: converter, ...sourceFields(page) });
@@ -6517,11 +6999,11 @@ async function libraryFetch(libraryDir, requested, args, converter, logs = {}, f
6517
6999
 
6518
7000
  // src/verify/cache.ts
6519
7001
  import { createHash as createHash8 } from "crypto";
6520
- import { existsSync as existsSync18, mkdirSync as mkdirSync15, readFileSync as readFileSync15 } from "fs";
6521
- 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";
6522
7004
 
6523
7005
  // src/verify/verify.ts
6524
- import { existsSync as existsSync17, readFileSync as readFileSync14 } from "fs";
7006
+ import { existsSync as existsSync18, readFileSync as readFileSync15 } from "fs";
6525
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.";
6526
7008
  function cleanMarkdown(md) {
6527
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");
@@ -6625,16 +7107,16 @@ async function readPaper(raw, libraryDir = FH_EVIDENCE_DIR) {
6625
7107
  if (p.error) return { id: p.requested, error: p.error };
6626
7108
  const paths = entryPaths(libraryDir, p.type, p.id);
6627
7109
  if (!entryExists(paths)) return { id: p.requested, error: "not in library" };
6628
- const full = existsSync17(paths.fulltextMd);
6629
- 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") };
6630
7112
  const meta = readMeta(paths);
6631
- 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") };
6632
7114
  }
6633
7115
  async function verifyClaim(claim, id, cfg, decide, read2 = readPaper) {
6634
7116
  const out = { claim, id, verdict: "error", reason: null, score: null, basis: null, windows: 0, glyphs_unresolved: 0, superseded: null, model: cfg?.model ?? null };
6635
- const words3 = claim.trim().split(/\s+/).filter(Boolean).length;
6636
- if (!words3) return { ...out, error: "claim empty" };
6637
- 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" };
6638
7120
  const frag = fragment(claim);
6639
7121
  if (frag) return { ...out, error: frag };
6640
7122
  const groups = citationGroups(claim);
@@ -6680,11 +7162,11 @@ ${id}
6680
7162
  ${model}
6681
7163
  ${threshold}
6682
7164
  ${text4}`).slice(0, 16);
6683
- 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`);
6684
7166
  function readVerdict(file3) {
6685
- if (!existsSync18(file3)) return null;
7167
+ if (!existsSync19(file3)) return null;
6686
7168
  try {
6687
- return JSON.parse(readFileSync15(file3, "utf8"));
7169
+ return JSON.parse(readFileSync16(file3, "utf8"));
6688
7170
  } catch {
6689
7171
  return null;
6690
7172
  }
@@ -6716,7 +7198,7 @@ async function verifyCached(claim, id, cfg, decide, libraryDir = FH_EVIDENCE_DIR
6716
7198
 
6717
7199
  // src/dailymedsearch.ts
6718
7200
  import { createHash as createHash9 } from "crypto";
6719
- 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";
6720
7202
  import { dirname as dirname10 } from "path";
6721
7203
  var MAX_RESULTS3 = 100;
6722
7204
  var DEFAULT_RESULTS3 = 20;
@@ -6766,9 +7248,9 @@ async function searchLabels(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = live6
6766
7248
  const q = normalizeQuery4(raw);
6767
7249
  if ("error" in q) return { ok: false, error: q.error, input: true };
6768
7250
  const file3 = searchFile(libraryDir, searchKey4(q));
6769
- if (existsSync19(file3)) {
7251
+ if (existsSync20(file3)) {
6770
7252
  try {
6771
- const r = JSON.parse(readFileSync16(file3, "utf8"));
7253
+ const r = JSON.parse(readFileSync17(file3, "utf8"));
6772
7254
  if (daysSince(r.searched) < searchCacheDays()) return { ok: true, result: { ...r, rows: r.rows.map((row3) => {
6773
7255
  const c = [...row3];
6774
7256
  c[5] = levelOf2(row3[0], libraryDir);
@@ -6794,13 +7276,12 @@ async function searchLabels(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = live6
6794
7276
 
6795
7277
  // src/citations.ts
6796
7278
  import { createHash as createHash10 } from "crypto";
6797
- 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";
6798
7280
  import { dirname as dirname11 } from "path";
6799
7281
  var MAX_RESULTS4 = 100;
6800
7282
  var DEFAULT_RESULTS4 = 20;
6801
7283
  var PAGE = 200;
6802
7284
  var MAX_PAGES = 50;
6803
- var citationsEnabled = (env = process.env) => /^(true|1|yes|on)$/i.test(env.FH_CITATIONS_ENABLED?.trim() ?? "");
6804
7285
  var ALIAS = { rct: "randomized controlled trial", "systematic-review": "systematic review" };
6805
7286
  var norm2 = (t) => {
6806
7287
  const s = t.toLowerCase().replace(/[-_\s]+/g, " ").trim();
@@ -6852,9 +7333,9 @@ async function citingArticles(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = liv
6852
7333
  const q = normalizeQuery5(raw);
6853
7334
  if ("error" in q) return { ok: false, error: q.error, input: true };
6854
7335
  const file3 = searchFile(libraryDir, searchKey5(q));
6855
- if (existsSync20(file3)) {
7336
+ if (existsSync21(file3)) {
6856
7337
  try {
6857
- const r = JSON.parse(readFileSync17(file3, "utf8"));
7338
+ const r = JSON.parse(readFileSync18(file3, "utf8"));
6858
7339
  if (daysSince(r.searched) < searchCacheDays()) return { ok: true, result: r, cached: true };
6859
7340
  } catch {
6860
7341
  }
@@ -7028,10 +7509,491 @@ function resultsText(nct, md, maxChars) {
7028
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 };
7029
7510
  }
7030
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
+
7031
7993
  // src/tools.ts
7032
7994
  var pkg = (() => {
7033
7995
  try {
7034
- 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"));
7035
7997
  } catch {
7036
7998
  return { name: "evidence-mcp", version: "0.0.0" };
7037
7999
  }
@@ -7047,10 +8009,10 @@ A URL is no ID: send the ID of a PubMed, doi.org, ClinicalTrials.gov or DailyMed
7047
8009
 
7048
8010
  Tools
7049
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?).
7050
- - 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)" : ""}.
7051
8013
  - Trials: fh_clinicaltrials_get_study_record, fh_clinicaltrials_get_study_results.
7052
8014
  - Web: fh_fetch_url, for every URL that is not an article, label or trial record.
7053
- ${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.
7054
8016
 
7055
8017
  Rules
7056
8018
  - fh_library_read and fh_verify_claim store a missing record themselves (added: true); no fh_library_add first.
@@ -7418,13 +8380,13 @@ function registerTools(server2) {
7418
8380
  }
7419
8381
  added = true;
7420
8382
  }
7421
- const stored = existsSync21(paths.fulltextMd);
7422
- if (abstractOnly && !existsSync21(paths.md)) {
8383
+ const stored = existsSync24(paths.fulltextMd);
8384
+ if (abstractOnly && !existsSync24(paths.md)) {
7423
8385
  log("read", parsed.requested, "error abstract only: no abstract stored");
7424
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" : ""}` });
7425
8387
  }
7426
8388
  const full = stored && !abstractOnly;
7427
- const md = readFileSync18(full ? paths.fulltextMd : paths.md, "utf8");
8389
+ const md = readFileSync20(full ? paths.fulltextMd : paths.md, "utf8");
7428
8390
  const text4 = full ? "full_text" : "abstract";
7429
8391
  const more = abstractOnly ? stored ? { fulltext: "stored" } : untried(paths) ? { fulltext: "not tried" } : {} : {};
7430
8392
  const base = { requested: parsed.requested, entry: paths.entry, text: text4, ...more, ...added ? { added: true } : {} };
@@ -7445,8 +8407,8 @@ function registerTools(server2) {
7445
8407
  const cap = max_chars ?? 6e3;
7446
8408
  let sec = readSection(md, section2, cap);
7447
8409
  let via = "";
7448
- if (!sec && /abstract/i.test(section2) && full && existsSync21(paths.md)) {
7449
- 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);
7450
8412
  via = " (from the abstract file)";
7451
8413
  }
7452
8414
  if (!sec && /declaration/i.test(section2)) {
@@ -7517,7 +8479,7 @@ ${st.funding.map((f) => `- ${f}`).join("\n")}` : ""].filter(Boolean).join("\n\n"
7517
8479
  );
7518
8480
  server2.tool(
7519
8481
  "fh_info",
7520
- `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).`,
7521
8483
  {},
7522
8484
  async () => {
7523
8485
  const info = libraryInfo(FH_EVIDENCE_DIR, HOST);
@@ -7581,8 +8543,8 @@ ${st.funding.map((f) => `- ${f}`).join("\n")}` : ""].filter(Boolean).join("\n\n"
7581
8543
  return { content: [{ type: "text", text: `Failed to fetch ${url}: ${added.error}` }], isError: true };
7582
8544
  }
7583
8545
  }
7584
- const file3 = pid.type === "pmid" ? paths.md : existsSync21(paths.fulltextMd) ? paths.fulltextMd : paths.md;
7585
- 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") : "";
7586
8548
  const text4 = title_only ? `Contents of ${url}:
7587
8549
  ${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "", max_length, start_index);
7588
8550
  bump("fetch", had);
@@ -7641,8 +8603,8 @@ ${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "
7641
8603
  return { content: [{ type: "text", text: searchAnswer(r.result) }] };
7642
8604
  }
7643
8605
  );
7644
- if (citationsEnabled()) server2.tool(
7645
- "fh_pubmed_citing_articles",
8606
+ server2.tool(
8607
+ "fh_citing_articles",
7646
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.
7647
8609
  - types: PubMed publication types, any of them; an article without one (many plain articles, some guidelines) never matches.
7648
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.
@@ -7744,46 +8706,144 @@ Citations from OpenAlex. Cached ${searchCacheDays()} days.`,
7744
8706
  );
7745
8707
  }
7746
8708
  if (evidenceMapEnabled()) server2.tool(
7747
- "fh_create_evidence_map",
7748
- "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.`,
7749
8711
  {
7750
8712
  topic: z.string().optional().describe('A topic, e.g. "Telmisartan for Health & Longevity".'),
7751
- evid: z.string().optional().describe('Instead of topic: an existing EVID with "topic" in its metadata.'),
7752
- 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])".`),
7753
- 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.')
7754
8714
  },
7755
- 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 } : {} });
7756
8717
  if (!topic === !evidArg) {
7757
8718
  log("evmap", evidArg ?? null, "error topic or evid, one of them");
7758
- 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);
7759
8720
  }
7760
- let evid = evidArg ?? "";
8721
+ let evid = evidArg ?? "", name = topic?.trim() ?? "";
7761
8722
  if (topic) {
7762
- const c = createEvid(FH_EVIDENCE_DIR, { topic: topic.trim() });
7763
- 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);
7764
8725
  evid = c.evid;
7765
- 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" });
7766
8743
  }
7767
- const r = await doResearch(FH_EVIDENCE_DIR, evid, queries, screening);
7768
- 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}`);
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" });
8763
+ }
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}`);
7769
8775
  const { ok, ...rest } = r;
7770
8776
  return { content: [{ type: "text", text: compact2(rest) }], ...ok ? {} : { isError: true } };
7771
8777
  }
7772
8778
  );
7773
8779
  if (evidenceMapEnabled()) server2.tool(
7774
- "fh_get_evidence_map",
7775
- "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.",
7776
8782
  {
7777
8783
  evid: z.string().describe("The EVID."),
7778
- 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.")
7779
8788
  },
7780
- async ({ evid, top }) => {
7781
- const r = getMap(FH_EVIDENCE_DIR, evid, { top });
7782
- 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}`);
7783
8792
  const { ok, ...rest } = r;
7784
8793
  return { content: [{ type: "text", text: compact2(rest) }], ...ok ? {} : { isError: true } };
7785
8794
  }
7786
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
+ );
7787
8847
  server2.tool(
7788
8848
  "fh_clinicaltrials_search_studies",
7789
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.`,
@@ -7878,7 +8938,7 @@ Citations from OpenAlex. Cached ${searchCacheDays()} days.`,
7878
8938
  return { content: [{ type: "text", text: compact2({ error: e.error }) }], isError: true };
7879
8939
  }
7880
8940
  const raw = e.paths.fulltextRaw("json");
7881
- const r = existsSync21(raw) ? recordSummary(readFileSync18(raw, "utf8")) : null;
8941
+ const r = existsSync24(raw) ? recordSummary(readFileSync20(raw, "utf8")) : null;
7882
8942
  if (!r) {
7883
8943
  log("trials", e.requested, "record error: no stored record");
7884
8944
  return { content: [{ type: "text", text: compact2({ error: "no stored record" }) }], isError: true };
@@ -7897,7 +8957,7 @@ Citations from OpenAlex. Cached ${searchCacheDays()} days.`,
7897
8957
  log("trials", nct, `results error: ${e.error}`);
7898
8958
  return { content: [{ type: "text", text: compact2({ error: e.error }) }], isError: true };
7899
8959
  }
7900
- const md = existsSync21(e.paths.fulltextMd) ? readFileSync18(e.paths.fulltextMd, "utf8") : "";
8960
+ const md = existsSync24(e.paths.fulltextMd) ? readFileSync20(e.paths.fulltextMd, "utf8") : "";
7901
8961
  const r = resultsText(e.requested.replace(/^nct:/, "NCT"), md, max_chars);
7902
8962
  log("trials", e.requested, `results ${r.has_results ? `${r.outcomes.length} outcomes${r.truncated ? " truncated" : ""}` : "none"}`);
7903
8963
  return { content: [{ type: "text", text: leanJson(r) }] };
@@ -7908,9 +8968,6 @@ Citations from OpenAlex. Cached ${searchCacheDays()} days.`,
7908
8968
  // src/devfeatures.ts
7909
8969
  function devFeatures(env = process.env) {
7910
8970
  const out = [];
7911
- const web = webSearchConfig(env);
7912
- if (web.length) out.push("FH_WEB_SEARCH_ENABLED");
7913
- if (citationsEnabled(env)) out.push("FH_CITATIONS_ENABLED");
7914
8971
  if (evidEnabled(env)) out.push("FH_EVID_ENABLED");
7915
8972
  if (evidenceMapEnabled(env)) out.push("FH_EVMAP_ENABLED");
7916
8973
  return out;