Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(robinhood): backtest a generated portfolio, and show what its rebalancing did

nirholas7d8806df4839
diff --git a/CLAUDE.md b/CLAUDE.md
index 71a677786..5bba65e8b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -305,7 +305,7 @@ The whole build + submit + purge in one command: `npm run deploy:gcp:full`.
- Frontend: vanilla JS modules + Vite (`npm run dev`, port 3000).
- 3D: Three.js with glTF/GLB.
- Backend touchpoints: serverless-style handlers in `api/`, workers in `workers/`.
-- **Production runs on Google Cloud Run, NOT Vercel** (migrated 2026-07-07 after Vercel disabled the deployment). One container ([server/index.mjs](server/index.mjs)) serves the static frontend, the vercel.json route table, and all `api/**` handlers; the crons (115 as of 2026-09-04, see vercel.json) run on Cloud Scheduler. `vercel.json` is a LIVE config file: `server/index.mjs` reads its `routes` array on boot (split at the `{handle:"filesystem"}` marker into pre- and post-filesystem phases), and `scripts/create-gcp-scheduler.mjs` reads its `crons` array to sync Cloud Scheduler jobs. The server itself never reads `crons`. Never delete `vercel.json` as a leftover. GCP builds/deploys must pin the `three-ws-build@` (build) and `three-ws@` (runtime) service accounts; the project's default compute SA was deleted. Deploys: see the "Deploy runbook" section above.
+- **Production runs on Google Cloud Run, NOT Vercel** (migrated 2026-07-07 after Vercel disabled the deployment). One container ([server/index.mjs](server/index.mjs)) serves the static frontend, the vercel.json route table, and all `api/**` handlers; the crons (116 as of 2026-09-08, see vercel.json) run on Cloud Scheduler. `vercel.json` is a LIVE config file: `server/index.mjs` reads its `routes` array on boot (split at the `{handle:"filesystem"}` marker into pre- and post-filesystem phases), and `scripts/create-gcp-scheduler.mjs` reads its `crons` array to sync Cloud Scheduler jobs. The server itself never reads `crons`. Never delete `vercel.json` as a leftover. GCP builds/deploys must pin the `three-ws-build@` (build) and `three-ws@` (runtime) service accounts; the project's default compute SA was deleted. Deploys: see the "Deploy runbook" section above.
- **Env-var trap:** `vercel env pull` returns EMPTY for secret-type vars. Never trust a Vercel env export as complete. Production env lives on the Cloud Run service (`gcloud run services describe/update three-ws-api --region us-central1`).
- Solana/agent SDKs in `sdk/`, `solana-agent-sdk/`, `agent-payments-sdk/`.
- Real APIs in use: Pump.fun feed, Solana RPC, OpenAI/Anthropic via worker proxies. Never mock these.
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 3496c5adf..80970c1c4 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -207,7 +207,7 @@ bottom.
| Escrowed knocks (pay-per-reply) | [contracts/knock-escrow/](contracts/knock-escrow) | In-repo | Anchor program making a knock's payment conditional instead of final: `knock` parks the price in a vault owned by the knock's own PDA, and only three things can happen to it. `answer` pays the owner minus a fee capped at 10% in the program itself, `refuse` refunds the sender in full and takes no fee, and `reclaim` refunds the sender once the reply window closes and can be called by anyone. Each `KnockRecord` snapshots the fee that was in force when it was made, so an authority cannot reprice money already in escrow, and it stores only the SHA-256 of the message and the reply, never their text. The trust-me version of this settles straight to the owner at [api/knock/](api/knock) (row above); this is the version that works between strangers. Both sides are reachable from a browser: senders escrow and crank their own refund from the door page, owners open their on-chain door, answer for payment or refuse for a refund from [/knock](pages/knock.html), all signed by their own wallet ([src/knock/escrow-checkout.js](src/knock/escrow-checkout.js)). Docs: [contracts/knock-escrow/README.md](contracts/knock-escrow/README.md), [docs/knock.md](docs/knock.md). Tests: [tests/knock-escrow-program.test.js](tests/knock-escrow-program.test.js), [tests/knock-escrow-pda.test.js](tests/knock-escrow-pda.test.js), [tests/api-knock-escrowed.test.js](tests/api-knock-escrowed.test.js), [tests/api-knock-escrow-sync.test.js](tests/api-knock-escrow-sync.test.js) |
| Cross-chain SDKs | [sdk/](sdk), [solana-agent-sdk/](solana-agent-sdk), [agent-payments-sdk/](agent-payments-sdk), [agent-protocol-sdk/](agent-protocol-sdk) | Published | Cross-chain agent SDKs |
| MCP integration | [mcp-server/](mcp-server), [mcp-bridge/](mcp-bridge), [packages/*-mcp/](packages) | 43 npm servers + 7 hosted remote (50 total, incl. the free `/api/mcp-studio` 3D Studio), all in the [MCP registry](https://registry.modelcontextprotocol.io/?q=io.github.nirholas). Canonical metadata: [prompts/store-submissions/_generated/mcp-listing-source.json](prompts/store-submissions/_generated/mcp-listing-source.json), generated from the manifests by [scripts/build-mcp-listing-source.mjs](scripts/build-mcp-listing-source.mjs) (`npm run audit:mcp-listing` fails when it drifts) | Model Context Protocol surface, full server list in [docs/mcp.md](docs/mcp.md). Searchable index of every tool: [pages/mcp-tools.html](pages/mcp-tools.html) `→ /mcp-tools`, rendered from the generated [public/mcp-catalog.json](public/mcp-catalog.json) ([scripts/build-mcp-catalog.mjs](scripts/build-mcp-catalog.mjs), `npm run build:mcp-catalog`, staleness gated by `npm run audit:mcp-catalog`). Tool safety annotations are verified against each handler by [scripts/audit-mcp-safety.mjs](scripts/audit-mcp-safety.mjs) (`npm run audit:mcp-safety`, rules in [scripts/lib/mcp-safety-check.mjs](scripts/lib/mcp-safety-check.mjs), guarded-file list shared with the golden snapshot via [scripts/lib/mcp-tool-sources.mjs](scripts/lib/mcp-tool-sources.mjs)); docs [docs/mcp-safety.md](docs/mcp-safety.md) `→ /docs/mcp-safety`. Trust policy: [api/mcp-policy.js](api/mcp-policy.js) `-> GET /api/mcp-policy` turns those verified labels into a ready-to-paste client allowlist (profiles strict/balanced/open x formats claude/vscode/json), surfaced by the builder panel on `/mcp-tools`. Connector-review readiness (every paid stdio tool answers a clean x402 challenge, and the reviewer entitlement lifts it): [scripts/audit-mcp-reviewer-path.mjs](scripts/audit-mcp-reviewer-path.mjs), `npm run audit:mcp-reviewer`. Tests: [tests/mcp-safety-audit.test.js](tests/mcp-safety-audit.test.js), [tests/mcp-catalog.test.js](tests/mcp-catalog.test.js), [tests/api/mcp-policy.test.js](tests/api/mcp-policy.test.js) |
-| Awesome 3D Agents (curated list) | Source [data/awesome.json](data/awesome.json), generator [scripts/build-awesome.mjs](scripts/build-awesome.mjs) (`npm run build:awesome`, drift-gated by `npm run check:awesome`), outputs [awesome/README.md](awesome/README.md) + [public/awesome.json](public/awesome.json), page [pages/awesome.html](pages/awesome.html) `-> /awesome`, link checker [scripts/check-awesome-links.mjs](scripts/check-awesome-links.mjs) (`npm run awesome:links`) | Live | An awesome-list of everything needed to give an AI agent a body: text-to-3D, capture and splatting, avatars, rigging, motion, lipsync and voice, web renderers, asset pipelines, physics and networking, agent frameworks, datasets, free assets, learning. One JSON source produces both the GitHub-facing list and the searchable page, so they cannot disagree. Every url is fetched and classified (ok / moved / bot-filtered / broken) before it ships; the checker stays out of the deploy path so a third-party outage cannot redden someone else's build. Contributing: [awesome/CONTRIBUTING.md](awesome/CONTRIBUTING.md) |
+| Awesome 3D Agents (curated list) | Source [data/awesome.json](data/awesome.json), generator [scripts/build-awesome.mjs](scripts/build-awesome.mjs) (`npm run build:awesome`, drift-gated by `npm run check:awesome`, publishable mirror via `npm run awesome:standalone`), outputs [awesome/README.md](awesome/README.md) + [public/awesome.json](public/awesome.json), page [pages/awesome.html](pages/awesome.html) `-> /awesome`, link checker [scripts/check-awesome-links.mjs](scripts/check-awesome-links.mjs) (`npm run awesome:links`) | Live | An awesome-list of everything needed to give an AI agent a body: text-to-3D, capture and splatting, avatars, rigging, motion, lipsync and voice, web renderers, asset pipelines, physics and networking, agent frameworks, datasets, free assets, learning. One JSON source produces both the GitHub-facing list and the searchable page, so they cannot disagree. Every url is fetched and classified (ok / moved / bot-filtered / broken) before it ships; the checker stays out of the deploy path so a third-party outage cannot redden someone else's build. The README is written to pass `npx awesome-lint`: badge on the heading line, no License section, no Contributing entry in the contents, and every description capitalised and ended with a period, all enforced by the generator and by [tests/awesome-list.test.js](tests/awesome-list.test.js). Its last two lint rules read GitHub repository topics, which a list inside a product repo cannot satisfy, so `--standalone` emits a ready-to-publish mirror repo (readme, contributing, code of conduct, license) outside this checkout. Contributing: [awesome/CONTRIBUTING.md](awesome/CONTRIBUTING.md) |
| Agent Skills pack | [.agents/skills/](.agents/skills) → manifest [.agents/skills/SKILLS.md](.agents/skills/SKILLS.md), [.agents/skills/skills-pack.json](.agents/skills/skills-pack.json) | In-repo; bundled in the `three-ws-core` [plugin](.claude-plugin/marketplace.json) | 40 portable `SKILL.md` folders (Agent Skills open standard) for any Claude surface — 3d/creative (cross-platform-safe), wallet/payments, intel/trading. Regenerate manifest: `node scripts/build-skills-pack.mjs`. Docs: [docs/agent-skills.md](docs/agent-skills.md) |
| Claude Code plugin marketplace | [marketplace/](marketplace) → plugins [three-ws-3d](marketplace/plugins/three-ws-3d), [three-ws-developer](marketplace/plugins/three-ws-developer) | In-repo · installable via `/plugin marketplace add nirholas/three.ws` | 3D generation + rigged avatars inside Claude Code (free lane + paid x402 tools) and developer tooling for building on three.ws. Index: [marketplace/README.md](marketplace/README.md) |
| SNS naming + pay-by-name | [api/sns.js](api/sns.js), [api/sns-subdomain.js](api/sns-subdomain.js), [api/threews/subdomain.js](api/threews/subdomain.js), [api/x402/pay-by-name.js](api/x402/pay-by-name.js), [src/solana/sns-subdomain.js](src/solana/sns-subdomain.js), [pages/threews-claim.html](pages/threews-claim.html) | In-repo | `*.threews.sol` subdomain mint, x402 payments addressed by name. Env: `THREEWS_SOL_PARENT_SECRET_BASE58` |
@@ -245,7 +245,7 @@ bottom.
| Market detail pages (exchange, category) + DeFi yields | [pages/exchange.html](pages/exchange.html) + [src/exchange-page.js](src/exchange-page.js) `→ /exchange/:id` over [api/coin/exchange.js](api/coin/exchange.js), [pages/category.html](pages/category.html) + [src/category-page.js](src/category-page.js) `→ /category/:id` over [api/coin/category.js](api/coin/category.js) + [api/coin/markets.js](api/coin/markets.js) (`?category=`), [pages/yields.html](pages/yields.html) + [src/yields.js](src/yields.js) `→ /yields` over [api/defi/yields.js](api/defi/yields.js) | In-repo | Rich detail pages that turn list rows into full profiles. Exchange: trust badge, normalized-volume stat, BTC-volume history chart, and a per-pair markets table (spot + derivatives fallback), reached from `/exchanges` and the new Derivatives Exchanges table. Category: rank, sector stats, the full sortable coins table for that sector, and related categories, reached from `/categories`. Yields: an explorer over ~15k live DeFiLlama pools with chain/project/stablecoin/min-TVL filters, APY/TVL sort, URL-synced state, and a per-pool APY+TVL history chart on row expand. Docs: [docs/coin-pages.md](docs/coin-pages.md) |
| Crypto news + archive + markets hub | [pages/markets.html](pages/markets.html) + [src/markets-page.js](src/markets-page.js) `→ /markets`, [pages/markets-news.html](pages/markets-news.html) + [src/markets-news.js](src/markets-news.js) `→ /markets/news`, [pages/news-article.html](pages/news-article.html) + [src/news-article.js](src/news-article.js) `→ /markets/news/article`, [pages/news-archive.html](pages/news-archive.html) + [src/news-archive.js](src/news-archive.js) `→ /markets/archive`, [pages/news-digest.html](pages/news-digest.html) + [src/news-digest.js](src/news-digest.js) `→ /markets/digest`; backend [api/news/](api/news) (feed, article, knowledge, archive, digest, rss, image) over [api/_lib/article-extract.js](api/_lib/article-extract.js) (page→reader→feed→preview ladder) and [api/_lib/news-rights.js](api/_lib/news-rights.js) (publisher rights layer, enforced at every read path), [api/_lib/news-coins.js](api/_lib/news-coins.js) (ticker→live market snapshot), [api/_lib/news-knowledge-store.js](api/_lib/news-knowledge-store.js) (durable `news_knowledge` corpus) + hourly archiver [api/cron/news-archive-append.js](api/cron/news-archive-append.js) over [api/_lib/news.js](api/_lib/news.js) + [api/_lib/news-sources.js](api/_lib/news-sources.js), corpus on `gs://three-ws-news-archive`, purge tooling [scripts/news-takedown-purge.mjs](scripts/news-takedown-purge.mjs) | In-repo | The Markets news wing + front door: /markets/news is “Your briefing”: live news aggregated natively from 197 publisher feeds (Featured/Trending/Saved tabs, breaking ticker, AI briefing card, top-stories hero + rail, search, sentiment, ticker chips, og:image preview resolution for imageless feeds), a rich article reader that shows a bounded lead excerpt plus our own summary/key points/entities/market context and sends the reader to the publisher for the rest (the excerpt cap and any rightsholder takedowns are enforced server-side across the reader, RSS mirror, archive search, and agent knowledge corpus, never just hidden client-side), and renders **live coin cards** (price/24h/7d/sparkline→/coin/:id) for detected tickers, and related coverage. Every read story is recorded to a durable **news knowledge base** (`GET /api/news/knowledge`) that grounds the 3D agents, itself subject to the same excerpt limit. Plus the largest open crypto-news archive (662,047 enriched articles, Sept 2017 → today, EN+中文, GCS-hosted) and the /markets hub aggregating global stats, the top-100 table, breaking news, and every market surface as a hero card. Docs: [docs/coin-pages.md](docs/coin-pages.md), [docs/api-reference.md](docs/api-reference.md), [docs/news-rights.md](docs/news-rights.md) (publisher takedown path) |
| Robinhood Chain markets + buy flow | Hub + detail pages [pages/markets-robinhood.html](pages/markets-robinhood.html) + [src/markets-robinhood.js](src/markets-robinhood.js) `→ /markets/robinhood`, [pages/robinhood-stock.html](pages/robinhood-stock.html) + [src/robinhood-stock.js](src/robinhood-stock.js) `→ /markets/robinhood/stock/:symbol`, [pages/robinhood-coin.html](pages/robinhood-coin.html) + [src/robinhood-coin.js](src/robinhood-coin.js) `→ /markets/robinhood/coin/:address`, buy flow [src/robinhood-purchase.js](src/robinhood-purchase.js), wallet desk [pages/hood-desk.html](pages/hood-desk.html) + [src/hood-desk.js](src/hood-desk.js) + [src/hood-desk.css](src/hood-desk.css) `→ /markets/robinhood/desk`; backend [api/_lib/robinhood.js](api/_lib/robinhood.js) + `api/v1/robinhood/{chain,stocks,stocks-detail,coins,coins-detail,launches,desk,wallet}.js` (free, the last two composed for the desk over [api/_lib/robinhood-desk.js](api/_lib/robinhood-desk.js)) + [api/x402/robinhood-portfolio.js](api/x402/robinhood-portfolio.js) (x402 paid) | In-repo | The 24/7 tokenized-equity board for Robinhood Chain (4663): live Chainlink NAV vs. Uniswap DEX premium for every Stock Token (one multicall, never 95 RPC calls), a memecoin screener across NOXA/The Odyssey launchpads (CoinGecko categories + on-chain launch logs via Blockscout), and chain TVL/gas/block stats. Detail pages add NAV history, holders, transfers, and contract links. Coin pages carry a real buy panel: injected-wallet connect, chain-switch to 4663, live Uniswap v3 `QuoterV2` quote + `SwapRouter02` swap with slippage, LI.FI bridge deep-link; Stock Tokens are display-only (tokenized securities, not offered to US persons) with an eligibility-gated outbound DEX link instead. Paid `portfolio` endpoint returns ERC-8056 `uiMultiplier`-correct holdings. The Hood Desk (`/markets/robinhood/desk`) is the wallet-first view of the same chain: paste or connect any address and it loads that wallet's book (native + priced ERC-20 positions), its native balance curve rebuilt from Blockscout's daily and per-transaction feeds (the public RPC is not an archive node), an activity tape that folds token transfers onto the transaction that emitted them, the NAV premium ridge layered by liquidity floor, counterparty flow, and memecoin movers. Read-only and signature-free; the trade ticket reuses the coin pages' swap panel and the Stock Token eligibility gate. Tests: [tests/robinhood-desk.test.js](tests/robinhood-desk.test.js) (the derivations) and [tests/e2e/hood-desk.spec.js](tests/e2e/hood-desk.spec.js) (the panels, the empty states, the ladder collapse and the trade ticket). Docs: [docs/robinhood-chain-markets.md](docs/robinhood-chain-markets.md) |
-| Robinhood Portfolios (generated index portfolios) | Generator [pages/hood-portfolios.html](pages/hood-portfolios.html) + [src/hood-portfolios.js](src/hood-portfolios.js) + [src/hood-portfolios.css](src/hood-portfolios.css) `→ /markets/robinhood/portfolios`, universe board [pages/hood-portfolios-universe.html](pages/hood-portfolios-universe.html) + [src/hood-portfolios-universe.js](src/hood-portfolios-universe.js) `→ /markets/robinhood/portfolios/universe`; backend [api/_lib/hood-portfolios.js](api/_lib/hood-portfolios.js) + `api/v1/hood-portfolios/{universe,generate,health}.js` (free, keyless); universe snapshot [data/hood-portfolios-universe.json](data/hood-portfolios-universe.json) built by [scripts/build-hood-portfolios-universe.mjs](scripts/build-hood-portfolios-universe.mjs) (`npm run hood:universe`); contracts [contracts/hood-portfolios/](contracts/hood-portfolios) | In-repo · contracts code-complete and fork-proven against live chain 4663, mainnet deploy owner-gated | Describe a portfolio in a sentence and get a real basket of Robinhood Chain assets. The screen ranks the whole holdable universe (727 assets: 167 tokenized equities, majors, and the chain-native long tail) through the platform free-first LLM chain, and every token it returns is validated back against that universe before it is shown. The result is committed as an immutable content-addressed manifest (`PortfolioRegistry`), held in kind by an ERC-20 share vault (`Portfolio`) whose backing is derived from balances rather than tracked, and rebalanced to published targets by a descending-price auction any address can fill: there is no function that lets a manager trade the fund. Needs no price oracle on any code path, which is what makes it work on a chain where only 34 of 95 registry equities have a Chainlink feed. Halt-aware: a paused tokenized equity stops issuance, redemption and rebalancing, and the UI says so. Ticker impersonation is resolved by contract address at build time (12 contracts on this chain call themselves USDG), so an impostor can never be selected. 38 offline tests incl. fuzz + 4 stateful invariants, plus 5 against a fork of live chain 4663. Docs: [docs/robinhood-portfolios.md](docs/robinhood-portfolios.md), [contracts/hood-portfolios/README.md](contracts/hood-portfolios/README.md) |
+| Robinhood Portfolios (generated index portfolios) | Generator [pages/hood-portfolios.html](pages/hood-portfolios.html) + [src/hood-portfolios.js](src/hood-portfolios.js) + [src/hood-portfolios.css](src/hood-portfolios.css) `→ /markets/robinhood/portfolios`, universe board [pages/hood-portfolios-universe.html](pages/hood-portfolios-universe.html) + [src/hood-portfolios-universe.js](src/hood-portfolios-universe.js) `→ /markets/robinhood/portfolios/universe`; backend [api/_lib/hood-portfolios.js](api/_lib/hood-portfolios.js) + `api/v1/hood-portfolios/{universe,generate,health}.js` (free, keyless); universe snapshot [data/hood-portfolios-universe.json](data/hood-portfolios-universe.json) built by [scripts/build-hood-portfolios-universe.mjs](scripts/build-hood-portfolios-universe.mjs) (`npm run hood:universe`); contracts [contracts/hood-portfolios/](contracts/hood-portfolios) | In-repo · contracts code-complete and fork-proven against live chain 4663, mainnet deploy owner-gated | Describe a portfolio in a sentence and get a real basket of Robinhood Chain assets. The screen ranks the whole holdable universe (727 assets: 167 tokenized equities, majors, and the chain-native long tail) through the platform free-first LLM chain, and every token it returns is validated back against that universe before it is shown. The result is committed as an immutable content-addressed manifest (`PortfolioRegistry`), held in kind by an ERC-20 share vault (`Portfolio`) whose backing is derived from balances rather than tracked, and rebalanced to published targets by a descending-price auction any address can fill: there is no function that lets a manager trade the fund. Needs no price oracle on any code path, which is what makes it work on a chain where only 34 of 95 registry equities have a Chainlink feed. Halt-aware: a paused tokenized equity stops issuance, redemption and rebalancing, and the UI says so. Ticker impersonation is resolved by contract address at build time (12 contracts on this chain call themselves USDG), so an impostor can never be selected. Backtests run the basket twice, on its schedule and never rebalanced, and report the difference: history comes from Chainlink round data (chunked into multicalls of 40, because this RPC silently drops calls out of a larger one) and a daily snapshot whose coverage compounds, with uncovered legs named rather than dropped. A generated portfolio shares as a deflate-compressed manifest in the URL, its hash re-derived server-side rather than trusted from the link. 38 offline contract tests incl. fuzz + 4 stateful invariants, 5 against a fork of live chain 4663, and 56 vitest across the screen, backtest engine, history reduction and SDK. Docs: [docs/robinhood-portfolios.md](docs/robinhood-portfolios.md), [contracts/hood-portfolios/README.md](contracts/hood-portfolios/README.md) |
| Premium Data API pass | [api/premium/](api/premium) + [api/_lib/premium.js](api/_lib/premium.js), dashboards [src/dashboard-next/pages/data-api.js](src/dashboard-next/pages/data-api.js) `→ /dashboard/data-api` + [src/dashboard-next/pages/billing.js](src/dashboard-next/pages/billing.js) `→ /dashboard/billing` | In-repo | Monthly pass in three tiers (Developer $19.99, Pro $99, Enterprise $499 per 30d, tiered rate limits) paid on Solana in $THREE (20% off), SOL, or USDC — replaces per-call x402 on the news archive with an `x402_live_` API key (existing access-control lane) + SIWX browser grants. Quote→sign→verify flow with on-chain balance-delta verification; tables `premium_passes`/`premium_quotes`. Docs: [docs/premium.md](docs/premium.md) |
| Liquidations pulse (/coins) | Collector [services/liquidation-collector/](services/liquidation-collector) (standalone always-on Node service, ported from SperaxOS), proxy [api/coin/liquidations.js](api/coin/liquidations.js) `→ GET /api/coin/liquidations`, UI strip in [src/coins-index.js](src/coins-index.js) `→ /coins` | Live — collector on Cloud Run (`liquidation-collector`, min-instances 1, unthrottled CPU) since 2026-07-10 | Real-time long/short liquidation pain across Binance, Bybit, and OKX public futures WebSocket streams: dominant-side badge (LONG PAIN / SHORT SQUEEZE / BALANCED), 1h long-vs-short bars, and the 3 largest recent liquidations, polled every 30s (pauses on hidden tab). The collector holds long-lived WebSockets so it can't run as a Vercel function — deploy it separately and point `LIQUIDATION_COLLECTOR_URL` at it. No fallback data: the proxy 503s `collector_offline` (never fabricated numbers) when unset or unreachable, and the strip degrades to a quiet single-line offline state. Docs: [docs/api-reference.md#liquidations](docs/api-reference.md#liquidations) |
| BNB Chain campaign hub | [pages/bnb.html](pages/bnb.html) + [src/bnb.js](src/bnb.js) `→ /bnb`, pure helpers [src/bnb-hub-helpers.js](src/bnb-hub-helpers.js), live block-time API [api/bnb/block-time.js](api/bnb/block-time.js) over [api/_lib/bnb/chains.js](api/_lib/bnb/chains.js) `probeBlockTime` | In-repo · hub live, tracks rolling out | The campaign's front door: three feature cards (gasless agent onboarding, on-chain-gated 3D vault, real-time on-chain world), each claim traced to `prompts/bnb-chain/00-CONTEXT.md`'s verified facts (0.45s blocks — never 20k TPS or 250ms finality). Embeds a live block-time widget (real RPC measurement on every load). Each card self-detects liveness via a real HTTP probe against its track's route/API on the running deployment — a 404 renders a designed "coming soon" state, never a dead link — so cards auto-light-up as the sibling tracks below ship: gasless registration `→ /create-agent` + `api/bnb/register-agent.js` (prompt 03), vault `→ /vault` (prompt 12), on-chain world `→ /bnb-latency` (prompt 17) + the Explore on-chain toggle (prompt 16). Campaign root: [prompts/bnb-chain/](prompts/bnb-chain) |
@@ -351,6 +351,7 @@ packages/metaplex-agent-mcp/ → @three-ws/metaplex-agent-mcp (MCP server: mint
packages/onchain-agent-wallets/ → @three-ws/onchain-agent-wallets (MCP server: agent wallets with an SPL-Token-enforced spending allowance, guardrails, x402, revocable custody)
packages/autopilot-mcp/ → @three-ws/autopilot-mcp (MCP server — agent execution control: scopes, SOL spend caps, propose/execute/undo)
packages/portfolio-mcp/ → @three-ws/portfolio-mcp (MCP server — portfolio, PnL, balances, trade feed, signed transfers)
+packages/hood-portfolios-sdk/ → @three-ws/hood-portfolios-sdk (Robinhood Chain portfolios: universe, generate, backtest, canonical manifest hashing)
packages/provenance-mcp/ → @three-ws/provenance-mcp (MCP server — append-only, signed, on-chain-verifiable agent action log)
packages/copy-mcp/ → @three-ws/copy-mcp (MCP server — manage copy-trade follows, sizing & guard rules)
packages/signals-mcp/ → @three-ws/signals-mcp (MCP server — discover signal feeds by proven edge; rank publishers)
diff --git a/api/_lib/hood-portfolios-backtest.js b/api/_lib/hood-portfolios-backtest.js
new file mode 100644
index 000000000..35daf3194
--- /dev/null
+++ b/api/_lib/hood-portfolios-backtest.js
@@ -0,0 +1,182 @@
+// The backtest: what this basket would have done, and what the rebalancing did to it.
+//
+// Pure functions over price series. No network, no clock, no randomness, so the
+// whole thing is unit-testable and a given set of inputs always produces the
+// same answer.
+//
+// The output that matters is not the headline return, it is the COMPARISON. A
+// rebalancing portfolio is a specific claim: that periodically selling what rose
+// and buying what fell beats leaving the basket alone. That claim is true for
+// some baskets and false for others, and it is the one thing a person choosing a
+// rebalance schedule actually needs to see. So every backtest runs the same
+// basket twice, once rebalanced on its published schedule and once never
+// rebalanced, and reports the difference.
+//
+// Prior art, and what this is NOT: it is not a strategy optimiser and it does
+// not search for a schedule. It answers one question about one published
+// manifest. Nothing here is fitted to the data.
+
+/** Trading costs are not modelled; a backtest that ignores them says so. */
+export const COST_MODEL = 'none';
+
+/**
+ * The days on which every supplied series has a price.
+ *
+ * A basket is only backtestable across the window where all of its covered legs
+ * have real observations. Taking the union instead and carrying prices forward
+ * would manufacture flat stretches for a token that simply was not being
+ * recorded, and those show up as fake stability rather than as missing data.
+ */
+export function commonDays(seriesByAddress) {
+ const lists = Object.values(seriesByAddress).map((s) => new Set(s.map((p) => p.day)));
+ if (!lists.length) return [];
+ const [first, ...rest] = lists;
+ return [...first].filter((day) => rest.every((s) => s.has(day))).sort();
+}
+
+/** Index a series by day for O(1) lookup during the walk. */
+function byDay(series) {
+ const m = new Map();
+ for (const p of series) m.set(p.day, p.priceUsd);
+ return m;
+}
+
+/**
+ * Largest peak-to-trough fall in a value series, as a positive percentage.
+ * Zero for a series that only ever rises.
+ */
+export function maxDrawdownPct(values) {
+ let peak = -Infinity;
+ let worst = 0;
+ for (const v of values) {
+ if (v > peak) peak = v;
+ if (peak > 0) {
+ const dd = ((peak - v) / peak) * 100;
+ if (dd > worst) worst = dd;
+ }
+ }
+ return worst;
+}
+
+/** Annualised standard deviation of daily returns, in percent. */
+export function volatilityPct(values) {
+ if (values.length < 3) return null;
+ const rets = [];
+ for (let i = 1; i < values.length; i++) {
+ if (values[i - 1] > 0) rets.push(values[i] / values[i - 1] - 1);
+ }
+ if (rets.length < 2) return null;
+ const mean = rets.reduce((a, b) => a + b, 0) / rets.length;
+ const variance = rets.reduce((a, r) => a + (r - mean) ** 2, 0) / (rets.length - 1);
+ return Math.sqrt(variance) * Math.sqrt(365) * 100;
+}
+
+/**
+ * Walk a basket through a price history.
+ *
+ * @param {object} args
+ * @param {Array<{address:string,weightBps:number}>} args.legs Covered constituents, weights renormalised to these legs.
+ * @param {Record<string, Array<{day:string,priceUsd:number}>>} args.series Daily closes per address.
+ * @param {number} args.rebalanceDays Days between rebalances. 0 means never.
+ * @param {number} [args.startValueUsd]
+ */
+export function walk({ legs, series, rebalanceDays, startValueUsd = 10_000 }) {
+ const days = commonDays(series);
+ if (days.length < 2) return { days: [], values: [], rebalances: 0 };
+
+ const prices = {};
+ for (const [addr, s] of Object.entries(series)) prices[addr] = byDay(s);
+
+ const totalBps = legs.reduce((a, l) => a + l.weightBps, 0) || 1;
+ const target = new Map(legs.map((l) => [l.address, l.weightBps / totalBps]));
+
+ // Units are set once at the start, and reset at each rebalance to whatever
+ // the current total value implies at target weights. Between rebalances the
+ // basket simply drifts, which is the behaviour being measured.
+ let units = new Map();
+ const allocate = (value, day) => {
+ const next = new Map();
+ for (const l of legs) {
+ const p = prices[l.address].get(day);
+ next.set(l.address, p > 0 ? (value * target.get(l.address)) / p : 0);
+ }
+ return next;
+ };
+
+ const valueOn = (day) => {
+ let v = 0;
+ for (const l of legs) v += (units.get(l.address) || 0) * (prices[l.address].get(day) || 0);
+ return v;
+ };
+
+ units = allocate(startValueUsd, days[0]);
+ const values = [startValueUsd];
+ let rebalances = 0;
+ let sinceRebalance = 0;
+
+ for (let i = 1; i < days.length; i++) {
+ const day = days[i];
+ sinceRebalance++;
+ let v = valueOn(day);
+ if (rebalanceDays > 0 && sinceRebalance >= rebalanceDays) {
+ units = allocate(v, day);
+ rebalances++;
+ sinceRebalance = 0;
+ v = valueOn(day);
+ }
+ values.push(v);
+ }
+
+ return { days, values, rebalances };
+}
+
+/**
+ * Run the basket both ways and summarise.
+ *
+ * `legs` are the constituents that actually have history; the caller decides
+ * which those are and reports the rest as uncovered. Weights are renormalised
+ * across the covered legs so the simulated basket is fully invested, and the
+ * covered fraction is reported so nobody reads a 40%-covered backtest as if it
+ * described the whole portfolio.
+ */
+export function backtest({ legs, series, rebalanceDays, startValueUsd = 10_000 }) {
+ const rebalanced = walk({ legs, series, rebalanceDays, startValueUsd });
+ const held = walk({ legs, series, rebalanceDays: 0, startValueUsd });
+
+ if (rebalanced.days.length < 2) {
+ return {
+ ok: false,
+ reason: 'not enough overlapping history to run a backtest',
+ days: rebalanced.days,
+ };
+ }
+
+ const summarise = (run) => {
+ const start = run.values[0];
+ const end = run.values[run.values.length - 1];
+ return {
+ startValueUsd: start,
+ endValueUsd: end,
+ totalReturnPct: start > 0 ? (end / start - 1) * 100 : null,
+ maxDrawdownPct: maxDrawdownPct(run.values),
+ volatilityPct: volatilityPct(run.values),
+ rebalances: run.rebalances,
+ series: run.days.map((day, i) => ({ day, valueUsd: run.values[i] })),
+ };
+ };
+
+ const r = summarise(rebalanced);
+ const h = summarise(held);
+
+ return {
+ ok: true,
+ costModel: COST_MODEL,
+ windowDays: rebalanced.days.length,
+ from: rebalanced.days[0],
+ to: rebalanced.days[rebalanced.days.length - 1],
+ rebalanced: r,
+ heldWithoutRebalancing: h,
+ // The number the schedule is actually judged on.
+ rebalancingAddedPct: r.totalReturnPct != null && h.totalReturnPct != null ? r.totalReturnPct - h.totalReturnPct : null,
+ };
+}
diff --git a/api/_lib/hood-portfolios-history.js b/api/_lib/hood-portfolios-history.js
new file mode 100644
index 000000000..bb5068605
--- /dev/null
+++ b/api/_lib/hood-portfolios-history.js
@@ -0,0 +1,179 @@
+// Price history for Robinhood Chain portfolios, and the daily snapshot that grows it.
+//
+// A portfolio product needs to show what a basket would have done, and on this
+// chain that is harder than it sounds. There is no OHLC API: DexScreener serves
+// only current state, GeckoTerminal does not index chain 4663 at all, and the
+// public RPC is pruned, so historical `eth_call` is unavailable.
+//
+// Reconstructing prices from Uniswap swap logs is the obvious next idea and it
+// does not survive contact with the chain's block rate. Robinhood Chain produces
+// roughly 864,000 blocks a day at ~100ms each, and the RPC caps a single
+// `eth_getLogs` at a 500k-block span or 10,000 results. One month of history for
+// ONE token is therefore 50+ archival queries, before any block-timestamp reads.
+// That is not something an API request can do, for any number of constituents.
+//
+// So history comes from the two sources that are actually cheap here:
+//
+// 1. CHAINLINK ROUND HISTORY, for the 34 registry equities that carry a feed.
+// Rounds are addressed by id and read at head state, so a pruned node
+// serves them fine, and one multicall returns hundreds. Measured
+// 2026-09-07: 80 rounds reach back 10 days on NVDA, 54 days on SPY, and
+// 67 days on SGOV (its entire life). This is real history available today.
+//
+// 2. A DAILY SNAPSHOT of the whole universe, written by
+// /api/cron/hood-portfolio-snapshot. This covers every token including the
+// memecoins that have no feed and never will, and its coverage compounds:
+// the chain cannot be asked what a token was worth last month, but it can
+// be asked every day from now on.
+//
+// Nothing here interpolates a price it does not have. A day with no observation
+// is absent from the series, and callers are told which legs they are missing
+// rather than being handed a chart with invented points in it.
+
+import { sql } from './db.js';
+import { cacheWrap } from './cache.js';
+import { feedRoundHistory } from './robinhood.js';
+
+/**
+ * How many Chainlink rounds to pull per feed.
+ *
+ * `feedRoundHistory` batches these into multicalls of 40, which is what makes
+ * depth safe here: this RPC silently DROPS calls out of a large multicall rather
+ * than failing it, so before chunking, asking for more history returned less of
+ * it (NVDA's feed, 2026-09-08: 80 rounds at depth 80, only 8 at depth 120, none
+ * at 160). That partial result was the dangerous mode, because it reads as a
+ * short-but-successful history rather than an error, and intersecting several of
+ * them produced an empty backtest window with nothing to explain it.
+ *
+ * Chunked, depth is honest and roughly linear: 300 rounds costs about two
+ * seconds a feed and reaches ~29 days on a feed as active as NVDA's, more on
+ * slower ones (SPY and SGOV update less often, so the same count spans longer).
+ * The daily snapshot extends coverage past that, and to the tokens with no feed.
+ */
+export const FEED_ROUND_DEPTH = 300;
+
+const SNAPSHOT_PREFIX = 'hood_prices:';
+
+/** `hood_prices:YYYY-MM-DD`: one row per day, holding the whole universe. */
+export function snapshotKey(date = new Date()) {
+ return `${SNAPSHOT_PREFIX}${date.toISOString().slice(0, 10)}`;
+}
+
+async function ensureTable() {
+ await sql`
+ CREATE TABLE IF NOT EXISTS app_settings (
+ key text PRIMARY KEY,
+ value jsonb NOT NULL,
+ updated_at timestamptz NOT NULL DEFAULT now()
+ )
+ `;
+}
+
+/**
+ * Write one day's prices for the whole universe.
+ *
+ * Stored as a compact { address: [priceUsd, liquidityUsd] } map rather than a
+ * row per token: 727 tokens is ~30KB of JSON a day, which is one small row,
+ * where a row per token would be 265k rows a year for a chart nobody reads at
+ * that granularity.
+ *
+ * Idempotent by day: running the cron twice in a day overwrites rather than
+ * duplicating, so a retry after a partial failure is always safe.
+ */
+export async function recordDailySnapshot(tokens, { at = new Date() } = {}) {
+ await ensureTable();
+ const prices = {};
+ let recorded = 0;
+ for (const t of tokens) {
+ if (t.priceUsd == null || !(t.priceUsd > 0)) continue;
+ prices[t.address] = [Number(t.priceUsd), Math.round(t.liquidityUsd || 0)];
+ recorded++;
+ }
+ const value = { at: at.toISOString(), count: recorded, prices };
+ await sql`
+ INSERT INTO app_settings (key, value) VALUES (${snapshotKey(at)}, ${JSON.stringify(value)}::jsonb)
+ ON CONFLICT (key) DO UPDATE SET value = excluded.value, updated_at = now()
+ `;
+ return { key: snapshotKey(at), recorded };
+}
+
+/** Every stored day, newest first, as [{ day, at, prices }]. */
+export async function readSnapshots({ days = 90 } = {}) {
+ return cacheWrap(`hp:snapshots:${days}`, 300, async () => {
+ await ensureTable();
+ const rows = await sql`
+ SELECT key, value FROM app_settings
+ WHERE key LIKE ${`${SNAPSHOT_PREFIX}%`}
+ ORDER BY key DESC
+ LIMIT ${Math.max(1, Math.min(days, 400))}
+ `;
+ return rows.map((r) => ({
+ day: String(r.key).slice(SNAPSHOT_PREFIX.length),
+ at: r.value?.at ?? null,
+ prices: r.value?.prices ?? {},
+ }));
+ });
+}
+
+/** Reduce irregular observations to one close per UTC day: the last at or before each day's end. */
+export function toDailyCloses(points) {
+ const byDay = new Map();
+ for (const p of points) {
+ if (!(p.priceUsd > 0)) continue;
+ const day = new Date(p.t).toISOString().slice(0, 10);
+ const prev = byDay.get(day);
+ if (!prev || p.t > prev.t) byDay.set(day, p);
+ }
+ return [...byDay.entries()]
+ .map(([day, p]) => ({ day, t: p.t, priceUsd: p.priceUsd }))
+ .sort((a, b) => (a.day < b.day ? -1 : 1));
+}
+
+/**
+ * Daily close series for one token, from whichever real source it has.
+ *
+ * A feed-backed equity gets Chainlink rounds, which reach back weeks today. Any
+ * other token gets the stored daily snapshots, which start the day the cron
+ * first ran. Where both exist the feed wins, because it is the denser series and
+ * it is the price the equity is actually marked at.
+ */
+export async function tokenHistory(token, { days = 30, snapshots = null } = {}) {
+ let feedError = null;
+ if (token.feed) {
+ // Retried, and paced. This RPC drops calls out of a large multicall under
+ // load rather than erroring, so a feed read can come back empty or short for
+ // no reason but timing. An empty read is treated as a failure to retry, not
+ // as a feed with no history: a token that HAS a feed has rounds by
+ // definition. Callers must also read feeds one at a time; firing several
+ // 80-call multicalls at this RPC concurrently makes most of them fail.
+ for (let attempt = 0; attempt < 3; attempt++) {
+ if (attempt) await new Promise((r) => setTimeout(r, 400 * attempt));
+ try {
+ const rounds = await feedRoundHistory(token.feed, FEED_ROUND_DEPTH);
+ const points = (rounds || [])
+ .filter((r) => r?.priceUsd > 0)
+ .map((r) => ({ t: Number(r.updatedAt) * 1000, priceUsd: Number(r.priceUsd) }));
+ const closes = toDailyCloses(points).slice(-days);
+ if (closes.length) return { source: 'chainlink', feed: token.feed, closes };
+ feedError = 'the feed returned no rounds';
+ } catch (err) {
+ feedError = String(err?.message || err);
+ }
+ }
+ }
+
+ const snaps = snapshots || (await readSnapshots({ days }));
+ const addr = String(token.address).toLowerCase();
+ const closes = snaps
+ .map((s) => {
+ const row = s.prices[addr];
+ const price = Array.isArray(row) ? row[0] : row;
+ return price > 0 ? { day: s.day, t: Date.parse(s.at || `${s.day}T00:00:00Z`), priceUsd: Number(price) } : null;
+ })
+ .filter(Boolean)
+ .sort((a, b) => (a.day < b.day ? -1 : 1))
+ .slice(-days);
+
+ if (closes.length) return { source: 'daily-snapshot', closes };
+ return { source: feedError ? 'unavailable' : 'none', closes: [], error: feedError };
+}
diff --git a/api/_lib/hood-portfolios.js b/api/_lib/hood-portfolios.js
index dbab1e17d..aec92778c 100644
--- a/api/_lib/hood-portfolios.js
+++ b/api/_lib/hood-portfolios.js
@@ -16,9 +16,11 @@
// • the manifest = canonical JSON + keccak256, so the document a
// user is shown hashes to the value that gets
// committed on-chain by PortfolioRegistry
-// • valuation and history = NAV from live prices, and real price history
-// from Chainlink rounds (equities) and Uniswap v4
-// swap events (everything else)
+// • valuation = NAV from live prices, refusing to answer rather
+// than under-reporting when a leg is unpriceable
+//
+// Price history and backtesting live next door in hood-portfolios-history.js and
+// hood-portfolios-backtest.js, because both are about time rather than about now.
//
// Nothing here invents a number. Where a price genuinely does not exist (a
// memecoin with no live pool, an equity feed that stopped updating when the US
@@ -34,7 +36,6 @@ import { llmComplete } from './llm.js';
import {
chainlinkSnapshot,
dexSnapshot,
- feedRoundHistory,
publicClient,
stockRegistry,
} from './robinhood.js';
@@ -535,37 +536,6 @@ export function valueBasket(constituents, priceByAddress) {
};
}
-// ── Real price history ──────────────────────────────────────────────────────
-
-/**
- * Daily USD price history for one token, from whatever real source it has.
- *
- * Two sources, in order of what actually exists on this chain:
- *
- * 1. Chainlink round history, for the 34 registry equities that carry a feed.
- * Read by round id at head state, so it works on the pruned public RPC.
- * 2. Uniswap v4 `Swap` events, for everything else. The post-swap
- * `sqrtPriceX96` is in the log data, so a real series can be reconstructed
- * from logs alone, which is the only historical source a pruned node can
- * still serve.
- *
- * Returns an empty series rather than a synthesised one when neither exists.
- * A backtest over a token with no history is a backtest with a hole in it, and
- * the caller is told which legs those are.
- */
-export async function priceHistory(token, { days = 30 } = {}) {
- if (token.feed) {
- // feedRoundHistory returns [{ roundId, priceUsd, updatedAt }], oldest first.
- const rounds = await feedRoundHistory(token.feed, Math.min(days * 2, 80)).catch(() => []);
- const points = (rounds || [])
- .filter((r) => r?.priceUsd != null && Number(r.priceUsd) > 0)
- .map((r) => ({ t: Number(r.updatedAt) * 1000, priceUsd: Number(r.priceUsd) }))
- .sort((a, b) => a.t - b.t);
- if (points.length) return { source: 'chainlink', feed: token.feed, points };
- }
- return { source: 'none', points: [] };
-}
-
/** Cheap health line for the status surfaces: is the chain answering, and how fresh is the universe. */
export async function portfoliosHealth() {
return cacheWrap('hp:health', 20, async () => {
diff --git a/api/cron/hood-portfolio-snapshot.js b/api/cron/hood-portfolio-snapshot.js
new file mode 100644
index 000000000..a29fa4bd5
--- /dev/null
+++ b/api/cron/hood-portfolio-snapshot.js
@@ -0,0 +1,47 @@
+// @ts-check
+// GET /api/cron/hood-portfolio-snapshot - records one day of Robinhood Chain
+// prices so portfolio backtests have history to run against.
+//
+// Runs once a day. Robinhood Chain has no price history API and a pruned RPC,
+// and reconstructing prices from Uniswap swap logs is not viable in a request:
+// the chain produces ~864,000 blocks a day and `eth_getLogs` caps at a
+// 500k-block span, so a single month for a single token is 50+ archival queries.
+//
+// The 34 registry equities that carry a Chainlink feed already have real history
+// through their round data, which is addressed by id and readable at head state.
+// Everything else on the chain, memecoins included, has none and never will
+// retroactively. This cron is the answer to that: the chain cannot be asked what
+// a token was worth last month, but it can be asked every day from now on, and
+// the coverage compounds.
+//
+// Idempotent by UTC day, so a retry after a partial failure overwrites rather
+// than duplicating.
+
+import { json, method, wrapCron } from '../_lib/http.js';
+import { requireCron } from '../_lib/cron-auth.js';
+import { liveUniverse } from '../_lib/hood-portfolios.js';
+import { recordDailySnapshot } from '../_lib/hood-portfolios-history.js';
+
+export default wrapCron(async (req, res) => {
+ if (!method(req, res, ['GET'])) return;
+ if (!requireCron(req, res)) return;
+
+ const universe = await liveUniverse();
+ const priced = universe.tokens.filter((t) => t.priceUsd > 0);
+
+ // A snapshot of almost nothing means the upstream failed rather than that the
+ // chain emptied out; recording it would write a hole into the history that
+ // every future backtest reads as real.
+ if (priced.length < 50) {
+ json(res, 200, {
+ ok: true,
+ skipped: 'too_few_prices',
+ priced: priced.length,
+ universe: universe.tokens.length,
+ });
+ return;
+ }
+
+ const { key, recorded } = await recordDailySnapshot(priced);
+ json(res, 200, { ok: true, key, recorded, universe: universe.tokens.length });
+});
diff --git a/api/v1/hood-portfolios/backtest.js b/api/v1/hood-portfolios/backtest.js
new file mode 100644
index 000000000..ea635677a
--- /dev/null
+++ b/api/v1/hood-portfolios/backtest.js
@@ -0,0 +1,146 @@
+// POST /api/v1/hood-portfolios/backtest - what this basket would have done, and
+// what its rebalancing schedule did to it.
+//
+// Every backtest runs the same basket twice: once rebalanced on the schedule the
+// manifest published, and once never rebalanced. The difference is the only
+// number that judges the schedule, and it goes both ways: rebalancing harvests
+// swings in a basket that oscillates and gives up upside in one that trends.
+//
+// Coverage is reported honestly. A constituent with no price history is excluded
+// and named, the remaining weights are renormalised, and `coveredWeightBps` says
+// how much of the portfolio the result actually describes. Nothing is carried
+// forward or interpolated to fill a gap.
+
+import { defineEndpoint, fail } from '../../_lib/gateway.js';
+import { rateLimited } from '../../_lib/http.js';
+import { limits } from '../../_lib/rate-limit.js';
+import { liveUniverse } from '../../_lib/hood-portfolios.js';
+import { readSnapshots, tokenHistory } from '../../_lib/hood-portfolios-history.js';
+import { backtest } from '../../_lib/hood-portfolios-backtest.js';
+
+const MAX_LEGS = 12;
+
+export default defineEndpoint({
+ name: 'v1.hood-portfolios.backtest',
+ method: 'POST',
+ auth: 'optional',
+ handler: async ({ res, body, ip, principal }) => {
+ const rl = await limits.robinhoodRead(principal?.userId || ip);
+ if (!rl.success) return rateLimited(res, rl, 'backtests are capped at 60 requests/min per caller');
+
+ const raw = Array.isArray(body?.constituents) ? body.constituents : [];
+ if (raw.length < 2) fail(400, 'bad_basket', 'supply at least two constituents as [{ address, weightBps }]');
+ if (raw.length > MAX_LEGS) fail(400, 'bad_basket', `a portfolio holds at most ${MAX_LEGS} constituents`);
+
+ const rebalanceDays = Math.max(0, Math.min(Number(body?.rebalanceDays) || 30, 365));
+ const days = Math.max(7, Math.min(Number(body?.days) || 90, 365));
+
+ const universe = await liveUniverse();
+ const byAddress = new Map(universe.tokens.map((t) => [t.address, t]));
+
+ const legs = [];
+ // An address the universe does not know is reported, never quietly skipped:
+ // silently backtesting two legs of a three-leg basket produces a number that
+ // looks complete and describes something the caller never asked for.
+ const unknown = [];
+ for (const c of raw) {
+ const address = String(c?.address || '').toLowerCase();
+ const token = byAddress.get(address);
+ const weightBps = Number(c?.weightBps);
+ if (!Number.isFinite(weightBps) || weightBps <= 0) {
+ unknown.push({ address, reason: 'weightBps must be a positive number' });
+ continue;
+ }
+ if (!token) {
+ unknown.push({ address, reason: 'not in the holdable universe on this chain' });
+ continue;
+ }
+ legs.push({ token, weightBps: Math.round(weightBps) });
+ }
+ if (legs.length < 2) {
+ fail(
+ 422,
+ 'unknown_constituents',
+ `fewer than two constituents resolved to holdable tokens${unknown.length ? `: ${unknown.map((u) => `${u.address} (${u.reason})`).join('; ')}` : ''}`,
+ );
+ }
+
+ // One snapshot read shared across every leg, rather than one per leg.
+ const snapshots = await readSnapshots({ days });
+
+ // Sequential on purpose. Each feed-backed leg is an 80-call multicall, and
+ // firing several at this RPC concurrently makes most of them fail: a
+ // three-equity basket read in parallel came back with one leg covered and
+ // the other two reported as having no history at all.
+ const histories = [];
+ for (const leg of legs) {
+ histories.push({ leg, history: await tokenHistory(leg.token, { days, snapshots }) });
+ }
+
+ const covered = [];
+ const uncovered = [];
+ const series = {};
+ for (const { leg, history } of histories) {
+ // Two points is the minimum that can express a return at all.
+ if (history.closes.length >= 2) {
+ covered.push({ ...leg, source: history.source, points: history.closes.length });
+ series[leg.token.address] = history.closes;
+ } else {
+ uncovered.push({
+ address: leg.token.address,
+ symbol: leg.token.symbol,
+ weightBps: leg.weightBps,
+ reason:
+ history.source === 'unavailable'
+ ? 'its Chainlink feed could not be read just now, so its history is temporarily unavailable'
+ : leg.token.feed
+ ? 'its Chainlink feed returned no usable rounds'
+ : 'it has no price feed, and the daily snapshot has not recorded it yet',
+ temporary: history.source === 'unavailable',
+ });
+ }
+ }
+
+ const totalBps = legs.reduce((a, l) => a + l.weightBps, 0);
+ const coveredBps = covered.reduce((a, l) => a + l.weightBps, 0);
+
+ if (covered.length < 2) {
+ return {
+ ok: false,
+ reason:
+ 'fewer than two constituents have price history yet. Equities are covered by their Chainlink feeds; every other token is covered from the day the daily snapshot first recorded it.',
+ coveredWeightBps: coveredBps,
+ totalWeightBps: totalBps,
+ covered: covered.map((c) => ({ address: c.token.address, symbol: c.token.symbol, source: c.source })),
+ uncovered,
+ unknown,
+ };
+ }
+
+ const result = backtest({
+ legs: covered.map((c) => ({ address: c.token.address, weightBps: c.weightBps })),
+ series,
+ rebalanceDays,
+ startValueUsd: 10_000,
+ });
+
+ res.setHeader('Cache-Control', 'public, max-age=300, s-maxage=300');
+ return {
+ ...result,
+ rebalanceDays,
+ requestedDays: days,
+ coveredWeightBps: coveredBps,
+ totalWeightBps: totalBps,
+ covered: covered.map((c) => ({
+ address: c.token.address,
+ symbol: c.token.symbol,
+ weightBps: c.weightBps,
+ source: c.source,
+ points: c.points,
+ })),
+ uncovered,
+ unknown,
+ snapshotDays: snapshots.length,
+ };
+ },
+});
diff --git a/api/v1/hood-portfolios/manifest.js b/api/v1/hood-portfolios/manifest.js
new file mode 100644
index 000000000..4c4d4ff98
--- /dev/null
+++ b/api/v1/hood-portfolios/manifest.js
@@ -0,0 +1,45 @@
+// POST /api/v1/hood-portfolios/manifest - canonicalise a manifest and return its hash.
+//
+// The hash a portfolio is published under is keccak256 of the CANONICAL
+// serialisation: object keys sorted at every depth, no insignificant whitespace.
+// `JSON.stringify` follows insertion order, so a document that has been round
+// tripped through a client, a file, or a URL serialises differently from the one
+// the generator produced and hashes to a different value.
+//
+// This endpoint is the shared referee. Anyone holding a manifest can ask what it
+// commits to and check it against what is on-chain, without reimplementing the
+// canonicalisation rules. It is a pure function: no storage, no chain reads,
+// nothing recorded.
+
+import { defineEndpoint, fail } from '../../_lib/gateway.js';
+import { canonicalise, manifestHash, MANIFEST_VERSION } from '../../_lib/hood-portfolios.js';
+
+const MAX_BYTES = 256 * 1024;
+
+export default defineEndpoint({
+ name: 'v1.hood-portfolios.manifest',
+ method: 'POST',
+ auth: 'public',
+ handler: async ({ res, body }) => {
+ const manifest = body?.manifest ?? body;
+ if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {
+ fail(400, 'bad_manifest', 'POST the manifest document as JSON, either bare or as { manifest }');
+ }
+
+ const canonical = canonicalise(manifest);
+ if (canonical.length > MAX_BYTES) {
+ fail(413, 'manifest_too_large', `a manifest must canonicalise to under ${MAX_BYTES} bytes`);
+ }
+
+ res.setHeader('Cache-Control', 'no-store');
+ return {
+ manifestHash: manifestHash(manifest),
+ canonicalBytes: canonical.length,
+ // Echoed so a caller can see exactly what was hashed rather than trusting
+ // that their serialisation matched ours.
+ canonical,
+ expectedVersion: MANIFEST_VERSION,
+ manifestVersion: manifest.version ?? null,
+ };
+ },
+});
diff --git a/data/changelog.json b/data/changelog.json
index d664d4b16..34ef9f0bc 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,13 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-09-08",
+ "title": "Robinhood Portfolios can now show you what a basket would have done, and what the rebalancing did to it",
+ "summary": "Every generated portfolio now comes with a backtest, and it runs the basket twice: once rebalanced on the schedule it published, and once left alone. The gap between those two lines is the whole reason to pick one schedule over another, and it goes both ways, since rebalancing quietly harvests the swings in a basket whose holdings move against each other and quietly gives up gains in one where a single holding keeps winning. Coverage is stated rather than glossed over: a holding with no price history is named and left out, the window shown is only the stretch where every remaining holding has real observations, and nothing is filled in to close a gap. Getting that history at all took some doing, because this chain keeps no price archive and produces about 864,000 blocks a day, so reading a month of prices back off the chain is not something a page can do while you wait. Tokenized stocks are covered from their price feeds going back weeks, and a nightly snapshot now records the whole market so coverage keeps growing for everything else, memecoins included. Sharing a portfolio also got fixed: a link now carries the portfolio itself rather than the sentence that produced it, so what you send is exactly what the other person opens, where before the wording was re-run and could quietly come back as a different basket. There is a new endpoint for checking that a portfolio document really is the one a portfolio was published under, and a client library for developers who want the market, the generator, the backtest and that check from their own code. Along the way two data bugs were fixed that were quietly under-reporting the market: the tokenized-stock board had been describing only a couple of tokens per batch instead of all thirty, and the price-history reads had been silently returning less history the more of it you asked for.",
+ "tags": ["feature", "improvement"],
+ "link": "/markets/robinhood/portfolios"
+ },
{
"date": "2026-09-07",
"title": "Robinhood Portfolios: describe a portfolio in a sentence, hold it on-chain",
@@ -18,7 +25,7 @@
{
"date": "2026-09-07",
"title": "Awesome 3D Agents: a curated list of everything you need to give an AI a body",
- "summary": "Giving an agent a body means assembling a pipeline out of a dozen separate fields, and the map of that pipeline did not exist anywhere. There is now one: 134 hand-picked projects across 13 sections, covering text-to-3D generation, photo and video capture, avatars, rigging, motion generation, lipsync and voice, web renderers, asset pipelines, physics and networking, agent frameworks, datasets, free assets, and where to learn all of it. Each entry says in one sentence what the thing does and why you would reach for it instead of the alternative. The list is searchable and filterable by tag at /awesome, copyable as Markdown, and published in the standard awesome-list format on GitHub so it can be read, forked, and contributed to there. Every link is fetched and verified before it ships.",
+ "summary": "Giving an agent a body means assembling a pipeline out of a dozen separate fields, and the map of that pipeline did not exist anywhere. There is now one: 152 hand-picked projects across 15 sections, covering text-to-3D generation, photo and video capture, avatars, rigging, motion generation, texturing, lipsync and voice, web renderers, asset pipelines, AR and XR, physics and networking, agent frameworks, datasets, free assets, and where to learn all of it. Each entry says in one sentence what the thing does and why you would reach for it instead of the alternative. The list is searchable and filterable by tag at /awesome, copyable as Markdown, and published in the standard awesome-list format on GitHub so it can be read, forked, and contributed to there. Every link is fetched and verified before it ships.",
"tags": ["feature", "docs"],
"link": "/awesome"
},
diff --git a/docs/robinhood-portfolios.md b/docs/robinhood-portfolios.md
index 72b92fcdb..31cba289c 100644
--- a/docs/robinhood-portfolios.md
+++ b/docs/robinhood-portfolios.md
@@ -169,6 +169,60 @@ recorded inputs, reproduces its recorded output, and that needs no bond: the man
universe snapshot and every constituent's price and liquidity at selection time, so anyone can
re-run it and publish the diff.
+## Backtesting
+
+Every backtest runs the same basket **twice**: once rebalanced on the schedule its manifest
+published, and once never rebalanced at all. The difference, `rebalancingAddedPct`, is the only
+number that judges a schedule, and it goes both ways. Rebalancing harvests the swings in a basket
+whose legs move against each other, and gives up upside in one where a single leg keeps winning.
+A backtest that could not produce the second result would not be measuring anything.
+
+### Where the history comes from
+
+This chain has no price history API. DexScreener serves only current state, GeckoTerminal does not
+index chain 4663, and the public RPC is pruned, so historical `eth_call` is unavailable.
+
+Reconstructing prices from Uniswap swap logs is the obvious next idea and it does not survive
+contact with the chain's block rate. Robinhood Chain produces roughly **864,000 blocks a day** at
+~100ms each, and the RPC caps `eth_getLogs` at a 500k-block span or 10,000 results. One month of
+history for *one* token is 50+ archival queries before any block-timestamp reads. That is not
+something an API request can do, for any number of constituents.
+
+So history comes from the two sources that are actually cheap here:
+
+| Source | Covers | Reach |
+|---|---|---|
+| Chainlink round history | the 34 registry equities with a feed | weeks, today |
+| Daily snapshot (`/api/cron/hood-portfolio-snapshot`) | every token, memecoins included | from the day it first ran, compounding |
+
+Rounds are addressed by id and read at head state, so a pruned node serves them fine.
+`feedRoundHistory` batches them into multicalls of **40**, which is load-bearing: this RPC silently
+*drops* calls out of a larger multicall rather than failing it, so before chunking, asking for more
+history returned less of it. Measured against NVDA's feed on 2026-09-08: 80 rounds at depth 80, only
+8 at depth 120, and none at 160. That partial result was the dangerous failure, because it reads as
+a short-but-successful history rather than an error, and intersecting several of them produced an
+empty backtest window with nothing to explain it. Chunked, 300 rounds costs about two seconds a feed.
+
+### Coverage is reported, never assumed
+
+A constituent with no history is **excluded and named**, the remaining weights are renormalised, and
+`coveredWeightBps` says how much of the portfolio the answer actually describes. The window is the
+**intersection** of the days on which every covered leg has a real observation, not the union with
+gaps carried forward, because carrying a price forward manufactures flat stretches for a token that
+simply was not being recorded, and those read as stability rather than as missing data.
+
+Trading costs are not modelled, and the response says so in `costModel`.
+
+## The permalink
+
+A generated portfolio is shared by putting the **manifest itself** in the URL (`?p=`), deflate
+compressed to about a kilobyte. Sharing the prompt instead (`?q=`, still supported) does not
+reproduce a portfolio: the screen is a language model, so the same sentence returns a different
+basket tomorrow, and a link that silently resolves to something else is worse than no link.
+
+The hash is never read from the link. It is re-derived from the document through
+`POST /manifest`, so a tampered link shows a different hash rather than a borrowed one.
+
## The universe
A token is selectable when it has a live pool and a readable price. Classification is either
@@ -243,6 +297,44 @@ Capped at 10 requests per minute per caller, because each one is a real model ca
model invents is dropped rather than repaired; weights are renormalised to sum to exactly 10000,
because that is arithmetic rather than judgement.
+### `POST /backtest`
+
+```bash
+curl -s -X POST https://three.ws/api/v1/hood-portfolios/backtest \
+ -H 'content-type: application/json' \
+ -d '{"constituents":[{"address":"0xd0601ce157db5bdc3162bbac2a2c8af5320d9eec","weightBps":5000},
+ {"address":"0x117cc2133c37b721f49de2a7a74833232b3b4c0c","weightBps":5000}],
+ "rebalanceDays":7}'
+```
+
+```jsonc
+{
+ "data": {
+ "ok": true,
+ "from": "2026-08-07", "to": "2026-09-08", "windowDays": 32,
+ "rebalanced": { "totalReturnPct": 1.42, "maxDrawdownPct": 3.39, "rebalances": 4 },
+ "heldWithoutRebalancing": { "totalReturnPct": 1.418 },
+ "rebalancingAddedPct": 0.002,
+ "coveredWeightBps": 10000, "totalWeightBps": 10000,
+ "uncovered": [], "unknown": [], "costModel": "none"
+ }
+}
+```
+
+An address the universe does not know is returned in `unknown` rather than quietly skipped:
+silently backtesting two legs of a three-leg basket produces a number that looks complete and
+describes something the caller never asked for.
+
+### `POST /manifest`
+
+Canonicalises a manifest and returns the hash it commits to, plus the exact bytes that were hashed.
+Pure: no storage, no chain reads.
+
+```bash
+curl -s -X POST https://three.ws/api/v1/hood-portfolios/manifest \
+ -H 'content-type: application/json' -d '{"manifest":{"b":2,"a":1}}'
+```
+
### `GET /health`
Whether the chain is answering and how fresh the universe snapshot is.
@@ -260,6 +352,24 @@ import { canonicalise, manifestHash } from './api/_lib/hood-portfolios.js';
manifestHash(manifest); // 0x… the value passed to PortfolioRegistry.publish
```
+## The SDK
+
+[`@three-ws/hood-portfolios-sdk`](../packages/hood-portfolios-sdk) wraps all five endpoints and
+ships the canonicaliser, so a client can verify a manifest hash without a server:
+
+```js
+import { HoodPortfolios, canonicalise } from '@three-ws/hood-portfolios-sdk';
+import { keccak256, toHex } from 'viem';
+
+const hood = new HoodPortfolios();
+const { screen, manifest, manifestHash } = await hood.generate('AI infrastructure across stocks and crypto');
+
+keccak256(toHex(canonicalise(manifest))) === manifestHash; // true, checked offline
+```
+
+Its test suite asserts that canonicaliser is byte-identical to the server's, because a divergence
+would only ever surface as an on-chain commitment that does not match the document it came from.
+
## Contracts
```bash
diff --git a/package.json b/package.json
index f2964b3de..2999ecd1c 100644
--- a/package.json
+++ b/package.json
@@ -79,6 +79,7 @@
"packages/avatar-cli",
"packages/assets-cli",
"packages/defi-utils",
+ "packages/hood-portfolios-sdk",
"packages/viewer-presets",
"packages/avatar-agent-mcp",
"packages/pumpfun-mcp",
diff --git a/packages/hood-portfolios-sdk/LICENSE b/packages/hood-portfolios-sdk/LICENSE
new file mode 100644
index 000000000..b5ae2a4e1
--- /dev/null
+++ b/packages/hood-portfolios-sdk/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2026 nirholas
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/packages/hood-portfolios-sdk/README.md b/packages/hood-portfolios-sdk/README.md
new file mode 100644
index 000000000..a831daa09
--- /dev/null
+++ b/packages/hood-portfolios-sdk/README.md
@@ -0,0 +1,147 @@
+# @three-ws/hood-portfolios-sdk
+
+Client for **Robinhood Chain portfolios**: read the holdable universe, generate a basket from a
+sentence, backtest it, and canonicalise a manifest to the exact bytes its on-chain hash commits.
+
+Zero dependencies. Every endpoint it calls is free and keyless.
+
+- Product: [three.ws/markets/robinhood/portfolios](https://three.ws/markets/robinhood/portfolios)
+- Protocol: [docs/robinhood-portfolios.md](../../docs/robinhood-portfolios.md)
+- Contracts: [contracts/hood-portfolios](../../contracts/hood-portfolios)
+
+## Install
+
+```bash
+npm install @three-ws/hood-portfolios-sdk
+```
+
+Node 18+ or any browser (it uses the global `fetch`; pass your own with `{ fetch }` if you need to).
+
+## Quickstart
+
+```js
+import { HoodPortfolios } from '@three-ws/hood-portfolios-sdk';
+
+const hood = new HoodPortfolios();
+
+// 1. What can a portfolio actually hold right now?
+const universe = await hood.universe({ assetClass: 'rwa-equity', limit: 5 });
+for (const t of universe.tokens) {
+ console.log(`${t.symbol.padEnd(6)} $${t.priceUsd} liquidity $${Math.round(t.liquidityUsd).toLocaleString()}`);
+}
+// NVDA $232.07 liquidity $6,863,835
+// GLD $410.43 liquidity $4,631,035
+// ...
+
+// 2. Turn a sentence into a basket.
+const { screen, manifest, manifestHash } = await hood.generate(
+ 'AI infrastructure: chip makers plus the crypto compute tokens',
+);
+console.log(screen.name, screen.symbol, manifestHash);
+for (const c of screen.constituents) {
+ console.log(`${(c.weightBps / 100).toFixed(2)}% ${c.symbol} ${c.rationale}`);
+}
+
+// 3. What would it have done, and did the rebalancing help?
+const bt = await hood.backtest({
+ constituents: screen.constituents.map((c) => ({ address: c.address, weightBps: c.weightBps })),
+ rebalanceDays: screen.rebalanceDays,
+});
+if (bt.ok) {
+ console.log(`${bt.from} to ${bt.to}: ${bt.rebalanced.totalReturnPct.toFixed(2)}% rebalanced`);
+ console.log(`rebalancing added ${bt.rebalancingAddedPct.toFixed(3)} percentage points`);
+}
+```
+
+## API
+
+### `new HoodPortfolios(options?)`
+
+| Option | Default | Meaning |
+|---|---|---|
+| `baseUrl` | `https://three.ws` | Point at another deployment. |
+| `fetch` | `globalThis.fetch` | Supply a transport (a proxy, a test double). |
+| `timeoutMs` | `60000` | Per-request timeout. |
+
+### `universe(options?)`
+
+Every token a portfolio may hold, re-priced live on each call.
+
+| Option | Meaning |
+|---|---|
+| `assetClass` | One class or an array: `rwa-equity`, `crypto-major`, `crypto-native`, `stablecoin` |
+| `minLiquidityUsd` | Floor on live on-chain liquidity |
+| `limit` | Cap the rows returned |
+| `selectableOnly` | Only what a portfolio may actually hold |
+
+Each token carries `canonical`. It is `false` when another contract is the real holder of that
+ticker, which matters more here than it sounds: **13 separate contracts on this chain call
+themselves USDG**, and five of them are deeper than the real one. Filter on it, or use
+`selectableOnly`, which does.
+
+### `generate(prompt)`
+
+Screens the universe and returns `{ screen, manifest, manifestHash, deployment }`. Weights are
+integers summing to exactly `10000`. `manifestHash` is the value
+`PortfolioRegistry.publish` commits on-chain.
+
+Rate limited to 10 per minute per caller, because each call runs a real model.
+
+### `backtest({ constituents, rebalanceDays?, days? })`
+
+Runs the basket twice, once on its schedule and once never rebalanced, and reports the difference
+as `rebalancingAddedPct`. That number goes both ways: rebalancing harvests swings in a basket that
+oscillates and gives up upside in one that trends.
+
+Coverage is explicit. A constituent with no price history is excluded and listed in `uncovered`
+with the reason, the rest are renormalised, and `coveredWeightBps` says how much of the portfolio
+the answer describes. Nothing is interpolated to close a gap.
+
+### `manifestHash(manifest)`
+
+Canonicalises server-side and returns `{ manifestHash, canonical, canonicalBytes }`. Use it to
+check a manifest you were handed against what is on-chain.
+
+### `canonicalise(value)`
+
+The same canonicalisation, locally and offline: keys sorted at every depth, no insignificant
+whitespace. `JSON.stringify` follows insertion order, so a document that has been round-tripped
+through a file, a URL or a database serialises differently and would hash to a different
+commitment. To hash it yourself:
+
+```js
+import { canonicalise } from '@three-ws/hood-portfolios-sdk';
+import { keccak256, toHex } from 'viem';
+
+const hash = keccak256(toHex(canonicalise(manifest))); // identical to what the API returns
+```
+
+The package's test suite asserts this canonicaliser is byte-identical to the server's.
+
+### `health()`
+
+Whether the chain is answering, and how fresh the universe snapshot is.
+
+## Errors
+
+Every non-2xx throws `HoodPortfoliosError` carrying `status` and the API's own `code`
+(`screen_failed`, `screen_unavailable`, `universe_unavailable`, `unknown_constituents`, ...), so a
+caller can branch on the cause rather than parse a message.
+
+```js
+import { HoodPortfoliosError } from '@three-ws/hood-portfolios-sdk';
+
+try {
+ await hood.generate('...');
+} catch (err) {
+ if (err instanceof HoodPortfoliosError && err.code === 'screen_unavailable') {
+ // every model provider is busy; retry shortly
+ }
+}
+```
+
+## Tests
+
+```bash
+npx vitest run packages/hood-portfolios-sdk/tests
+```
diff --git a/packages/hood-portfolios-sdk/package.json b/packages/hood-portfolios-sdk/package.json
new file mode 100644
index 000000000..67f3b698c
--- /dev/null
+++ b/packages/hood-portfolios-sdk/package.json
@@ -0,0 +1,34 @@
+{
+ "name": "@three-ws/hood-portfolios-sdk",
+ "version": "0.1.0",
+ "description": "Client for Robinhood Chain portfolios: read the holdable universe, generate a basket from a sentence, backtest it, and canonicalise a manifest to the exact bytes its on-chain hash commits.",
+ "keywords": [
+ "three.ws",
+ "robinhood-chain",
+ "tokenized-equities",
+ "index",
+ "portfolio",
+ "rebalancing",
+ "defi"
+ ],
+ "author": "three.ws <[email protected]> (https://three.ws)",
+ "license": "Apache-2.0",
+ "homepage": "https://three.ws/markets/robinhood/portfolios",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/nirholas/three.ws.git",
+ "directory": "packages/hood-portfolios-sdk"
+ },
+ "private": true,
+ "type": "module",
+ "main": "./src/index.js",
+ "module": "./src/index.js",
+ "exports": {
+ ".": {
+ "import": "./src/index.js",
+ "default": "./src/index.js"
+ }
+ },
+ "files": ["src", "README.md", "LICENSE"],
+ "engines": { "node": ">=18" }
+}
diff --git a/packages/hood-portfolios-sdk/src/index.js b/packages/hood-portfolios-sdk/src/index.js
new file mode 100644
index 000000000..925822382
--- /dev/null
+++ b/packages/hood-portfolios-sdk/src/index.js
@@ -0,0 +1,182 @@
+/**
+ * @three-ws/hood-portfolios-sdk
+ *
+ * A typed-by-JSDoc client for the Robinhood Chain portfolios API, plus the one
+ * piece of logic a client genuinely needs locally: canonical manifest
+ * serialisation.
+ *
+ * Zero dependencies, and no network at import time. Every method maps to one
+ * free, keyless endpoint on https://three.ws.
+ */
+
+export const DEFAULT_BASE_URL = 'https://three.ws';
+export const CHAIN_ID = 4663;
+
+/** The asset classes a constituent can be tagged with. */
+export const ASSET_CLASSES = /** @type {const} */ ([
+ 'rwa-equity',
+ 'crypto-major',
+ 'crypto-native',
+ 'stablecoin',
+]);
+
+/** Thrown for any non-2xx response, carrying the API's own error code. */
+export class HoodPortfoliosError extends Error {
+ /**
+ * @param {string} message
+ * @param {{ status?: number, code?: string }} [meta]
+ */
+ constructor(message, meta = {}) {
+ super(message);
+ this.name = 'HoodPortfoliosError';
+ this.status = meta.status;
+ this.code = meta.code;
+ }
+}
+
+/**
+ * Canonical JSON: object keys sorted at every depth, no insignificant whitespace.
+ *
+ * This is the exact serialisation whose keccak256 `PortfolioRegistry.publish`
+ * commits on-chain, so it is reproduced here rather than fetched. `JSON.stringify`
+ * follows insertion order, which differs between the generator and any client
+ * that round-tripped the document through a file, a URL or a database, and a
+ * different byte string hashes to a different commitment.
+ *
+ * @param {unknown} value
+ * @returns {string}
+ */
+export function canonicalise(value) {
+ if (value === null || typeof value !== 'object') return JSON.stringify(value);
+ if (Array.isArray(value)) return `[${value.map(canonicalise).join(',')}]`;
+ const record = /** @type {Record<string, unknown>} */ (value);
+ const keys = Object.keys(record).sort();
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalise(record[k])}`).join(',')}}`;
+}
+
+/**
+ * Client for the Robinhood Chain portfolios API.
+ *
+ * @example
+ * import { HoodPortfolios } from '@three-ws/hood-portfolios-sdk';
+ *
+ * const hood = new HoodPortfolios();
+ * const equities = await hood.universe({ assetClass: 'rwa-equity', limit: 5 });
+ * console.log(equities.tokens.map((t) => `${t.symbol} $${t.priceUsd}`));
+ */
+export class HoodPortfolios {
+ /**
+ * @param {{ baseUrl?: string, fetch?: typeof globalThis.fetch, timeoutMs?: number }} [options]
+ */
+ constructor(options = {}) {
+ this.baseUrl = (options.baseUrl || DEFAULT_BASE_URL).replace(/\/+$/, '');
+ this.fetch = options.fetch || globalThis.fetch;
+ this.timeoutMs = options.timeoutMs ?? 60_000;
+ if (typeof this.fetch !== 'function') {
+ throw new HoodPortfoliosError('no fetch implementation available; pass one as options.fetch');
+ }
+ }
+
+ /** @private */
+ async _request(path, { method = 'GET', body = null, query = null } = {}) {
+ const url = new URL(`${this.baseUrl}/api/v1/hood-portfolios${path}`);
+ for (const [k, v] of Object.entries(query || {})) {
+ if (v !== undefined && v !== null && v !== '') url.searchParams.set(k, String(v));
+ }
+
+ const res = await this.fetch(url.toString(), {
+ method,
+ headers: body ? { 'content-type': 'application/json' } : undefined,
+ body: body ? JSON.stringify(body) : undefined,
+ signal: AbortSignal.timeout(this.timeoutMs),
+ });
+
+ let payload = null;
+ try {
+ payload = await res.json();
+ } catch {
+ payload = null;
+ }
+ if (!res.ok) {
+ throw new HoodPortfoliosError(
+ payload?.error_description || payload?.error || `request failed with HTTP ${res.status}`,
+ { status: res.status, code: payload?.error },
+ );
+ }
+ return payload?.data ?? payload;
+ }
+
+ /**
+ * Every token a portfolio may hold, re-priced live on each call.
+ *
+ * @param {{ assetClass?: string|string[], minLiquidityUsd?: number, limit?: number, selectableOnly?: boolean }} [options]
+ */
+ async universe(options = {}) {
+ const assetClass = Array.isArray(options.assetClass) ? options.assetClass.join(',') : options.assetClass;
+ return this._request('/universe', {
+ query: {
+ class: assetClass,
+ minLiquidity: options.minLiquidityUsd,
+ limit: options.limit,
+ selectable: options.selectableOnly ? '1' : undefined,
+ },
+ });
+ }
+
+ /**
+ * Screen the universe against a sentence and return a validated basket plus
+ * its manifest and the hash that manifest commits to.
+ *
+ * @param {string} prompt
+ */
+ async generate(prompt) {
+ if (!prompt || !String(prompt).trim()) {
+ throw new HoodPortfoliosError('a prompt is required');
+ }
+ return this._request('/generate', { method: 'POST', body: { prompt: String(prompt).trim() } });
+ }
+
+ /**
+ * Backtest a basket, and compare it against the same basket never rebalanced.
+ *
+ * Coverage is reported rather than assumed: a constituent with no price
+ * history is excluded and named, and `coveredWeightBps` says how much of the
+ * portfolio the result actually describes.
+ *
+ * @param {{ constituents: Array<{ address: string, weightBps: number }>, rebalanceDays?: number, days?: number }} request
+ */
+ async backtest(request) {
+ const constituents = request?.constituents || [];
+ if (constituents.length < 2) {
+ throw new HoodPortfoliosError('supply at least two constituents as [{ address, weightBps }]');
+ }
+ return this._request('/backtest', {
+ method: 'POST',
+ body: {
+ constituents,
+ rebalanceDays: request.rebalanceDays ?? 30,
+ days: request.days ?? 90,
+ },
+ });
+ }
+
+ /**
+ * Canonicalise a manifest server-side and return the hash it commits to.
+ *
+ * Use this to check a manifest you were given against what is on-chain. To
+ * hash locally instead, `canonicalise()` from this package produces the exact
+ * bytes; keccak256 them with any library (`viem`'s `keccak256(toHex(bytes))`).
+ *
+ * @param {Record<string, unknown>} manifest
+ */
+ async manifestHash(manifest) {
+ return this._request('/manifest', { method: 'POST', body: { manifest } });
+ }
+
+ /** Whether the chain is answering, and how fresh the universe snapshot is. */
+ async health() {
+ return this._request('/health');
+ }
+}
+
+export default HoodPortfolios;
diff --git a/packages/hood-portfolios-sdk/tests/hood-portfolios-sdk.test.js b/packages/hood-portfolios-sdk/tests/hood-portfolios-sdk.test.js
new file mode 100644
index 000000000..c25ad2e7c
--- /dev/null
+++ b/packages/hood-portfolios-sdk/tests/hood-portfolios-sdk.test.js
@@ -0,0 +1,144 @@
+// Tests for @three-ws/hood-portfolios-sdk.
+//
+// The transport is injected, so these exercise the client's own behaviour (URL
+// construction, argument validation, error surfacing) without a network. The one
+// test that matters most compares this package's canonicaliser against the
+// server's actual implementation: they must agree byte for byte, because the
+// hash of those bytes is what a portfolio is published under, and a divergence
+// would only ever show up as an on-chain commitment that does not match the
+// document it came from.
+
+import { describe, it, expect } from 'vitest';
+import { canonicalise as serverCanonicalise } from '../../../api/_lib/hood-portfolios.js';
+import {
+ ASSET_CLASSES,
+ CHAIN_ID,
+ HoodPortfolios,
+ HoodPortfoliosError,
+ canonicalise,
+} from '../src/index.js';
+
+/** A fetch stand-in that records calls and replays a scripted response. */
+function stubFetch(response = { data: { ok: true } }, status = 200) {
+ const calls = [];
+ const fetch = async (url, init) => {
+ calls.push({ url, init });
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ json: async () => response,
+ };
+ };
+ return { fetch, calls };
+}
+
+describe('canonicalise', () => {
+ it('matches the server implementation exactly', () => {
+ const cases = [
+ { z: 1, a: 2 },
+ { nested: { b: [3, { d: 4, c: 5 }], a: 'x' } },
+ { n: null, t: true, s: 'with "quotes" and \\ backslash', f: 1.5 },
+ { empty: {}, list: [] },
+ { unicode: 'naïve café 日本語' },
+ ];
+ for (const c of cases) {
+ expect(canonicalise(c)).toBe(serverCanonicalise(c));
+ }
+ });
+
+ it('is stable under key reordering', () => {
+ expect(canonicalise({ a: 1, b: 2 })).toBe(canonicalise({ b: 2, a: 1 }));
+ });
+
+ it('distinguishes values JSON.stringify would render alike', () => {
+ expect(canonicalise({ a: '1' })).not.toBe(canonicalise({ a: 1 }));
+ });
+});
+
+describe('constants', () => {
+ it('targets Robinhood Chain', () => {
+ expect(CHAIN_ID).toBe(4663);
+ expect(ASSET_CLASSES).toContain('rwa-equity');
+ expect(ASSET_CLASSES).toContain('crypto-native');
+ });
+});
+
+describe('HoodPortfolios', () => {
+ it('builds the universe query from its options', async () => {
+ const { fetch, calls } = stubFetch({ data: { tokens: [] } });
+ const hood = new HoodPortfolios({ fetch });
+ await hood.universe({ assetClass: ['rwa-equity', 'stablecoin'], limit: 5, selectableOnly: true });
+
+ const url = new URL(calls[0].url);
+ expect(url.pathname).toBe('/api/v1/hood-portfolios/universe');
+ expect(url.searchParams.get('class')).toBe('rwa-equity,stablecoin');
+ expect(url.searchParams.get('limit')).toBe('5');
+ expect(url.searchParams.get('selectable')).toBe('1');
+ });
+
+ it('omits query params that were not supplied', async () => {
+ const { fetch, calls } = stubFetch({ data: {} });
+ await new HoodPortfolios({ fetch }).universe();
+ expect(new URL(calls[0].url).search).toBe('');
+ });
+
+ it('unwraps the data envelope', async () => {
+ const { fetch } = stubFetch({ data: { chainOk: true, head: 42 } });
+ const out = await new HoodPortfolios({ fetch }).health();
+ expect(out).toEqual({ chainOk: true, head: 42 });
+ });
+
+ it('surfaces the API error code rather than a bare status', async () => {
+ const { fetch } = stubFetch({ error: 'screen_failed', error_description: 'not enough usable constituents' }, 422);
+ const hood = new HoodPortfolios({ fetch });
+ await expect(hood.generate('anything')).rejects.toMatchObject({
+ name: 'HoodPortfoliosError',
+ status: 422,
+ code: 'screen_failed',
+ message: 'not enough usable constituents',
+ });
+ });
+
+ it('refuses an empty prompt before making a request', async () => {
+ const { fetch, calls } = stubFetch();
+ await expect(new HoodPortfolios({ fetch }).generate(' ')).rejects.toBeInstanceOf(HoodPortfoliosError);
+ expect(calls).toHaveLength(0);
+ });
+
+ it('refuses a one-legged backtest before making a request', async () => {
+ const { fetch, calls } = stubFetch();
+ const hood = new HoodPortfolios({ fetch });
+ await expect(hood.backtest({ constituents: [{ address: '0x1', weightBps: 10_000 }] })).rejects.toBeInstanceOf(
+ HoodPortfoliosError,
+ );
+ expect(calls).toHaveLength(0);
+ });
+
+ it('defaults the backtest schedule and window', async () => {
+ const { fetch, calls } = stubFetch({ data: { ok: true } });
+ await new HoodPortfolios({ fetch }).backtest({
+ constituents: [
+ { address: '0xa', weightBps: 5000 },
+ { address: '0xb', weightBps: 5000 },
+ ],
+ });
+ expect(JSON.parse(calls[0].init.body)).toMatchObject({ rebalanceDays: 30, days: 90 });
+ });
+
+ it('honours a custom base URL without doubling slashes', async () => {
+ const { fetch, calls } = stubFetch({ data: {} });
+ await new HoodPortfolios({ fetch, baseUrl: 'http://localhost:3000/' }).health();
+ expect(calls[0].url).toBe('http://localhost:3000/api/v1/hood-portfolios/health');
+ });
+
+ it('falls back to the global fetch when none is supplied', () => {
+ // `null` means "not provided", so it must fall through rather than fail:
+ // the common case is a browser or a modern Node with fetch built in.
+ expect(() => new HoodPortfolios({ fetch: null })).not.toThrow();
+ expect(() => new HoodPortfolios()).not.toThrow();
+ });
+
+ it('refuses a transport that is not callable', () => {
+ expect(() => new HoodPortfolios({ fetch: 'not a function' })).toThrow(HoodPortfoliosError);
+ });
+});
diff --git a/pages/hood-portfolios.html b/pages/hood-portfolios.html
index beb50f5bf..624900cf2 100644
--- a/pages/hood-portfolios.html
+++ b/pages/hood-portfolios.html
@@ -197,6 +197,8 @@
<p>
When the published interval comes due, the move is offered as a descending-price auction
any address can fill. There is no function that lets a manager trade the fund's assets.
+ Every portfolio is backtested twice, on its schedule and never rebalanced, so you can see
+ what the schedule actually did rather than assume it helped.
</p>
</li>
</ol>
diff --git a/src/hood-portfolios.css b/src/hood-portfolios.css
index ba0c3ed0b..77f05df73 100644
--- a/src/hood-portfolios.css
+++ b/src/hood-portfolios.css
@@ -863,3 +863,112 @@
.hp-row-flagged:hover td {
opacity: 1;
}
+
+/* ── Backtest ───────────────────────────────────────────────────────────── */
+
+.hp-backtest {
+ border-top: 1px solid var(--cv-border);
+ padding: 1.25rem 1.5rem;
+}
+
+.hp-backtest h3 {
+ margin: 0 0 0.9rem;
+ font-size: 0.75rem;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ color: var(--cv-text-3);
+}
+
+.hp-bt-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
+ gap: 1rem;
+ margin-bottom: 1.1rem;
+}
+
+.hp-bt-label {
+ display: block;
+ font-size: 0.75rem;
+ color: var(--cv-text-3);
+ margin-bottom: 0.25rem;
+}
+
+.hp-bt-value {
+ display: block;
+ font-family: var(--cv-font-mono);
+ font-size: 1.25rem;
+ font-weight: 600;
+ letter-spacing: -0.02em;
+ color: var(--cv-text);
+}
+
+/*
+ * Two polylines on one shared axis. `vector-effect` keeps the strokes a constant
+ * width even though the viewBox is stretched by preserveAspectRatio="none", which
+ * is what lets the chart be fluid without the lines going wedge-shaped.
+ */
+.hp-chart {
+ display: block;
+ width: 100%;
+ height: 180px;
+ overflow: visible;
+}
+
+.hp-chart path {
+ fill: none;
+ vector-effect: non-scaling-stroke;
+}
+
+.hp-chart-area {
+ fill: var(--cv-accent);
+ opacity: 0.08;
+ stroke: none;
+}
+
+.hp-chart-line {
+ stroke: var(--cv-accent);
+ stroke-width: 2;
+ stroke-linejoin: round;
+ stroke-linecap: round;
+}
+
+.hp-chart-held {
+ stroke: var(--cv-text-3);
+ stroke-width: 1.5;
+ stroke-dasharray: 4 3;
+ stroke-linejoin: round;
+}
+
+.hp-chart-key {
+ display: flex;
+ align-items: center;
+ gap: 0.45rem;
+ flex-wrap: wrap;
+ margin: 0.6rem 0 0;
+ font-size: 0.75rem;
+ color: var(--cv-text-2);
+}
+
+.hp-key-line,
+.hp-key-held {
+ display: inline-block;
+ width: 18px;
+ height: 0;
+ border-top: 2px solid var(--cv-accent);
+}
+
+.hp-key-held {
+ border-top: 1.5px dashed var(--cv-text-3);
+ margin-left: 0.6rem;
+}
+
+@media (max-width: 640px) {
+ .hp-backtest {
+ padding-left: 1rem;
+ padding-right: 1rem;
+ }
+
+ .hp-chart {
+ height: 140px;
+ }
+}
diff --git a/src/hood-portfolios.js b/src/hood-portfolios.js
index b3856d333..38a89bd45 100644
--- a/src/hood-portfolios.js
+++ b/src/hood-portfolios.js
@@ -54,6 +54,108 @@ const CLASS_LABEL = {
stablecoin: 'Stable',
};
+// ── Shareable permalinks ────────────────────────────────────────────────────
+
+/*
+ * A generated portfolio is shared by putting the manifest itself in the URL.
+ *
+ * The alternative was sharing the prompt, which is what `?q=` does, and a prompt
+ * does not reproduce a portfolio: the screen is a language model, so the same
+ * sentence returns a different basket tomorrow. A link that silently resolves to
+ * something else is worse than no link. The manifest IS the portfolio, so it
+ * travels whole and the recipient sees exactly what the sender saw.
+ *
+ * Deflate-compressed where the browser has CompressionStream (every current one),
+ * which takes a typical manifest from ~4KB to under 1KB of base64url and keeps
+ * the URL comfortably inside the limits proxies impose. Uncompressed is a valid
+ * payload too, so an older browser still reads links and only writes longer ones.
+ */
+
+function bytesToBase64Url(bytes) {
+ let binary = '';
+ for (const b of bytes) binary += String.fromCharCode(b);
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
+}
+
+function base64UrlToBytes(text) {
+ const padded = text.replace(/-/g, '+').replace(/_/g, '/');
+ const binary = atob(padded + '='.repeat((4 - (padded.length % 4)) % 4));
+ return Uint8Array.from(binary, (c) => c.charCodeAt(0));
+}
+
+async function encodeManifest(manifest) {
+ const raw = new TextEncoder().encode(JSON.stringify(manifest));
+ if (typeof CompressionStream !== 'function') return `0${bytesToBase64Url(raw)}`;
+ const stream = new Blob([raw]).stream().pipeThrough(new CompressionStream('deflate-raw'));
+ const packed = new Uint8Array(await new Response(stream).arrayBuffer());
+ return `1${bytesToBase64Url(packed)}`;
+}
+
+async function decodeManifest(text) {
+ const flag = text[0];
+ const bytes = base64UrlToBytes(text.slice(1));
+ if (flag === '0') return JSON.parse(new TextDecoder().decode(bytes));
+ if (flag !== '1' || typeof DecompressionStream !== 'function') {
+ throw new Error('this link needs a browser with decompression support');
+ }
+ const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream('deflate-raw'));
+ return JSON.parse(await new Response(stream).text());
+}
+
+/** Rebuild the on-screen result from a shared manifest, with the hash re-derived server-side. */
+async function openSharedManifest(encoded) {
+ setBusy(true);
+ showSkeleton();
+ el.status.textContent = 'Opening a shared portfolio...';
+ try {
+ const manifest = await decodeManifest(encoded);
+ const constituents = (manifest.constituents || []).map((c) => ({
+ address: c.address,
+ symbol: c.symbol,
+ assetClass: c.assetClass,
+ weightBps: c.weightBps,
+ rationale: c.rationale,
+ priceUsd: c.priceUsdAtSelection ?? null,
+ liquidityUsd: c.liquidityUsdAtSelection ?? null,
+ change24hPct: null,
+ }));
+ if (constituents.length < 2) throw new Error('that link does not contain a portfolio');
+
+ // The hash is never taken from the link. It is re-derived from the document
+ // by the same canonicalisation the registry commits, so a tampered link
+ // shows a different hash rather than a borrowed one.
+ const { manifestHash } = await getJson(`${API}/manifest`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ manifest }),
+ });
+
+ el.prompt.value = manifest.prompt || '';
+ updateCounter();
+ renderResult({
+ screen: {
+ name: manifest.name,
+ symbol: manifest.symbol,
+ thesis: manifest.thesis,
+ rebalanceDays: manifest.rebalance?.intervalDays ?? 30,
+ constituents,
+ },
+ manifest,
+ manifestHash,
+ provider: 'shared link',
+ model: null,
+ universeConsidered: manifest.universe?.consideredCount ?? constituents.length,
+ shared: true,
+ });
+ el.status.textContent = '';
+ } catch (err) {
+ showError(new Error(`That shared link could not be opened: ${err.message}`));
+ el.status.textContent = '';
+ } finally {
+ setBusy(false);
+ }
+}
+
// ── Network ─────────────────────────────────────────────────────────────────
async function getJson(url, init) {
@@ -220,6 +322,12 @@ function renderResult(result) {
</table>
</div>
+ <section class="hp-backtest" id="hp-backtest" aria-label="Backtest">
+ <h3>What this basket would have done</h3>
+ <div class="hp-sk-line" style="width:60%"></div>
+ <div class="hp-sk-line" style="width:40%;margin-bottom:0"></div>
+ </section>
+
<div class="hp-manifest">
<h3>Manifest</h3>
<div class="hp-hash">
@@ -241,11 +349,16 @@ function renderResult(result) {
Weights are binding; the prompt is provenance.
</p>
<div class="hp-actions">
+ <button type="button" class="hp-btn hp-btn-ghost" data-action="copy-link">Copy shareable link</button>
<button type="button" class="hp-btn hp-btn-ghost" data-action="refine">Refine this portfolio</button>
<a class="hp-btn hp-btn-ghost" href="/markets/robinhood/portfolios/universe">Inspect the universe</a>
</div>
</div>
</article>`;
+
+ // Every surface that renders a portfolio gets its backtest, rather than only
+ // the freshly generated one: a shared link showed an empty panel forever.
+ loadBacktest(result);
}
async function generate(prompt) {
@@ -266,10 +379,17 @@ async function generate(prompt) {
});
renderResult(result);
el.status.textContent = '';
- // Make the result shareable without a backend: the prompt reproduces it.
- const url = new URL(window.location.href);
- url.searchParams.set('q', prompt);
- window.history.replaceState(null, '', url);
+ // Share the manifest, not the prompt: the screen is a model, so the same
+ // sentence returns a different basket tomorrow.
+ try {
+ const url = new URL(window.location.href);
+ url.searchParams.delete('q');
+ url.searchParams.set('p', await encodeManifest(result.manifest));
+ window.history.replaceState(null, '', url);
+ } catch {
+ // A URL that got too long for the browser is not a reason to lose the
+ // result that is already on screen.
+ }
el.output.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
} catch (err) {
if (err.name === 'AbortError') return;
@@ -281,6 +401,118 @@ async function generate(prompt) {
}
}
+// ── Backtest ────────────────────────────────────────────────────────────────
+
+/**
+ * A two-line area chart, drawn as inline SVG.
+ *
+ * No chart library: this is two polylines and a fill, the page already ships no
+ * runtime dependencies, and an external script would be blocked by the CSP on
+ * embedded surfaces anyway. Both series are scaled to one shared axis so the gap
+ * between them is readable, which is the entire point of the chart.
+ */
+function sparkChart(rebalanced, held) {
+ const W = 720;
+ const H = 180;
+ const PAD = 4;
+ const all = [...rebalanced.map((p) => p.valueUsd), ...held.map((p) => p.valueUsd)];
+ const min = Math.min(...all);
+ const max = Math.max(...all);
+ const span = max - min || 1;
+ const x = (i, n) => PAD + (i / Math.max(1, n - 1)) * (W - PAD * 2);
+ const y = (v) => H - PAD - ((v - min) / span) * (H - PAD * 2);
+ const path = (pts) => pts.map((p, i) => `${i ? 'L' : 'M'}${x(i, pts.length).toFixed(1)},${y(p.valueUsd).toFixed(1)}`).join(' ');
+
+ const rPath = path(rebalanced);
+ const area = `${rPath} L${x(rebalanced.length - 1, rebalanced.length).toFixed(1)},${H - PAD} L${PAD},${H - PAD} Z`;
+
+ return `<svg class="hp-chart" viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" role="img"
+ aria-label="Value of the rebalanced basket against the same basket never rebalanced, over ${rebalanced.length} days">
+ <path class="hp-chart-area" d="${area}" />
+ <path class="hp-chart-held" d="${path(held)}" />
+ <path class="hp-chart-line" d="${rPath}" />
+ </svg>`;
+}
+
+function renderBacktest(data) {
+ const slot = document.getElementById('hp-backtest');
+ if (!slot) return;
+
+ if (!data || data.ok === false) {
+ const uncovered = (data?.uncovered || []).map((u) => u.symbol).filter(Boolean);
+ slot.innerHTML = `
+ <h3>What this basket would have done</h3>
+ <p class="hp-note" style="margin-top:0">
+ ${escapeHtml(data?.reason || 'No price history is available for this basket yet.')}
+ ${uncovered.length ? `Waiting on: ${escapeHtml(uncovered.join(', '))}.` : ''}
+ </p>`;
+ return;
+ }
+
+ const r = data.rebalanced;
+ const h = data.heldWithoutRebalancing;
+ const delta = data.rebalancingAddedPct;
+ const sign = (n) => `${n >= 0 ? '+' : ''}${n.toFixed(2)}%`;
+ const cls = (n) => (n > 0 ? 'hp-pos' : n < 0 ? 'hp-neg' : 'hp-muted');
+ const coveredPct = ((data.coveredWeightBps / data.totalWeightBps) * 100).toFixed(0);
+ const uncovered = data.uncovered || [];
+
+ slot.innerHTML = `
+ <h3>What this basket would have done</h3>
+ <div class="hp-bt-grid">
+ <div>
+ <span class="hp-bt-label">Rebalanced every ${escapeHtml(String(data.rebalanceDays))} days</span>
+ <span class="hp-bt-value ${cls(r.totalReturnPct)}">${escapeHtml(sign(r.totalReturnPct))}</span>
+ </div>
+ <div>
+ <span class="hp-bt-label">Never rebalanced</span>
+ <span class="hp-bt-value ${cls(h.totalReturnPct)}">${escapeHtml(sign(h.totalReturnPct))}</span>
+ </div>
+ <div>
+ <span class="hp-bt-label">Rebalancing added</span>
+ <span class="hp-bt-value ${cls(delta)}">${escapeHtml(`${delta >= 0 ? '+' : ''}${delta.toFixed(3)} pp`)}</span>
+ </div>
+ <div>
+ <span class="hp-bt-label">Worst drawdown</span>
+ <span class="hp-bt-value">${escapeHtml(`-${r.maxDrawdownPct.toFixed(2)}%`)}</span>
+ </div>
+ </div>
+
+ ${sparkChart(r.series, h.series)}
+
+ <p class="hp-chart-key">
+ <span class="hp-key-line"></span> rebalanced
+ <span class="hp-key-held"></span> never rebalanced
+ <span class="hp-muted">${escapeHtml(`${data.from} to ${data.to}, ${data.windowDays} days`)}</span>
+ </p>
+
+ <p class="hp-note" style="margin-top:.75rem">
+ Real prices only: ${escapeHtml(String(data.covered.length))} of
+ ${escapeHtml(String(data.covered.length + uncovered.length))} holdings had history, covering
+ ${escapeHtml(coveredPct)}% of the portfolio by weight, and the window is the overlap where all of
+ them have data.
+ ${uncovered.length ? `Not included: ${escapeHtml(uncovered.map((u) => u.symbol).join(', '))}, because ${escapeHtml(uncovered[0].reason)}.` : ''}
+ Trading costs are not modelled. Past prices are not a forecast.
+ </p>`;
+}
+
+async function loadBacktest(result) {
+ try {
+ const data = await getJson(`${API}/backtest`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ constituents: result.screen.constituents.map((c) => ({ address: c.address, weightBps: c.weightBps })),
+ rebalanceDays: result.screen.rebalanceDays,
+ days: 90,
+ }),
+ });
+ renderBacktest(data);
+ } catch (err) {
+ renderBacktest({ ok: false, reason: `The backtest could not be run: ${err.message}` });
+ }
+}
+
// ── Actions ─────────────────────────────────────────────────────────────────
async function copyHash(button) {
@@ -319,6 +551,23 @@ function downloadManifest() {
setTimeout(() => URL.revokeObjectURL(url), 0);
}
+async function copyShareLink(button) {
+ if (!currentResult) return;
+ const original = button.textContent;
+ try {
+ const url = new URL(window.location.href);
+ url.searchParams.delete('q');
+ url.searchParams.set('p', await encodeManifest(currentResult.manifest));
+ await navigator.clipboard.writeText(url.toString());
+ button.textContent = 'Link copied';
+ } catch {
+ button.textContent = 'Could not copy';
+ }
+ setTimeout(() => {
+ button.textContent = original;
+ }, 1600);
+}
+
function refine() {
if (!currentResult) return;
el.prompt.value = `${currentResult.manifest.prompt}, but `;
@@ -389,14 +638,21 @@ function init() {
const action = button.dataset.action;
if (action === 'copy-hash') copyHash(button);
else if (action === 'download') downloadManifest();
+ else if (action === 'copy-link') copyShareLink(button);
else if (action === 'refine') refine();
else if (action === 'retry') el.form.requestSubmit();
});
- // A shared link carries its prompt, so the page reproduces the portfolio.
- const shared = new URL(window.location.href).searchParams.get('q');
- if (shared) {
- el.prompt.value = shared.slice(0, MAX_PROMPT);
+ // `?p=` carries a whole manifest and reproduces the portfolio exactly. `?q=`
+ // is the older prompt-only form, kept working: it re-runs the screen, which
+ // may return something different, so the manifest link is what we now write.
+ const params = new URL(window.location.href).searchParams;
+ const packed = params.get('p');
+ const prompt = params.get('q');
+ if (packed) {
+ openSharedManifest(packed);
+ } else if (prompt) {
+ el.prompt.value = prompt.slice(0, MAX_PROMPT);
updateCounter();
generate(el.prompt.value.trim());
}
diff --git a/tests/hood-portfolios-backtest.test.js b/tests/hood-portfolios-backtest.test.js
new file mode 100644
index 000000000..63cd6e294
--- /dev/null
+++ b/tests/hood-portfolios-backtest.test.js
@@ -0,0 +1,160 @@
+// Unit tests for the backtest engine (api/_lib/hood-portfolios-backtest.js).
+//
+// The engine is pure, so every case here is an exact arithmetic assertion rather
+// than a tolerance on live data. The series are constructed to isolate one
+// behaviour each: what rebalancing does to a basket that oscillates, what it
+// does to one that trends, and what the walk does when a leg is missing a day.
+
+import { describe, it, expect } from 'vitest';
+import {
+ backtest,
+ commonDays,
+ maxDrawdownPct,
+ volatilityPct,
+ walk,
+} from '../api/_lib/hood-portfolios-backtest.js';
+
+const series = (prices, start = 1) =>
+ prices.map((priceUsd, i) => ({ day: `2026-01-${String(start + i).padStart(2, '0')}`, priceUsd }));
+
+describe('commonDays', () => {
+ it('intersects, so a leg missing a day removes that day for everyone', () => {
+ const out = commonDays({
+ a: series([1, 1, 1, 1]),
+ b: [
+ { day: '2026-01-01', priceUsd: 1 },
+ { day: '2026-01-03', priceUsd: 1 },
+ ],
+ });
+ expect(out).toEqual(['2026-01-01', '2026-01-03']);
+ });
+
+ it('returns nothing when the windows do not overlap at all', () => {
+ expect(
+ commonDays({
+ a: [{ day: '2026-01-01', priceUsd: 1 }],
+ b: [{ day: '2026-02-01', priceUsd: 1 }],
+ }),
+ ).toEqual([]);
+ });
+});
+
+describe('maxDrawdownPct', () => {
+ it('is zero for a series that only rises', () => {
+ expect(maxDrawdownPct([100, 110, 120])).toBe(0);
+ });
+
+ it('measures peak to trough, not start to end', () => {
+ // Peaks at 200, falls to 100: a 50% drawdown, even though it ends up.
+ expect(maxDrawdownPct([100, 200, 100, 150])).toBeCloseTo(50, 10);
+ });
+});
+
+describe('volatilityPct', () => {
+ it('is zero for a flat series', () => {
+ expect(volatilityPct([100, 100, 100, 100])).toBeCloseTo(0, 10);
+ });
+
+ it('declines to answer without enough observations', () => {
+ expect(volatilityPct([100])).toBeNull();
+ expect(volatilityPct([100, 101])).toBeNull();
+ });
+});
+
+describe('walk', () => {
+ const legs = [
+ { address: 'a', weightBps: 5000 },
+ { address: 'b', weightBps: 5000 },
+ ];
+
+ it('holds value flat when prices do not move', () => {
+ const out = walk({ legs, series: { a: series([1, 1, 1]), b: series([2, 2, 2]) }, rebalanceDays: 0 });
+ expect(out.values).toEqual([10_000, 10_000, 10_000]);
+ expect(out.rebalances).toBe(0);
+ });
+
+ it('tracks a 50/50 basket where one leg doubles', () => {
+ const out = walk({ legs, series: { a: series([1, 2]), b: series([1, 1]) }, rebalanceDays: 0 });
+ // $5k doubles to $10k, $5k stays: $15k.
+ expect(out.values[1]).toBeCloseTo(15_000, 6);
+ });
+
+ it('renormalises weights across the legs it was given', () => {
+ // Two legs at 2500bps each: still a 50/50 basket of what is present.
+ const out = walk({
+ legs: [
+ { address: 'a', weightBps: 2500 },
+ { address: 'b', weightBps: 2500 },
+ ],
+ series: { a: series([1, 2]), b: series([1, 1]) },
+ rebalanceDays: 0,
+ });
+ expect(out.values[1]).toBeCloseTo(15_000, 6);
+ });
+
+ it('counts rebalances on the published cadence', () => {
+ const out = walk({
+ legs,
+ series: { a: series([1, 1, 1, 1, 1]), b: series([1, 1, 1, 1, 1]) },
+ rebalanceDays: 2,
+ });
+ expect(out.rebalances).toBe(2);
+ });
+});
+
+describe('backtest', () => {
+ const legs = [
+ { address: 'a', weightBps: 5000 },
+ { address: 'b', weightBps: 5000 },
+ ];
+
+ it('shows rebalancing helping a basket that oscillates', () => {
+ // The textbook case: two anti-correlated legs that both end where they
+ // started. Buy-and-hold returns exactly zero; selling the winner to buy
+ // the loser each step harvests the swings.
+ const a = series([100, 200, 100, 200, 100]);
+ const b = series([100, 50, 100, 50, 100]);
+ const out = backtest({ legs, series: { a, b }, rebalanceDays: 1 });
+
+ expect(out.ok).toBe(true);
+ expect(out.heldWithoutRebalancing.totalReturnPct).toBeCloseTo(0, 6);
+ expect(out.rebalanced.totalReturnPct).toBeGreaterThan(0);
+ expect(out.rebalancingAddedPct).toBeGreaterThan(0);
+ });
+
+ it('shows rebalancing hurting a basket that trends', () => {
+ // The honest other half: when one leg keeps winning, repeatedly selling it
+ // to top up the loser costs money. A backtest that could not produce this
+ // result would not be measuring anything.
+ const a = series([100, 200, 400, 800, 1600]);
+ const b = series([100, 100, 100, 100, 100]);
+ const out = backtest({ legs, series: { a, b }, rebalanceDays: 1 });
+
+ expect(out.ok).toBe(true);
+ expect(out.rebalanced.totalReturnPct).toBeLessThan(out.heldWithoutRebalancing.totalReturnPct);
+ expect(out.rebalancingAddedPct).toBeLessThan(0);
+ });
+
+ it('reports the window it actually covered', () => {
+ const out = backtest({ legs, series: { a: series([1, 1, 1]), b: series([1, 1, 1]) }, rebalanceDays: 0 });
+ expect(out.from).toBe('2026-01-01');
+ expect(out.to).toBe('2026-01-03');
+ expect(out.windowDays).toBe(3);
+ expect(out.rebalanced.series).toHaveLength(3);
+ });
+
+ it('refuses rather than inventing a result when there is no overlap', () => {
+ const out = backtest({
+ legs,
+ series: { a: [{ day: '2026-01-01', priceUsd: 1 }], b: [{ day: '2026-02-01', priceUsd: 1 }] },
+ rebalanceDays: 0,
+ });
+ expect(out.ok).toBe(false);
+ expect(out.reason).toMatch(/overlapping history/);
+ });
+
+ it('states that it models no trading costs', () => {
+ const out = backtest({ legs, series: { a: series([1, 1]), b: series([1, 1]) }, rebalanceDays: 0 });
+ expect(out.costModel).toBe('none');
+ });
+});
diff --git a/tests/hood-portfolios-history.test.js b/tests/hood-portfolios-history.test.js
new file mode 100644
index 000000000..36dfdfe32
--- /dev/null
+++ b/tests/hood-portfolios-history.test.js
@@ -0,0 +1,68 @@
+// Unit tests for the daily-close reduction (api/_lib/hood-portfolios-history.js).
+//
+// Chainlink rounds arrive irregularly: several within an hour when a price is
+// moving, then nothing for two days. Everything downstream assumes one
+// observation per day, so this reduction is where that assumption is made, and
+// getting it wrong shifts an entire backtest by a day.
+
+import { describe, it, expect } from 'vitest';
+import { snapshotKey, toDailyCloses } from '../api/_lib/hood-portfolios-history.js';
+
+const at = (iso, priceUsd) => ({ t: Date.parse(iso), priceUsd });
+
+describe('toDailyCloses', () => {
+ it('keeps the last observation of each UTC day', () => {
+ const out = toDailyCloses([
+ at('2026-09-01T01:00:00Z', 100),
+ at('2026-09-01T23:59:00Z', 110),
+ at('2026-09-02T00:01:00Z', 120),
+ ]);
+ expect(out.map((p) => [p.day, p.priceUsd])).toEqual([
+ ['2026-09-01', 110],
+ ['2026-09-02', 120],
+ ]);
+ });
+
+ it('is order independent', () => {
+ const points = [
+ at('2026-09-02T10:00:00Z', 120),
+ at('2026-09-01T23:00:00Z', 110),
+ at('2026-09-01T02:00:00Z', 100),
+ ];
+ const forward = toDailyCloses(points);
+ const reversed = toDailyCloses([...points].reverse());
+ expect(forward).toEqual(reversed);
+ });
+
+ it('returns days in ascending order', () => {
+ const out = toDailyCloses([
+ at('2026-09-05T10:00:00Z', 1),
+ at('2026-09-01T10:00:00Z', 2),
+ at('2026-09-03T10:00:00Z', 3),
+ ]);
+ expect(out.map((p) => p.day)).toEqual(['2026-09-01', '2026-09-03', '2026-09-05']);
+ });
+
+ it('drops non-positive prices rather than charting them as zero', () => {
+ const out = toDailyCloses([at('2026-09-01T10:00:00Z', 0), at('2026-09-02T10:00:00Z', -5), at('2026-09-03T10:00:00Z', 7)]);
+ expect(out).toHaveLength(1);
+ expect(out[0].priceUsd).toBe(7);
+ });
+
+ it('leaves gaps as gaps, never filling a day it did not observe', () => {
+ const out = toDailyCloses([at('2026-09-01T10:00:00Z', 100), at('2026-09-05T10:00:00Z', 105)]);
+ expect(out.map((p) => p.day)).toEqual(['2026-09-01', '2026-09-05']);
+ });
+
+ it('handles an empty series', () => {
+ expect(toDailyCloses([])).toEqual([]);
+ });
+});
+
+describe('snapshotKey', () => {
+ it('is one key per UTC day, so a second run in a day overwrites', () => {
+ expect(snapshotKey(new Date('2026-09-08T00:00:01Z'))).toBe('hood_prices:2026-09-08');
+ expect(snapshotKey(new Date('2026-09-08T23:59:59Z'))).toBe('hood_prices:2026-09-08');
+ expect(snapshotKey(new Date('2026-09-09T00:00:00Z'))).toBe('hood_prices:2026-09-09');
+ });
+});
diff --git a/vercel.json b/vercel.json
index 49ee68582..d2bca0f1b 100644
--- a/vercel.json
+++ b/vercel.json
@@ -6068,6 +6068,10 @@
}
],
"crons": [
+ {
+ "path": "/api/cron/hood-portfolio-snapshot",
+ "schedule": "17 2 * * *"
+ },
{
"path": "/api/cron/economy-tick",
"schedule": "* * * * *"