Files
substrata/scripts/db/004-source-sweep.sql
CatoandClaude Sonnet 5 4bdf827736 fix(chat): retrieval quality — word-boundary scoring, IDF weighting, relevance floor (#73)
* docs: the concept — one corpus, five latencies, and who actually pays

Strategy SSOT for where the research goes and who it is for. The three
questions it answers:

- Why the nearest comparable product (sell-side equity research) is
  beatable: its unit of analysis is a ticker while the unit of causation
  is a node, coverage follows market capitalisation rather than causal
  weight, the horizon is a quarter against constraints that clear on a
  decade, sector silos cut across every interesting chain, and nothing it
  publishes can be scored.
- The idea to build around: a constraint is visible in five record
  systems at five different latencies — science (5-15y), funding (2-7y),
  talent (1-5y), policy (0-3y), market (0-1y). Equity research reads the
  bottom row. Reading the top rows years earlier, and showing the working,
  is the whole product claim. It needs one schema change: every
  observation typed by layer and carrying both dates, so lead time becomes
  a measured property of the corpus rather than a boast.
- Who pays, ranked by fit rather than cheque size. Procurement and supply
  assurance first, because they are the only customer who corrects the map
  instead of only reading it.

Also records the rule that keeps a holistic map from becoming a general
database: every row must traverse to a bottleneck and through it to a
loop, enforced as a build gate rather than as editorial taste. The corpus
has already failed this once — 30 of 51 country rows connected to nothing.

No code or corpus changes; everything described is unbuilt and the
document says so.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01C9tLC1kS4qNVdRxcHuPZ5c

* feat(chat): bring your own frontier key, and a web-lookup gate that lied

Two changes to the assistant, one a real bug fix and one a new feature.

FIX: `webLookupEnabled()` checked SEARXNG_URL only, while `webSearch()`
itself walks three backends (SearXNG, then Brave, then Tavily). A box
configured with just a Brave or Tavily key had a fully working lookup
behind a gate reporting it off — the system prompt told the model "You
have no tools", the outside-corpus escape hatch never opened, and the
one env var that would have fixed it was the one this function forgot
to read. Now checks all three, with a regression test.

FEATURE: a reader can now supply their own API key (OpenAI, Anthropic,
or OpenRouter — a fixed list, never a free-form base URL, because this
server makes the outbound call on their behalf and an arbitrary URL
there is SSRF with their bearer token attached) and get answered by a
genuine frontier model instead of the free tier's small, rationed
chain:

- `lib/byok-shared.ts` — types, the closed vendor list, and validation,
  with no server-only dependency, so the client settings panel can
  import it without pulling `@bitbaum/ai-kit` into the browser bundle.
- `lib/byok.ts` — `completeByok()`. OpenAI and OpenRouter go through
  ai-kit's `complete()` with a one-link ephemeral chain (never
  `process.env`); Anthropic's Messages API isn't the OpenAI shape
  everything else in ai-kit speaks, so it's called directly.
- `lib/byok-store.ts` — the reader's own browser is where the key lives
  between requests, guarded against private-mode/blocked-storage
  failures. It is never sent anywhere but this component's own request
  and never touches this project's servers between requests.
