Architecture
One Node 24 process, one store, and a web app served by the process itself. Everything the fund knows is an event in the record. Everything it shows is a fold over those events.
seats ──► pipeline ──► proposal ──► kernel ──► owner signs ──► gateway ──► venue (paper | IBKR)
▲ │ │ │
└──── wire, market ─────────────────┴──────── record (append-only, hash-chained) ◄┘
│
projection · replay · evidence
The parts
| Path | Part | Job |
|---|---|---|
src/record/ | Record | Appends events and hands them back. Each event carries the hash of the one before. verify() recomputes the chain and returns {ok, count, broken_at, reason}; it hashes the payload as stored, not as upcast. schemas.ts defines every event type and the upcasters for older versions. |
src/db/ | Store | pglite in-process by default, Postgres when DATABASE_URL is set. Triggers refuse UPDATE and DELETE on the event table, so append-only holds even against the application. Also holds the blobs, bars, wire items, orders and the jobs table. |
src/kernel/ | Kernel | A pure function: evaluate(FrozenInputs) → Verdict. No I/O and no clock. RULES is the catalogue of 26 rules with their default grades and mandate keys; FLOOR_RULES and OVERRIDABLE are fixed sets. Also largestPassingQty, sizeScale and drawdownTier. |
src/gateway/ | Gateway | The only path to a broker. Checks the owner's signature against the kernel digest, holds a lease so only one process submits, gives every order a deterministic client order id, and recovers after a crash by reconciling against the broker, holding the lease while it does. |
src/broker/ | Venues | paper.ts fills at the market's price with fees. ibkr.ts sends orders to Interactive Brokers through the owner's Client Portal Gateway. venue.ts is the interface both implement, and the stand-in that sends nothing when a live fund's process lacks the broker. |
src/market/ | Market | synthetic (seeded, with one documented planted effect) or live (public quotes and ECB FX, falling back to synthetic with a label). Caches bars for the screens and the factor model. |
src/seats/ | Seats | The research desk. providers.ts and connect-catalogue.ts are the catalogue of 52 providers with models and prices; roster.ts gives each seat its own provider and model; audit.ts stores each call's prompt and response as content-addressed blobs, with keys scrubbed; viewschema.ts sets every number and watch threshold on a view (the seat writes only words); debate.ts has the judge read the bears in both orders. Seat output is text and probabilities, never money figures. |
src/screens/ | Screens | Eight pure screens over daily bars that turn the universe into candidates, each with the screen's name and why it fired. source.ts gathers bars without a network call per name. |
src/ideabook/ | Idea book | An LMSR market that prices views against each other. balances.ts: seat balances, bankruptcy and re-float. |
src/evidence/ | Evidence | Brier score and decomposition, calibration, sequential tests, drift, the verdict calendar. hypotheses.ts: pre-registered hypotheses with alpha-spending looks and a stop clause. |
src/measure/ | Measurement | nulls.ts: the random, benchmark, momentum and system books. controls.ts: the fund against its hardest control. attribution.ts: the day's P&L split into market, residual, fees and other, summing exactly. daily.ts: the step that runs them after the NAV, and their read side. |
src/risk/ | Risk | factors.ts: a diagnostic factor model (market, sector, momentum, size) estimated from bars. stress.ts: scenario losses on the current book. sizing.ts: a size as named steps, the ask against the caps. All pure. |
src/claims/ | Claims | Every statement the fund relies on, with its source; confirmations and contradictions are kept beside it, and reliability is counted per source. |
src/wire/ | Wire | Residual moves beyond 1.5σ and feed headlines. Everything on it is data. |
src/pipeline/ | Scheduler and jobs | scheduler.ts ticks every 60 seconds. day.ts runs the day's steps as jobs. jobs.ts runs a job once per key, with retries and backoff, and records job.dead. guard.ts holds a breaker per provider and the per-wake spend cap. |
src/firm/ | Firm | Wires the parts together. projection.ts is the fold and DEFAULT_MANDATE; governance.ts folds overrides, the rung, claims, the security master, corporate actions, discontinuities and the roster. overrides.ts, ladder.ts, monitor.ts (the thesis monitor), corpactions.ts, analytics.ts (the factsheet) and assist.ts (the ranked action list). demo.ts seeds the demo. |
src/kill/ | Kill switch | cli.ts: engage or release from a terminal, through the running server or straight into the store. |
src/notify/ | Notifications | Email (a minimal SMTP client), ntfy and Telegram. watch.ts decides from each event whether it deserves a notice. |
src/backup/ | Backups | Encrypted dump and restore of the whole store, and the in-memory drill. |
src/ops/ | Operations | health.ts: health with a clause per reason. anchor.ts: signed checkpoints of the head. verify.ts: offline check of chain, anchors and projection. service.ts: one operations desk per firm. assist.ts: the operations items on the assistant's list. |
src/replay/ | Replay | Rebuilds the fund from the record up to any event, using the same fold, re-reading stored seat responses instead of calling a model. npm run replay checks it against the live state. |
src/server/ | Server | HTTP, auth, SSE, and snapshot.ts, the one read model the web app renders. governance-routes.ts holds the governance and operations routes. |
web/ | Web app | Preact and htm, vendored. No bundler, no third-party requests. web/lib/mandate.js is the catalogue of every mandate key and rule with its explanation, typical values and when it bites. |
A trading day
The scheduler wakes Firm.day() once per trading day at SESSION_UTC. Each step runs as a job keyed
day:<date>:<n>:<step>, so a restart resumes the day without redoing finished steps. Research steps get
one retry, the others two. Each appends events; none edits one.
gateway.tick: submit signed approvals, sync fills.expire: stale proposals and approvals.resolve: views whose horizon has passed, scored.research: the screens and the wire feed candidates to the seats, which write views, debated by the bears and ruled on by the judge.propose: an order for each surviving view, sized and checked by the kernel.cooled: orders for owner ideas whose cooling-off has passed.monitor: the thesis monitor checks every machine-checkable falsifier, recordsview.falsified, settles claims, looks for discontinuities and records a change of rung.exits: exits for positions whose view has resolved or broken.- In the demo only, the labelled demo key signs; then
gateway.tickagain. recon: live only, against the venue.nav: strike the NAV.rung: the readiness ladder.measure: null books, factors, stress, attribution, hypotheses' looks and stop clauses, seat balances.- A
wake.outcomeevent with the steps, what failed or was skipped and why, the stop reason if any, and model spend againstwake_spend_cap_usd.
If an open breaker or the spend cap stops a research step, research stops for the run. Reaching the cap
also raises a budget halt scoped to research, which stays until the owner clears it. Risk, reconciliation, NAV and maintenance steps
always run.
An owner's idea
POST /api/ideas does not wait for the day. Firm.submitIdea runs under the same exclusive lock as the
day, queued behind a running one, and:
- refuses, recording
idea.refused, if the kill switch is engaged or an open view on the instrument exists; - records
candidate.sourced(sourceowner) and the thesis asclaim.recorded; - runs the analyst, the bears and the judge on it at once;
- if the view survives, sizes an order and checks it with the kernel.
It returns killed, view, blocked (with the HARD failures), cooling (with cooled_at) or
awaiting_signature. L-PROC-COOLING fails until idea_cooling_sessions session closes have passed
since the idea arrived, unless a signed override is active; the day's cooled step proposes it then.
Each event is visible on the stream as it lands, which is what the live trace renders.
Signing
A proposal's kernel inputs are frozen and canonicalised. Their hash is the digest. The owner's browser
signs that digest with a WebCrypto ECDSA P-256 key the server never sees. At submission the gateway
re-derives the digest, checks the signature against a registered public key, checks the approval has
not expired (30 minutes by default), and re-runs the kernel. Any difference is a GatewayRefusal, and
the refusal is recorded.
Going live is signed the same way, over live:<account>:<terms hash>. The terms fix the account, the
fund's cash, the account's holdings at that moment (the baseline, left out of the fund's book), the
live order cap, the collar, and the IBKR contract for every instrument. When the fund is live, every
digest names the venue, account and contract, and the gateway refuses to send an approval to a venue
other than the one it was signed for.
Two more things are signed in the browser with the same key:
- An override of
L-PROC-COOLINGorL-RUNG, overoverride:<rule>:<instrument>:<expires_at>:<sha256(reason)>.POST /api/overridewithout a signature returns the terms to sign. It lasts 7 days by default and 30 at most. Each proposal it lets through is recorded asoverride.used. - A corporate action, over
corpaction:<id>:<instrument>:<kind>:<ratio>:<new symbol>.
Rules
RULES in src/kernel/kernel.ts, in check order. Each rule's limit and grade are mandate rows; the grade
row is grade:<RULE_ID>. HARD blocks, SOFT warns with the measured number, LOG records. A floor is always
HARD and a grade row for it is refused.
| Rule | Default grade | Mandate key | Checks |
|---|---|---|---|
| L-OPS-HALT | floor | — | The kill switch, or a halt whose scope covers the order. |
| L-RESTRICTED | floor | — | The restricted list. |
| L-PROC-DEBATE | HARD | debate | An alpha order's view was debated before it was sized. |
| L-PROC-STALE | HARD | max_data_age_min | The price data is fresh. |
| L-LIVE-PRICE | floor | — | Live only: the price came from a real feed. |
| L-LIVE-SIZE | HARD | live_max_order | Live only: a risk-adding order is no larger than the cap. |
| L-LOSS-DAILY | HARD | daily_loss_pct | Today's loss against the limit. |
| L-LOSS-DD | HARD | drawdown_pct | Drawdown from peak, in tiers: watch at 50%, halve new risk at 75%, halt at 100%. |
| L-CASH | floor | — | Enough cash to settle. |
| L-SHORT-SINGLE | HARD | allow_short | Single-name shorts, if the mandate forbids them. |
| L-EXP-GROSS | HARD | gross_pct | Gross exposure. |
| L-EXP-NET | SOFT | net_pct | Net exposure. |
| L-CONC-NAME | HARD | name_pct | The largest single name. |
| L-LIQ-ADV | HARD | adv_pct | The order as a share of average daily volume. |
| L-CONC-SECTOR | SOFT | sector_pct | Sector concentration. |
| L-CONC-COUNTRY | LOG | country_pct | Country concentration. |
| L-FX-CCY | SOFT | ccy_pct | Currency exposure. |
| L-FACTOR-BETA | SOFT | beta_max | Portfolio beta, from the factor model's estimates where there are enough sessions. |
| L-EVENT-WINDOW | SOFT | event_window_days | A scheduled event on the name within the window. |
| L-PROC-COOLING | HARD | idea_cooling_sessions | An owner idea has cooled. Overridable. |
| L-RUNG | HARD | live_min_rung | The readiness rung before going live. Overridable. |
| L-STRESS-WORST | SOFT | stress_loss_pct | The worst stress scenario's loss on the book after the order. |
| L-CONC-COUNT | HARD | max_positions | Names the book would hold after an order that opens a new one. |
| L-COST-WARN | SOFT | cost_warn_pct | Round-trip fees (twice the entry estimate), % of a risk-adding order's notional. |
Mandate
Limits are signed mandate rows. A new row that tightens applies at once; one that loosens waits
cooling_days (7 by default). base_currency and capital are set once, at setup, and the setup's
mandate applies without cooling. Direction per key, from src/firm/projection.ts:
- Loosening when raised (or turned on):
daily_loss_pct,drawdown_pct,gross_pct,net_pct,name_pct,sector_pct,country_pct,ccy_pct,beta_max,adv_pct,allow_short,max_data_age_min,approval_expiry_min,cost_warn_pct,max_positions,monthly_model_budget,live_max_order,live_collar_pct,wake_spend_cap_usd,breaker_failures,backup_max_age_days,stress_loss_pct,vol_target_pct,seat_float_rp,discontinuity_jump_pct. - Loosening when lowered:
cooling_days,bear_twins,seat_refloat_sessions,event_window_days,idea_cooling_sessions,live_min_rung,ladder_min_sessions,ladder_min_views. - Grades: moving right along HARD, SOFT, LOG is a loosening.
- Other:
debateorjudge_independent_vendorturned off andmodeaway fromproposeare loosenings. Any other key, thescreen:*switches andbreaker_cooldown_minamong them, applies at once either way.
Events added by the product update
| Area | Events |
|---|---|
| Setup and ideas | book.seeded, book.cleared, idea.refused, universe.reviewed, event.scheduled |
| Views and debate | view.drafted (now version 2, upcast from 1), view.falsified, debate.orders_compared |
| Measurement | null.struck, stress.run, attribution.struck, hypothesis.registered, hypothesis.looked, hypothesis.stopped, seat.bankrupt, seat.refloated, balances.shrunk |
| Governance | override.signed, override.used, rung.changed, claim.recorded, claim.contradicted, claim.confirmed, instrument.recorded, corpaction.recorded, corpaction.applied, recon.discontinuity, roster.set |
| Operations | job.dead, breaker.changed, notification.sent, backup.written, restore.drilled, anchor.written |
The snapshot
GET /api/state returns one object the web app renders, and SSE tells it when to fetch again. Keys added
by the product update:
| Key | Holds |
|---|---|
rules | The kernel's rule catalogue. |
example, profile, providers_count, ideas_refused | Whether the example book is held; the setup profile; the catalogue size; recent refusals. |
sourcing | The screens and their switches, max_candidates, recent screened candidates, event_window_days, the event calendar, and the universe review (last, due_on, overdue). |
nulls | The state word against the hardest control, the owner's effect, each null book, and an index series. |
factors | Loadings per instrument, the book's volatility and its contributions, vol_target_pct. |
stress | Each scenario's loss, the worst, the cap and whether it is breached, with history. |
attribution | The day and cumulative, by line, position and sector. |
hypotheses | Each registration with its looks, calendar, status and halt. |
balances | The float and each seat's balance, bankruptcy and re-floats. |
notify, ops, backups, anchors | Channels (configured or not, never an address) and recent sends; health with reasons; backup files, age and last drill; the last anchor and its check. |
ladder | The rung, what live needs, and each criterion with its number and threshold. |
claims | Counts, items, contradictions and reliability per source. |
instruments, corpactions, discontinuities | The security master, corporate actions, and flagged discontinuities. |
overrides, cooling | Signed overrides with an active flag; owner ideas waiting on the cooling-off. |
roster | Its source and each seat's provider, model and whether a key is set. Never a key. |
API
Every route but /healthz needs the token, as the cookie or as Authorization: Bearer <token>. Every
write needs the header x-resolution: 1.
| Method | Route | Does |
|---|---|---|
| GET | /api/state | The snapshot. |
| GET | /api/events, /api/events/stream | Events, filterable and paged; server-sent events as the record grows. |
| GET | /api/verify, /api/replay, /api/export | The chain check; the fund after a given event; the whole record as JSON lines. |
| GET | /api/universe, /api/quote, /api/wire | Instruments (with ?bars=N, 2–250, their closes and the bars' source); prices; the wire. |
| GET | /api/analytics | The factsheet. Figures that cannot be computed are null, with reasons in missing. |
| GET | /api/assist | The ranked action list. |
| GET | /api/providers | The provider catalogue and the one in use. No keys. |
| GET, POST, DELETE | /api/model | The model in use; test and save a key; forget it. Refused (409) when the key is from the environment or the store is in memory. |
| GET, POST | /api/roster | The per-seat roster; save it, with optional keys per provider. Refused when SEAT_ROSTER is set or the store is in memory. |
| POST | /api/setup | Starts a fund: base_currency, capital, profile, mandate, answers, example. |
| POST | /api/example | {action: "seed" | "clear"} the example book. |
| POST | /api/founding, /api/mandate, /api/keys | A founding step; a mandate row; a public signing key. |
| POST | /api/ideas | An owner idea, researched at once. |
| POST | /api/assist/brief | The chief of staff's briefing, recorded as a seat call. |
| POST | /api/check | The pre-trade check, with sizing. Records nothing as an order. |
| POST | /api/hypotheses | Registers a hypothesis. |
| POST | /api/events, /api/universe/review | An event on the calendar; a universe review. |
| POST | /api/sign, /api/demo/sign | An owner signature, or the demo key's. |
| POST | /api/fx/issue, /api/fx/sign | A currency conversion ticket, and the owner's signature on it (paper only). |
| POST | /api/note, /api/owner-record | Notes, and owner records. |
| POST | /api/wire/send | Sends a wire item to the desk. |
| POST | /api/day | Runs the day's steps now. On the simulated clock it first advances a session. |
| POST | /api/override | Without a signature, the terms to sign; with one, override.signed. |
| GET, POST | /api/claims, /api/claim, /api/claim/contradict, /api/claim/confirm | The claims store. |
| POST | /api/instrument, /api/corpaction, /api/corpaction/apply | The security master; record a corporate action (returns the preview and the message to sign); apply it with a signature. |
| POST, DELETE | /api/kill | Engages or releases the kill switch. |
| POST | /api/kill/cancel-orders | Cancels the fund's working orders at the venue. |
| POST | /api/halt/clear | Clears a named halt. |
| GET, POST, DELETE | /api/live | The go-live checklist and terms; sign live; back to paper. |
| GET | /api/ops | Health with reasons, connectors, seat latency, runs, breakers, dead jobs. |
| POST | /api/notify/test | A test notice on every channel. 409 when none is configured. |
| GET, POST | /api/backups, /api/backup | Backup files; write one now. |
| POST | /api/backup/drill | Restores a backup into memory and records restore.drilled. |
| GET, POST | /api/anchors | Anchors and their check; write one now. |
| GET | /healthz | Status, failing clause names and whether setup has run, without auth. |