20 Commits
Author SHA1 Message Date
CatoandClaude f55c127901 feat(research): runs record what their search backends did, and /api/health/web says it now (#376)
* feat(research): runs record what their search backends did, and /api/health/web says it now

The event sweep and producer sourcing failed for a day on production with
nothing on /data/freshness but "no search reached a search backend".

- Each sweep and sourcing run records its search backends' outcome in
  ai-kit's own words (search_note, e.g. "searxng unreachable"); migration
  018 adds the column. /data/freshness shows it beside a failing run.
- /api/health/web searches once for a fixed phrase and reports which
  backends are configured (names only) and what each did. One probe per
  ten minutes, shared by concurrent callers.
- docs/operations/auto-updates.md: what runs, when, what it needs, where
  it leaves a trace, and what to do when a run is failing.

Claude-Session: https://claude.ai/code/session_019MDtmuvTGrpo3VChP3skH8

* fix(data-layer): read double-quoted identifiers in migrations

declaredObjects read `CREATE TABLE IF NOT EXISTS "users"` as a table named
"if", so 017-accounts.sql looked incomplete on any database that predates
the ledger: it would be re-run, and the ownership hand-over would miss its
real tables. CI's real-Postgres test caught it once 017 stopped being the
newest file ("must be owner of table accounts").

Tables, indexes, ALTER TABLE targets and added columns may now be quoted.

Claude-Session: https://claude.ai/code/session_019MDtmuvTGrpo3VChP3skH8

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-12 08:16:31 +01:00
CatoandClaude Opus 5.5 c5d7c99d77 feat(auth): Substrata accounts on @bitbaum/accountkit, not only OrangeCat (#294)
* feat(auth): Substrata accounts on @bitbaum/accountkit, not only OrangeCat

Readers can create an account with an email and a password or a passkey,
and turn on two-step codes. Continue with OrangeCat stays one way in.
next-auth and lib/identity.ts are gone; /api/auth serves AccountKit's
runtime, and /sign-in, /sign-up and the account panel in
/account/settings are its shared screens in Substrata's look.

Desks, follows, saved AI keys and SUBSTRATA_REVIEWER_ACTOR_IDS stay keyed on
the OrangeCat actor id: legacyIdentityProvider keeps it for anyone whose
first way in was OrangeCat. The six account tables are
scripts/db/017-accounts.sql, additive and re-runnable, applied by the deploy.

Rebuilds the stale draft #184 on current main.

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

* test(data-layer): the pre-ledger case names the newest migration, not 016

Adding 017-accounts.sql made the test treat 016 as one of the files that
predate the ledger; it now asks for whatever file is newest.

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-29 11:57:03 +01:00
CatoandClaude Sonnet 5.5 ad9fb7932c feat(deploy): the deploy applies migrations, installs timers, runs the price backfill once (#276)
* feat(deploy): the deploy applies migrations, installs timers and runs the one-time price backfill

Before the release goes live, deploy.yml now applies pending scripts/db/*.sql
(one transaction each, recorded in public.schema_migrations, first run checks
existing objects before baselining) and installs deploy/systemd units. A failure
stops the deploy with the live release untouched. After the release, the price
backfill runs once and is recorded in public.schema_oneshots.

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

* docs: name no migration file that does not exist

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-27 23:22:53 +01:00
CatoandClaude Opus 5.5 73dd498f49 feat(market-data): share prices, SEC fundamentals and filing-based holders, with Ask tools and charts (#249)
* feat(market-data): share prices, SEC fundamentals and filing-based holders, with Ask tools and charts

Prices: daily split-adjusted closes from Yahoo Finance's chart endpoint (query1,
then query2), stored in research_price_points by /api/cron/prices, read by
priceHistory(ticker, range) with a live fallback; returns, 52-week extremes,
drawdown and moving averages computed in code. Stooq (browser challenge),
Nasdaq (browser agent only) and Alpha Vantage (unadjusted free closes) were
tested and rejected; the reasons and the licence position are in
lib/market-data/prices/chain.ts.

Fundamentals: SEC XBRL company facts per CIK — revenue, margins, R&D, capex,
cash, assets, debt, shares — each point with form, accession and filing link;
a typed "unavailable" with the reason for companies the SEC holds nothing for.

Holders: the proxy's ownership table, structured Schedules 13G/13D filed since
(issuer checked, 0% amendments honoured) and recent Forms 4, with the rest as a
typed remainder that says what it is — never a bare "Other 87%". The company
page's ownership view and share bar carry the same remainder.

Ask: price_history, fundamentals and holders tools; a price question plans
price_history and the answer draws a line chart built in code (answer charts
routed like answer tables); four ask-evals rows.

Keyed by ticker in lib/market-data/identity.ts with a committed seed
(config/market-seed.ts) as the seam for the company universe.

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

* fix(market-data): fundamentals lists newest first so a length cut keeps the latest years

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-27 08:47:33 +01:00
CatoandClaude 757d1b3a1d feat(chat): the answer feedback loop — thumbs, transcript export, nightly review (#198)
Substrata was the product whose Ask answered "nothing in our database" with
no way forward, and nobody knew until the owner said so. From here every
turn is in the loop:

- chatkit 0.14: thumbs under every answer (ChatThread onFeedback); a thumb
  down asks why. POST /api/chat/feedback (zod, same-origin, rate limited)
  keeps it in chat_feedback.
- chat_turns: /api/chat logs the question and, when the loop ends, the
  answer with the status and tool labels the reader watched, the page it was
  asked from and whether it failed. Ids are random uuids the browser mints
  per thread and per answer; no reader, no IP, no key.
- GET /api/chat/review-export: bearer CHAT_REVIEW_TOKEN (constant-time; 401
  otherwise, 503 while unset), {product, scope, transcripts} in chatkit's
  ChatTranscript shape — at most 50 conversations since `since`, 30 turns
  each, 4,000 characters a turn, with their feedback. The scope is built
  from the system prompt's role line and the tool registry, never typed
  twice.
- scripts/db/015-chat-review.sql, .env.example, docs/INFRASTRUCTURE.md
  "Chat review", test/chat-review.test.ts.


Claude-Session: https://claude.ai/code/session_018WZnBnaLP6RhwFkLxRTKgE

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-22 19:02:13 +02:00
CatoandClaude Opus 5.5 3cf5c26f49 feat(data): quality criteria, automated checks and /data/quality; fix what they found (#116)
* fix(data): correct what the quality checks and a 36-row source sample found

- listings: 8 pinned home lines stored a composite FIGI that OpenFIGI cannot
  resolve (openfigi.com/id 404, ID_BB_GLOBAL mapping empty); pinnedLine now
  keeps the exchange line's own FIGI (TSMC, UMC, GlobalWafers, ASE, SMIC,
  Rio Tinto, NKT, TSMC Advanced Packaging)
- sanctions: all 49 EU amendment dates were a day early (Brussels-midnight
  stamps read in UTC); 4 OFAC programmes had empty titles (menu link parsed first)
- usgs-producers: wrapped workbook cells were split into bogus facilities
  (64 fragments -> 5); Chile's copper table had lost Escondida, Spence, Sierra
  Gorda and 12 more rows behind a 'Continued' commodity cell
- events/dependencies: 7 paraphrased quotes replaced with the source's
  verbatim text; SK Siltron event names its directory company
- series: 18 Cameco points get the date their MD&A states
- directory: Shin-Etsu Handotai source 404 replaced; Fangyuan careers URL
  (domain does not resolve) set to null as its evidence already said

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* feat(data): written quality criteria per dataset, automated checks, /data/quality

- config/substrata-quality.ts: 15 datasets x 6 criteria (completeness,
  correctness, provenance, freshness, link health, consistency); each a rule or
  'na' with a reason; freshness reuses config/substrata-freshness.ts
- lib/quality: pure checks (USGS world sums, quote states the value, names
  resolve, cross-dataset agreement with USGS) run in verify with a failure-count
  ratchet (test/quality.test.ts); network checks (links with 3 tries and a
  blocked/broken distinction, quotes on page, SEC ticker file, OpenFIGI mapping,
  USGS values on the chapter PDF) run on a rotation via /api/cron/quality
- migration 014: research_quality_checks + research_quality_runs (trend)
- /data/quality: scores, counts, trend and every failing row with its source
  and a prefilled correction issue; linked from /data, footer, palette
- check-series.ts shares the reader (CDATA and ' ,' fixes found by the sample)
- pnpm run quality [-- --network | --all | --json out.json]; no AI anywhere

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 00:23:09 -07:00
CatoandClaude Opus 5.5 6b1801359c feat(updates): reader-initiated news updates; AI drafting only on readers' own keys (#102)
* feat(ai): drafting runs only on readers' own keys; ratchet against free-tier background AI

The hourly drafter spent the site's free models. Remove the free-chain path
(freeAsk, backgroundMay); drafting now takes an Ask built from a reader key
(lib/byok-ask.ts). /api/cron/drafts is gone; /api/cron/auto-updates drafts
only for readers who opted in, on their stored key, capped per day (013).
test/no-free-background-ai walks the import graph from every cron route and
fails on any path to the free chain; proven by mutation.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* feat(updates): Update news now for every reader; AI summaries and auto-updates on the reader's own key

- Bottleneck, company and desk pages: "Update news now" sweeps the web
  (no AI, signed out too, rate-limited, 15-min cooldown) and lists the leads.
- "Summarise with AI" drafts up to three on the reader's key (browser or
  sealed); without one it explains the free AI is kept for questions and
  opens the key panel.
- /account/settings#auto-updates: opt-in hourly drafting on the stored key,
  daily cap with a token estimate (3.4k/draft, measured).
- Honest copy: /data/freshness reports drafting as on demand, /review, /data
  AI spend, desk and docs say drafting runs only on readers' keys.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 22:33:46 -07:00
CatoandClaude Opus 5.5 76e7a7675e perf(ask): plan the obvious lookups before the model, one call for page questions (#98)
Measured live 2026-09-25 on the three questions George's report named: first
text 9.0-33.0 s, done 18.7-34.4 s, all served by 10 s OpenRouter links.

- lib/chat-agent/plan.ts: lookups the page and the question's words make
  obvious (listed_exposure, recent_leads, trace_dependencies, named records)
  run locally in parallel before the first model call. When the plan found the
  record AND the ask, the model gets no tools: one call. Page questions are
  capped at two model calls; the web is never pre-fetched.
- listed_exposure tool + listing on get_company: tickers with the listed /
  parent / private status in words (Hitachi Energy -> parent Hitachi 6501 JP).
- 【/path】 and similar training-format markers become markdown links.
- ai-kit 1.14.0: light reasoning on Groq gpt-oss, rolling-window cooldowns,
  per-model daily refusals (bitbaum/ai-kit#71).
- research_ask_timing (012) + /data#ask-latency: p50/p90 over the last day,
  no question text stored; journal line 'substrata ask-timing'.
- test/ask-plan.test.ts: the three measured questions take one model call; any
  page question at most two, even against a model that always wants more.

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 17:40:18 -07:00
CatoandClaude Opus 5.5 03309d4713 feat(series): dated, sourced number series per bottleneck — key numbers, claims, /data/series, CSV, desk alerts (#92)
* feat(series): dated, sourced number series per bottleneck, with key numbers, claims, CSV and desk alerts

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(series): keep desk.ts and the desk page under the size ceiling; showSeries optional like showScience

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(methods): series methods in their own file, like graph and science

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 15:12:37 -07:00
CatoandClaude Opus 5.5 319da42e0a feat(ai): readers first — background jobs draw from a capped, reserved slice of the free budget (#93)
ai-kit 1.13.0 classBudget: drafting may spend <=25% of the day and never below
a 50% floor kept for Ask (env-tunable); spend recorded per class per UTC day
(research_ai_spend) and shown on /data#ai-budget with its method.

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 15:02:28 -07:00
CatoandClaude Opus 5.5 303350b1e3 feat(careers): open roles from public job boards, skills and training per bottleneck (#91)
* feat(careers): open roles from public job boards, skills and training paths per bottleneck

- research/job-boards.json: all 138 directory companies' careers pages and ATS,
  each checked on the company's own site; 6 on public Greenhouse/Ashby APIs are
  read daily (ASM, MetOx, Anthropic, OpenAI, xAI, CoreWeave), the rest linked.
- research_jobs (scripts/db/011-jobs.sql) + POST /api/cron/jobs: daily fetch,
  filed under role family, seniority, bottlenecks and skills by published rules.
- /careers: filters (bottleneck, family, company, country, seniority, remote),
  which bottlenecks are hiring most; /careers/[slug] per bottleneck;
  /careers/paths (O*NET 31.0 + ESCO records, posting skill counts, 56 checked
  learning paths); /careers/companies; hiring section on company pages.
- Desk: follow companies/role families for jobs; new postings are a desk source.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Signed-off-by: Cato <41178744+catomean@users.noreply.github.com>

* feat(careers): chain roles by default, sidebar hiring board, tighter filing rules

Software and business postings are filed under bottlenecks by title only (AI
labs' boilerplate named foundries and grid interconnection); the board defaults
to roles in the chain with a scope switch; the hiring counts sit beside the
list; learning paths come before the occupational record.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Signed-off-by: Cato <41178744+catomean@users.noreply.github.com>

* refactor(desk): relative dates in lib/when.ts, job rows loaded in lib/desk-jobs.ts

Keeps lib/desk.ts and the desk page under the 300-line ceiling with the job
and science sources both on the desk.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Signed-off-by: Cato <41178744+catomean@users.noreply.github.com>

---------

Signed-off-by: Cato <41178744+catomean@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 14:47:53 -07:00
CatoandClaude Opus 5.5 b2dea2fcef feat(ask): fast, any AI via shared ai-kit BYOK, one-click claim verification (#89)
* feat(ask): fast, any-AI via shared ai-kit BYOK, and one-click claim verification

- BYOK on @bitbaum/ai-kit/byok (1.12.0): ten OpenAI-shaped vendors incl.
  Anthropic and Gemini, streamed with tools; drops @anthropic-ai/sdk and the
  local byok-shared copy. Signed-in keys sealed server-side (ai-kit/seal,
  SUBSTRATA_BYOK_SECRET, research_ai_keys); signed-out keys stay in the browser.
  Model picker reads the vendor's live catalogue. Panel in Ask and /account/settings#ai.
- Speed: status before any lookup, parallel tool calls, 3-round cap, page-only
  questions skip tools, free-chain link cooldown after 429s, parallel web reads,
  trimmed history.
- Verify: Check this on every Figure, event rows, bottleneck facts, company lede.
  Reads the cited source + searches the web in parallel before the model, answers
  Supported/Contradicted/Outdated/Unverifiable with quoted passages and links.
- /api/factcheck now runs the same agent loop.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(ask): claim context for list values, computed figures check via their method, no web search for bare numbers

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 14:10:02 -07:00
CatoandClaude Opus 5.5 f4278f89fa feat(science): the science pipeline — stages, live paper/grant feeds, who is doing it (#87)
* feat(science): pipeline feeds — stage model, OpenAlex/arXiv/NSF/OpenAIRE/DOE parsers, store

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* feat(science): /science/pipeline views, bottleneck section, desk source, cron route

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* feat(science): institution stats, stage re-read on refetch, tighter lab wording

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 13:48:53 -07:00
CatoandClaude Opus 5.5 ff66ed6918 feat(review): AI-drafted events from sweep leads, one-click review, accept path to git (#85)
* feat(review): AI-drafted events from sweep leads, one-click review, accept path to git

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* feat(review): pace drafting on per-minute limits, mark the quote in context, document the accept path

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* chore(db): number the drafts migration 010 — 007 is taken by two parallel branches

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 13:13:56 -07:00
CatoandClaude Opus 5.5 fc1c8f8be0 feat: exposure screen, tickers from SEC + OpenFIGI, SEC filings on the desk (#84)
* feat(exposure): listings from SEC+OpenFIGI, exposure screen + CSV, EDGAR filings fetch

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* feat(exposure): strict listing matcher with regressions; filings on the desk; tickers on company and bottleneck pages

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* feat(exposure): listings data for all 138 directory companies

96 listed (13 via a parent), 7 private, 35 no listing found. Every ticker
carries its OpenFIGI or SEC source; matches were reviewed by hand, and the
three false matches the first rule made are now regression tests.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 11:59:07 -07:00
CatoandClaude Opus 5.5 a8bd9cdf84 feat(desk): a desk you control — filters, read/save/hide, rails, sweep settings, no god files (#81)
* feat(desk): make the desk controllable — filters, marks, rails, sweep settings

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(desk): reconcile with Ask — one railsOf, lead reads in sweep-queue

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(desk): whole-word rail matching; split review queue; size ratchet baseline

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(desk): trace every number to a constant; no 'analyst' wording; rebaseline sizes

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 02:28:15 -07:00
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
CatoandClaude Opus 5 c54611814a feat(sweep): run the research sweep on a timer, into a queue rather than the corpus (#68)
The site's promise is that it tells you what changed, and it has been reading
"Updated 2026-09-14" for four days because the sweep only ran when a person ran
it. 92% of company profiles carry no dated event at all. That is the deepest
problem on the site: a research service that is visibly stale has stopped being
the thing it claims to be.

The sweep now runs unattended, and deliberately cannot publish.

Where it writes is the whole design. The corpus stays files in git, accepted by
a person in a commit, because "a human read this and accepted it" is the claim
every row on the site makes. A timer writing into it would publish rows nobody
read, and a release directory is replaced by the next deploy anyway. So findings
land in `research_sweep_candidates`: a queue of leads, none of which reaches a
page until somebody promotes it. A test greps the scheduled path for `writeFile`
and the corpus paths to keep that true.

It is a route rather than a script because the box runs releases, not checkouts,
and the fleet's cron convention calls an authenticated route. A missing
CRON_SECRET refuses with 503 rather than running: an open sweep endpoint spends
web and model budget for whoever finds it.

Runs are bounded to four nodes and rotate by least-recently-swept, so a run fits
the wrapper's 300s and coverage still moves across all 33 bottlenecks. Each run
records what it did, so "how fresh is this" is answerable from evidence instead
of inferred from the newest event — and a node the search backend could not
reach is recorded as blindness, not as a quiet week.

What decides whether something IS an event moved to `lib/sweep.ts`, shared by
the script and the timer. Two copies of that judgement would have drifted, and
the hand-run and scheduled sweeps would have quietly stopped agreeing.


Claude-Session: https://claude.ai/code/session_01Y6ecRd91ZsPPcjuNkKTFV2

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-18 07:37:59 -07:00
Cato 053c95e68c feat: Equal Earth map, threadkit comments, AI fact-check (#54)
Replace the hand-drawn SVG with react-simple-maps (Equal Earth).
Notes, learn, and bottleneck pages get comments (threadkit) and a
corpus-grounded fact-check button. Ask shows whether ai-kit is
configured. Same complete() engine as Cat and Loki — not the Cat UI.
2026-09-16 08:23:31 -07:00
Cato ecca727058 feat: build checkable research atlas and Substrata companion (#43) 2026-09-15 15:26:35 -07:00