- `lib/chat.ts` — one `runCompletion` closure now backs all three
  completion call sites (initial answer, outside-corpus fallback,
  grounding repair), fed by either the free chain or `completeByok`.
  BYOK gets a larger token budget and longer timeout — the free tier's
  ceiling exists to ration a shared pool that does not apply to a
  reader's own paid key — and the system prompt names the model running
  and tells it to use more of its own judgement in BACKGROUND, while
  the citation rules (a finding is a numbered row, nothing else is
  [F#] or [W#]) stay identical regardless of which model is answering.
  Works even with zero free providers configured.
- `app/api/chat/route.ts` — validates `byok` if present, skips the
  free-chain `isOfferedModel` gate (irrelevant to a vendor-native model
  id), and surfaces a `ByokError` message to the reader directly ("your
  key was rejected") rather than the generic "temporarily unavailable"
  wall, since that failure is the vendor talking to them, not this
  deployment breaking.
- `components/portal/ResearchChat.tsx` — a "Frontier key" control next
  to the model picker opens a small panel (provider, key, model id);
  once set it replaces the free-model select with a pill naming what
  is answering, and the empty-state copy says so too.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01C9tLC1kS4qNVdRxcHuPZ5c

* feat(coverage): 16 producer rows sourced, 2 removed for being wrong

A pass over the 31 unverified producer leads still open in the coverage
universe, cross-referenced against `research/evidence.json`'s candidate
pages (20 leads already had a candidate excerpt on file, waiting for
someone to read it and decide) plus fresh web research for the rest and
for the ones whose only stored evidence was too weak to stand behind.

PROMOTED TO SOURCED (16), each read and cited against a specific source:
- Sibanye-Stillwater and Impala Platinum — ruthenium, mining role. The
  Sibanye row cites their own SEC trading-statement filing, which reports
  actual ruthenium ounces produced (258koz, 2025) — about as primary as a
  production claim gets.
- Ferrotec — quartz, own site.
- Chalco, East Hope Group, Zhuhai Fangyuan, 5N Plus — gallium, refining.
  The first of these was on file as "Chinalco", which turned out to be
  the wrong entity: Chalco (Aluminum Corporation of China Limited) is the
  listed subsidiary that actually runs the alumina refineries gallium
  comes off; Chinalco is its unlisted state-owned parent. Renamed, with
  both names kept as aliases since trade press uses both for the same
  business — and the evidence file's own row renamed to match, since a
  test holds every evidence row to a producer that still exists.
- Chemours, Syensqo, AGC, Engineered Fluids — two-phase dielectric
  immersion coolant, refining/conversion.
- AMSC — REBCO tape, conversion.
- QatarEnergy and Linde — liquid helium. Off-take from Qatar's Ras Laffan
  Helium 2 (the world's largest liquefaction train) splits Air Liquide
  50% / Linde 30% / Iwatani the remainder, per the same source for both.
- China Northern Rare Earth and Shenghe Resources — Nd-Pr metal,
  refining. Shenghe's dysprosium row stays unverified: the evidence found
  supports their Nd-Pr business specifically, not dysprosium, and a
  citation that does not name the actual claim is not a citation.

REMOVED, not promoted (2) — the research found the row was no longer
true, and a wrong row is worse than an absent one:
- REC Silicon, electronic-grade polysilicon. Butte, Montana stopped
  polysilicon production in Feb 2024; Moses Lake shut down Dec 2024 and
  stayed closed through the Feb 2026 restart decision; the company now
  says it has "completely discontinued the production of polysilicon" —
  Butte makes only silane gas today.
- 3M, two-phase dielectric immersion coolant. 3M announced in Dec 2022 it
  would exit all PFAS manufacturing by end of 2025, and did: Novec and
  Fluorinert stopped shipping (last order date 31 March 2025). Left as an
  inline, sourced note rather than forced into the EVENTS/PARTICIPANTS
  schemas, which are their own curated exercises this pass didn't attempt.

LEFT ALONE ON PURPOSE (not promoted): Baosteel Gases (every source is a
syndicated press-release aggregator repeating the same sentence — no
primary trace); Nyrstar (Trafigura's own release says they are
CONSIDERING a gallium project at Port Pirie, not running one — an
aspiration is not a role).

`sourced()` gained an optional `aliases` param, matching `lead()`, for
the Chalco/Chinalco rename. Coverage: 63/94 (67%) sourced before this
pass, 79/92 (86%) after.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01C9tLC1kS4qNVdRxcHuPZ5c

* feat(research): the producer-sourcing engine runs on a timer too, two ways

The event sweep already outgrew being a CLI-only tool: it has a shared
judgement module (`lib/sweep.ts`), a scheduled route
(`POST /api/cron/sweep`), a Postgres review queue, and a `/review` page a
human reads. Producer sourcing (`pnpm research:source`) was still stuck
where the sweep started — a script a person has to remember to run. This
closes that gap by extending the exact pattern that already proved itself,
rather than inventing a second one, plus a fully independent second leg
that needs no box access at all.

WHAT MOVED

- `lib/source.ts` — the query, the domain ranking and the excerpt-match
  judgement, extracted from `scripts/research/source-producers.ts` so the
  CLI and the timer cannot quietly stop agreeing about what counts as a
  candidate. `scripts/research/source-producers.ts` now imports it and
  keeps only what is genuinely its own: argument parsing, the evidence
  FILE, and the blindness-streak guard.

SCHEDULED, BOX-DRIVEN (needs manual setup, documented in
docs/INFRASTRUCTURE.md and docs/IMPLEMENTATION-PLAN.md):

- `lib/source-store.ts` — `runScheduledSourcing()` examines a few
  least-recently-checked unsourced rows per call and files candidates into
  `research_source_candidates`, never into the coverage file: a running
  server has no working tree to commit a promotion into, same reasoning
  `lib/sweep-store.ts` already documents for events.
- `scripts/db/004-source-sweep.sql` — the queue, mirroring
  `003-sweep.sql`'s shape. Apply via `scripts/provision-service.py`; the
  generic deploy workflow does not do this automatically.
- `app/api/cron/source/route.ts` — `CRON_SECRET`-gated, same as
  `app/api/cron/sweep`. Needs registering in whatever schedule
  `/opt/_appcron/run.sh` already drives the sweep on.
- `/review` gains a third feed: candidates from producer sourcing, decided
  the same way as event leads — accepting marks a candidate worth
  promoting, it does not write `sourced()` anywhere. That stays a person
  reading the excerpt and editing `config/substrata-coverage.ts`.

SCHEDULED, GITHUB-ACTIONS-DRIVEN (works today once a secret is added, no
box access needed):

- `.github/workflows/research-sweep.yml` — runs `research:source` and
  `research:sweep` weekly against a Brave or Tavily key
  (`BRAVE_SEARCH_API_KEY` / `TAVILY_API_KEY` — ai-kit's `webSearch()`
  already falls through to these when SearXNG, loopback-only on bitbaum,
  isn't reachable) and opens a DRAFT PR with whatever lands in
  `research/evidence.json` / `research/events.json`. Skips cleanly with an
  `::notice::` until a secret exists. Draft on purpose: the fleet's
  auto-merge sweep leaves drafts alone, so nothing merges until a person
  has actually read the rows. Never touches `config/`.

Tests: `test/source.test.ts` covers the pure judgement in `lib/source.ts`
(normalise, nameStem, query building, own-domain detection, the
window-match rule) the same way `test/sweep.test.ts` already covers
`lib/sweep.ts`. `test/sweep.test.ts` gains one more assertion: the new
cron route is gated the same way the old one is.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01C9tLC1kS4qNVdRxcHuPZ5c

* feat(participants): source 54 of 101 directory entries (equipment through deployment)

Every row in `substrata-participants.ts` started `source: null` — unlike
the producer coverage universe, this directory had no sourcing helper at
all, so nothing in it could ever read as verified. Added `s()` alongside
`p()`, mirroring `sourced()`/`lead()` in `substrata-coverage.ts`, and used
it to cite every entry across five layers: equipment (12, e.g. ASML,
Carl Zeiss SMT, Trumpf, Applied Materials — each checked against the
company's own product page), fabrication (6: TSMC, Samsung Foundry,
Intel Foundry, SMIC, GlobalFoundries, UMC), packaging (6: TSMC Advanced
Packaging's CoWoS, ASE, Amkor, and the three HBM makers), systems (7:
NVIDIA, AMD, Broadcom, Marvell, Vertiv, Arista, Supermicro), energy (8:
transformer, turbine, HV cable and grid-equipment makers), actuation (7:
the precision-drive duopoly, the robot makers, Renishaw), and deployment
(8: the hyperscalers, the three frontier labs named in the directory, and
CoreWeave).

Every citation was checked against a live fetch or search of the source
itself before being added — a company's own product/technology page where
one exists and answers the claim, trade press or a filing where it does
not (Sibanye-Stillwater's own SEC production-update filing for its
ruthenium row, Data Center Frontier for xAI's Colossus). Names, layers and
roles are what is claimed sourced; the scarcity grade stays a judgement,
exactly as `s()`'s own comment says.

46 rows remain unverified: extraction, refining and conversion layers —
left for a follow-up pass rather than rushed.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01C9tLC1kS4qNVdRxcHuPZ5c

* feat(participants): source extraction and refining layers (27 more)

Continues the pass started for equipment through deployment. 81 of 101
rows now carry a source.

Extraction (12): The Quartz Corp and Sibelco's own Spruce Pine pages,
Sibanye-Stillwater's SEC filing and Impala Platinum reused from the
earlier producer-coverage pass, Nornickel, MP Materials' own Mountain
Pass page, Lynas's own about page, and the three tin miners plus
QatarEnergy/ExxonMobil reused from `substrata-coverage.ts` — same
companies, same claims, no reason to re-derive a citation already found.

Refining (15): the three merchant polysilicon refiners plus OCI, the PGM
refiners (Heraeus, Johnson Matthey, Umicore), the gas majors, and
`Chinalco` renamed to `Chalco` here too — same entity correction as the
coverage file: Chalco (Aluminum Corporation of China Limited) is the
listed subsidiary that actually runs the gallium-yielding alumina
refineries.

20 rows remain: the conversion layer.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01C9tLC1kS4qNVdRxcHuPZ5c

* feat(participants): source the conversion layer — all 101 directory rows now sourced

Completes the pass: every row in `substrata-participants.ts` now carries
a primary source, up from zero at the start of it. Conversion (19): the
prime-wafer makers, the fused-quartz specialists, the wide-bandgap and
diamond materials firms, the REBCO tape makers, the two rare-earth
magnet-alloy specialists (Neo Performance Materials, Less Common Metals
— the only two genuinely new searches in this batch; the other 17 reused
citations already found and checked in `substrata-coverage.ts` for the
same companies), and the electrical-steel and solder makers.

`p()`, the unverified-lead helper, is now unused — every row calls `s()`.
Kept rather than deleted (the file's own header says a new participant
starts as a lead), with an eslint-disable and a comment saying why, dated,
so the next person to touch this file knows the state was checked, not
missed.

Coverage summary for this whole pass: 101/101 participants sourced,
against 0/101 at the start. Two entity-name corrections carried over
from the producer-coverage pass (Chinalco → Chalco, in both refining and
extraction) for consistency across the two files.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01C9tLC1kS4qNVdRxcHuPZ5c

* refactor(byok): use Anthropic's own SDK instead of a hand-rolled client

Decision on "should this use a package": yes, for exactly one of the two
vendor calls in `lib/byok.ts`, and deliberately no for the other — the
two are not the same situation.

WHY THE OPENAI-COMPATIBLE PATH STAYS AS IS

`completeOpenAiCompatible` (OpenAI and OpenRouter) already goes through
`@bitbaum/ai-kit`'s `complete()`, which exists specifically to be the one
client for every vendor that speaks the OpenAI chat-completions shape.
Adding the `openai` npm package here would mean two clients for the same
wire format in one file, and it's the fleet's own documented lesson
(ai-kit's `complete.ts` header) that duplicated hand-rolled clients are
the failure mode, not the fix. No change.

WHY THE ANTHROPIC PATH DOES NOT

Anthropic's Messages API isn't the shape ai-kit speaks, so this file
hand-rolled a hand-rolled `fetch` call: manual AbortController/timeout
racing, manual JSON error-body parsing, manual status-code-to-message
mapping. That is precisely the "conventions differ because nothing ever
offered to own them" pattern ai-kit's own header describes for the fleet
at large — just scoped to one vendor instead of eight. Anthropic
publishes the thing that owns it: `@anthropic-ai/sdk` gives typed errors
(`AuthenticationError`, `NotFoundError`, `RateLimitError`,
`APIConnectionTimeoutError`) that already distinguish exactly the
failures this file was hand-classifying by status code, and a `timeout`
+ `signal` pair on the request options that race correctly against each
other (verified by reading `client.js`: the external signal is wired
into the same internal AbortController the timeout arms, not left to
fight it). Swapping in the SDK deletes the hand-rolled error mapping in
favour of five `instanceof` checks and removes the manual
AbortController plumbing entirely. `maxRetries: 0`, deliberately: this is
one link, not a chain the caller can fall through, so a failure should
reach the reader immediately rather than being silently retried inside a
budget the caller already timed.

Verified against the real Anthropic API with a syntactically-valid but
invalid key: the SDK's `AuthenticationError` maps to the same
"Anthropic rejected that key." message the hand-rolled version produced,
confirming the swap is behaviour-preserving where it matters — what the
reader sees on the four error paths (bad key, unknown model, rate limit,
timeout) is unchanged; only how this file gets there is simpler.

Lockfile note for whoever next touches `pnpm-lock.yaml` by hand: this
sandbox cannot fetch `bitbaum/listkit`'s git-hosted tarball (its own
CI can), so the new `@anthropic-ai/sdk` entries here were generated
against a temporary local git-protocol substitution for that one
dependency, then merged back byte-for-byte against the committed
`listkit` resolution — verified with `pnpm install --frozen-lockfile`
reporting "Lockfile is up to date, resolution step is skipped" before
failing on the same pre-existing, sandbox-only `listkit` fetch this
repo already had. `git diff pnpm-lock.yaml` is pure addition; the three
`listkit` lines are untouched.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01C9tLC1kS4qNVdRxcHuPZ5c

* fix(chat): retrieval quality — word-boundary scoring, IDF weighting, relevance floor

The assistant answered a "biggest robotics bottleneck" question with a thin,
wrong "ABB Robotics" citation, "not in your data" for the actual chokepoints,
and a source list dominated by unrelated development banks and country
directory rows. Root causes, all in the retrieval path rather than the model
or prompt:

- searchResearch()/chatContext() scored raw substring hits with a flat
  title/body bonus and no notion of how common a word is across the corpus,
  so boilerplate connector text ("Bottlenecks its mandate could fund relief
  for: …", repeated on every capital and country row) systematically
  outscored real, specific content.
- Actuation-layer companies (Harmonic Drive Systems, Nabtesco, FANUC,
  Yaskawa, Renishaw, KUKA) derived their searchable topics only from a
  COVERAGE materials join they don't have, so they carried empty topics and
  were unreachable by any query — and the same join gap meant their
  already-sourced directory citation (person.source) was never surfaced,
  so their pages read "unverified" when a real source existed.
- Bottleneck entities never used the word "bottleneck"/"chokepoint" in their
  own retrieval text, while capital/country boilerplate used it constantly.

Fixes: word-boundary tokenization with document-frequency weighting in
research-index.ts (rare words score more than ubiquitous ones); participants.ts
now also derives technologies/industries and a directory source from a
participant's own chain layer, not only the coverage join; boilerplate
connector phrases reworded to drop the generic "bottleneck(s)" wording while
keeping the specific cross-referenced names; a minimum relevance floor in
chatContext so a single coincidental common-word match no longer fills the
citation list; an expanded stopword list for generic superlatives/category
nouns ("biggest", "companies") that discriminate nothing in this corpus.

Added a regression test reproducing the reported query and pinning that the
known noise (European Investment Bank, DOE Loan Programs Office, KfW) is
excluded and an actual robotics/actuation record is retrieved.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01C9tLC1kS4qNVdRxcHuPZ5c

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-21 05:32:17 -07:00

61 lines
2.7 KiB
PL/PgSQL

BEGIN;
-- Candidates the scheduled producer-sourcing run finds. NOT the corpus.
--
-- Same reasoning as `research_sweep_candidates` (003-sweep.sql): the corpus
-- stays file-SSOT in git, accepted by a person in a commit, because that is
-- the whole claim of the site. A timer writing straight into
-- `config/substrata-coverage.ts` would publish unread rows, and the box runs
-- releases rather than checkouts anyway — there is no working tree at
-- runtime to commit a promotion into. So the scheduled run lands here: a
-- queue of candidate pages a reviewer can read and, if they hold up, use to
-- promote a `lead()` to a `sourced()` by hand.
CREATE TABLE IF NOT EXISTS research_source_candidates (
-- sha1(material || producer || url), so the same page found on a later run
-- for the same row is the same id rather than a duplicate.
id text PRIMARY KEY,
material text NOT NULL,
producer text NOT NULL,
query text NOT NULL,
url text NOT NULL,
title text NOT NULL,
excerpt text NOT NULL,
-- Company-name and material terms the page matched on, comma-joined —
-- carried through so a reviewer sees why the engine kept this page without
-- needing to re-read it themselves.
matched text NOT NULL,
found_at timestamptz NOT NULL DEFAULT now(),
-- Set when a person has decided. Nothing here reaches the coverage file
-- until then, and accepting a row here does not write it — see the header.
reviewed_at timestamptz,
reviewed_by text,
verdict text CHECK (verdict IN ('accepted', 'rejected'))
);
CREATE INDEX IF NOT EXISTS research_source_candidates_open
ON research_source_candidates (found_at DESC) WHERE reviewed_at IS NULL;
-- When each unsourced row was last looked at, so a bounded run rotates
-- through the queue rather than examining the same few rows every time.
CREATE TABLE IF NOT EXISTS research_source_state (
-- evidenceKey(material, producer) — "<material> :: <producer>".
row_key text PRIMARY KEY,
last_checked timestamptz NOT NULL DEFAULT now(),
last_status text NOT NULL
);
-- What the timer actually did, so "is the engine still running" has an
-- answer that is not a guess.
CREATE TABLE IF NOT EXISTS research_source_runs (
id bigserial PRIMARY KEY,
started_at timestamptz NOT NULL DEFAULT now(),
finished_at timestamptz,
rows_examined integer NOT NULL DEFAULT 0,
candidates_found integer NOT NULL DEFAULT 0,
could_not_look integer NOT NULL DEFAULT 0
);
COMMENT ON TABLE research_source_candidates IS 'Candidate producer sources from the scheduled run. The coverage file is git; nothing here is a finding until a person reads it and promotes it by hand.';
COMMENT ON TABLE research_source_runs IS 'Evidence that the producer-sourcing timer ran, so staleness is measurable rather than inferred.';
COMMIT;