@ysgao/web-cli 0.0.0-stage → 0.1.3

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.
@@ -0,0 +1,834 @@
1
+ ---
2
+ name: web-cli
3
+ description: >
4
+ How to drive `web-cli`, the self-discovering search/retrieval CLI for subscription
5
+ medical-knowledge sites (UpToDate, ClinicalKey) and any other registered site (e.g. a Google
6
+ Programmable Search Engine). Covers the three-tier replay/discovery model, when a query needs
7
+ `login` first, when to fall back to `observe`, how to read a site's error whose message contains
8
+ `chrome-profile.lock`/`EPERM` (a sandbox filesystem denial blocking tier-2 discovery for a site
9
+ with no cached endpoint yet — not that site's API or subscription being broken), the per-site
10
+ `parsed` output (read `references/parsed-output.md` instead of hand-rolling your own parsing of
11
+ a site's raw JSON — every `parsed.hits[]` entry is guaranteed a title and a real, absolute,
12
+ clickable url, e.g. UpToDate's article text living only inside HTML that `parsed.text` already
13
+ strips, or ClinicalKey's search hits carrying no URL field at all in the raw response, which
14
+ `parsed.hits[].url` fixes by constructing ClinicalKey's real article URL from its id), why
15
+ `search` deliberately does NOT fetch full text for every hit (cheap title/url/year/source come
16
+ free for the whole hit list; only a small percentage-based `keyReferences` selection costs an
17
+ extra fetch — see the "keyReferences" section), that `web-cli` itself never reads or answers a
18
+ question — it only retrieves, so after a `search` you must read the retrieved `keyReferences`
19
+ full text yourself and write the actual prose answer, citing sources, rather than relaying the
20
+ JSON/its `summary` field and calling that done (see "After `search` returns" section), that
21
+ `search`/`finalize` auto-detect JSON vs. a HUMAN-READABLE report from whether stdout is a real
22
+ terminal (an agent's own command-execution mechanism gets JSON automatically, no flag needed;
23
+ pass `--json` explicitly for certainty, or if generating a standalone JSON file use `render-markdown`/`--out` — see "`--json`/`--pretty`" section), and —
24
+ critically — when NOT to trust a subscription clinical site's search results at all: UpToDate and
25
+ ClinicalKey are practice-medicine resources, not anatomical/terminological references, and
26
+ silently autocorrect or drop unfamiliar terms. Use this whenever you're about to run `web-cli
27
+ search`/`get`/`login`/`observe`, whenever a site's result contains an unexpected `error`/`code`
28
+ field, or whenever a query is about a specific anatomical structure, layer, or historical/Latin
29
+ anatomical synonym — in which case read `references/anatomy-lookup.md` and check FMA /
30
+ Terminologia Anatomica directly rather than relying on a `web-cli search` of a clinical site
31
+ alone.
32
+ ---
33
+
34
+ # web-cli
35
+
36
+ `web-cli` searches and retrieves content from subscription medical-knowledge sites by discovering
37
+ their REST APIs at runtime, reusing your own logged-in session in a dedicated Chrome profile. Every
38
+ command's failure path is the same JSON envelope on stderr (`{"error", "code"}`) — there is no
39
+ interactive UI to drive. On success, every command except `search`/`finalize` always prints one
40
+ JSON document to stdout, no exceptions.
41
+
42
+ **`search` and `finalize` are different: they can ALSO print a human-readable report instead of
43
+ JSON.** Which one prints by default is auto-detected per invocation from `process.stdout.isTTY` —
44
+ a real, interactive terminal (a human typing the command) gets the readable report; anything else
45
+ (an AI agent's own command-execution mechanism, a shell redirect, a pipe) gets the JSON envelope
46
+ **automatically, with no flag needed**. Confirmed empirically from inside a harness's own exec
47
+ tool: `process.stdout.isTTY` reports `undefined` there (not a terminal) — exactly the signal this
48
+ auto-detection reads, so the common case of an agent driving this CLI already gets JSON by
49
+ default. `agentTask`, `keyReferences[].article.text`, `summary`, `usedCount`,
50
+ `unmatchedAnswerUrls`, and `unverifiedQuotes` — everything the rest of this document tells you to
51
+ read — only exist in that JSON, never in the human-readable text. **Still pass `--json` explicitly
52
+ when you want certainty regardless of environment** (some execution mechanisms might allocate a
53
+ real pty to a subprocess, in which case auto-detection would otherwise pick the readable report) —
54
+ it's a harmless, portable way to guarantee JSON rather than relying on the auto-detected default.
55
+ `--pretty` is the inverse override, for forcing the readable report even when stdout isn't a
56
+ terminal. See "`--json`/`--pretty`" below for the full rationale.
57
+
58
+ `search` additionally writes plain-text progress lines to stderr as it runs (which sites are being
59
+ searched, each one finishing/failing, a final totals line) — see "Reading a `search` result" below;
60
+ these are for a human watching the terminal and are never part of the JSON, so don't parse them
61
+ either.
62
+
63
+ **If you (or whatever harness is running this command for you) capture stdout+stderr merged
64
+ together, or your captured output ever gets wrapped with extra framing** (a command echo, a
65
+ per-line log prefix, a trailing "exit code"/"EXIT:0" marker appended after the process exits) —
66
+ **pass `--out [path]` instead of relying on parsing captured terminal output at all.** It writes
67
+ the exact same object `--json` would print directly to a standalone `.json` file via this
68
+ process's own filesystem call, immune to anything added around a captured stdout transcript by
69
+ whatever ran this command; the file's path comes back as `outPath`, and the file's entire content
70
+ is plain, standard `JSON.parse`-able JSON with nothing else in it — no need to scan the file's head
71
+ for where the real JSON actually starts. See "Writing JSON output to disk (`--out`)" below.
72
+
73
+ Run with no arguments (or `--help`) to see the full current command list; that is the source of
74
+ truth over anything below.
75
+
76
+ ## Commands
77
+
78
+ ```
79
+ web-cli auth status [--site <site>]
80
+ web-cli login <site> [--durationSeconds 90]
81
+ web-cli search "<query>" [--site <site>]... [--allow-visible-login] [--disable-login-recovery] [--loginTimeoutSeconds 240] [--markdown [path]] [--out [path]] [--json] [--pretty]
82
+ web-cli get <site> <idOrUrl> [--allow-visible-login] [--disable-login-recovery] [--loginTimeoutSeconds 240]
83
+ web-cli websearch "<query>" [--engine google|bing|gemini] [--model <model>] [--maxResults <n>] [--fallbackWaitSeconds <n>] # general open-web search, google->bing->gemini chain
84
+ web-cli weather <location> # current conditions + 3-day forecast via wttr.in, no API key — ALWAYS use this for weather, never websearch
85
+ web-cli observe --site <site> --intent <search|getArticle> --param "<value>" [--durationSeconds 120]
86
+ web-cli learned [--site <site>]
87
+ web-cli finalize [--markdown [path]] [--json] [--pretty] # reads {query, finalAnswer, summary?, keyReferences, answers} as JSON on stdin
88
+ web-cli render-markdown [--from <path>] [--markdown [path]] [--json] # renders a Markdown report from an ALREADY-RETRIEVED search result -- zero network calls, see its own section below
89
+ ```
90
+
91
+ ### `--json`/`--pretty`: auto-detected by default, these are the explicit overrides
92
+
93
+ `search`/`finalize` auto-detect JSON vs. the human-readable report from `process.stdout.isTTY` — a
94
+ real terminal gets the readable report, anything else (including how you, as an agent, invoke this
95
+ command) gets JSON automatically. **You still don't need to think hard about this: passing
96
+ `--json` explicitly is always a safe, portable choice** that guarantees JSON regardless of exactly
97
+ how your own execution mechanism attaches stdout — cheap insurance against the one edge case
98
+ auto-detection can't resolve on its own (a mechanism that happens to allocate a real pty to its
99
+ subprocess). `--pretty` is the inverse override (forces the readable report even off a terminal);
100
+ passing both together is a usage error (`INVALID_ARGUMENT`).
101
+
102
+ ```bash
103
+ web-cli search "myocardial infarction" # as an agent: already JSON, automatically
104
+ web-cli search "myocardial infarction" --json # same result, guaranteed regardless of environment
105
+ web-cli search "myocardial infarction" --pretty # force the human report even though stdout isn't a terminal
106
+ ```
107
+
108
+ Every JSON field this document describes below — `agentTask`, `sites`, `keyReferences`, `summary`,
109
+ and everything `finalize` returns — exists ONLY in the JSON output, never the human-readable
110
+ report. The readable report is a real, complete artifact in its own right (title/url/snippet/status
111
+ for `search`, the full final-answer-with-quotes report for `finalize`) — it is not "broken" or
112
+ "less informative" if that's what you end up with, it simply has nothing in it your own
113
+ code/parsing can reliably extract, which is why explicit `--json` remains the unambiguous choice
114
+ whenever you're not certain which mode you'd otherwise get.
115
+
116
+ `search` ALWAYS covers `uptodate`, `clinicalkey`, and `googlemedsearch` — the login-gated/
117
+ medically-scoped subscription sites this CLI is actually built around; there is no other,
118
+ general-purpose site set it falls back to. `web-cli` has no judgment of its own to decide whether a
119
+ query is actually about medicine/anatomy/substances/organisms, so **that call is yours: only run
120
+ `search` for queries that actually are** — the three sites are pure overhead (possibly including an
121
+ interactive sign-in) on anything else. `--site` (repeatable) adds a site *beyond* that base set.
122
+ `get` is unaffected and still takes exactly one `<site>`, since fetching a specific article only
123
+ ever makes sense against the one site that has it.
124
+
125
+ **For a genuinely open-ended/general query — anything outside medicine/anatomy/substances/
126
+ organisms — use `web-cli websearch "<query>"` instead of forcing it through `search`.** This is
127
+ not just a recommendation: `search` has no general-purpose site to fall back to at all anymore, so
128
+ running a non-medical query through it will just waste time against three sites with nothing
129
+ relevant to say.
130
+
131
+ **Exception: for ANY weather query, use `web-cli weather <location>` instead of `websearch`
132
+ (regardless of which `--engine` you'd otherwise pick) — never route a weather question through
133
+ general/open-web search at all.** This is a dedicated, no-API-key/no-billing command backed by
134
+ wttr.in that actually geocodes `location` (confirmed live, correctly resolving "Manchester" to
135
+ Manchester, Greater Manchester, UK — see `src/weather/wttr.ts`) and returns real current
136
+ conditions plus a forecast (`{query, location, region, country, current: {...}, forecast: [{date,
137
+ minTempC, maxTempC, hourly: [...]}, ...]}`, 3 days: today + 2 more) — where BOTH `websearch`
138
+ engines demonstrably fail this specific kind of query (see each one's own confirmed-live example
139
+ below). `location` is a place name only, never a relative date phrase like "this weekend"/"this
140
+ Friday" — wttr.in has no way to interpret those; compute the actual date yourself and compare it
141
+ against each returned `forecast[].date`, and say so plainly if the date asked about falls outside
142
+ the 3 days returned (there is no way to get further ahead without a paid API this command
143
+ deliberately doesn't integrate — see that module's own doc comment).
144
+
145
+ For every other kind of genuinely open-ended/general query, `websearch` is not restricted to any
146
+ fixed site/domain list. Three engines are CHAINED together via `--engine` (default `google`), so
147
+ no single one is a hard dependency for this to return something usable:
148
+
149
+ ```
150
+ --engine google (default) --fails--> bing --fails--> gemini
151
+ --engine bing --fails--> gemini
152
+ --engine gemini (no further fallback)
153
+ ```
154
+
155
+ The result's own `"engine"` field always reports which engine actually answered (NOT necessarily
156
+ the one requested/defaulted into); a `"fallback"` array is present whenever at least one earlier
157
+ engine in the chain was tried and failed first — one entry per failed engine, in order, each with
158
+ its own `{from, reason}` — so you can always tell what happened, not just what you got back.
159
+
160
+ - **`google` (the default)**: drives web-cli's own automation Chrome (the same launch/kill
161
+ machinery `search`/`get`/`login`/`observe` use, via a completely separate CDP connection of its
162
+ own — see `src/search/googleSearch.ts`'s own doc comment; this never touches
163
+ `discovery/cdpSession.ts` or otherwise affects the subscription-site discovery path) against
164
+ `www.google.com/search` directly — no API key or billing, and (confirmed live, real, checked-in
165
+ fixture — see that module's own doc comment) genuinely relevant results, not geo-biased noise.
166
+ Confirmed live: a plain headless attempt alone is NOT reliable — Google answers either with a
167
+ hard IP-reputation CAPTCHA (`/sorry/index`, "unusual traffic from your computer network") or a
168
+ softer, very common cookie-consent interstitial ("Before you continue to Google…"), and a full
169
+ JS-executing headless browser does not bypass either on its own. So: if a headless attempt
170
+ returns nothing, this **opens a REAL, VISIBLE Chrome window** (same pattern as `web-cli login`)
171
+ for `--fallbackWaitSeconds` (default 90) so a human can actually resolve it by hand, explicitly
172
+ captures whatever cookies that produced, and retries headless with them already injected —
173
+ meaning it can take anywhere from a few seconds (headless succeeds outright, the common case
174
+ once this has been resolved once against this profile — cookies persist) up to
175
+ `--fallbackWaitSeconds` plus a few seconds. Only if THAT retry is still blocked does this move on
176
+ to `bing` next, rather than throwing.
177
+ - **`bing`**: no API key or billing at all — scrapes Bing's own HTML search results page directly
178
+ and returns a plain `hits: [{title, url, snippet}, ...]` list (same shape as a `search` site's
179
+ own `parsed.hits`) — unsynthesized, since nothing here has read the linked pages. Confirmed live
180
+ to actually work (Google's own results page and DuckDuckGo's HTML endpoint both refused a plain
181
+ scripted request when this was tested — see `src/search/bingSearch.ts`'s own doc comment for the
182
+ full comparison), but it is HTML-scraping a search engine's results page, not a documented/
183
+ stable API: markup drift or bot-detection can break or block it at any time with no notice, and
184
+ automated scraping may run against that engine's own Terms of Service. It's also geo-biased
185
+ toward wherever the request actually originates from, confirmed live: a "weather in Manchester
186
+ this weekend" query returned Herefordshire results, not Manchester — exactly the query type the
187
+ dedicated `web-cli weather <location>` command above exists for instead. If bing ALSO fails
188
+ (whether reached via `google`'s own fallback or requested directly), this moves on to `gemini`
189
+ next.
190
+ - **`gemini`**: hands the query to Gemini's own Google Search grounding tool and returns one
191
+ synthesized answer directly (`answer` instead of `hits` in the result — no separate
192
+ full-text-reading step to do here, the answer text itself is the whole result). Requires
193
+ `GEMINI_API_KEY` or `GOOGLE_API_KEY` to be configured (see the package's own README's "API keys"
194
+ section) and is subject to that key's own Gemini API quota — exactly why it sits at the END of
195
+ the chain rather than being tried first, and has no further engine to fall back to itself: with
196
+ no key configured, reaching `gemini` at the end of the chain still ends the whole call in a
197
+ thrown `CliError`, same as requesting it directly would.
198
+
199
+ If the whole chain doesn't work for you (no Gemini key configured AND both `google`/`bing` are
200
+ blocked/broken), or you already have your own general web-search tool available (e.g.
201
+ `WebSearch`/`web_search`), use whichever is actually available to you.
202
+
203
+ ## After `search` returns: your job is to answer the question, not relay the JSON
204
+
205
+ **`web-cli` has no LLM in it at all — it only retrieves.** Its `summary` field is a coverage/volume
206
+ digest (how many sites answered, how many hits, how many key references got full text — see
207
+ "`summary`" below), not an answer to whatever the person actually asked. Handing back the raw JSON,
208
+ or a restatement of `summary`, is not the deliverable when a person asked a substantive question —
209
+ reading the retrieved content and answering it is a step *you* do, every time, not something the
210
+ CLI does for you and not something to skip because the JSON "looks complete."
211
+
212
+ ### `agentTask`: the same instruction, reprinted in every result so it can't be missed
213
+
214
+ Every `search` result also carries a top-level `agentTask` field — `{"question": "<the exact
215
+ query you passed>", "instructions": "<what to do with it>"}`. This exists because a rule read once
216
+ from a skill doc at session start is easy to forget by the time a tool result actually lands
217
+ several turns later; `agentTask` puts the same expectation directly in the data itself, every
218
+ single time, next to the material to satisfy it from:
219
+
220
+ ```json
221
+ {
222
+ "agentTask": {
223
+ "question": "is finger the same as digit of the hand",
224
+ "instructions": "Answer the question above using the material already retrieved into \"keyReferences\" — do not just relay this JSON, \"summary\", or a list of titles as if that were the answer. For each \"keyReferences\" entry that has \"article.text\": read it and decide whether it actually helps answer the question. If it does, cite it (its \"url\") in your answer. If it does not, treat it as irrelevant to this question — leave it out of your answer entirely, rather than citing it just because it was fetched. ..."
225
+ }
226
+ }
227
+ ```
228
+
229
+ **"Treat it as irrelevant" means leave it out of *your answer*** — `web-cli` never deletes or
230
+ hides a `keyReferences` entry based on relevance (it has no way to judge that, and doing so would
231
+ throw away data already paid for with a real network fetch, possibly useful for a different
232
+ follow-up question later). The full, unfiltered list is always still there in `keyReferences`;
233
+ `agentTask` only ever tells you what to do with it, never mutates it.
234
+
235
+ Concretely, after a `search` whose result you intend to answer a question from:
236
+
237
+ 1. **Read `keyReferences` first** (see below) — these are the hits already judged worth a
238
+ full-text fetch. Read each entry's `article.text` where present; where it isn't
239
+ (`fetchError`/`fullTextUnparsed` — see `summary.keyReferences`), fall back to that entry's own
240
+ `snippet` rather than skipping it.
241
+ 2. **Skim titles/snippets across every site's `parsed.hits`** for anything clearly relevant that
242
+ the 20%-capped `keyReferences` selection didn't happen to include — that selection is a
243
+ defensible default ranking, not proof nothing else in the hit list matters.
244
+ 3. **Write an actual prose answer to the person's question**, citing the specific `url` from the
245
+ `keyReferences`/hit entry that backs each claim — see "keyReferences" below for the exact
246
+ citation convention. Counts, titles, or a coverage summary are not a substitute for this.
247
+ 4. **If the query touches anatomical terminology**, cross-check against FMA/Terminologia Anatomica
248
+ (`references/anatomy-lookup.md`) before treating a clinical site's search as authoritative for
249
+ it — see "don't trust a single site's silence" below.
250
+
251
+ Doing this by hand every time (rather than automating it into `search` itself) is deliberate:
252
+ automating it would mean wiring an LLM call into the CLI's own process — a real architectural
253
+ change (a new dependency, an API key to manage, a per-call cost) this project doesn't make; see
254
+ `CLAUDE.md`. This four-step read is the actual last step of using this tool, not an optional
255
+ afterthought — but `web-cli finalize` (next) is a genuinely optional fifth step for turning that
256
+ reading into its own polished artifact.
257
+
258
+ ### `agentTask.unrecoveredFailures`: a failed source, named in the data, so it can't be swapped out silently
259
+
260
+ `agentTask` gains a second field, **only when at least one site or `keyReferences` entry actually
261
+ failed** (commonly `SESSION_EXPIRED` — see "Sessions" above — after `web-cli`'s own default silent
262
+ recovery already ran and did not succeed):
263
+
264
+ ```json
265
+ {
266
+ "agentTask": {
267
+ "question": "...",
268
+ "instructions": "... IMPORTANT: \"unrecoveredFailures\" lists 1 source that did NOT come back ... Never silently substitute another site's results or any previously-cached/saved data in their place ...",
269
+ "unrecoveredFailures": [
270
+ {
271
+ "scope": "site",
272
+ "site": "clinicalkey",
273
+ "code": "SESSION_EXPIRED",
274
+ "error": "no cookies for clinicalkey",
275
+ "recommendedAction": "The silent, credential-based session refresh for \"clinicalkey\" already ran and did not recover — do not retry the same call expecting a different result. Tell the user to run \"web-cli login clinicalkey --save-credentials\" once so every future run recovers silently with no human needed, or re-run with --allow-visible-login if a human can sign in right now. Never substitute another site's results, a previously-saved file, or any other data in place of this one without saying so."
276
+ }
277
+ ]
278
+ }
279
+ }
280
+ ```
281
+
282
+ This is the **data-backed, code-enforced form** of this skill's own "A `SESSION_EXPIRED` you
283
+ actually receive must never be silently worked around" rule above — present in every result,
284
+ regardless of whether you happen to still recall that rule from reading this doc at session start.
285
+ It cannot force what you write in your own final answer (this CLI has no visibility into, or
286
+ control over, anything that happens after it exits — there is no LLM inside it at all, see
287
+ `CLAUDE.md`), but it does guarantee the failure and its concrete fix travel with the result itself
288
+ rather than depending on you remembering a rule from a separate document. Each entry has:
289
+
290
+ - `scope`: `"site"` (a whole site's search failed — see `sites.<site>.error`) or `"keyReference"`
291
+ (one selected hit's full-text fetch failed — see `keyReferences[].fetchError`); a `"keyReference"`
292
+ entry also carries that hit's own `title`/`url` so it's identifiable without cross-referencing.
293
+ - `code`/`error`: the exact same values already on `sites.<site>`/`keyReferences[].fetchError` —
294
+ repeated here so this list is self-contained.
295
+ - `recommendedAction`: the concrete next step for `code` — for `SESSION_EXPIRED`, naming
296
+ `web-cli login <site> --save-credentials` (silent, no human needed on every future run) or
297
+ `--allow-visible-login` (a human signs in now); for `DISCOVERY_FAILED`/`ARTICLE_MISMATCH`, the
298
+ `web-cli observe` re-learning step; for `PAYWALLED`, a plain statement that there is nothing to
299
+ retry. An unrecognized code still gets an explicit "state this plainly, don't drop it" fallback
300
+ rather than silence.
301
+
302
+ **Absent entirely (not an empty array) when nothing failed** — same "presence is the signal"
303
+ convention as `markdownPath`/`outPath`'s own error siblings — so `"unrecoveredFailures" in
304
+ agentTask` is itself a reliable one-line check for "did everything come back clean."
305
+
306
+ ### `web-cli finalize`: turn your reading into a curated report (optional fifth step)
307
+
308
+ Once you've done the four-step read above, you can hand your own conclusions back to `web-cli` and
309
+ get a report organized around the ANSWER — not around "everything that happened to get fetched."
310
+ Pipe JSON on **stdin** (the only command in this package that reads stdin rather than flags):
311
+
312
+ ```bash
313
+ echo '{
314
+ "query": "is finger the same as digit of the hand",
315
+ "finalAnswer": "Yes — FMA lists Finger as the preferred name with Digit of hand as a direct synonym; same structure, different register.",
316
+ "summary": { /* optional: the exact "summary" field from the search result, for a coverage recap */ },
317
+ "keyReferences": [ /* the exact keyReferences array from the search result */ ],
318
+ "answers": [
319
+ {
320
+ "url": "https://www.uptodate.com/contents/...",
321
+ "quote": "a verbatim excerpt from THAT reference's own article.text (or snippet) — the evidence",
322
+ "summary": "Your own take on what this source says in answer to the question, in your words — not a re-quote."
323
+ }
324
+ ]
325
+ }' | web-cli finalize --json --markdown
326
+ ```
327
+
328
+ (`--json` here for the same reason as `search`: `usedCount`/`unmatchedAnswerUrls`/`unverifiedQuotes`
329
+ only exist in the JSON envelope, not in the human-readable report text `finalize` prints without it.)
330
+
331
+ - **`finalAnswer` is required** — your own overall synthesized answer to `query`, drawn from every
332
+ entry in `answers`. It's rendered first, ahead of any per-source detail, because that's what a
333
+ reader actually came here for.
334
+ - If you pass through the original search result's own `summary` field, a "Search coverage"
335
+ section (sites/hits/key-reference counts) renders right after `finalAnswer`, for context.
336
+ - Every `keyReferences` entry you name in `answers` (matched by its exact `url`) gets its own
337
+ section under "Sources", with **your** `quote` and `summary` — never the raw snippet, never the
338
+ full article text. You already read the full text; `quote` is the evidence, `summary` is what
339
+ you concluded from it.
340
+ - **`quote` is required and mechanically checked**: it must be a verbatim excerpt of that
341
+ reference's own `article.text` (or `snippet` if there's no full text) — `web-cli` checks this
342
+ itself (a plain substring test, whitespace-normalized; no LLM needed for it) and flags a quote
343
+ that doesn't actually appear in the retrieved text, both inline in the report and in the
344
+ result's `unverifiedQuotes` array. This exists specifically to catch a summary that isn't
345
+ actually grounded in what was retrieved — don't paraphrase into `quote`, and don't reuse the
346
+ same quote for an unrelated claim just to pass the check.
347
+ - Every `keyReferences` entry you do NOT name in `answers` is treated as fetched-but-not-relevant
348
+ to this question: left out of "Sources", but never deleted — it still appears, unused, in a
349
+ closing "All retrieved sources" list, so nothing you fetched vanishes without a trace, and a
350
+ later follow-up question can still find it.
351
+ - Without `--json`, `finalize` prints the rendered report as plain text (mentioning where a
352
+ `--markdown` file was saved, or that you can pass `--markdown` to get one, right in that text
353
+ since there's no JSON for that to live in). **With `--json`**, you get the same report in a
354
+ `report` field, plus `usedCount`/`notUsedCount`, and — worth checking — `unmatchedAnswerUrls`
355
+ (a non-empty one means an `answers[].url` didn't match anything in `keyReferences` at all,
356
+ almost always a typo on your side) and `unverifiedQuotes` (see the `quote` bullet above).
357
+ `--markdown [path]` independently writes the report to disk either way (same convention as
358
+ `search --markdown` — off by default, a write failure reported as `markdownError`/on stderr
359
+ rather than losing the report).
360
+ - This step is entirely optional. Skipping it just means your answer to the person lives only in
361
+ your own chat response, the way it always has — `finalize` exists for when a durable, curated
362
+ artifact (a file someone can reopen later) is actually wanted.
363
+
364
+ Known sites are registered in the CLI itself (currently `uptodate`, `clinicalkey`, and
365
+ `googlemedsearch` — a Google Programmable Search Engine used as a broad medical-web fallback);
366
+ run `web-cli auth status` with no `--site` to see every registered site and whether a session
367
+ exists for it.
368
+
369
+ ### Sessions: `search` recovers expired logins by itself, silently, by default — no flag needed
370
+
371
+ **Read this before running `search` unattended** (which, as an AI agent, is almost always how you
372
+ run it). **By default, if a site's session has expired, `search`/`get` try a quick, SILENT,
373
+ credential-based refresh — a real, visible browser window is NEVER opened unless you explicitly
374
+ ask for one.** You do not need to run `web-cli login` first, and you should not treat
375
+ `SESSION_EXPIRED` as something to pre-empt.
376
+
377
+ - **The default behavior (no flag at all) is exactly what you want as an unattended agent.** If a
378
+ credential was saved for the site beforehand (`web-cli login <site> --save-credentials`), a
379
+ quick, silent, headless refresh using that credential runs automatically and needs no human at
380
+ all, typically recovering the session in a few seconds with no window shown. If nothing is
381
+ saved, this is a cheap no-op (no browser launched at all) and the command reports
382
+ `SESSION_EXPIRED` right away — no wasted wait either way. Concretely: a run that ends up with
383
+ `SESSION_EXPIRED` means either nobody has ever run `web-cli login <site> --save-credentials` for
384
+ that site, or the saved credential itself no longer works (password changed, account locked, a
385
+ CAPTCHA/2FA page the auto-fill heuristic can't get past) — not "you forgot a flag."
386
+ - **`--allow-visible-login` opts IN to the older, human-friendly convenience**: if the silent
387
+ refresh above doesn't recover the session, open a real, visible window and wait for a human to
388
+ sign in (up to `--loginTimeoutSeconds`, default **240s**). Pass this only when you know a human
389
+ is actually watching and able to act on a window that appears — otherwise this just means the
390
+ command can sit waiting for a sign-in that will never happen. As an unattended agent, you should
391
+ essentially never need this flag.
392
+ - **`--disable-login-recovery` is a DIFFERENT, stricter, rarely-needed flag.** It disables session
393
+ recovery entirely: not even the default silent, credential-based refresh is attempted, and zero
394
+ browser processes (not even headless) are ever launched. Use it only when you know the
395
+ environment genuinely cannot tolerate ANY browser automation attempt at all (a sandbox that
396
+ denies launching even a headless Chrome process — see the `chrome-profile.lock` EPERM case
397
+ below). Reaching for this by habit instead of just letting the default run loses the one
398
+ recovery path that needs no human at all, which is almost always the wrong tradeoff for an
399
+ agent that already has a saved credential to work with. If both flags are passed together,
400
+ `--disable-login-recovery` wins (it is the strict superset — nothing is attempted either way).
401
+ - **If you want every future unattended run of this CLI to recover a site's expired session with
402
+ no human involved at all**, tell a human to run `web-cli login <site> --save-credentials` once,
403
+ interactively, to save that site's username/password — after that, the default behavior recovers
404
+ that site silently with zero flags needed on every later call.
405
+ - **If a human is available and you want the old interactive convenience**, pass
406
+ `--allow-visible-login`, or tell them to run `web-cli login <site>` once beforehand. A visible
407
+ window needs an actual human sign-in; it will not complete on its own.
408
+
409
+ ### A `SESSION_EXPIRED` you actually receive must never be silently worked around
410
+
411
+ By the time `SESSION_EXPIRED` reaches you in a result, the CLI itself has **already** tried the
412
+ default, no-human-needed recovery (the silent credential-based refresh above) and it did not
413
+ succeed — this is not a transient blip to quietly paper over, and it is not your call to decide
414
+ it "doesn't matter" because other sites or cached data happened to cover the gap. **This exact
415
+ rule is also enforced in the data itself**, not just in this prose — see
416
+ `agentTask.unrecoveredFailures` further below, which `search` populates automatically whenever
417
+ this happens, naming the failed source and its concrete fix directly in the JSON you read.
418
+ Concretely, when you see it (on a whole site's `sites.<site>.error`, or on one
419
+ `keyReferences[].fetchError`, or — the hard-to-miss form — listed in
420
+ `agentTask.unrecoveredFailures`):
421
+
422
+ 1. **Say so, plainly, in your answer** — e.g. "ClinicalKey's session had expired and couldn't be
423
+ refreshed automatically, so its results/full text aren't included below." Never produce an
424
+ answer that reads as complete (or quietly leans on `googlemedsearch`/a previously-saved file/
425
+ another site's hits instead) without disclosing that a specific source actually failed and why.
426
+ Reusing an old result file (from an earlier `search --out`, or anything else already sitting on
427
+ disk) as a stand-in for a source that just failed is exactly the kind of silent substitution
428
+ this rule forbids — stale cached data is not a substitute for a disclosed failure, and
429
+ presenting it as if it were fresh is worse than just saying the fetch failed.
430
+ 2. **Don't just retry the identical call hoping it works differently** — the silent phase already
431
+ ran and failed once; calling `search`/`get` again with no new flag will almost certainly repeat
432
+ the same `SESSION_EXPIRED`, burning time without starting a session.
433
+ 3. **Take (or ask for) one of the concrete, documented recovery actions instead**, matching your
434
+ situation:
435
+ - A human is present and can act now → re-run with `--allow-visible-login` so a real sign-in
436
+ window opens or re-check the one that's already open, or just prompt them to run
437
+ `web-cli login <site>` directly, then retry.
438
+ - No human is present (the common unattended-agent case) → check whether a credential was ever
439
+ saved for that site. If you don't know, tell the person a credential needs to be saved once
440
+ (`web-cli login <site> --save-credentials`) so every future run recovers silently with zero
441
+ flags — this is the fix that actually starts a new, durable session rather than working
442
+ around the missing one. If a credential WAS saved and this still failed, say that explicitly
443
+ too (password changed / account locked / a CAPTCHA the auto-fill heuristic can't clear) —
444
+ don't guess silently and move on.
445
+ - If only one `keyReferences` entry failed while the rest of that site's search worked, you can
446
+ retry just that one item after recovery (`web-cli get <site> <its url>`) rather than
447
+ re-running the whole `search`.
448
+ 4. **A site/entry failing this way never blocks you from reporting what every other source did
449
+ return** — see the next section. The requirement here is disclosure and an attempt at real
450
+ recovery for the part that failed, not blocking everything else on it.
451
+
452
+ `web-cli auth status` reports whether cookies exist, but note that **cookies existing is not the
453
+ same as being signed in** — ClinicalKey in particular hands out an anonymous session that satisfies
454
+ search while still refusing full text. So a nonempty `auth status` does not guarantee full-text
455
+ access; the authoritative check is whether the call you actually need succeeds. `auth status` also
456
+ has no way to tell you whether a credential is saved for silent recovery — there is currently no
457
+ read command for that; the only way to find out is to try a search (with no flags — this is simply
458
+ the default) and see whether `SESSION_EXPIRED` appears (in which case either nothing is saved, or
459
+ the saved one no longer works).
460
+
461
+ A site missing a session never fails the whole `search` call — see "reading a `search` result"
462
+ below.
463
+
464
+ ### Reading a `search` result: per-site outcomes, not one flat list
465
+
466
+ Everything below assumes you passed `--json` (see above) — without it, this is prose text, not the
467
+ object this section describes. `search --json` queries every site concurrently and returns
468
+ `{"query": ..., "sites": {"<site>": {...}, ...}}` — one entry per site searched (the 3 defaults,
469
+ plus anything passed via `--site`), each independently either:
470
+
471
+ - `{"discovered": true|false, "results": ..., "parsed": ...}` — that site's normal result.
472
+ `discovered` tells you which of the three-tier model's stages produced `results` (see below);
473
+ `parsed` is a normalized extraction of `results` — see "Parsed output" below, and prefer it over
474
+ hand-parsing `results` yourself. This per-site entry is deliberately cheap: it never triggers an
475
+ extra network call beyond the one search itself — see `keyReferences` (top-level, not nested per
476
+ site) for the small subset of hits that get a full-text fetch.
477
+ - `{"error": "...", "code": "..."}` — that one site failed (commonly `SESSION_EXPIRED` — see
478
+ above — or `DISCOVERY_FAILED`); the *other* sites' entries are still real, usable results. A
479
+ `SESSION_EXPIRED` here is NOT just another field to note and move past — see "A `SESSION_EXPIRED`
480
+ you actually receive must never be silently worked around" above for what you must actually do
481
+ with it before writing your answer.
482
+
483
+ The command itself only fails (exit non-zero, `SEARCH_FAILED`) when every site failed — a mix of
484
+ some-succeeded/some-failed is a normal exit-0 result, so check each site's entry rather than
485
+ assuming a successful exit means every site returned data.
486
+
487
+ A `keyReferences` entry with a `fetchError` instead of an `article` is worth reading precisely: the
488
+ hit itself is real and citable (title/url/snippet are present), only its full text is missing.
489
+ `SESSION_EXPIRED` there means signed in but not entitled to that specific item — same disclose-and-
490
+ recover rule as above applies, it just applies to one entry rather than the whole site;
491
+ `DISCOVERY_FAILED`
492
+ means that site's article endpoint needs re-learning via `observe`; **`ARTICLE_MISMATCH`** means the
493
+ fetch technically succeeded but came back with a DIFFERENT article than the one this entry is
494
+ about — confirmed live (not hypothetical): a stale/mismatched `getArticle` endpoint template can
495
+ silently serve whatever topic it was last learned against, with no transport-level error at all, so
496
+ a mismatch is caught by cross-checking the response's own claimed id against the id actually
497
+ requested and deliberately never kept as `article` (an entry with the wrong content is worse than
498
+ no content — it can't be mistaken for a real answer). If you see this, the fix is the same as
499
+ `DISCOVERY_FAILED`: `web-cli observe --site <site> --intent getArticle --param "<a real article for
500
+ that site>"` to relearn a correct template.
501
+
502
+ ### `summary`: coverage and volume at a glance, without walking `sites`/`keyReferences` yourself
503
+
504
+ Every `search` result also carries a top-level `summary` field — a small, pre-computed digest of
505
+ exactly the two questions `sites`/`keyReferences` otherwise make you re-derive by hand: **which
506
+ sites actually came back**, and **how much did they return**. Example:
507
+
508
+ ```json
509
+ {
510
+ "sitesRequested": ["uptodate", "clinicalkey", "googlemedsearch"],
511
+ "sitesSucceeded": ["uptodate", "clinicalkey", "googlemedsearch"],
512
+ "sitesFailed": [],
513
+ "hitsBySite": { "uptodate": 12, "clinicalkey": 40, "googlemedsearch": 8 },
514
+ "totalHits": 60,
515
+ "keyReferences": { "selected": 8, "fullTextFetched": 7, "fullTextFailed": 1, "fullTextUnparsed": 0 }
516
+ }
517
+ ```
518
+
519
+ Read this first when you just need "did it work and how much did I get" — `sitesFailed` being
520
+ non-empty is the coverage check (compare its length against `sitesRequested`'s to see if it was
521
+ every site or just some), `totalHits`/`hitsBySite` is the volume check, and
522
+ `keyReferences.fullTextFetched` vs `.selected` tells you how many of the selected references
523
+ actually came back with readable text without checking each entry's `.article`/`.fetchError`
524
+ yourself. It never replaces `sites`/`keyReferences` — those still carry the actual data — `summary`
525
+ is purely a derived convenience on top of them.
526
+
527
+ A site missing from `hitsBySite` entirely means it's in `sitesFailed` (a failed site never produced
528
+ hits to count). A site present in `hitsBySite` with a value of `null` (rather than `0`) means it
529
+ succeeded but its raw response didn't match that site's parser — a parsing gap, not evidence of an
530
+ empty result set; don't read `null` as zero. `keyReferences.fullTextUnparsed` is the same distinction
531
+ applied to a `keyReferences` entry: its `getArticle` fetch succeeded (no `fetchError`) but the
532
+ response wasn't recognized (no `article` either) — rare, but real, and distinct from a fetch that
533
+ outright failed.
534
+
535
+ ### Progress on stderr while `search` is still running
536
+
537
+ Because `search` can legitimately take minutes (an interactive login, a tier-2 discovery pass) and
538
+ prints its one JSON document only at the very end, `search` also writes plain-text lines to stderr
539
+ as it goes — useful for a human watching, never meant to be parsed (parse the final JSON instead).
540
+ Example:
541
+
542
+ ```
543
+ web-cli: searching 3 sites — uptodate, clinicalkey, googlemedsearch
544
+ web-cli: clinicalkey finished — 40 hits
545
+ web-cli: googlemedsearch finished — 8 hits
546
+ web-cli: uptodate finished — 12 hits
547
+ web-cli: search complete — 3/3 sites succeeded, 60 hits total, 8 key references selected (7 with full text)
548
+ ```
549
+
550
+ Sites announce as *they* finish, not in request order (they run concurrently), and a failed site
551
+ gets its own distinct line (`web-cli: <site> failed — <code>: <message>`) instead of a "finished"
552
+ one. The final "search complete" line mirrors `summary` above and is written even when every site
553
+ fails, right before the command throws `SEARCH_FAILED` — so the reason is visible on the terminal,
554
+ not just in the thrown error.
555
+
556
+ ### Writing a report to disk (`--markdown`)
557
+
558
+ `--markdown` *additionally* writes a human-readable Markdown report; stdout stays exactly one JSON
559
+ document and gains a `markdownPath` field pointing at the file. Use it when a person will read the
560
+ output, not for your own parsing — parse the JSON. `--markdown` alone writes into the working
561
+ directory; `--markdown <file.md>` or `--markdown <dir>` picks a location. It is off by default, and
562
+ a failure to write it never fails the search: the results come back with a `markdownError` field
563
+ instead, so check that rather than assuming the file exists.
564
+
565
+ **The report is a citation index, not a full-text dump** — each key reference gets its
566
+ title/url/snippet and a status line (retrieved/unavailable/not retrieved), never the article text
567
+ itself (a single real reference's full text has run to several thousand report lines by itself).
568
+ Read the actual full text from the JSON's `keyReferences[].article.text` — that's what step 1 of
569
+ "After `search` returns" above is for, and it's true whether or not `--markdown` was passed at
570
+ all. Don't go looking for full text in the `.md` file; it was deliberately left out of it.
571
+
572
+ ### Writing JSON output to disk (`--out`) — prefer this over parsing captured stdout
573
+
574
+ `--out` writes the exact object `--json` prints — the complete result, including every
575
+ `keyReferences[].article.text` — directly to a standalone `.json` file on disk, via this process's
576
+ own filesystem write. Its path comes back as `outPath` (and a write failure as `outError`, never
577
+ failing the search itself — same convention as `markdownPath`/`markdownError` above). Freely
578
+ combine it with `--markdown`/`--json`; none of the three implies or excludes the others.
579
+
580
+ ```bash
581
+ web-cli search "myocardial infarction" --json --out # stdout: full JSON envelope; disk: a pure-JSON copy at "outPath"
582
+ ```
583
+
584
+ **Use this instead of parsing whatever you captured from this command's stdout/stderr whenever
585
+ that capture might not be pristine** — concretely: you merged stdout and stderr (`search`'s own
586
+ progress notices land on stderr, ahead of the real JSON, if so — see above), or the tool/harness
587
+ you're running this command through adds its own framing around captured output (a command echo,
588
+ a per-line log prefix, a trailing "exit code"/"EXIT:0" marker once the process exits). None of that
589
+ is unparseable in principle, but it means you'd otherwise have to inspect the captured text's own
590
+ head/tail to work out where the real JSON actually starts and ends — exactly the bespoke,
591
+ per-situation scripting `--out` exists to make unnecessary. A file written this way is produced by
592
+ this process's own `fs` call, so nothing outside the process ever gets a chance to wrap it in
593
+ anything: read it with a plain `JSON.parse`/`jq`, no pre-processing, regardless of how the same
594
+ command's own terminal output turned out to look.
595
+
596
+ ### A report from a result you already have — `web-cli render-markdown` (zero network calls)
597
+
598
+ `search --markdown` renders its report inline, as part of a live search. `render-markdown` is the
599
+ standalone counterpart: hand it a `search` result you already retrieved — the exact JSON
600
+ `search --json` printed, or a file written via `search --out` — and it renders the identical report
601
+ with **no network call and no re-querying any site**:
602
+
603
+ ```bash
604
+ web-cli search "aspirin" --json --out result.json # retrieve once, save the JSON
605
+ web-cli render-markdown --from result.json # render a report from it, any time later, for free
606
+ web-cli render-markdown < result.json # or pipe it in on stdin (the default input)
607
+ ```
608
+
609
+ Reach for this when you (or a human) want a readable report from a JSON blob that's already on
610
+ disk, without re-running a search that could take minutes and another interactive sign-in. Its
611
+ input validation only checks the three fields it actually reads (`query`, `sites`,
612
+ `keyReferences`), so the exact object `search --json` printed always satisfies it — extra fields
613
+ like `summary`/`agentTask`/`outPath` are simply ignored if present.
614
+
615
+ **Unlike `search`/`finalize`, this command's own default output is NOT isatty-gated** — it always
616
+ prints the rendered Markdown text to stdout, period, since that text is the one thing this command
617
+ exists to produce. `--json` opts into `{query, markdown, markdownPath?, markdownError?}` instead
618
+ (useful for confirming a `--markdown` write without reading stderr, or embedding the text in a
619
+ larger pipeline); `--markdown [path]` additionally writes a copy to disk, same off-by-default,
620
+ never-fails conventions as `search --markdown`.
621
+
622
+ ### `keyReferences`: only a small, cheaply-selected slice gets a full-text fetch
623
+
624
+ `search`'s top-level result also includes `keyReferences` — a single flattened list (not nested per
625
+ site) across every site searched, of the few hits judged worth a full-text fetch. **This is
626
+ deliberately not "fetch full text for every hit"**: every hit already gets a title/url/snippet (and,
627
+ where the site's raw data has it, `year`/`source`) for free from the one search call via
628
+ `parsed.hits` above, at no extra network cost — only `keyReferences` costs one extra `getArticle`
629
+ call per entry, so it is kept small on purpose (see "How selection works" below) rather than
630
+ expanding everything indiscriminately.
631
+
632
+ Each entry:
633
+
634
+ ```json
635
+ {
636
+ "site": "uptodate",
637
+ "title": "...",
638
+ "url": "https://...",
639
+ "id": "...",
640
+ "year": "2025",
641
+ "source": "UpToDate",
642
+ "snippet": "...",
643
+ "article": { "title": "...", "text": "...", "html": "...", "outline": [...], "meta": {...} }
644
+ }
645
+ ```
646
+
647
+ or, if the full-text fetch itself failed (rare — the hit was still worth selecting, but couldn't be
648
+ expanded):
649
+
650
+ ```json
651
+ { "site": "...", "title": "...", "url": "...", "fetchError": { "error": "...", "code": "..." } }
652
+ ```
653
+
654
+ A `fetchError` never removes the entry or the site's own `results`/`parsed` — the title/url/snippet
655
+ selected are still valid even when the deeper full-text fetch didn't succeed; check for the
656
+ presence of `article` rather than assuming every `keyReferences` entry has one. `site` is included
657
+ on every entry (unlike a hit inside `sites.<site>.parsed.hits`, where the site is only implicit from
658
+ its place in the response) precisely because this list is flattened across all sites searched — you
659
+ need it to know where each key reference was found.
660
+
661
+ **How selection works**: per site, the top `min(5, ceil(hits.length × 20%))` hits **in that site's
662
+ own returned order** (already its own relevance ranking) are selected — e.g. 10 UpToDate hits → 2
663
+ key references, 40 ClinicalKey hits → 5 (capped). No cross-site scoring/reweighting is applied; the
664
+ percentage is of hits actually returned in this response, not a site's own much larger reported
665
+ total match count (e.g. ClinicalKey's `numberfound`, routinely in the thousands).
666
+
667
+ **`googlemedsearch` is deliberately never expanded into `keyReferences`** — confirmed live: its own
668
+ `getArticle` endpoint is a known-stale decoy that returns unrelated tracking-pixel content for any
669
+ id, and the pages its hits link to are arbitrary third-party sites outside this CLI's
670
+ subscription-site scope anyway. Its `parsed.hits[].url` is already the correct, real destination —
671
+ fetch it yourself (e.g. via `WebFetch`) if you need that page's full text.
672
+
673
+ **Writing that answer (see "After `search` returns" above — this is step 3, not optional) has a
674
+ citation convention: cite the specific `url` from a `keyReferences` entry that backs each factual
675
+ statement** (e.g. "Aspirin is contraindicated in active peptic ulcer disease
676
+ [uptodate.com/contents/...]") rather than a general, unlinked claim — that's the whole point of
677
+ selecting a few hits for full-text expansion instead of leaving you with only a title/snippet. If a
678
+ statement instead comes from a hit that wasn't selected into `keyReferences`, don't invent a link
679
+ for it — say so as coming from the search-result snippet itself
680
+ (`sites.<site>.parsed.hits[].snippet`), not a full document.
681
+
682
+ ### Parsed output: use `parsed`, don't hand-roll your own per-site parsing
683
+
684
+ Every `search` site outcome, every `keyReferences[]` entry's `article`, and every `get` result also
685
+ carries a `parsed` field (on a key reference it's simply named `article` — see above) — a
686
+ normalized extraction produced by this package's own maintained per-site parsers
687
+ (`src/parsers/uptodate.ts`, `src/parsers/clinicalkey.ts`, `src/parsers/googlemedsearch.ts`), built
688
+ and tested against real captured output from each site. **Read `references/parsed-output.md` before
689
+ writing your own script to parse a site's raw JSON** — each site's raw shape has a real, confirmed
690
+ gotcha that a first-time ad-hoc parser is likely to get wrong.
691
+
692
+ **Every hit in `parsed.hits` is guaranteed to carry both a `title` and a real, absolute, directly
693
+ clickable `url`** (a hit missing either is dropped by that site's parser rather than emitted
694
+ half-formed) — you should never need to fall back to a root-relative path or an id-only hit to get
695
+ something citable. Each hit may also carry `year`/`source` (best-effort bibliographic metadata —
696
+ publication/last-revision year, and the site's own notion of "journal"/publisher — extracted only
697
+ from whatever the site's search response already has, never a new network call; absent when the
698
+ site's raw data has nothing to extract, e.g. UpToDate's own search hits carry no date field at all):
699
+
700
+ - **UpToDate**: the article's actual text exists *only* inside an HTML fragment (`bodyHtml`) — there
701
+ is no plain-text field in the raw response at all. `parsed.text` is that HTML already stripped to
702
+ plain text. The raw response's own `url` is root-relative; `parsed.hits[].url`/`parsed.url` are
703
+ already resolved absolute against `https://www.uptodate.com`. UpToDate has no real
704
+ publication-year/journal concept (it's a continuously-revised topic review, not a dated paper) —
705
+ `year`/`source` are unset at the search-hit level; a fully-expanded `keyReferences` entry's
706
+ `article.meta` fixes `source: "UpToDate"` and derives `year` from the topic's own last-major-update
707
+ timestamp as the closest available proxy.
708
+ - **ClinicalKey**: its raw search hits carry *no* URL/link field whatsoever — only an opaque id
709
+ (`eid`). `parsed.hits[].url` is nonetheless present and real: the parser constructs ClinicalKey's
710
+ actual hash-routed article URL itself from `eid` + `contenttype`
711
+ (`https://www.clinicalkey.com/#!/content/<contenttype>/<eid>`, confirmed against two independent
712
+ fields of ClinicalKey's own learned `getArticle` template). To fetch full content through this
713
+ CLI, either `parsed.hits[].url` or `parsed.hits[].id` works as `web-cli get clinicalkey <...>`'s
714
+ argument — but prefer `url`: it's what `search`'s own `keyReferences` expansion uses, since a
715
+ bare `id` alone can't be navigated to if a fresh discovery pass is ever needed (confirmed live:
716
+ it sent tier-2 discovery to a nonexistent page for every key reference once the cached template
717
+ went stale). `year`/`source` come from its own `pubdatetxt`/`copyrightyr` and `srctitle` fields,
718
+ already present on every search hit.
719
+ - **googlemedsearch**: a real test run confirmed the generic link-extraction approach this CLI used
720
+ to rely on was picking a Google click-tracking redirect URL instead of a hit's real destination —
721
+ now fixed by `parsed.hits[].url` using the correct field (`unescapedUrl`, never `clicktrackUrl`).
722
+ `year` is extracted from a leading "D Mon YYYY" date in the snippet when present (this site's only
723
+ date signal); `source` comes from Google's own `richSnippet.metatags.dcPublisher`.
724
+
725
+ `parsed` is purely additive and best-effort — a parsing gap or an unrecognized raw shape degrades to
726
+ `parsed: null`, never an error, and never removes or changes the existing raw `results`/`content`/
727
+ `article` field it was derived from. If `parsed` is `null`, fall back to the raw field (which may
728
+ still have ClinicalKey's URL-less shape or UpToDate's root-relative path, unresolved).
729
+
730
+ `parsed.didYouMean` (UpToDate, ClinicalKey) is also the concrete, structured version of this skill's
731
+ "don't trust a single site's silence" guidance below — a positive signal when present, but its
732
+ absence is still not proof the query was matched literally.
733
+
734
+ ### The three-tier model — what `discovered: true/false` means
735
+
736
+ Under the hood, `search` and `get` each resolve per-site (and, for `search`, per key reference
737
+ expanded) via the same 3-tier flow, per `(site, intent, param)`:
738
+
739
+ 1. **Replay** a previously learned endpoint template directly over HTTP — fast, no browser. A
740
+ result with `"discovered": false` came from here.
741
+ 2. **Discover**: launch a headless automation Chrome, drive the page (type into a search box, or
742
+ navigate to an article URL), and identify the real REST call from observed network traffic. A
743
+ result with `"discovered": true` came from here — expect it to take longer (the engine gives
744
+ in-flight requests up to ~10s to resolve) and, on success, the endpoint is cached so the *next*
745
+ search of that intent goes through tier 1 instead. Concurrent sites/key-reference fetches all
746
+ needing tier-2 discovery at once don't run truly simultaneously — they share one persistent
747
+ automation Chrome profile, so they queue for it internally — but that queuing never blocks a
748
+ site that didn't need discovery at all, so it only shows up as extra latency on the calls that
749
+ actually needed it.
750
+ 3. **Fail structured**: if discovery can't find a plausible candidate either, that site's (or key
751
+ reference's, via `fetchError` — see "keyReferences" above) entry gets a `DISCOVERY_FAILED` error
752
+ naming `web-cli observe` as the fallback.
753
+
754
+ ### When to use `observe` instead of `search`
755
+
756
+ `observe` runs the same discovery engine headful, with a human driving the actual interaction
757
+ (typing a search, clicking into a result) instead of the automated search-box heuristic. Reach for
758
+ it when one site's entry in a `search` result keeps coming back `DISCOVERY_FAILED` — that means the
759
+ automated heuristic couldn't find or successfully trigger a search box on that particular page, and
760
+ a human needs to do it once so the engine can watch and learn the real endpoint from that.
761
+
762
+ ### A site's error is `EPERM ... chrome-profile.lock`: a sandbox denial, not that site's fault
763
+
764
+ If a site's `search`/`get` entry looks like:
765
+
766
+ ```json
767
+ {"error": "EPERM: operation not permitted, open '.../chrome-profile.lock'", "code": "INTERNAL_ERROR"}
768
+ ```
769
+
770
+ this means the *execution environment itself* denied filesystem access to the automation-Chrome
771
+ lock file — tier 2 (see above) can't even launch Chrome to attempt discovery. **This is not
772
+ evidence the site's own API is broken, that the account isn't subscribed, or that this particular
773
+ site is somehow unsupported** — it fires whenever a `(site, intent)` reaches tier 2 in an
774
+ environment that blocks that lock path, and *any* site with nothing yet in
775
+ `~/.web-cli/learned/<site>.json` for that intent will hit it identically. Concretely: if one site
776
+ (say `uptodate`) already has a learned template from an earlier, unrestricted run and another (say
777
+ `clinicalkey`) doesn't, the same `search` call will show `uptodate` succeeding via tier 1 (no
778
+ Chrome, no lock) while `clinicalkey` fails this way — that's a caching-order artifact, not a sign
779
+ that `clinicalkey` itself is broken or unsupported while `uptodate` is fine. Don't report this to a
780
+ person as "ClinicalKey doesn't work" (or whichever site hit it) — report it as "this environment
781
+ can't run tier-2 discovery for a site with no cached endpoint yet."
782
+
783
+ What actually unblocks it, in order of preference:
784
+
785
+ 1. **Run `web-cli search`/`get` once for that site from an unrestricted shell** (outside whatever
786
+ sandboxed environment produced the `EPERM`) so tier 2 can complete normally there. That learns
787
+ and persists the template to `~/.web-cli/learned/<site>.json`; the exact same restricted
788
+ environment will then hit tier 1 for that `(site, intent)` and never touch Chrome or the lock
789
+ again for it.
790
+ 2. **Preseed the endpoint template** (`src/discovery/preseed.ts`'s `PRESEED_TEMPLATES`, checked
791
+ automatically between tier 1 and tier 2 — see `CLAUDE.md`'s architecture section for the exact
792
+ shape) so tier 1 works even on a machine that has never successfully run discovery at all. This
793
+ requires a code change (adding an entry) by whoever maintains this checkout — flag it as the fix
794
+ to make rather than attempting to work around the sandbox denial yourself.
795
+ 3. If neither is possible in the moment, treat that one site's entry the same as any other
796
+ site-level failure (see "reading a `search` result" above): report the other sites' results,
797
+ and name the concrete blocker (sandboxed lock-file access) rather than a generic "search
798
+ failed."
799
+
800
+ ### Interpreting results — don't trust a single site's silence
801
+
802
+ A site's entry showing `discovered` set and a nonempty `results` object is *not* proof the query
803
+ was actually understood by that site — search engines routinely autocorrect an unfamiliar or
804
+ technical term to something more common and return confident-looking, completely unrelated
805
+ results, often with no error and no "did you mean" flag at all (`parsed.didYouMean` surfaces one
806
+ when UpToDate/ClinicalKey's own response happens to carry that signal — see "Parsed output" above —
807
+ but its *absence* is not proof the query was matched literally). Concretely:
808
+ searching UpToDate/ClinicalKey for a precise anatomical term (e.g. a specific brain-structure layer
809
+ name) commonly returns real search results for a *different*, more common term the query got
810
+ silently corrected to — inspect the actual result titles/snippets for topical relevance before
811
+ treating a nonempty response as an answer. `search` returns all three medical sites' entries side
812
+ by side in one call, so use that to cross-check — if `uptodate` and
813
+ `clinicalkey` agree on a topic but `googlemedsearch`'s results look unrelated (or vice versa),
814
+ that's a sign one of them silently autocorrected. If the query is specifically about anatomical
815
+ structure/layer naming or a historical/Latin synonym, see `references/anatomy-lookup.md` — for
816
+ that class of query, none of these three sites' results should be trusted over FMA/Terminologia
817
+ Anatomica, regardless of how confident they look.
818
+
819
+ ### googlemedsearch as a broad fallback
820
+
821
+ `googlemedsearch` (a Google Programmable Search Engine scoped to medical sites) has no login wall
822
+ and searches much more broadly than UpToDate/ClinicalKey — useful when a query needs general
823
+ medical/scientific web coverage (overviews, peer-reviewed papers, Wikipedia) rather than a
824
+ specific subscription resource's own clinical-practice content. Its results are JSONP under the
825
+ hood; the CLI already unwraps that transparently, so its `results` entry is always plain parsed
826
+ JSON. It's included in every `search` call (there's no separate flag to opt into it — see this
827
+ skill's own note above on `search` always covering all three medical sites). Use
828
+ `parsed.hits[].url` rather than a raw hit's `clicktrackUrl` if you need its link — see "Parsed
829
+ output" above.
830
+
831
+ `search` itself has no general-purpose (non-medical) site to fall back to at all — for anything
832
+ outside medicine/anatomy/substances/organisms, use `web-cli websearch` instead (see that command's
833
+ own section above): a real Google/Bing/Gemini fallback chain, not restricted to any fixed site
834
+ list.