57 Commits
Author SHA1 Message Date
CatoandClaude 901e349e6c fix(quality,graph): entity quality counts, registry/graph import cycle, repo docs (#425)
Co-authored-by: Claude <noreply@anthropic.com>
2026-12-02 08:39:51 +01:00
CatoandClaude 64f37d740a chore(deps): @bitbaum/ai-kit 1.26.0: Google out of the free AI chain (#389)
ai-kit <=1.25 put Google's Gemini API in the free chain on the fleet-wide
GEMINI_API_KEY, which sits on a billed Google project. 1.26 builds no Google
link (Groq, then OpenRouter :free), keeps paid AI off unless an app opts in,
and adds daily caps.

- .env.example: drop GEMINI_API_KEY, no longer read
- docs: the screenshot note names the one free link that can see


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-13 10:08:59 +01:00
CatoandClaude 116e9537d0 feat(comments): page discussion is chatkit's CommentThread (#387)
* feat(comments): page discussion is chatkit's CommentThread

The discussion under notes, learn, resources and profile pages was a
hand-rolled list and a bare <textarea> with no microphone. The fleet rule
is that comments are chatkit's CommentThread and that anywhere a person
types words there is a microphone, so:

- Bump @bitbaum/chatkit ^0.22.1 -> ^0.25.0 (CommentThread arrived in 0.23).
  Ask (ResearchChat, AskBox) type-checks and renders unchanged.
- PageDiscussion renders CommentThread: the box is chatkit's Composer with
  the microphone (/api/transcribe), Enter-to-send, and a refused post keeps
  the draft. Posting still goes to /api/comments, where threadkit's
  canWrite decides who may write; a signed-out reader (from /api/me) sees
  "Sign in to comment" linking to sign-in and back to the page instead of
  a box that only fails on submit. Dates keep the YYYY-MM-DD form and
  authors keep "Reader" / "Substrata". Fact-check stays Substrata's and
  re-mounts the thread with its new comment.
- Drop the CSS the package now owns (.page-comments, .comment-meta,
  .comment-form); bind PageDiscussion under the chat block of
  package-plan.json; note it in docs/IMPLEMENTATION-PLAN.md.

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

* fix(comments): a refused comment says why, and no sign-in link where sign-in is off

The route's refusals (too short, the hourly limit, sign in) are thrown as
chatkit's CommentRefused, so the thread shows them instead of a generic
"try again" that would fail the same way forever; a comment under the
route's 3-character floor is refused before it is sent. The sign-in link
shows only once /api/me says sign-in exists on this deployment.

Needs @bitbaum/chatkit 0.28.0 (CommentRefused); the bump follows.

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

* chore(deps): @bitbaum/chatkit ^0.28.0 (CommentRefused)

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-12 12:48:41 +01:00
CatoandClaude 6c5f235de8 feat(contribute): a microphone in the contribution boxes (chatkit Composer) (#384)
* feat(contribute): chatkit Composer with microphone for contribution boxes

"Know something, or want us to look?" (Inquire, on bottleneck pages,
empty states and the world panel) and "Send evidence" beside Ask
(ContributeForm) were bare textareas: no microphone, and a different send
from Ask. The fleet rule is that anywhere a person types words there is a
microphone, and the experience belongs to the package, so both now use
chatkit's Composer with the same /api/transcribe voice leg as Ask.

- Enter sends, Shift+Enter breaks the line, as in Ask.
- useContribution.send answers Composer's onSend: a message under 10
  characters, a missing consent tick (Send evidence) or a failed request
  is said in the box and returns false, so the draft is kept.
- ContributeForm is no longer a <form>, so nothing submits twice; the
  optional reply email and credit name stay.
- Inquire reuses useContribution instead of its own copy of the POST.
- The .inquire-form textarea style is dropped: the composer keeps its own look.
- package-plan.json binds Composer in both files.

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

* fix(contribute): say the length cap before sending, and start each box clean

Composer has no maxLength, so the inbox's 12,000-character cap is now
checked before the request and said in words. Opening or closing a
contribution box clears an earlier refusal, so it never shows over a new
draft.

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-12 09:06:25 +01:00
CatoandClaude fc26f09019 refactor(lists): directory, series index and careers search through listkit (#379)
The company directory, the data series index and the careers SQL search
each hand-rolled what listkit already ships: facet parsing and validation,
facet counts with the facet's own selection lifted, a "show more" URL rebuilt
from scratch, and a LIKE escape. The package rule says use the package.

- lib/universe/directory.ts: the four filters are a ListSpec (directorySpec);
  parseQuery validates them, applyQuery filters, counts and draws the rows.
  Typed words stay with searchkit (textFilter), so a slip is still forgiven.
- app/data/series/page.tsx: bottleneck, measure and origin are a ListSpec;
  applyQuery and matches replace the hand-written predicate and slice.
- lib/list-more.ts: "Show more" keeps the ?n= URLs and writes the next one
  with writeQuery over the reader's params (empty and invalid values dropped).
- lib/careers-query.ts: title search uses likeContains instead of a local
  escape.

Same rows for the same URLs: 1890 directory filter combinations compared
old against new, identical rows, matched counts and facet counts. Tests pin
the spec, the ?n= paging and that a comma in typed words is not a list.

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

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-12 08:26:30 +01:00
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 bf1f73e259 feat(auth): account mail on, so the sign-in link and recovery appear (#322)
Substrata created its account runtime with `mail: { configured: false }`, so
the sign-in link, "Forgot your password?" and address confirmation could
never appear, and a forgotten password had no way back.

- lib/auth.ts sends account mail through AccountKit's `createAuthMailer`
  (mail-kit, the fleet's RESEND_API_KEY). Without a key the options stay
  hidden, as before; confirming an address is never a wall.
- The sign-in, sign-up and account pages pass `mailConfigured()` to
  `signInMethods`, and a reset link that lands on /sign-in is no longer
  redirected away for a signed-in reader.
- The account journey first asserts every way in the env switches on:
  password and passkey always, the link only with mail, "Continue with
  OrangeCat" and the shared sign-in button with their clients. CI sets
  synthetic, unreachable OIDC clients so both buttons are checked.
- @bitbaum/mail-kit is a direct dependency (AccountKit's optional peer).


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-01 23:21:22 +01:00
CatoandClaude Opus 5.5 70258beed0 feat(globe): Substrata's globe on the fleet's one renderer, @bitbaum/geo-kit/map (#306)
* wip(globe): Substrata's globe on @bitbaum/geo-kit/map (lockfile follows the 0.3.0 release)

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

* feat(globe): Substrata's globe on the fleet's one renderer, @bitbaum/geo-kit/map

The world globe moves onto @bitbaum/geo-kit/map 0.3.0, the renderer that was
extracted from it and that Solon's commune map already draws with. Seven
modules go (cull, trace, motion, pick, input, loop, control); globe-geo and
globe-paint keep only Substrata's side (countries keyed by ISO code, the
tokens, the hatch, the layer's fills); the sites, routes, figures and pulse
stay Substrata's, drawn over the Earth through the renderer's `over` hook and
given the first say on a tap or hover through `pickFirst`. The renderer's
wiring is its own file (globe-renderer.ts), so Globe.tsx stays under its
300-line ceiling. The globe's geometry tests now live in geo-kit; the ones
here test Substrata's side.

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-30 23:35:59 +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 f4ee258bc8 refactor(ask): chatkit 0.19 — send handle, initial message, Retry keeps pictures; three answer fixes (#264)
* refactor(ask): chatkit 0.19 — send handle and initial message, thrown turn failures

Delete lib/chat/drive-composer.ts and useAutoAsk.ts, which typed into
chatkit's composer and pressed Send. /chat?q= is ChatApp's deepLinkParam
(sent at once, as before), the home box's ?send= handoff is its
initialMessage, and "Check this" goes through the ref's send with
newChat. The transport throws ChatTurnError instead of returning a failed
message, so the bubble keeps the server's words and Retry re-sends the
pictures.

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

* fix(ask): an attributed claim is Reported when the source only shows it was said

"Confirmed" over "Gartner estimates a $4.9T gap [W2]" told the reader
the gap was real when the page showed only that Gartner said so. The
writer is told the difference, and code downgrades an attributed
claim's Confirmed to Reported when its source line names the speaker or
reports a saying. Partly and Not found are unchanged.

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

* fix(ask): never cut a markdown link in two when dropping sentences

A link whose title held a full stop was split at it; when a guard dropped
the first half the reader saw "…IaaS… ](https://x.com/…))" in the
Reasoning. withoutMaterialFigures, withoutSentencesHolding and
uncitedForecasts split with a bare regex; default-deny masked links
itself. All four now split through lib/chat-agent/sentences.ts, which
masks links (URLs with one level of parentheses included) while
splitting.

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

* fix(ask): a web chip only on a sentence its page supports

The opening of a screenshot answer ended its generic analysis in [W1],
drawn as a finance.yahoo.com chip, and the page (a stock quote) said
nothing of the kind. Before default deny, a [W#] now stays only on a
sentence that carries a figure the cited passage prints or a name it
gives; otherwise the marker comes off and the sentence is judged as
uncited.

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

* fix(ask): the panel's chat list is a drawer at every width

ChatApp's rail follows the window (64rem), so in the ~30rem panel on a
desktop the list took half the panel and left the answer a 12rem column.
The panel passes railQuery="not all"; /chat keeps the rail.

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

* docs(changelog): the answer fixes and the panel's chat list

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 21:44:15 +01:00
CatoandClaude 38a44ceee7 docs(adr): frontier registry — a list of entities we deliberately track (#274)
Claude-Session: https://claude.ai/code/session_018WZnBnaLP6RhwFkLxRTKgE

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-27 19:06:40 +01:00
CatoandClaude Sonnet 5.5 f172a773f6 feat(markets): a directory of every company in the universe, and an honest count of what each page can show (#272)
* feat(markets): a directory of every company in the universe, and an honest count of what each page can show

/markets/directory filters the universe by theme, country, tier and page kind
and searches by name, ticker or theme through searchkit; one column of rows on
a phone, sixty at a time. /data/companies now counts what each page can show
(quote and SEC filings, quote only, identity only) from identifiers alone, and
lists every company considered and out with the test it failed.

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

* fix(markets): the directory's Show more is a 44px target

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 16:02:02 +01:00
CatoandClaude d6185e5bd5 feat(universe): defence theme, 22 fund files, 20 SEC codes, and revenue for filers with no float (#269)
The first wave admitted 594 companies from 731 candidates. This wave reads
22 issuer holdings files (was 14) and 20 SEC industry codes (was 6), adds the
twelfth theme (defence & aerospace) and lets a 20-F or 40-F filer, which
states no 10-K cover float, clear the revenue floor on its own tagged annual
revenue in US dollars (no rate is ever invented).

793 admitted (tier A 133, tier B 660) from 1,013 candidates; 220 considered
and not admitted. Funds read and dropped because their subject is not a
theme (KOMP, XME, PAVE, HYDR, CTEC, RNRG, QCLN, FAN) are named in the ADR.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-27 15:57:03 +01:00
CatoandClaude Sonnet 5.5 cc7fcb4f1f Company page: what constrains it, what it constrains, and no more "holds 0 of 33" (slice 2) (#270)
* feat(markets): what constrains a company, what it constrains, and a lede that never says holds 0

Two sections in the market frame of every company kind, a lede and two tiles
read from the exposure model; the old dependency module now serves bottleneck
pages only.

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

* style: prettier

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 15:51:29 +01:00
CatoandClaude a88a29e447 feat(company): prices for the whole universe, a name check on every new line, and a list of what is not known (#271)
The daily run kept prices and filings for the 28 hand-checked seed lines only;
every other company page read its source live, per request. It now walks the
seed first, then every admitted universe line the price source serves, stalest
first, within its time.

A ticker can be another company's on another exchange, so a line that is not
a seed line is stored and drawn only if the source's own name for the symbol
agrees with the company's; a mismatch is refused with both names. More venue
codes are read (Sao Paulo, Madrid, Milan, Stockholm, Oslo, Warsaw, Johannesburg,
Singapore, Shanghai/Shenzhen by symbol, TSX then TSX Venture).

Each company page gets 'What we do not know yet': every gap with its reason,
the documents that would fill it and a work-queue task, and a 'Why it is here'
sentence built only from the rows that admit it.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-27 15:50:37 +01:00
CatoandClaude 66b3d435e6 feat(markets): company exposure model, ADR, and cited NVIDIA/TSMC supply edges (#268)
Derives what constrains a company, what it constrains, and what it holds
from the dependency layer, directory rows and the relation graph. Ten
buys_from candidate rows, each with a verbatim quote the gate re-read.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-27 15:37:22 +01:00
CatoandClaude Opus 5.5 f5a3619f02 feat(company): quote first, a clean price line, and no Ask pill over a figure (#265)
* feat(company): quote first on a listed company; Ask pill never covers a figure

- A listed company reads like a quote page: name, quote, then the share
  price's range row and chart. Its role in the chain (the lede, the five
  tiles at a glance, why it is graded so, where the role is cited, and the
  update news) moves below Key statistics as "Role in the chain"
  (section id chain-role; `role` is already the "What this holds up"
  module). Unlisted, identified and stub companies are unchanged.
- From 768px the page column keeps a right gutter as wide as the floating
  Ask pill, which sat on NVIDIA's "Largest fall from a peak" at 1440px.
- On a phone the floating pill is hidden again: Ask is the top-bar button
  there. The rule was lost in the chatkit move (#140), leaving two Asks and
  the pill over the same figure at 390px.
- docs/design/company-page.md follows the new order and the rule.

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

* feat(company): a year of closes is a clean line with a light fill

chartkit 0.3.0 (LineChart markers + area): the price chart passes
markers="auto" and area, so a range of more than 60 closes draws no dot
per close (about 120 beads on 1Y before); each close still shows its
value on hover and keyboard focus, and the table holds them all. Short
ranges (1M) keep their dots.

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 14:17:31 +01:00
CatoandClaude Opus 5.5 6e5bbf3483 feat(markets): a company page that reads like a markets product (#259)
* feat(markets): a company page that reads like a markets product

The owner, 2026-10-25: "I don't see any beautiful charts on stock
performance … think Bloomberg, think Yahoo Finance", and on NVIDIA's
holders, "'other' is 87%. We have a vague idea of what that means."

Every company page now carries one market frame, in one order, whatever
the company is (docs/design/company-page.md): a header quote (ticker,
exchange, currency, last close, 1-day change, date, "delayed end-of-day ·
Yahoo Finance"), then share price, key statistics, revenue and net income
by year, who owns it, how it does business, and peers. A section with no
data stays and says what source would fill it, with a Send-evidence link.

- Share price: a line chart with one row of six equal range cells
  (1M·3M·6M·YTD·1Y·5Y), the page's only client island. Every range is
  computed on the server, along with its return, span and largest fall,
  the 52-week range, a returns table and the 50/200-day averages
  (prices/compute.ts).
- Key statistics: eight equal cells. Market value is computed only where
  close × cover shares is the value; otherwise "Not computed" with the
  reason. Each annual figure shows its fiscal year, growth and filing.
- Financials: chartkit's new ColumnChart (0.2.0) for five fiscal years
  from XBRL, plus rows with growth and margin computed in code.
- Who owns it: holders from 13G/13D/proxy. The remainder is labelled
  "Others, each below 5%" in the legend (chartkit's new ShareBars
  otherLabel) and explained in its row. A company with no listing shows
  the owners the relation graph states.
- How it does business: customers, suppliers, competitors (always), and
  stakes, sites and partners from lib/graph, one row anatomy. An empty
  group names the filings that would fill it, and points to the quoted
  dependency rows where they exist.
- Peers: the same chain step (tier A) or the same theme (tier B), with
  last close, 1Y return and a sparkline.

Tier B companies get prices, financials and holders: lib/market-data/company.ts
joins a slug to a listing. It tries the seed first, then the universe
ticker on a venue the price source serves. New venues (US composite,
London, Hong Kong, Korea, Taiwan, Toronto, SIX) are added to Yahoo's
suffixes. Ambiguous venue codes are not guessed. Sections stream in their
own Suspense boundaries, with reads deduplicated per request, so a slow
price source never delays the header. Ask charts link "Open <Company>" to
the page, and the holders bar in answers carries the remainder label.

Verified: pnpm run verify; pnpm run build; test/company-page.test.ts;
scripts/ux/company-layout.mjs at 320/390/768/1440 on NVIDIA, Oklo,
SpaceX, NAC Kazatomprom and a stub, against live Yahoo and SEC.

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

* docs(design): the header's quote lives in price-view.ts

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 13:43:25 +01:00
CatoandClaude ac8056fd77 refactor(ask): chatkit ChatApp for the panel and /chat (#262)
The Ask panel and /chat were Substrata's own assembly of chatkit's pieces
(ChatScreen, Composer, ChatThread) with no chat list, no New chat and no
reload. They are now chatkit 0.18's ChatApp, the same app Heidi, Loki and
OrangeCat move onto: Chats drawer (a rail on a wide screen) with search,
rename and delete, New chat, temporary chat, titles, the queue, Stop and
the open chat reopened on reload. Chats are kept on the reader's device
(localConversationStore); no server conversations, no migration.

Substrata keeps only its own parts: the transport (askTransport: /api/chat
with pictures, the stream into turn.update, the evidence on the message,
the server's own words on a failed turn), chartkit renderers, AnswerFooter,
the key and "Send evidence" under the composer, one composer configuration
shared with the home box. Panel and /chat share the store and the open
chat, so Expand is only a bigger frame (lib/ask-thread.ts goes). A message
from elsewhere (Check this, ?q=, the home box's ?send= with its pictures)
opens a new chat and is sent through the composer, since ChatApp has no
send handle yet (lib/chat/drive-composer.ts says so).


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-27 12:35:27 +01:00
CatoandClaude 0dc40c2530 feat(ask): attach screenshots, read them, check their claims (#260)
The owner could not ask Substrata about a screenshot of a post: every
composer passed attach={false}, and /api/chat took no pictures.

- One composer (AskComposer) on the home box, the Ask panel and /chat:
  Camera / Photos / Files, paste and drop, pictures shrunk to 1024px in
  the browser (Heidi's limits), text files inlined, a message queued while
  a turn runs, the draft shared between surfaces.
- /api/chat validates pictures (strict data URLs, three at most, 1.5 MB,
  never stored or logged) and attached text, with a larger body cap.
- A turn that brings material is a claim check: one read call returns the
  visible text and checkable claims as JSON (claims whose numbers the
  material never printed are dropped), each claim is searched and, for a
  seed company, priced; the answer is bottom line first, one status per
  claim with a citation or "Not found", reasoning labelled, and no figure
  only the material gives repeated as fact. Every existing guard runs.
- No model that can see: one sentence (paste the text, or add a key);
  nothing is guessed.
- The home box hands its message and attachments to /chat (?send=).

Tests: claim-check (fixture, fake vision model, fake web), handoff, image
validation; two eval rows; ask-layout picks a picture into /chat's box.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-27 10:36:52 +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 30c7137d60 feat(ask): research mode for analytical and forward-looking questions (#248)
The owner, 2026-10-25: asked about future demand for neon, the Ask read six
pages and answered with one US table. Analytical questions (outlooks,
forecasts, what-ifs, comparisons of impact, "when could X be commercial") are
now routed to a research mode:

- route.ts classifies `analysis`; loop.ts hands those to research.ts
- research-plan.ts: one model call writes 3-6 sub-questions with a query each,
  validated in code (listed corpus tools, their own arguments); a code plan by
  question kind when the call fails or times out (7 s)
- research-read.ts: every sub-question searched in parallel through lookUp
  (SSRF-safe readPage, PDFs), one 15 s deadline, passages kept round-robin,
  one URL once, two per site, primary/trade/analyst before farms, as [W#]
- research-shape.ts: bottom line first, then What is established, What drives
  it, Scenarios, What would change this, Confidence and gaps, Sources (from
  the citations); uncited forecasts dropped; unanswered sub-questions said by
  code and filed through gaps.ts
- scenario-calc.ts: the model names cited inputs and cases, code checks every
  input against its passage, computes low/base/high with the formula shown and
  draws a line chart through the chat_ui chart block
- default deny holds reasoning sections to the labelled-background rule
- api/chat: "Reading <site>…" now reaches the reader (onRead was dropped);
  analysis answers get more output room
- tests with fakes for the five owner questions; ask-evals rows; a script to
  ask them live after deploy (scripts/ux/ask-live.ts)


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-25 12:59:15 +01:00
CatoandClaude Opus 5.5 3ed7dff5ed feat(universe): a written rule for which companies are in — and the first 461 identified companies (#250)
* docs(universe): the company-universe methodology — three tests, tiers, evidence

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

* feat(universe): admit companies by a written rule — theme, materiality, identity, each cited

A company is in when cited sources place it in a frontier-technology theme,
show it clears a size floor, and identify it in a registry. admit() applies
the rule from config/universe-themes.ts; whyCompany() answers for any name
(in, out with the failed test, considered, named, or queued as a GapTask);
company_membership lets the Ask answer it; /data/companies prints the rule
from the same config. Tier B companies are a derived entity source with an
'Identified, not profiled' page; a stub the universe identifies is promoted
in place. Adapters: issuer fund holdings (ARK, Global X, First Trust,
Defiance, State Street), SEC EDGAR tickers/public float/SIC, GLEIF and
Wikidata by ISIN, Wikidata industry classes; tested on recorded responses.

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

* data(universe): first wave — 461 tier B companies from 14 funds, EDGAR, GLEIF, Wikidata

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-25 12:54:53 +01:00
CatoandClaude Opus 5.5 8e85c7e7b4 feat(ask): search and read the web up front for open-world questions (#244)
* feat(ask): search and read the web up front for open-world questions

The owner read the recent chats: the Ask behaved like a search over the
corpus, not like a language model that researches. Asked for Kazatomprom's
2026 guidance it opened with "The Substrata corpus does not track..." and
never gave the figure; asked how competitors' share prices moved this month
it said Substrata "does not record" equity moves, with web leads unused.

- route.ts: a pure router decides per question whether the web is needed
  (news, prices, guidance, what someone said, competitors, people,
  explanations, and by default anything but questions about Substrata
  itself or off-topic chat). runPlan searches it in parallel with the
  corpus lookups; "this month"/"today" become dated queries.
- Pages are read, not snippets: top four in parallel, PDFs as text via
  unpdf behind readPage's SSRF checks, the matching passages verbatim with
  the page's date.
- Prompt: answer first and directly from corpus rows, [W#] passages and
  marked general knowledge; figures only from a row or a dated passage;
  never open with what the corpus lacks.
- Guards: a figure cited [W#] must be in that passage (sent back once,
  then dropped); marked background survives default deny without figures
  or link claims; corpus-gap openings move to the end and "Unchecked web
  results" headings go. Corpus table guards unchanged.
- UI: [W#] renders as a chatkit source chip linked to the page with its
  site and date; "Web pages read · not checked by Substrata" under it;
  "Reading <domain>…" steps while it works.
- Evals and tests for the router, page reading (fake fetch), the PDF
  path, the web-figure guard, answer-first, and the six new questions.

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

* docs(ask): record the open-web Ask policy and why

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-24 18:49:23 +02:00
CatoandClaude ddcbf3d340 docs(architecture): the research systems — the answer ladder, the relation graph, dossiers (#217)
The live Ask said Kazakh uranium operators were "not recorded in the corpus"
while research/usgs-producers.json holds 35 Kazakh facility rows with operator
and owner. The wall was missing plumbing, not missing data. This records the
skeleton to build before more data: a ladder that never ends in a refusal, a
typed sourced relation graph, evidence grades, derived-edge rules with a
mass-balance coverage ratio, dossiers whose completeness is computed, and a gap
queue a cheaper model can work. lib/graph/types.ts is the shared contract.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-24 07:20:51 +02:00
CatoandClaude Fable 5.1 2085534968 docs(architecture): the knowledge system — index, significance, data entry, primers, new kinds (#210)
* docs(architecture): the knowledge system — index, significance, data entry, primers, new kinds

The owner's bar (2026-10-23): showable to funds, journalists and think
tanks; 'Niger → oil before uranium is a failure of a system'; build the
systems so a cheaper model can add data; primers per entity. This ADR
names the retrieval index, the known-for ranking that fixes Niger at the
root, the data-entry contract, primers with PDF, and the person/party/force
kinds, with the PR sequence that builds them.

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

* docs(architecture): date the knowledge-system ADR in its filename

The docs-truth gate judges every doc under docs/ against the tree and held
the PR for naming 26 files the sequence will create. A proposal describes
its date, not today; the fleet's rule exempts a dated filename.

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-23 11:40:35 +02: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 40eadda31d docs(infra): name the removed worklists in the sentence that removes them (#187)
The removal of research/events.json and research/evidence.json was stated across a line break, so the paths read as live references. Same facts, one clause.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-19 13:57:30 +02:00
CatoandClaude Opus 5.5 56c8c77901 docs: correct drift in README, infrastructure and plan docs (#186)
* docs: correct drift in README, ROADMAP-adjacent docs and the implementation ledger

- README: beta status, lib/ and app/ descriptions match the tree, the nav
  lives in components/shell (PublicNav.tsx is gone), merge-then-deploy path
- INFRASTRUCTURE: drop the background-share/reader-floor env vars no code
  reads; the free-AI ledger is readers-only since 2026-09-25
- CONCEPT: 'Where this goes' was unbuilt when written; Exposure shipped since
- IMPLEMENTATION-PLAN: mark as a dated ledger; correct the current chrome,
  map renderer, chatkit adoption and sweep cadence

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

* docs(env): list CRON_SECRET, NEXT_PUBLIC_FC_WIDGET_TOKEN and OPENALEX_API_KEY in .env.example

All three are read by the code and were missing from the example.

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-19 12:03:28 +02:00
CatoandClaude 25bb2a16d1 feat(atlas): every chain read six ways — markets, research, money, people, policy (#176)
The chain panel gains six tabs (?lens=): Overview, Markets, Research, Money,
People, Policy. Each lens is built from records only (app/atlas/lenses/) and
shares one shape: what it means in sentences, the figures that carry it, the
records behind it, and the page that holds all of it, naming the reader it
serves most.

- Overview: why it binds (the research claim), the grade that ships, the four
  severity tests in words (labels now shared from config/substrata-assessment),
  the analyst's rationale, and dated events.
- Markets: listed makers by ticker, what a stop reaches (the scenario engine's
  own propagation), exposed companies listed first, and key numbers.
- Research: ways around it by readiness, substitutes kept apart, the claims
  the numbers back, and whether its papers are watched.
- Money: whether money is the constraint, funders with a mandate, and what
  each kind of capital will and will not fund.
- People: the work it needs, the registers' names for it, where to train, and
  where its makers hire.
- Policy: rules that touch it, export restrictions on its raw material (the
  maker's own country first), and sanctions over where it is made.

The tabs are links: shareable, script-free, a 3 x 2 grid that never hides a
tab, and the chosen lens rides along as the reader walks the chain. The
separate "What you can do" block is folded into the lenses. Countries read
"the Netherlands" in prose.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-12 06:34:47 -07:00
CatoandClaude c9b421d54f feat(atlas): producer sites on the globe, and every chain as a route you can follow (#175)
Producers on the globe
- research/producer-places.json places 997 of the 1,167 facility locations in
  the USGS Minerals Yearbook tables, in 37 countries, from GeoNames (CC BY 4.0),
  matched offline by scripts/research/geocode-producers.py.
- Each point states its precision (the facility, the nearest town, or only
  the province) and the GeoNames entry it came from. A named province must
  hold the point, "N km north of X" is applied as an offset, and a bare name
  with distant namesakes is left out rather than guessed.
- test/producer-sites.test.ts fails if a dot lands inside another country.
  The quality page measures the same through lib/quality/checks-places.ts.
- The globe draws sites as dots, or rings when only the province is known.
  A click flies in close and opens the site's facilities, capacity and both
  sources in the panel.

Chains as routes
- app/atlas/chain-route.ts is the one route model: every step two levels up
  and down, numbered in the order material moves, each placed where it is made.
- The diagram (AtlasChain) now reads left to right through every step, with
  makers inside the bottleneck's card. This fixes the connector that ran
  through the part suppliers' cards.
- "On the globe" lays the same route over the Earth: one lifted arc per hop,
  a light running input to output, and labels numbered like the panel's list.

The globe's input wiring moves to globe-control.ts; sites and routes are
painted by globe-overlay.ts.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-12 05:11:11 -07:00
CatoandClaude 0f0648048f feat(atlas): the globe says where, flies there, and every chain says what you can do (#174)
From the owner (2026-10-12): Substrata should feel like an analyst's
instrument — more motion, a country zoom that is beautiful, maps that show
where a resource comes from and who makes it — and the research has to be
actionable, with the action depending on who is reading.

Globe
- Callouts: a painted resource labels its top producers on the globe itself
  ("Australia · 32%", "Chile · 19%"), largest first, at most eight, faded
  toward the limb. mapLayer() returns them; the name comes from the map.
- Picking a resource turns the globe to its largest producer. Lithium used
  to open on Europe with Australia and Chile on the far side.
- A ring opens from a picked country as the globe flies to it.
- globe-marks.ts holds the annotations (globe-paint.ts stays under 300
  lines); label colours come from the tokens via readPalette.
- Fix: the frame loop's cleanup cancelled a pending frame but kept its
  handle, so a remount (React's development double-mount) left the globe
  blank forever. The cleanup now forgets the handle.

Chains
- "What you can do" on every chain, one row per audience the site already
  names (config/audiences.ts): equity investors get the listed holders and
  tickers on file and the stop scenario; commodity traders the raw material
  on the globe and the rules that touch it; industry teams the relief
  pipeline with its best readiness and whether money is the constraint; job
  seekers the roles filed under the bottleneck; learners the dossier. Built
  from the data in app/atlas/chain-actions.ts; a row with nothing behind it
  is not shown; "Not investment advice" beside it.

docs/DESIGN.md writes the direction down: the register (precise, calm,
sourced; not neon), motion only where it answers a question, who comes back
and why, and the next five steps (producer points, chain arcs on the globe,
a reader setting, sourced AI briefs, a dark atlas).

Tests: chain-actions (new), globe callouts; full suite 506/506, tsc, eslint,
prettier clean. Checked rendered at 390 and 1440: lithium, copper, the
flight to Chile, the EUV actions.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-12 04:09:08 -07:00
Cato 9782009df0 Bound geography manifest loading and make globe failures retryable (#127) 2026-09-30 10:06:24 -07:00
CatoandClaude Opus 5.5 02796b0195 feat(ai-key): check a pasted key with its vendor; pick from the models it can use (#114)
- ai-kit ^1.17.0; /api/ai-key/models uses @bitbaum/ai-kit/byok-probe instead
  of fetchCatalog, which said "works" for a dead OpenRouter key (its /models
  is public; only /key refuses)
- PUT and PATCH probe the key again before sealing and reject a model the key
  cannot use (lib/byok-check.ts); a dead key is never stored
- one admission rule, lib/byok-admit.ts, shared by the server and the
  browser-only path, so "Use this key" stays off until a check passed
- panel: paste -> auto-check (600ms) -> select of the key's models with the
  strongest preselected; free text only when the vendor lists none; the
  vendor's refusal in its own words; Change model / Replace key / Remove
- tests: unchecked, refused and unlisted keys rejected; routes vet before
  they write (each guard proven by mutation)
- docs: Ask moves to @bitbaum/chatkit once it is published

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 23:10:52 -07:00
CatoandClaude Opus 5.5 6c32aa5931 refactor(research): one queue per engine; fix(ask): usable model picker on phones (#111)
* refactor(research): one queue per engine — the database, not committed worklists

The event sweep and producer sourcing each had two queues: a committed file
from the old hand-run CLI (research/events.json, research/evidence.json) and
the database queue the box timers fill. /api/events read the file and reported
a sweep from 2026-09-15 while the real one runs hourly, and the freshness gate
would have failed the build around 2026-10-16.

- /api/events reads freshness() from research_sweep_candidates (force-dynamic),
  with sweep.readable=false instead of a fake answer when the DB is down.
- Bottleneck pages read open research_source_candidates live
  (ProducersTable + openCandidatesFor); null -> "could not be read", never
  "nothing found". The corpus now says sourced/unverified only; found pages
  never change a row's state, the export or the search index.
- Removed EVENT_WORKLIST/candidatesAwaiting, EVIDENCE/evidenceFor, both JSON
  files, both CLIs, the weekly research-sweep workflow and their npm scripts.
  Unreviewed rows were copied into the DB first (25 sweep leads, 2 source
  pages; the rest were present or belonged to rows since sourced).
- Freshness: dropped the two file datasets; new test fails when a committed
  research/*.json has no DATASETS row or a declared file is gone; a test fails
  if either worklist file comes back.

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

* fix(ask): model picker gets a labelled button on narrow composers

At 390px the free-model select was squeezed to "A…", at 320px to a bare
chevron. Below a 28rem composer width (a container query, so the dock counts
too) the bar shows Dictate, Attach, "Model <name> ▾", Ask; the button opens
the picker full width underneath together with "Use your own AI key instead".
Wide composers are unchanged.

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-25 08:39:07 -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 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 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 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 cfaf05a10c refactor: split the god files by job, and globals.css by feature (#83)
Every code file the size ratchet grandfathered is now under its 300-line
ceiling, split by what it does rather than by line count:

- lib/search.ts -> entry + lib/search/{text,corpus,build,expand,score,snippets}
- lib/chat-tools.ts -> lib/chat-tools/ (one module per tool family + registry)
- lib/chat-agent.ts -> lib/chat-agent/{loop,parse,turn,prompt,stream-gate}
- lib/chat.ts -> lib/chat/{types,retrieve,models,answer}
- ResearchChat.tsx -> components/portal/chat/ (thread, turn, composer,
  BYOK panel, contribute form, hooks)
- SearchBox.tsx -> components/portal/search/ (popover, page form, shared)
- profile modules, lib/bottlenecks.ts, lib/participants.ts -> build/board
  and module-family files beside them
- app/page.tsx, app/markets/[slug]/page.tsx, app/policy/page.tsx -> section
  components in private _home/_sections folders

globals.css (2379 -> 664 lines) keeps tokens, base and site chrome; the
feature blocks moved to app/styles/*.css, imported from the root layout in
the order they had inside globals.css so the cascade is unchanged.
Screenshots of /, /search?q=asml, /markets/asml, the EUV bottleneck, /chat,
/notes, /atlas, /policy and /talent at 390/820/1440px are pixel-identical
to main.

The config/ corpus files stay grandfathered as data; the logic that was in
them moved to lib/ (coverage-progress.ts, participants.ts, geo.ts).

Also: the desk's "Open on" select said "Last all time"; and
INFRASTRUCTURE.md now records the hourly :17 sweep timer, the everyHours
setting that decides whether a run is due, and that 005-desk.sql is applied.

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 11:22:12 -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 1875632420 feat(chat): let the assistant look things up, without letting the web pretend to be research (#64)
Asking "what are the other fields" got a wall, and the wall was two things, not
one. The corpus genuinely does not name the helium fields — that part is a data
gap, recorded in docs/DATA-MODEL.md. But the assistant also could not go and
find out, and that was not a considered limit: ai-kit has had `webSearch` and
`readPage` all along, and `SEARXNG_URL` is simply not set for this app, so
"You have no tools" in the prompt described the deployment rather than a policy.

It can look now, and what it finds arrives as a lead rather than a finding.

The corpus is the product: a claim on it has been read and accepted by a person.
So three rules keep the two apart. Web passages travel in their own channel and
render under their own heading — they never become `[F#]`, which means a corpus
row. A fetched page is attacker-controlled text, so it is fenced, labelled, and
the model is told that nothing inside the quotes is an instruction; the defence
is the framing rather than sanitising somebody's prose. And it is bounded: one
search, two pages, short excerpts, tight timeouts, and only after the corpus has
already failed to answer. A question is not permission to crawl.

Grounding verification still guards corpus answers, and is skipped only for an
answer that is openly citing the web, because that answer is not claiming to be
corpus-grounded.

Off unless `SEARXNG_URL` is set, and it reports "off" rather than "nothing" —
"we did not look" and "we looked and found nothing" are different answers.
Enabling it in production is one line in the box env, and is deliberately left
to a human: it turns anonymous questions into outbound fetches.


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

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 09:14:28 -07:00
CatoandClaude Opus 5 b8bea17976 A kind is one file, loops become entities, and the assistant knows what you are reading (#63)
* feat(entities): a kind is one file now, and the loops stop being a dead end

Two changes that only make sense together.

The nine entity adapters lived in one growing module. The corpus is about to
grow sideways — people in public roles, parties, lobbies, think tanks,
laboratories, more of the capital world — and each of those is a new KIND of
thing rather than more of an existing one. They are one file each now, in
`lib/entities/sources/`, registered in one place. A test holds the claim: every
declared kind has exactly one source, and every source a declared kind.

Then the kind that was already implied by the data: the loops. A loop — design,
build, measure — is what the whole corpus is about, since the site's claim is
that technology improves at the speed of the slowest turn. They were the only
thing in the model with no page: not linkable, not searchable, not discussable,
and a dead end in the web. They are entities now, with `/loops/<id>`, and they
cost one adapter file, because everything else came free — identity, retrieval,
the relation web, a profile with discussion, and the path to and from them.

`gates` joins bottleneck to loop, 50 of them, so the web now answers "why does
this matter" and not only "what is next to this". Read from the loop's end the
same relations answer what is in its way, worst first, because the slowest gate
sets the pace.

Loop rows say what they are: the project's own model, not a measurement.

Also new: a test that every entity's href resolves to a route the app actually
serves. A new kind whose href points nowhere is otherwise invisible until a
reader clicks it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y6ecRd91ZsPPcjuNkKTFV2

* feat(profile,chat): competitors, news that reaches the page, and an assistant that knows what you are reading

Three faults found by reading the site as a reader rather than as its author.

**The assistant did not know what page you were on.** Asking "what are the other
fields" on the ExxonMobil profile returned "Not in your data", because the
question was answered against the whole corpus. The dock already knew the path
and threw it away: `topic=""` went to the chat, and `topic` was only ever used
by the contribution form. The path now reaches retrieval, the entity under the
reader is seeded ahead of any keyword match along with its neighbours, and the
system prompt says which record "it" and "they" should resolve against. The path
is validated as a local path and length-bounded, because it reaches retrieval.

**A profile asserted concentration and did not show the other makers.** "One
company on earth builds them" is exactly the kind of claim this site exists to
substantiate, and a reader could not check it. "Who else makes it" derives the
other producers of the same material from the relation layer, each with the
evidence of its own row — so ExxonMobil now names QatarEnergy, Gazprom, Air
Liquide and Linde, and says which of those rows are sourced and which are
candidates. It says plainly that this is coverage and not a market: "the only
producer" and "the only producer we have sourced" are different claims and only
the second one is ours.

**News could not reach a company through what it makes.** A timeline only holds
events that name the organisation, so ExxonMobil read "nothing recorded" while
the helium shortage its own product suffered sat one page away. Those events are
listed now, labelled as being about a material it makes rather than about it.

Also: docs/DATA-MODEL.md, written after reviewing what the corpus says when read
cold. It records the three faults with numbers — 30 of 51 country rows connect
to no bottleneck at all — and the direction out: production and reserves with a
year, a basis and a source; named facilities so "a few fields" names them;
derived reads (share, per capita, concentration, reserves-to-production) that
are computed and never stored; and strategic chokepoints, because the model
knows where things are made and nothing about how they move.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y6ecRd91ZsPPcjuNkKTFV2

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 08:42:45 -07:00
CatoandClaude Opus 5 375a2448f8 The web as a schema, and the seams for eight languages (#61)
* feat(relations): the web becomes a schema, and every join says how well it is evidenced

Substrata's claim is that these constraints are connected — a firm makes a
material, a rule governs it, a mandate could fund relief. The joins are the
product, so they now get the same discipline as the rows.

Relations were free strings built ad hoc per kind, and that cost three things.

`makes` and `produced by` were the same fact declared twice, in two directions,
with nothing making them agree. A relation is declared once now and read from
both ends, so they cannot drift.

A policy instrument was emitted with `kind: 'capital'`, so rules rendered as
capital on a country dossier. Instruments are policy entities, and a test holds
that.

And no edge carried evidence at all, so an unverified lead and a sourced finding
rendered as the same line — the one thing this site exists to keep apart. Every
relation now states how well THE JOIN is stood up, which is not how well either
end is: a sourced company and a sourced material can still be connected by
nothing but a directory guess, and it says so.

335 relations across seven kinds. `governed-by` is new: which rules govern a
bottleneck was not in the graph at all.

`lib/graph.ts` keeps its shape and becomes an adapter, so /api/graph, the
country dossier, chat retrieval and the profile module inherit the fixes. Labels
come from the entity registry, so a country is its name rather than its ISO
code, and the graph route stops carrying a hand-copied kind list that had
already fallen a kind behind.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y6ecRd91ZsPPcjuNkKTFV2

* feat(i18n): open the seams for eight languages, without faking a single translation

The expensive part of shipping in eight languages is not translating. It is
discovering afterwards that the code assumed one — strings welded into
components, dates built by hand, a layout that only goes left to right. Those
assumptions are cheap to remove now and painful to remove at scale, so they are
removed now. No translation is invented in the process.

The content divides into three kinds that cannot share a mechanism.

**Interface strings** are keyed, in `lib/i18n/messages.ts`. English is the
source and defines the key set, so a missing key is a type error rather than a
blank on a page. Every other locale is deliberately partial: a missing string
falls back to English, and `gapsIn()` and `coverageOf()` report exactly what
fell back. A fallback nobody can measure is how a half-translated product ships
without anyone finding out. All twenty profile-module titles and the evidence
vocabulary are migrated, and a test fails the build if a module writes a title
into the component — a string welded into a component is one no translator can
reach. Proved by mutation.

**Research prose** — about 5,500 words — is Substrata's own writing, so it is
translatable, and a translation is a claim like any other: it carries who made
it and when. `readProse()` reports whether the text is really in the language
asked for. A machine translation may exist as a draft and may never count as
checked, because prose that reads fluently but was never verified is
indistinguishable, to a reader, from prose that was.

**Quotations** — about 1,000 words — are never translated. The entire
evidentiary value of a quote is that these are the words the source published;
a translated mandate sentence presented as the EIB's own would be invented
evidence. `Quotation` has no translations field, so the type enforces it rather
than a convention.

Also: `lang` and `dir` on the document, so Arabic flips the layout and not just
the text, and locale-aware date and number formatting, because the corpus stores
ISO dates for storage reasons and no reader wants to read one.

Not done, and deliberately not faked: no translations exist, every non-English
locale reports 0%, and there is no /de/ routing — that is cheap to add once
strings are external and pointless before translations exist, since it would
ship seven locales silently serving English. docs/LOCALIZATION.md records the
rules and what is left.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y6ecRd91ZsPPcjuNkKTFV2

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 06:07:52 -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 70022c7202 feat(map): a dossier for every country, not a demo for one (#53)
* feat(map): a dossier for every country, not a demo for one

Index all 177 landmasses. Geology directory plus extra endowments so
Chile, Kenya, Greenland, Colombia are real pages. Lithium countries
link to the chemicals bottleneck; uranium countries to the fuel cycle.
World view gets resource filters, coverage counts, similar geologies,
and an SVG of connected records.

* fix(map): drop unused country-resources import
2026-09-16 08:01:48 -07:00
Cato 478d0d8866 feat(ask): Grok-like thread on ai-kit grounding (#52)
Replace the one-shot form with a companion thread: starters, follow-up
turns, citation chips, stop, and a separate evidence inbox. Retrieval
joins the corpus, country directory and graph neighbours, then answers
through ai-kit complete() + grounding. No second HTTP client.
2026-09-16 07:39:58 -07:00
Cato ca1b70b8e9 feat(map): country dossiers, resource directory, derived graph (#51)
Clicking Niger or Argentina is no longer a blank panel. Each country
opens a dossier: public-geology directory, related bottlenecks, corpus
rows, and graph neighbours. Paint is resource vs researched vs both.

New unverified leads: lithium chemicals, uranium fuel cycle, metal AM
machines, SMR licensing. GET /api/graph is the join; config files stay
the producer. Bloomberg numbers, job scrapes and newsletters are
documented, not faked.
2026-09-16 07:10:47 -07:00