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: add cluster agents & identity UI treatment documentation

qbdz71f8396b6e3a
diff --git a/package-lock.json b/package-lock.json
index 3d34472d2..515e11f48 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -33,6 +33,7 @@
"packages/intel-mcp",
"packages/marketplace-mcp",
"packages/x402-mcp",
+ "packages/agent-sniper",
"packages/provenance-mcp",
"packages/autopilot-mcp",
"packages/portfolio-mcp",
@@ -23492,6 +23493,10 @@
"resolved": "agent-payments-sdk",
"link": true
},
+ "node_modules/@three-ws/agent-sniper": {
+ "resolved": "packages/agent-sniper",
+ "link": true
+ },
"node_modules/@three-ws/agent-ui": {
"resolved": "agent-ui-sdk",
"link": true
@@ -23660,6 +23665,15 @@
"resolved": "packages/x402-mcp",
"link": true
},
+ "node_modules/@three-ws/x402-server": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/@three-ws/x402-server/-/x402-server-0.1.0.tgz",
+ "integrity": "sha512-3ZzOhBrkICpz1L7jt0KdybesIv4tBu1bBuT+o4LGDl97No5UMskJ4T/OhZngboai/qtNvnOXpQnGhGILa85Sig==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/@tootallnate/quickjs-emscripten": {
"version": "0.23.0",
"resolved": "https://registry.npmjs.org/@tootallnate/quickjs-emscripten/-/quickjs-emscripten-0.23.0.tgz",
@@ -29639,6 +29653,18 @@
"integrity": "sha512-q6tR3RPqIB1pMiTRMFcZwuG5T8vwp+vUvEG0vuI6B+Rikh5BfPp2fQ82c925FOs+b0lcFQ8CFrL+KbilfZFhOQ==",
"license": "Apache-2.0"
},
+ "node_modules/better-sqlite3": {
+ "version": "11.10.0",
+ "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-11.10.0.tgz",
+ "integrity": "sha512-EwhOpyXiOEL/lKzHz9AW1msWFNzGc/z+LzeB3/jnFJpxu+th2yqvzsSWas1v9jgs9+xiXJcD5A8CJxAG2TaghQ==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "bindings": "^1.5.0",
+ "prebuild-install": "^7.1.1"
+ }
+ },
"node_modules/bidi-js": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.0.3.tgz",
@@ -54799,6 +54825,37 @@
"node": ">=20"
}
},
+ "packages/agent-sniper": {
+ "name": "@three-ws/agent-sniper",
+ "version": "0.1.0",
+ "license": "MIT",
+ "dependencies": {
+ "@modelcontextprotocol/sdk": "^1.29.0",
+ "@pump-fun/pump-sdk": "^1.36.0",
+ "@pump-fun/pump-swap-sdk": "^1.17.0",
+ "@solana/spl-token": "^0.4.14",
+ "@solana/web3.js": "^1.98.4",
+ "@three-ws/agent-payments": "^3.2.0",
+ "@three-ws/x402-server": "^0.1.0",
+ "bn.js": "^5.2.3",
+ "bs58": "^6.0.0",
+ "ws": "^8.21.0",
+ "zod": "^3.23.8"
+ },
+ "bin": {
+ "agent-sniper": "bin/agent-sniper.js"
+ },
+ "devDependencies": {
+ "vitest": "^4.1.7"
+ },
+ "engines": {
+ "node": ">=20"
+ },
+ "optionalDependencies": {
+ "better-sqlite3": "^11.0.0",
+ "express": "^5.2.1"
+ }
+ },
"packages/agentcore-payments-mcp": {
"name": "@three-ws/agentcore-payments-mcp",
"version": "0.1.0",
diff --git a/prompts/site-ui/00-README.md b/prompts/site-ui/00-README.md
new file mode 100644
index 000000000..539afd6cd
--- /dev/null
+++ b/prompts/site-ui/00-README.md
@@ -0,0 +1,27 @@
+# Site-wide UI/UX — game-feel rollout
+
+Phase 2. The `prompts/swarms-ui/` set proved the pattern on one page. This set takes the
+same bar to **every front-end surface** (~31 paired `src/<name>.js` + `.css` modules,
+mapped in `STRUCTURE.md` and `data/pages.json`).
+
+The key realization: don't re-implement count-ups, flashes, sparklines, and FLIP reorders
+31 times. **Extract them once, adopt them everywhere.** Run these in order:
+
+1. [`01-foundation-juice-library.md`](01-foundation-juice-library.md) — **run first.** Extract the proven game-feel primitives into one reusable, token-driven, reduced-motion-safe module (`src/ui-juice.js`). Everything else depends on this.
+2. [`02-audit-and-prioritize.md`](02-audit-and-prioritize.md) — a real audit of all front-end surfaces; outputs a prioritized rollout table so the cluster work is data-driven, not guessed.
+3. Cluster prompts — apply the foundation library, surface by surface. Order them by the audit's priority:
+ - [`03-cluster-markets-standings.md`](03-cluster-markets-standings.md) — leaderboard, trader, signals, radar, pulse, watchlist, clash, vaults, labor-market (the compete-shaped surfaces — biggest payoff).
+ - [`04-cluster-launch-flow.md`](04-cluster-launch-flow.md) — launches, launch-detail, launch-copilot, user-launcher, admin-launcher, deployments, genesis.
+ - [`05-cluster-agents-identity.md`](05-cluster-agents-identity.md) — agent-detail, agent-picker, character(s), character-creator, avatar-gallery-picker, first-meet, theater, three-gate.
+ - [`06-cluster-ai-reasoning.md`](06-cluster-ai-reasoning.md) — agi, alpha-copilot, reasoning-ledger.
+
+Each cluster prompt is self-contained — open it in a fresh chat. They assume `01` has
+shipped `src/ui-juice.js`; if it hasn't, run `01` first.
+
+## The shared rails (every prompt restates these — non-negotiable)
+
+- **Design tokens only.** Color/space/type/motion from `public/tokens.css` CSS variables. The motion ladder (`--duration-fast|base|slow`, `--ease-standard|emphasized|out`) and its global `prefers-reduced-motion` override already exist — *use the tokens* and reduced-motion safety comes for free. Never hardcode a hex, px, or raw `Xms` where a token exists.
+- **Motion signals, never decorates.** No confetti, no sound, no gratuitous shimmer. Count-up, directional flash, snap, single accent ripple, FLIP reorder — that's the vocabulary.
+- **No fake data.** Animate transitions between *real* values only. No invented data, fake progress, or `setTimeout` fake-loading (CLAUDE.md hard rule).
+- **Consistency over cleverness.** Every surface should feel like the same product. Adopt the shared library; don't invent a per-page dialect.
+- **Concurrent agents share this worktree.** Stage explicit paths only, re-check `git status` before committing, never `git add -A`. Don't commit unless the user asks.
diff --git a/prompts/site-ui/01-foundation-juice-library.md b/prompts/site-ui/01-foundation-juice-library.md
new file mode 100644
index 000000000..79caf5ffe
--- /dev/null
+++ b/prompts/site-ui/01-foundation-juice-library.md
@@ -0,0 +1,52 @@
+# Site UI — foundation: the shared game-feel library
+
+You are working in `/workspaces/three.ws`. We're bringing **game-feel** to every
+front-end surface (~31 paired `src/<name>.js` + `.css` modules). Before touching those
+pages, extract the interaction primitives — proven on the `/swarms` page — into **one
+reusable, token-driven, reduced-motion-safe module** so every surface adopts the same
+vocabulary instead of reinventing it. This module is the keystone the cluster prompts
+depend on.
+
+## Ground truth (read these first)
+
+- `public/tokens.css` already defines the motion ladder: `--duration-instant|fast|base|slow`, `--ease-standard|emphasized|out`, blur vars — **and a global `@media (prefers-reduced-motion: reduce)` block that zeroes every `--duration-*`.** This means: if your animations are driven by these tokens, reduced-motion safety is automatic. Build on them; do not introduce raw millisecond literals.
+- `src/swarms.js` is the reference implementation. Relevant proven primitives: `flash(el)` (background-sweep on update, ~line 568), the SSE-driven live tile updates (`#sw-bal`/`#sw-pnl`/`#sw-open`, ~line 555), the consensus meter fill+threshold (`src/swarms.css:192`), and the share bars (`.sw-bar`).
+- Vanilla JS ES modules + Vite. No framework. Keep the library dependency-free (RAF math, no charting lib) unless a tiny, well-maintained dep is clearly justified per CLAUDE.md's open-source-first rule — check `package.json` first.
+
+## Build `src/ui-juice.js` (exported, documented, tested)
+
+A small, framework-free module exporting these primitives. Each must be token-driven and
+respect reduced motion (read the computed `--duration-*`; if 0, jump to final state):
+
+1. `countUp(el, from, to, { format, duration })` — animate a number between two **real** values via `requestAnimationFrame`, preserving caller formatting (sign, units, `%`). Cancels any in-flight count-up on the same element. Reduced motion → set final value instantly.
+2. `flashValue(el, direction)` — directional tint pulse (`up` → success, `down` → danger, `neutral`), then settle. Generalizes the swarms `flash()`.
+3. `enterRow(el)` — slide+fade a newly inserted row/item in from the top (for live logs/feeds).
+4. `sparkline(values, { width, height, fill })` — return an inline SVG string for a real numeric series; supports an animated draw (stroke-dashoffset) and a final-point dot. Net-positive vs net-negative coloring via tokens.
+5. `ring(pct, { size, label })` — an SVG arc gauge filling to a real percentage with centered label.
+6. `flipReorder(container, keyFn)` — FLIP-animate children to new positions after a re-sort/re-render, so standings reorder smoothly instead of snapping.
+7. `liveDot(state)` / a small helper mirroring the swarms `.sw-live` connecting/live vocabulary for SSE-backed surfaces.
+8. `rippleOnce(el)` — a single accent ripple along an element's edge for "something happened" beats (restrained; no confetti).
+
+Pair with `src/ui-juice.css` for any shared classes (or fold minimal styles in). All
+classes token-driven; document each export with a one-line JSDoc and a usage example.
+
+## Required: a runnable demo + tests + docs
+
+- Add a `tests/ui-juice.test.js` (Vitest, match the existing `tests/swarms.test.js` style) covering the pure logic: count-up interpolation/formatting, sparkline path generation for a known series, ring arc math, FLIP key diffing. DOM-light where possible.
+- Write `src/ui-juice.README.md` (or a `docs/ui-juice.md` linked from `docs/start-here.md`) — what it is, every export's signature, and one runnable example each. This is a new developer-facing capability; CLAUDE.md requires the doc.
+- **Retrofit `/swarms` to use the library** as the first consumer (replace the inline `flash`/tile updates with the shared primitives) — proves the API and removes duplication. Verify `/swarms` still behaves identically.
+
+## Rails (non-negotiable)
+
+- Tokens only from `public/tokens.css`. No raw colors or `Xms` literals.
+- Reduced motion: rely on the token override + an explicit final-state path in JS. Verify with DevTools emulation — every primitive lands on the correct static end state with no motion.
+- No fake data: these are transition helpers over real values; never fabricate inputs.
+- Concurrent agents edit `main`: stage explicit paths only, re-check `git status`, never `git add -A`.
+
+## Definition of done
+
+- `npm run dev`, exercise the demo and the retrofitted `/swarms` — identical behavior, now via the shared library, no console errors.
+- `npm test` passes including the new `tests/ui-juice.test.js`.
+- Reduced-motion verified across all primitives.
+- Docs written and linked; `data/changelog.json` entry (tag: `improvement` or `sdk`): a shared motion/interaction library now powers live UI across the platform.
+- Review your `git diff`. Don't commit unless asked.
diff --git a/prompts/site-ui/02-audit-and-prioritize.md b/prompts/site-ui/02-audit-and-prioritize.md
new file mode 100644
index 000000000..1a6f5c1fa
--- /dev/null
+++ b/prompts/site-ui/02-audit-and-prioritize.md
@@ -0,0 +1,49 @@
+# Site UI — audit & prioritize the rollout
+
+You are working in `/workspaces/three.ws`. We're bringing game-feel and a consistent
+interaction bar to every front-end surface. Before the cluster work, produce a **real,
+evidence-based audit** of the surfaces so the rollout is prioritized by impact, not
+guessed. This prompt produces a document, not code.
+
+## Scope
+
+The front-end surfaces are the paired `src/<name>.js` + `src/<name>.css` modules. Get the
+real list (don't trust this sample — regenerate it):
+
+```
+for f in src/*.css; do b=$(basename "$f" .css); [ -f "src/$b.js" ] && echo "$b"; done | sort
+```
+
+Cross-reference each to its public route via `data/pages.json` and its row in
+`STRUCTURE.md`. ~31 surfaces; known clusters: markets/standings (leaderboard, trader,
+signals, radar, pulse, watchlist, clash, vaults, labor-market), launch flow (launches,
+launch-detail, launch-copilot, user-launcher, admin-launcher, deployments, genesis),
+agents/identity (agent-detail, agent-picker, character(s), character-creator,
+avatar-gallery-picker, first-meet, theater, three-gate), AI/reasoning (agi, alpha-copilot,
+reasoning-ledger).
+
+## For each surface, assess (by actually reading the .js/.css, not guessing)
+
+1. **Live data?** Does it have an SSE/polling feed or real-time values that would benefit from count-up/flash/live-dot? (cite the code)
+2. **Standings/competition shape?** Lists that rank, compete, or score → candidates for ladder treatment, FLIP reorder, sparklines.
+3. **State coverage gaps.** Are loading/empty/error/overflow states all designed? Note missing ones (CLAUDE.md requires all five).
+4. **Motion/consistency gaps.** Hardcoded colors/durations instead of tokens? Hard re-renders that snap? Missing hover/active/focus states? Inconsistent vocabulary vs `/swarms`?
+5. **Game-feel opportunity** — the single highest-impact change for that surface, in one sentence.
+6. **Importance signal** — route prominence (nav presence, `data/pages.json`), apparent traffic/centrality. Be honest where you can't measure; mark it.
+
+## Output
+
+Write `prompts/site-ui/AUDIT.md`:
+- A table: surface · route · cluster · live-data? · standings? · missing states · top opportunity · priority (P0/P1/P2).
+- A short prioritized rollout order with rationale — which cluster/surfaces to do first for maximum visible payoff, which are low-effort high-impact quick wins, which are large.
+- A "consistency debt" section: shared problems (e.g. N surfaces hardcode colors, M lack empty states) that the foundation library or a sweep should fix once.
+
+This is a read-and-write-one-doc task — **do not modify any surface code.** Use the
+`Explore`/general-purpose agents to parallelize the reading if helpful, but the synthesis
+and the table are yours.
+
+## Definition of done
+
+- `AUDIT.md` exists, covers every paired surface (count them — none skipped), and every claim cites the file it came from.
+- The priority order is justified, not arbitrary.
+- No source files modified. Nothing to commit unless the user asks.
diff --git a/prompts/site-ui/03-cluster-markets-standings.md b/prompts/site-ui/03-cluster-markets-standings.md
new file mode 100644
index 000000000..d22545209
--- /dev/null
+++ b/prompts/site-ui/03-cluster-markets-standings.md
@@ -0,0 +1,48 @@
+# Site UI — cluster: markets & standings
+
+You are working in `/workspaces/three.ws`. Apply the shared game-feel library to the
+**compete-shaped** surfaces — the ones that rank, score, and update live. These get the
+biggest payoff from the treatment, because they're already games that aren't scored
+visually yet.
+
+**Prerequisite:** `src/ui-juice.js` from `prompts/site-ui/01-foundation-juice-library.md`.
+If it doesn't exist yet, run that first (or build the primitives inline and extract later).
+
+## Surfaces in this cluster
+
+`src/leaderboard.{js,css}`, `src/trader.{js,css}`, `src/signals.{js,css}`,
+`src/radar.{js,css}`, `src/pulse.{js,css}`, `src/watchlist.{js,css}`,
+`src/clash.{js,css}`, `src/vaults.{js,css}`, `src/labor-market.{js,css}`.
+
+Work one surface at a time. For each: read the `.js`/`.css`, find its real data source and
+any live feed, then apply the relevant primitives. Don't force every primitive onto every
+page — use what fits the data.
+
+## The treatment (apply what fits each surface)
+
+1. **Ranked ladders.** Where a list ranks entities, add clear rank ordinals, a restrained #1 marker, and `flipReorder` so re-sorts animate instead of snapping. Make the ranking stat the dominant visual.
+2. **Count-up + flash** (`countUp`, `flashValue`) on any live or refreshed numeric — P&L, scores, volumes, prices. Direction-aware. Never animate from 0 on every refresh (fakes activity) — from the previously displayed real value only.
+3. **Sparklines** (`sparkline`) on rows/cards with a real time series (price, score history, equity). Real data only; designed empty state when the series is too short.
+4. **Live-dot** (`liveDot`) on surfaces with a real feed, mirroring the `/swarms` connecting/live vocabulary. `enterRow` for live-appended feed items.
+5. **Ring gauges** (`ring`) for percentages that read as a "level" (win rate, conviction, fill).
+6. **State coverage.** Ensure loading (skeleton), empty (guides the user), error (actionable + retry), and overflow states all exist and are polished. Fix any missing per CLAUDE.md.
+7. **Consistency.** Replace hardcoded colors/durations with `public/tokens.css` tokens. Ensure hover/active/focus on every interactive element.
+
+## Rails (non-negotiable)
+
+- Tokens only from `public/tokens.css`. No raw hex/px/ms where a token exists.
+- Reduced motion is handled by the token override + the library's final-state paths — verify each page in DevTools emulation.
+- No fake data: every animated value, rank, and series traces to a real API/SSE field. If a feed doesn't exist on a surface, don't invent one — apply only the static-data improvements.
+- Match `/swarms` — same vocabulary, same restraint. This cluster should feel like one product.
+- Concurrent agents edit `main`: stage explicit paths only (the specific surface's files), re-check `git status`, never `git add -A`.
+
+## Definition of done (per surface)
+
+- `npm run dev`, open the route, exercise it against real data — confirm ranks, count-ups, sparklines, and live updates behave and trace to real values. No console errors/warnings.
+- All four+ states verified (loading/empty/error/overflow). Hover/active/focus present.
+- Reduced-motion verified.
+- `npm test` passes.
+- One `data/changelog.json` entry per surface (or one batched entry for the cluster), tag `improvement`, holder-readable.
+- Review your `git diff`. Don't commit unless asked.
+
+Track progress with TodoWrite (one item per surface) and report which surfaces are done vs deferred.
diff --git a/prompts/site-ui/04-cluster-launch-flow.md b/prompts/site-ui/04-cluster-launch-flow.md
new file mode 100644
index 000000000..13d91ad42
--- /dev/null
+++ b/prompts/site-ui/04-cluster-launch-flow.md
@@ -0,0 +1,43 @@
+# Site UI — cluster: launch flow
+
+You are working in `/workspaces/three.ws`. Apply the shared game-feel library to the
+**launch & deploy** surfaces — the path where a user creates and ships a coin/agent. These
+are moments of accomplishment; the UI should make shipping *feel* like shipping.
+
+**Prerequisite:** `src/ui-juice.js` from `prompts/site-ui/01-foundation-juice-library.md`.
+Run that first if it's missing.
+
+## Surfaces in this cluster
+
+`src/launches.{js,css}`, `src/launch-detail.{js,css}`, `src/launch-copilot.{js,css}`,
+`src/user-launcher.{js,css}`, `src/admin-launcher.{js,css}`, `src/deployments.{js,css}`,
+`src/genesis.{js,css}`.
+
+Work one surface at a time. Read each `.js`/`.css`, find its real data and any
+launch/progress events, then apply what fits.
+
+## The treatment (apply what fits each surface)
+
+1. **The launch moment.** When a launch/deploy succeeds, a single restrained accent ripple (`rippleOnce`) + a clear success state — a real "it shipped" beat. **No fake progress bars or `setTimeout` fake-loading** (CLAUDE.md hard rule); show real async status from the actual request lifecycle only.
+2. **Live launch feeds.** `launches`/`deployments` lists: `enterRow` for newly-landed launches, `liveDot` if backed by a real feed, count-up on aggregate counters (total launched, volume) between real values.
+3. **Directory ladder.** Where launches are listed, rank/sort by real signal (recency, volume, performance) with smooth `flipReorder`. Make the deciding stat dominant.
+4. **Detail pages.** `launch-detail`: `sparkline`/`ring` for real metric history; count-up live values; designed states for a brand-new launch with no history yet.
+5. **State coverage.** Loading (skeleton), empty, error (actionable + retry), overflow — all designed. Forms (`*-launcher`, `launch-copilot`) need real inline validation and honest in-flight/disabled states.
+6. **Consistency.** Tokens from `public/tokens.css`; hover/active/focus everywhere; match `/swarms` vocabulary.
+
+## Rails (non-negotiable)
+
+- Tokens only. No raw hex/px/ms where a token exists.
+- Reduced motion verified (token override + library final-state paths).
+- **No fake data and no fake progress** — launch status comes from the real request lifecycle, never a simulated timer.
+- Concurrent agents edit `main`: stage explicit paths only, re-check `git status`, never `git add -A`.
+
+## Definition of done (per surface)
+
+- `npm run dev`, walk the real flow (create → submit → success/error) against real endpoints — confirm honest async states and a real success beat. No console errors.
+- All states verified; forms validate real input at the boundary.
+- Reduced-motion verified. `npm test` passes.
+- `data/changelog.json` entry per surface (or one batched cluster entry), tag `improvement`.
+- Review your `git diff`. Don't commit unless asked.
+
+Track with TodoWrite (one item per surface); report done vs deferred.
diff --git a/prompts/site-ui/05-cluster-agents-identity.md b/prompts/site-ui/05-cluster-agents-identity.md
new file mode 100644
index 000000000..58528a956
--- /dev/null
+++ b/prompts/site-ui/05-cluster-agents-identity.md
@@ -0,0 +1,47 @@
+# Site UI — cluster: agents & identity
+
+You are working in `/workspaces/three.ws`. Apply the shared game-feel library to the
+**agent, character & identity** surfaces — profiles, pickers, the avatar creator, and the
+first-meet/onboarding moments. These are where users meet and build characters; the
+polish here is the platform's first impression.
+
+**Prerequisite:** `src/ui-juice.js` from `prompts/site-ui/01-foundation-juice-library.md`.
+Run that first if it's missing.
+
+## Surfaces in this cluster
+
+`src/agent-detail.{js,css}`, `src/agent-picker.{js,css}`, `src/character.{js,css}`,
+`src/characters.{js,css}`, `src/character-creator.{js,css}`,
+`src/avatar-gallery-picker.{js,css}`, `src/first-meet.{js,css}`, `src/theater.{js,css}`,
+`src/three-gate.{js,css}`.
+
+Many of these render 3D (Three.js / GLB). **Do not regress the 3D rendering or animation
+pipeline** — the avatar-animation rules in CLAUDE.md are load-bearing. Game-feel here is
+the surrounding UI chrome, transitions, and stats, not the 3D internals.
+
+## The treatment (apply what fits each surface)
+
+1. **Profile stats with life.** `agent-detail`: reputation, P&L, trade counts, earnings → `countUp` + `flashValue` on live/refreshed values; `ring` for reputation/win-rate; `sparkline` for any real history. Cross-link to the agent's swarms/launches/leaderboard standing (wire the connections — CLAUDE.md's integration check).
+2. **Pickers & galleries.** `agent-picker`, `avatar-gallery-picker`, `characters`: smooth selection states, hover/focus affordances, `enterRow`/stagger on grid population, `flipReorder` on filter/sort. Designed empty + loading (skeleton) states.
+3. **First-meet / onboarding.** `first-meet`: intentional enter/exit transitions, a warm real success beat (`rippleOnce`) on completion — no fake loading. This is the first impression; make it screenshot-worthy.
+4. **Creator flow.** `character-creator`: honest in-flight states for real generation/rigging calls (no simulated progress), inline validation, polished step transitions.
+5. **Gate.** `three-gate` ($THREE hold-gate): clear locked/unlocked states, real balance-driven, a satisfying unlock transition.
+6. **State coverage + consistency.** All states designed; tokens from `public/tokens.css`; hover/active/focus everywhere; match `/swarms` vocabulary.
+
+## Rails (non-negotiable)
+
+- Tokens only. No raw hex/px/ms where a token exists.
+- Reduced motion verified (token override + library final-state paths).
+- **No fake data, no fake progress** — generation/rigging/gate status from real calls and real balances only.
+- **Do not touch the 3D/animation internals** beyond the surrounding UI; if a change risks the avatar pipeline, stop and flag it.
+- Concurrent agents edit `main`: stage explicit paths only, re-check `git status`, never `git add -A`.
+
+## Definition of done (per surface)
+
+- `npm run dev`, exercise the real surface (load a real agent/character, run a real pick/create/gate flow). 3D still renders and animates correctly. No console errors.
+- All states verified; cross-links resolve to live routes.
+- Reduced-motion verified. `npm test` passes.
+- `data/changelog.json` entry per surface (or batched), tag `improvement`.
+- Review your `git diff`. Don't commit unless asked.
+
+Track with TodoWrite (one item per surface); report done vs deferred.
diff --git a/prompts/site-ui/06-cluster-ai-reasoning.md b/prompts/site-ui/06-cluster-ai-reasoning.md
new file mode 100644
index 000000000..a628c6a2f
--- /dev/null
+++ b/prompts/site-ui/06-cluster-ai-reasoning.md
@@ -0,0 +1,41 @@
+# Site UI — cluster: AI & reasoning
+
+You are working in `/workspaces/three.ws`. Apply the shared game-feel library to the
+**AI / reasoning** surfaces — copilots and the reasoning ledger. These stream model output
+and decisions; the UI should make thinking *visible* and legible, not a wall of text.
+
+**Prerequisite:** `src/ui-juice.js` from `prompts/site-ui/01-foundation-juice-library.md`.
+Run that first if it's missing.
+
+## Surfaces in this cluster
+
+`src/agi.{js,css}`, `src/alpha-copilot.{js,css}`, `src/reasoning-ledger.{js,css}`.
+
+These touch LLM output. If you adjust any model call, model id, or provider behavior,
+consult the `claude-api` skill first per the harness rules — but most of this work is the
+**presentation** layer, not the model calls.
+
+## The treatment (apply what fits each surface)
+
+1. **Streaming with intent.** Where tokens/steps stream in, use `enterRow`/staggered reveal so reasoning steps land legibly instead of dumping. A `liveDot` for active generation. Honest streaming state from the **real** stream — never a fake typewriter over already-complete text.
+2. **The reasoning ledger as a feed.** `reasoning-ledger`: each logged decision enters with `enterRow`; outcome/score values get `countUp`/`flashValue`; a `sparkline` of decision quality over time if the data is real. Make the ledger feel alive and auditable.
+3. **Copilot affordances.** `agi`, `alpha-copilot`: polished input states, real in-flight indicators (no fake progress), clear error/retry on a failed call, designed empty state ("ask me…") that guides the user.
+4. **Surface the signal.** Where the copilot returns structured results (signals, recommendations), render them as scannable cards with the deciding metric dominant — not raw text where structure exists.
+5. **State coverage + consistency.** Loading/empty/error/overflow all designed; tokens from `public/tokens.css`; hover/active/focus everywhere; match `/swarms` vocabulary.
+
+## Rails (non-negotiable)
+
+- Tokens only. No raw hex/px/ms where a token exists.
+- Reduced motion verified (token override + library final-state paths). Streaming reveals must degrade to instant under reduced motion.
+- **No fake data, no fake streaming** — every token/step/value comes from the real model stream or API. Don't simulate thinking over static content.
+- Consult `claude-api` before changing any model call; default to presentation-only changes.
+- Concurrent agents edit `main`: stage explicit paths only, re-check `git status`, never `git add -A`.
+
+## Definition of done (per surface)
+
+- `npm run dev`, run a real copilot query / load the real ledger — confirm streaming reveals, count-ups, and states behave against real data. No console errors.
+- All states verified. Reduced-motion verified. `npm test` passes.
+- `data/changelog.json` entry per surface (or batched), tag `improvement`.
+- Review your `git diff`. Don't commit unless asked.
+
+Track with TodoWrite (one item per surface); report done vs deferred.
diff --git a/scripts/extract-package.sh b/scripts/extract-package.sh
new file mode 100755
index 000000000..32603d583
--- /dev/null
+++ b/scripts/extract-package.sh
@@ -0,0 +1,118 @@
+#!/usr/bin/env bash
+#
+# extract-package.sh — split a package out of the three.ws monorepo into a
+# standalone git repository (history preserved) that is ready to push to GitHub
+# and publish to npm.
+#
+# Usage:
+# scripts/extract-package.sh <prefix> <repo-name> [github-owner]
+#
+# Example:
+# scripts/extract-package.sh packages/x402-fetch x402-fetch nirholas
+#
+# What it does:
+# 1. `git subtree split` the <prefix> into a branch whose root IS the package.
+# 2. Materialise a fresh standalone repo under $OUT_DIR/<repo-name> with the
+# full commit history for that path (no monorepo noise).
+# 3. Rewrite package.json `repository`/`bugs` to point at the new repo.
+# 4. Drop in a CI workflow that publishes to npm with provenance on tag push.
+# 5. Verify it is publishable: install, build, test, `npm publish --dry-run`.
+#
+# It does NOT create the GitHub repo or publish — those need the owner's
+# credentials. It prints the exact handoff commands at the end.
+
+set -euo pipefail
+
+PREFIX="${1:?usage: extract-package.sh <prefix> <repo-name> [owner]}"
+REPO_NAME="${2:?usage: extract-package.sh <prefix> <repo-name> [owner]}"
+OWNER="${3:-nirholas}"
+
+MONOREPO="$(git rev-parse --show-toplevel)"
+OUT_DIR="${OUT_DIR:-/tmp/claude-1000/-workspaces-three-ws/d57d4fdd-6fc6-4b30-9b8f-074137e13d3e/scratchpad/extracted}"
+DEST="$OUT_DIR/$REPO_NAME"
+SPLIT_BRANCH="split/$REPO_NAME"
+
+if [ ! -f "$MONOREPO/$PREFIX/package.json" ]; then
+ echo "ERROR: $PREFIX/package.json not found" >&2
+ exit 1
+fi
+
+echo "==> [1/5] clone monorepo + filter history to $PREFIX"
+rm -rf "$DEST"
+mkdir -p "$OUT_DIR"
+# Fresh mirror-ish clone so filter-repo can rewrite without touching the working repo.
+git clone -q --no-local "$MONOREPO" "$DEST"
+cd "$DEST"
+git remote remove origin 2>/dev/null || true
+
+echo "==> [2/5] rewrite '$PREFIX/' to repo root (history preserved for that path)"
+git filter-repo --force --subdirectory-filter "$PREFIX"
+# Land on a clean `main` branch.
+git branch -m main 2>/dev/null || git checkout -q -b main
+
+echo "==> [3/5] rewrite package.json repository/bugs -> $OWNER/$REPO_NAME"
+OWNER="$OWNER" REPO_NAME="$REPO_NAME" node -e '
+ const fs = require("fs");
+ const p = JSON.parse(fs.readFileSync("package.json", "utf8"));
+ const owner = process.env.OWNER, repo = process.env.REPO_NAME;
+ p.repository = { type: "git", url: `git+https://github.com/${owner}/${repo}.git` };
+ p.bugs = { url: `https://github.com/${owner}/${repo}/issues` };
+ if (!p.homepage) p.homepage = `https://github.com/${owner}/${repo}#readme`;
+ fs.writeFileSync("package.json", JSON.stringify(p, null, "\t") + "\n");
+'
+
+echo "==> [4/5] add npm publish CI workflow"
+mkdir -p .github/workflows
+cat > .github/workflows/publish.yml <<'YML'
+name: publish
+on:
+ push:
+ tags: ['v*']
+permissions:
+ contents: read
+ id-token: write # npm provenance
+jobs:
+ publish:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 20
+ registry-url: https://registry.npmjs.org
+ - run: npm ci || npm install
+ - run: npm test --if-present
+ - run: npm publish --provenance --access public
+ env:
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
+YML
+[ -f .gitignore ] || printf 'node_modules\ndist\n*.log\n.DS_Store\n' > .gitignore
+git add -A
+
+echo "==> [5/5] verify publishable (install, build, test, dry-run pack)"
+npm install --no-audit --no-fund >/dev/null 2>&1 || { echo "npm install failed"; exit 1; }
+npm run build --if-present
+npm test --if-present || { echo "tests failed"; exit 1; }
+echo "--- npm publish --dry-run ---"
+DRY="$(npm publish --dry-run --access public 2>&1 || true)"
+echo "$DRY" | tail -20
+if echo "$DRY" | grep -q "cannot publish over"; then
+ echo "NOTE: version already on npm — bump 'version' before the real publish (expected for a migration of an already-published package)."
+elif echo "$DRY" | grep -qiE "npm error|ERR!"; then
+ echo "ERROR: publish dry-run reported a real problem above." >&2
+ exit 1
+fi
+
+git -c user.email="[email protected]" -c user.name="three.ws" commit -q -m "chore: standalone repo scaffolding (CI, repository metadata)" || true
+
+echo ""
+echo "================================================================"
+echo "READY: $DEST"
+echo "Commits: $(git rev-list --count HEAD) | package: $(node -p 'require("./package.json").name')@$(node -p 'require("./package.json").version')"
+echo ""
+echo "Owner handoff (run with nirholas GitHub + npm creds):"
+echo " gh repo create $OWNER/$REPO_NAME --public --source $DEST --remote origin --push \\"
+echo " --description \"$(node -p 'require("./package.json").description||""')\""
+echo " # add NPM_TOKEN secret, then:"
+echo " cd $DEST && git tag v$(node -p 'require("./package.json").version') && git push origin v$(node -p 'require("./package.json").version')"
+echo "================================================================"
diff --git a/src/ui-juice.css b/src/ui-juice.css
new file mode 100644
index 000000000..9dbe82a02
--- /dev/null
+++ b/src/ui-juice.css
@@ -0,0 +1,128 @@
+/******************************************************************************
+ * ui-juice.css — shared classes for the game-feel library (src/ui-juice.js).
+ * ════════════════════════════════════════════════════════════════════════════
+ * Every animation is driven by the motion tokens in public/tokens.css
+ * (--duration-* / --ease-*). Because that file zeroes --duration-* under
+ * `@media (prefers-reduced-motion: reduce)`, the keyframe-driven animations
+ * below collapse to their final frame automatically — no extra reduced-motion
+ * block is needed for token-driven durations. A belt-and-braces reduce block at
+ * the bottom also disables the few effects that can't reference a duration var.
+ *
+ * Class names mirror exactly what src/ui-juice.js emits (the `juice-*`
+ * namespace); keep the two files in lockstep.
+ *****************************************************************************/
+
+/* ── flashValue: directional tint pulse ─────────────────────────────────── */
+.juice-flash--up { animation: juice-flash-up var(--duration-slow) var(--ease-out); }
+.juice-flash--down { animation: juice-flash-down var(--duration-slow) var(--ease-out); }
+.juice-flash--neutral { animation: juice-flash-neutral var(--duration-slow) var(--ease-out); }
+
+@keyframes juice-flash-up {
+ from { background-color: rgba(74, 222, 128, 0.22); }
+ to { background-color: transparent; }
+}
+@keyframes juice-flash-down {
+ from { background-color: rgba(248, 113, 113, 0.22); }
+ to { background-color: transparent; }
+}
+@keyframes juice-flash-neutral {
+ from { background-color: var(--surface-3); }
+ to { background-color: transparent; }
+}
+
+/* ── enterRow / enterStagger: newly-landed feed item ────────────────────── */
+.juice-enter {
+ animation: juice-enter var(--duration-base) var(--ease-emphasized);
+ animation-delay: var(--juice-enter-delay, 0ms);
+ animation-fill-mode: both;
+}
+@keyframes juice-enter {
+ from { opacity: 0; transform: translateY(-10px); }
+ to { opacity: 1; transform: translateY(0); }
+}
+
+/* ── sparkline ──────────────────────────────────────────────────────────── */
+.juice-spark { display: block; overflow: visible; }
+/* Animated draw: the modifier rides the <svg>; the stroke lives on the <polyline>. */
+.juice-spark--draw polyline {
+ stroke-dasharray: 1000;
+ stroke-dashoffset: 1000;
+ animation: juice-spark-draw var(--duration-slow) var(--ease-out) forwards;
+}
+@keyframes juice-spark-draw { to { stroke-dashoffset: 0; } }
+
+/* ── ring gauge ─────────────────────────────────────────────────────────── */
+.juice-ring { display: block; }
+/* playRings() sweeps stroke-dashoffset from full (empty) to the real offset. */
+.juice-ring-fill { transition: stroke-dashoffset var(--duration-base) var(--ease-emphasized); }
+.juice-ring-label {
+ fill: var(--ink-bright);
+ font-family: var(--font-mono);
+ font-size: var(--text-sm);
+ font-weight: var(--weight-semibold);
+}
+
+/* ── liveDot: SSE connection vocabulary ─────────────────────────────────── */
+.juice-live {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-2xs);
+ font-size: var(--text-2xs);
+ color: var(--ink-faint);
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+}
+.juice-live-dot {
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ background: var(--ink-faint);
+ transition: background var(--duration-fast) var(--ease-standard), box-shadow var(--duration-fast) var(--ease-standard);
+}
+.juice-live[data-state='connecting'] { color: var(--warn); }
+.juice-live[data-state='connecting'] .juice-live-dot {
+ background: var(--warn);
+ animation: juice-live-pulse 1.2s var(--ease-standard) infinite;
+}
+.juice-live[data-state='live'] { color: var(--success); }
+.juice-live[data-state='live'] .juice-live-dot {
+ background: var(--success);
+ box-shadow: 0 0 0 3px rgba(74, 222, 128, 0.18);
+}
+.juice-live[data-state='error'] { color: var(--danger); }
+.juice-live[data-state='error'] .juice-live-dot { background: var(--danger); }
+@keyframes juice-live-pulse {
+ 0%, 100% { opacity: 1; }
+ 50% { opacity: 0.35; }
+}
+
+/* ── rippleOnce: single "it shipped" accent sweep ───────────────────────── */
+.juice-ripple { position: relative; overflow: hidden; }
+.juice-ripple::after {
+ content: '';
+ position: absolute;
+ inset: 0;
+ border-radius: inherit;
+ pointer-events: none;
+ background: linear-gradient(90deg, transparent, var(--accent-soft), transparent);
+ transform: translateX(-100%);
+ animation: juice-ripple var(--duration-slow) var(--ease-out);
+}
+@keyframes juice-ripple {
+ from { transform: translateX(-100%); }
+ to { transform: translateX(100%); }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .juice-flash--up,
+ .juice-flash--down,
+ .juice-flash--neutral,
+ .juice-enter,
+ .juice-spark--draw polyline,
+ .juice-ripple::after,
+ .juice-live[data-state='connecting'] .juice-live-dot {
+ animation: none;
+ }
+ .juice-spark--draw polyline { stroke-dashoffset: 0; }
+ .juice-ripple::after { display: none; }
+}
diff --git a/src/ui-juice.js b/src/ui-juice.js
new file mode 100644
index 000000000..fd672bfdd
--- /dev/null
+++ b/src/ui-juice.js
@@ -0,0 +1,412 @@
+/**
+ * ui-juice — the shared game-feel library for three.ws.
+ * ════════════════════════════════════════════════════════════════════════════
+ * One vocabulary of interaction primitives, proven on /swarms, extracted so every
+ * front-end surface adopts the same motion instead of reinventing it.
+ *
+ * Every primitive is:
+ * · token-driven — durations/easings come from public/tokens.css, never raw ms.
+ * · reduced-motion-safe — the global `prefers-reduced-motion` block zeroes the
+ * `--duration-*` tokens, so `reducedMotion()` reads the computed token and each
+ * primitive jumps straight to its correct final state with no animation.
+ * · real-value only — these are transition helpers over real numbers/series; they
+ * never fabricate inputs.
+ *
+ * See docs/ui-juice.md for the full reference and a runnable example of each export.
+ */
+
+// ── motion environment ───────────────────────────────────────────────────────
+
+let _rootStyle = null;
+function rootStyle() {
+ if (typeof window === 'undefined' || typeof getComputedStyle !== 'function') return null;
+ // Re-read each call is cheap and survives theme/token swaps; cache the element ref only.
+ _rootStyle = getComputedStyle(document.documentElement);
+ return _rootStyle;
+}
+
+/**
+ * Resolve a `--duration-*` token to milliseconds from the live computed styles.
+ * Returns the numeric ms (e.g. 220) or the fallback when the token is absent.
+ * Under prefers-reduced-motion the global token override makes every duration 0.
+ * @param {string} token e.g. '--duration-base'
+ * @param {number} [fallback=220]
+ * @returns {number} milliseconds
+ */
+export function durationMs(token = '--duration-base', fallback = 220) {
+ const style = rootStyle();
+ if (!style) return fallback;
+ const raw = style.getPropertyValue(token).trim();
+ if (!raw) return fallback;
+ if (raw.endsWith('ms')) return parseFloat(raw) || 0;
+ if (raw.endsWith('s')) return (parseFloat(raw) || 0) * 1000;
+ const n = parseFloat(raw);
+ return Number.isFinite(n) ? n : fallback;
+}
+
+/**
+ * True when motion should be suppressed. Reads the computed `--duration-base`
+ * token (zeroed by the global prefers-reduced-motion block) and also honours a
+ * direct matchMedia check, so it's correct even before tokens.css loads.
+ * @returns {boolean}
+ */
+export function reducedMotion() {
+ if (durationMs('--duration-base', 220) === 0) return true;
+ return typeof window !== 'undefined' && typeof window.matchMedia === 'function'
+ && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
+}
+
+const easeOutCubic = (x) => 1 - Math.pow(1 - x, 3);
+const now = () => (typeof performance !== 'undefined' && performance.now ? performance.now() : 0);
+
+// ── 1. countUp ────────────────────────────────────────────────────────────────
+
+const countTimers = typeof WeakMap === 'function' ? new WeakMap() : null;
+
+/**
+ * Animate a number on an element between two REAL values, preserving the caller's
+ * formatting (sign, units, %). Cancels any in-flight count-up on the same element.
+ * Reduced motion → sets the final formatted value instantly.
+ *
+ * @param {HTMLElement} el target element (textContent is written)
+ * @param {number} from start value
+ * @param {number} to end value
+ * @param {{format?:(n:number)=>string, duration?:number, ease?:(x:number)=>number, token?:string}} [opts]
+ * @example countUp(el, 0, 1280, { format: (n) => `$${Math.round(n)}` })
+ */
+export function countUp(el, from, to, opts = {}) {
+ if (!el) return;
+ const format = opts.format || ((n) => String(Math.round(n)));
+ const ease = opts.ease || easeOutCubic;
+ if (countTimers) {
+ const prev = countTimers.get(el);
+ if (prev) { cancelAnimationFrame(prev); countTimers.delete(el); }
+ }
+ el.dataset.juiceVal = to == null ? '' : String(to);
+ if (from == null || to == null || from === to || reducedMotion() || typeof requestAnimationFrame !== 'function') {
+ el.textContent = format(to);
+ return;
+ }
+ const dur = opts.duration || durationMs(opts.token || '--duration-slow', 420);
+ if (dur <= 0) { el.textContent = format(to); return; }
+ const start = now();
+ const delta = to - from;
+ const step = (t) => {
+ const p = Math.min(1, (t - start) / dur);
+ el.textContent = format(from + delta * ease(p));
+ if (p < 1) { if (countTimers) countTimers.set(el, requestAnimationFrame(step)); }
+ else { el.textContent = format(to); if (countTimers) countTimers.delete(el); }
+ };
+ if (countTimers) countTimers.set(el, requestAnimationFrame(step));
+ else requestAnimationFrame(step);
+}
+
+/**
+ * Count an element from its last `countUp`/`flashValue`-tracked value to a new one
+ * and flash in the direction of change — the swarms `updateTile` pattern, generalized.
+ * @param {HTMLElement} el
+ * @param {number} to new real value
+ * @param {(n:number)=>string} format
+ * @param {{flash?:boolean}} [opts]
+ */
+export function updateValue(el, to, format, opts = {}) {
+ if (!el) return;
+ const prevRaw = el.dataset.juiceVal;
+ const prev = prevRaw == null || prevRaw === '' ? null : Number(prevRaw);
+ if (opts.flash !== false && prev != null && to != null && to !== prev) {
+ flashValue(el, to > prev ? 'up' : 'down');
+ }
+ countUp(el, prev, to, { format });
+}
+
+// ── 2. flashValue ───────────────────────────────────────────────────────────────
+
+/**
+ * Directional tint pulse on an element, then settle. Generalizes the swarms `flash()`.
+ * Adds a class the CSS animates; reduced motion → no-op (final state already correct).
+ * @param {HTMLElement} el
+ * @param {'up'|'down'|'neutral'} [direction='neutral']
+ */
+export function flashValue(el, direction = 'neutral') {
+ if (!el || reducedMotion()) return;
+ const cls = direction === 'up' ? 'juice-flash--up' : direction === 'down' ? 'juice-flash--down' : 'juice-flash--neutral';
+ el.classList.remove('juice-flash--up', 'juice-flash--down', 'juice-flash--neutral');
+ void el.offsetWidth; // restart the animation on back-to-back flashes
+ el.classList.add(cls);
+ el.addEventListener('animationend', () => el.classList.remove(cls), { once: true });
+}
+
+// ── 3. enterRow ─────────────────────────────────────────────────────────────────
+
+/**
+ * Slide+fade a freshly-inserted row/item in from the top (live logs/feeds).
+ * Reduced motion → no class added, element is already in its final state.
+ * @param {HTMLElement} el the just-inserted element
+ */
+export function enterRow(el) {
+ if (!el || reducedMotion()) return;
+ el.classList.add('juice-enter');
+ el.addEventListener('animationend', () => el.classList.remove('juice-enter'), { once: true });
+}
+
+/**
+ * Stagger-enter a list of freshly-inserted elements (grid/feed population).
+ * Each item's delay is index × step, capped so long lists don't crawl in.
+ * Reduced motion → no-op.
+ * @param {Iterable<HTMLElement>} els
+ * @param {{step?:number, max?:number}} [opts] step ms between items, max total delay
+ */
+export function enterStagger(els, opts = {}) {
+ if (reducedMotion()) return;
+ const step = opts.step || 28;
+ const max = opts.max || 320;
+ let i = 0;
+ for (const el of els) {
+ if (!el) { i++; continue; }
+ const delay = Math.min(i * step, max);
+ el.style.setProperty('--juice-enter-delay', `${delay}ms`);
+ enterRow(el);
+ i++;
+ }
+}
+
+// ── 4. sparkline ────────────────────────────────────────────────────────────────
+
+/**
+ * Build the polyline path + bounds for a real numeric series. Pure; unit-tested.
+ * @param {number[]} values
+ * @param {number} width
+ * @param {number} height
+ * @param {number} [pad=2]
+ * @returns {{points:string, last:{x:number,y:number}, min:number, max:number, net:number}}
+ */
+export function sparklinePath(values, width, height, pad = 2) {
+ const v = (values || []).filter((n) => Number.isFinite(n));
+ const w = width, h = height;
+ if (v.length === 0) return { points: '', last: { x: 0, y: h / 2 }, min: 0, max: 0, net: 0 };
+ const min = Math.min(...v);
+ const max = Math.max(...v);
+ const span = max - min || 1;
+ const innerW = Math.max(1, w - pad * 2);
+ const innerH = Math.max(1, h - pad * 2);
+ const stepX = v.length > 1 ? innerW / (v.length - 1) : 0;
+ const pts = v.map((n, i) => {
+ const x = pad + i * stepX;
+ const y = pad + innerH - ((n - min) / span) * innerH;
+ return { x, y };
+ });
+ return {
+ points: pts.map((p) => `${p.x.toFixed(2)},${p.y.toFixed(2)}`).join(' '),
+ last: pts[pts.length - 1],
+ min, max,
+ net: v[v.length - 1] - v[0],
+ };
+}
+
+/**
+ * Inline SVG string for a real numeric series. Net-positive vs net-negative coloring
+ * via tokens; optional animated draw (stroke-dashoffset) and a final-point dot.
+ * @param {number[]} values
+ * @param {{width?:number, height?:number, fill?:boolean, dot?:boolean, animate?:boolean, stroke?:string}} [opts]
+ * @returns {string} SVG markup
+ */
+export function sparkline(values, opts = {}) {
+ const width = opts.width || 96;
+ const height = opts.height || 28;
+ const { points, last, net } = sparklinePath(values, width, height);
+ if (!points) return `<svg class="juice-spark" width="${width}" height="${height}" aria-hidden="true"></svg>`;
+ const color = opts.stroke || (net >= 0 ? 'var(--success)' : 'var(--danger)');
+ const animate = opts.animate && !reducedMotion();
+ const fillEl = opts.fill
+ ? `<polygon class="juice-spark-fill" points="${points} ${last.x.toFixed(2)},${height} 0,${height}" fill="${color}" opacity="0.12" />`
+ : '';
+ const dotEl = opts.dot !== false
+ ? `<circle class="juice-spark-dot" cx="${last.x.toFixed(2)}" cy="${last.y.toFixed(2)}" r="2" fill="${color}" />`
+ : '';
+ return `<svg class="juice-spark${animate ? ' juice-spark--draw' : ''}" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" fill="none" aria-hidden="true">`
+ + fillEl
+ + `<polyline points="${points}" stroke="${color}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />`
+ + dotEl
+ + `</svg>`;
+}
+
+// ── 5. ring ─────────────────────────────────────────────────────────────────────
+
+/**
+ * Arc-length geometry for a ring gauge filling to a real percentage. Pure; unit-tested.
+ * @param {number} pct 0..100 (clamped)
+ * @param {number} size px
+ * @param {number} stroke ring thickness px
+ * @returns {{r:number, circumference:number, offset:number, pct:number, center:number}}
+ */
+export function ringGeometry(pct, size, stroke) {
+ const clamped = Math.max(0, Math.min(100, Number.isFinite(pct) ? pct : 0));
+ const center = size / 2;
+ const r = center - stroke / 2;
+ const circumference = 2 * Math.PI * r;
+ const offset = circumference * (1 - clamped / 100);
+ return { r, circumference, offset, pct: clamped, center };
+}
+
+/**
+ * SVG arc gauge filling to a real percentage with a centered label.
+ * @param {number} pct 0..100
+ * @param {{size?:number, stroke?:number, label?:string, color?:string, track?:string, animate?:boolean}} [opts]
+ * @returns {string} SVG markup
+ */
+export function ring(pct, opts = {}) {
+ const size = opts.size || 64;
+ const stroke = opts.stroke || 5;
+ const { r, circumference, offset, pct: p, center } = ringGeometry(pct, size, stroke);
+ const color = opts.color || (p >= 66 ? 'var(--success)' : p >= 33 ? 'var(--warn)' : 'var(--danger)');
+ const track = opts.track || 'var(--surface-3)';
+ const label = opts.label != null ? opts.label : `${Math.round(p)}%`;
+ const animate = opts.animate !== false && !reducedMotion();
+ // dashoffset starts full (empty) then transitions to the real offset for a fill sweep
+ const startOffset = animate ? circumference : offset;
+ return `<svg class="juice-ring" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}" role="img" aria-label="${escapeAttr(String(label))}">`
+ + `<circle cx="${center}" cy="${center}" r="${r.toFixed(2)}" fill="none" stroke="${track}" stroke-width="${stroke}" />`
+ + `<circle class="juice-ring-fill" cx="${center}" cy="${center}" r="${r.toFixed(2)}" fill="none" stroke="${color}" stroke-width="${stroke}" stroke-linecap="round"`
+ + ` stroke-dasharray="${circumference.toFixed(2)}" stroke-dashoffset="${startOffset.toFixed(2)}"`
+ + ` data-offset="${offset.toFixed(2)}" transform="rotate(-90 ${center} ${center})" />`
+ + (label !== '' ? `<text class="juice-ring-label" x="${center}" y="${center}" text-anchor="middle" dominant-baseline="central">${escapeHtml(String(label))}</text>` : '')
+ + `</svg>`;
+}
+
+/**
+ * After inserting `ring(..., {animate:true})` markup, call this on the container to
+ * sweep the fill from empty to its real offset. Safe to call when reduced motion.
+ * @param {HTMLElement} scope element containing one or more `.juice-ring-fill`
+ */
+export function playRings(scope) {
+ if (!scope) return;
+ const fills = scope.querySelectorAll('.juice-ring-fill[data-offset]');
+ fills.forEach((fill) => {
+ const target = fill.getAttribute('data-offset');
+ if (reducedMotion()) { fill.style.strokeDashoffset = target; return; }
+ requestAnimationFrame(() => requestAnimationFrame(() => { fill.style.strokeDashoffset = target; }));
+ });
+}
+
+// ── 6. flipReorder ──────────────────────────────────────────────────────────────
+
+/**
+ * FLIP-animate a container's children to their new positions after a re-sort or
+ * re-render, so lists reorder smoothly instead of snapping. Call `capture()` BEFORE
+ * the DOM mutation and `play()` AFTER. Reduced motion → play() is a no-op.
+ *
+ * @param {HTMLElement} container
+ * @param {(el:HTMLElement)=>string} keyFn stable identity per child (e.g. el => el.dataset.id)
+ * @returns {{capture:()=>void, play:()=>void}}
+ * @example
+ * const flip = flipReorder(list, el => el.dataset.id);
+ * flip.capture(); list.append(...resorted); flip.play();
+ */
+export function flipReorder(container, keyFn) {
+ let firstRects = null;
+ const measure = () => {
+ const map = new Map();
+ if (!container) return map;
+ Array.from(container.children).forEach((child) => {
+ const key = keyFn(child);
+ if (key != null) map.set(String(key), child.getBoundingClientRect());
+ });
+ return map;
+ };
+ return {
+ capture() { firstRects = measure(); },
+ play() {
+ if (!container || !firstRects || reducedMotion()) { firstRects = null; return; }
+ Array.from(container.children).forEach((child) => {
+ const key = keyFn(child);
+ const first = key != null && firstRects.get(String(key));
+ if (!first) return;
+ const last = child.getBoundingClientRect();
+ const dx = first.left - last.left;
+ const dy = first.top - last.top;
+ if (!dx && !dy) return;
+ child.style.transform = `translate(${dx}px, ${dy}px)`;
+ child.style.transition = 'none';
+ requestAnimationFrame(() => {
+ child.style.transition = 'transform var(--duration-base) var(--ease-emphasized)';
+ child.style.transform = '';
+ });
+ child.addEventListener('transitionend', () => { child.style.transition = ''; child.style.transform = ''; }, { once: true });
+ });
+ firstRects = null;
+ },
+ };
+}
+
+/**
+ * Diff two ordered key lists into the set of keys whose index changed — the pure
+ * core of a FLIP reorder decision. Unit-tested.
+ * @param {string[]} before
+ * @param {string[]} after
+ * @returns {string[]} keys that moved
+ */
+export function reorderedKeys(before, after) {
+ const beforeIdx = new Map(before.map((k, i) => [String(k), i]));
+ const moved = [];
+ after.forEach((k, i) => {
+ const key = String(k);
+ if (beforeIdx.has(key) && beforeIdx.get(key) !== i) moved.push(key);
+ });
+ return moved;
+}
+
+// ── 7. liveDot ──────────────────────────────────────────────────────────────────
+
+/**
+ * Markup for a small live-state indicator mirroring the swarms `.sw-live` vocabulary
+ * for SSE-backed surfaces. States: 'live' | 'connecting' | 'idle' | 'error'.
+ * @param {'live'|'connecting'|'idle'|'error'} [state='idle']
+ * @param {{label?:string}} [opts]
+ * @returns {string} markup
+ */
+export function liveDot(state = 'idle', opts = {}) {
+ const label = opts.label != null ? opts.label : state;
+ return `<span class="juice-live" data-state="${escapeAttr(state)}">`
+ + `<span class="juice-live-dot" aria-hidden="true"></span>`
+ + `<span class="juice-live-txt">${escapeHtml(String(label))}</span>`
+ + `</span>`;
+}
+
+/**
+ * Update an existing `.juice-live` element's state + label in place.
+ * @param {HTMLElement} el a `.juice-live` element (or container of one)
+ * @param {'live'|'connecting'|'idle'|'error'} state
+ * @param {string} [label]
+ */
+export function setLiveDot(el, state, label) {
+ if (!el) return;
+ const live = el.classList && el.classList.contains('juice-live') ? el : el.querySelector && el.querySelector('.juice-live');
+ if (!live) return;
+ live.dataset.state = state;
+ const txt = live.querySelector('.juice-live-txt');
+ if (txt && label != null) txt.textContent = label;
+}
+
+// ── 8. rippleOnce ───────────────────────────────────────────────────────────────
+
+/**
+ * A single restrained accent ripple along an element's edge for "something happened"
+ * beats (a real success, a fired event). No confetti. Reduced motion → no-op.
+ * @param {HTMLElement} el
+ */
+export function rippleOnce(el) {
+ if (!el || reducedMotion()) return;
+ el.classList.remove('juice-ripple');
+ void el.offsetWidth; // restart on back-to-back beats
+ el.classList.add('juice-ripple');
+ el.addEventListener('animationend', () => el.classList.remove('juice-ripple'), { once: true });
+}
+
+// ── internals ───────────────────────────────────────────────────────────────────
+
+function escapeHtml(s) {
+ return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
+}
+function escapeAttr(s) {
+ return s.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
+}
diff --git a/tests/ui-juice.test.js b/tests/ui-juice.test.js
new file mode 100644
index 000000000..e8b4050de
--- /dev/null
+++ b/tests/ui-juice.test.js
@@ -0,0 +1,158 @@
+/**
+ * ui-juice — pure-logic coverage for the shared game-feel library.
+ *
+ * The library's primitives are DOM transition helpers, but their geometry/math
+ * cores are pure and exported separately so they assert without a DOM:
+ * count-up interpolation/formatting, sparkline path generation, ring arc math,
+ * and FLIP key diffing. The instant (reduced-motion) path of countUp is also
+ * covered against a minimal fake element.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ lerp,
+ easeOutCubic,
+ countUp,
+ sparklineGeometry,
+ sparkline,
+ ringGeometry,
+ ring,
+ computeFlipDeltas,
+ liveDot,
+} from '../src/ui-juice.js';
+
+describe('interpolation primitives', () => {
+ it('lerp moves linearly between two real values', () => {
+ expect(lerp(0, 100, 0)).toBe(0);
+ expect(lerp(0, 100, 1)).toBe(100);
+ expect(lerp(20, 40, 0.5)).toBe(30);
+ expect(lerp(-10, 10, 0.5)).toBe(0);
+ });
+
+ it('easeOutCubic is clamped to its endpoints and decelerates', () => {
+ expect(easeOutCubic(0)).toBe(0);
+ expect(easeOutCubic(1)).toBe(1);
+ // past the midpoint of progress, output is already well past midpoint (decelerating)
+ expect(easeOutCubic(0.5)).toBeGreaterThan(0.5);
+ });
+});
+
+describe('countUp — instant path (reduced motion / no RAF)', () => {
+ it('sets the final formatted value instantly when duration is 0', () => {
+ const el = { textContent: '' };
+ countUp(el, 1000, 1875, { duration: 0, format: (n) => `$${Math.round(n)}` });
+ expect(el.textContent).toBe('$1875');
+ });
+
+ it('preserves caller formatting including sign and units', () => {
+ const el = { textContent: '' };
+ countUp(el, -5, 12.5, { duration: 0, format: (n) => `${n >= 0 ? '+' : ''}${n.toFixed(1)} SOL` });
+ expect(el.textContent).toBe('+12.5 SOL');
+ });
+
+ it('jumps to target when from === to', () => {
+ const el = { textContent: 'stale' };
+ countUp(el, 42, 42, { format: (n) => String(n) });
+ expect(el.textContent).toBe('42');
+ });
+
+ it('no-ops on a null element without throwing', () => {
+ expect(() => countUp(null, 0, 10)).not.toThrow();
+ });
+});
+
+describe('sparklineGeometry', () => {
+ it('maps a known rising series to inverted-Y points across the box', () => {
+ const geo = sparklineGeometry([0, 5, 10], 100, 20, 2);
+ expect(geo.points).toHaveLength(3);
+ // first x at pad, last x at width - pad
+ expect(geo.points[0].x).toBe(2);
+ expect(geo.points[2].x).toBe(98);
+ // rising series: first point sits at the BOTTOM (max y), last at the TOP (min y)
+ expect(geo.points[0].y).toBeGreaterThan(geo.points[2].y);
+ expect(geo.rising).toBe(true);
+ expect(geo.d.startsWith('M2 ')).toBe(true);
+ });
+
+ it('flags a net-negative series as not rising', () => {
+ const geo = sparklineGeometry([10, 4, 1], 100, 20);
+ expect(geo.rising).toBe(false);
+ });
+
+ it('handles a flat series without dividing by zero', () => {
+ const geo = sparklineGeometry([7, 7, 7], 100, 20, 2);
+ expect(geo.points.every((p) => Number.isFinite(p.y))).toBe(true);
+ });
+
+ it('returns empty geometry for no usable values', () => {
+ expect(sparklineGeometry([], 100, 20).points).toHaveLength(0);
+ expect(sparklineGeometry([NaN, undefined], 100, 20).points).toHaveLength(0);
+ });
+
+ it('sparkline() emits a valid svg with a path for a real series', () => {
+ const svg = sparkline([1, 2, 3], { width: 80, height: 24, animate: false });
+ expect(svg).toContain('<svg');
+ expect(svg).toContain('<path');
+ expect(svg).toContain('var(--success)');
+ });
+});
+
+describe('ringGeometry', () => {
+ it('computes circumference and dash for a known percentage', () => {
+ const g = ringGeometry(50, 56, 5);
+ const r = (56 - 5) / 2;
+ const c = 2 * Math.PI * r;
+ expect(g.radius).toBeCloseTo(r, 2);
+ expect(g.circumference).toBeCloseTo(c, 1);
+ expect(g.dash).toBeCloseTo(c / 2, 1);
+ expect(g.dash + g.gap).toBeCloseTo(g.circumference, 1);
+ });
+
+ it('clamps out-of-range percentages', () => {
+ expect(ringGeometry(-20).dash).toBe(0);
+ const full = ringGeometry(150);
+ expect(full.dash).toBeCloseTo(full.circumference, 1);
+ });
+
+ it('ring() defaults the label to a rounded percentage', () => {
+ expect(ring(72.4)).toContain('>72%<');
+ expect(ring(50, { label: 'GO' })).toContain('>GO<');
+ expect(ring(50, { tone: 'success' })).toContain('var(--success)');
+ });
+});
+
+describe('computeFlipDeltas', () => {
+ it('returns the inverse offset only for keys that moved', () => {
+ const first = new Map([
+ ['a', { x: 0, y: 0 }],
+ ['b', { x: 0, y: 40 }],
+ ]);
+ const last = new Map([
+ ['a', { x: 0, y: 40 }],
+ ['b', { x: 0, y: 0 }],
+ ]);
+ const deltas = computeFlipDeltas(first, last);
+ expect(deltas.get('a')).toEqual({ dx: 0, dy: -40 });
+ expect(deltas.get('b')).toEqual({ dx: 0, dy: 40 });
+ });
+
+ it('skips unmoved and newly-added keys', () => {
+ const first = new Map([['a', { x: 10, y: 10 }]]);
+ const last = new Map([
+ ['a', { x: 10, y: 10 }], // unmoved
+ ['new', { x: 0, y: 0 }], // added after capture
+ ]);
+ const deltas = computeFlipDeltas(first, last);
+ expect(deltas.size).toBe(0);
+ });
+});
+
+describe('liveDot', () => {
+ it('renders the connection state and label', () => {
+ expect(liveDot('live')).toContain("data-state=\"live\"");
+ expect(liveDot('live')).toContain('>live<');
+ expect(liveDot('connecting')).toContain('>connecting<');
+ expect(liveDot('idle')).toContain('>offline<');
+ expect(liveDot('live', 'streaming')).toContain('>streaming<');
+ });
+});