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.

refactor: update CSS for table layout and improve text wrapping

nirholas05216baae312
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ca71abf57..393039bfc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,8 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **The Story So Far** (`/timeline`) — three.ws's history as an explorable 3D scene: every launch, partnership, listing, and milestone laid out along a path you can orbit in 360° or walk end to end, with a synced scrubber and source links.
- **three.ws is an OpenAI Select Partner** (`/openai`) — three.ws is an OpenAI Select Partner in the OpenAI Partner Network. Connect the free three.ws 3D Studio MCP server to ChatGPT and turn a prompt into an interactive, riggable, AR-ready 3D model inline in the conversation.
- **three.ws Named an OpenAI Select Partner** (`/blog/three-ws-openai-select-partner`) — three.ws has been named an OpenAI Select Partner within the OpenAI Partner Network. What we ship on OpenAI surfaces today: a free 3D Studio MCP connector for ChatGPT, custom GPT Actions, the open Spatial MCP response shape, and one-tap AR.
+- **The KOL Tracker is now reachable, and its numbers are real** — The KOL Tracker page shipped listed in the sitemap but with no route behind it, so three.ws/tracker returned a 404 for everyone who followed the link, and the API behind it was answering with three placeholder rows left over from a test fixture. Both are fixed. The page is served, and it now ranks real Solana traders from the live kolscan board: realized profit, win rate and trade count for the 24h, 7d and 30d windows, enriched with our own on-chain FIFO profit calculation wherever we have the trades for a wallet. Every row states where its number came from, and when a source is unreachable the board shows an honest empty state instead of inventing traders. A new test blocks the whole class of mistake: any page advertised in the site index that has no route, or that never gets built, now fails the suite before it can reach production. (`/tracker`) `[fix, feature]`
+- **The trading fleet never sells 100% of a winner again** — New rule across every autonomous trading strategy: once a position has earned back what it cost, we never sell all of it. Any exit taken in profit now sells just enough to recover the original stake (or banks the gain down to a floor if the stake is already home) and keeps the rest, which then rides indefinitely. The logic is simple: after the cost is recovered the leftover position is free, so it is worth nothing at worst and has no ceiling at best. Selling that last slice to lock in a few thousandths of a SOL gives up every large outcome for a rounding error, and large outcomes are the entire reason to hold. Concretely: a position that ran to 1.4x and then hit its trailing stop used to be dumped completely for about +0.003 SOL; it now sells 71% to return the stake and keeps 29% riding at zero cost. Losses are unchanged and still exit completely, because nothing is free until the stake is back, and the hard stop-loss still overrides everything while real money is at risk. Held positions are booked as closed for accounting the moment the profit is banked, so they never occupy a slot that would stop a strategy from taking its next trade. Each strategy's held bags and their current value are now shown on the experiments board, tracked separately from realized profit since nothing counts as profit until it is sold. This also repairs the take-initials ladder, which could never actually fire: the exit settings lived on the strategy but were missing from the query the position loop reads, so every position silently fell back to selling everything no matter how it was configured. (`/sniper/experiments`) `[feature, fix]`
- **three.ws is an OpenAI Select Partner** — three.ws has been named an OpenAI Select Partner within the OpenAI Partner Network. A new page at /openai lays out everything the platform already ships on OpenAI surfaces: the free, keyless 3D Studio MCP connector for ChatGPT with nine tools (text to 3D, avatars, auto-rigging, conversational refinement, and a living agent body), the custom GPT Actions surface for plans without connectors, one-tap AR on iOS and Android, and Spatial MCP, the open CC0 shape for returning a live 3D scene as a tool result. The partner directory at /partners was also rewritten to list only the programs three.ws is actually enrolled in today, with NVIDIA correctly described as Inception membership. (`/openai`) `[feature, docs]`
- **Trading arms now earn their freedom from their own track record** — The autonomous trading fleet used to give every strategy the same leash: the same limits on how far its settings could move, the same short list of settings it could change, and the same information in front of it before each decision. A strategy that had been making money for weeks was kept in exactly the same box as one that had never had a winning day. Now each arm is graded on its own real, on-chain results and placed in one of four tiers. A profitable arm gets a wider range to work in, moves faster, unlocks settings a losing arm can't touch (which launches it hunts, how confident it needs to be before buying, and the take-initials exit that banks your stake at 2x and lets the rest ride), takes a bigger share of the fleet's fixed daily budget, and is shown far more evidence before it decides: how often launches actually succeed, which signals genuinely predict a winner, its own trading history, and how well its own past calls turned out. A bleeding arm is held tighter instead. Grading is on realized profit rather than win rate, so an arm that wins only a third of its trades but makes real money is rewarded, while one that wins most of its trades and still loses money is not. Every tier is re-earned continuously, so an arm that stops paying loses the extra rope automatically. None of it can touch the safety limits: the trade firewall, the daily loss cap, position limits, and a hard stop-loss apply at every tier, no matter how well an arm is doing. Each arm's tier and the evidence behind it are visible on the experiments board. (`/sniper/experiments`) `[feature, improvement]`
diff --git a/STRUCTURE.md b/STRUCTURE.md
index dab1e62be..82ddf11ef 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -118,6 +118,7 @@ bottom.
| Economy master audit ledger + breach monitor | ledger [api/_lib/economy-ledger.js](api/_lib/economy-ledger.js) ([schema](api/_lib/migrations/20260702010000_economy_master_ledger.sql)), reconcile cron [api/cron/economy-reconcile.js](api/cron/economy-reconcile.js), export [scripts/economy-ledger-export.mjs](scripts/economy-ledger-export.mjs) | In-repo | Tamper-evident (SHA-256 hash-chained) accounting book of every SOL movement from the master, with running balance + USD-at-transfer-time. The reconcile cron checks it every 30 min for tamper, unrecorded on-chain outbound (breach/key-compromise), and on-chain integrity; findings land in `payment_reconciliation`. Accounting CSV/JSON export. See [docs/economy-master.md](docs/economy-master.md#audit-accounting--breach-monitoring) |
| Earned autonomy (sniper fleet) | tier engine [api/_lib/sniper-autonomy.js](api/_lib/sniper-autonomy.js), tier-scaled optimizer [api/_lib/sniper-optimizer.js](api/_lib/sniper-optimizer.js) + cron [api/cron/sniper-optimize.js](api/cron/sniper-optimize.js), tier-weighted portfolio layer [scripts/sniper-evolve.mjs](scripts/sniper-evolve.mjs) + cron [api/cron/sniper-evolve.js](api/cron/sniper-evolve.js), judge knowledge pack [workers/agent-sniper/judge-knowledge.js](workers/agent-sniper/judge-knowledge.js) → [workers/agent-sniper/llm-judge.js](workers/agent-sniper/llm-judge.js), board [api/sniper/experiments.js](api/sniper/experiments.js) + [src/sniper-experiments.js](src/sniper-experiments.js) `→ /sniper/experiments` | Live | A trading arm's own realized record decides how much rope it gets, recomputed every optimizer run: `probation → standard → trusted → autonomous`. The tier scales how far and how fast the optimizer may move a knob, which fields it may touch at all (trusted unlocks the entry universe, the LLM confidence bar, and the take-initials ladder), how much of the fixed fleet budget the evolution loop concentrates on the arm, and how much real evidence the LLM judge is handed before it rules (base rate, learned signal weights, the arm's own record, the realized win-rate table, the model's own calibration). Decided on realized net P&L and average edge, never win rate, so a 36%-hit-rate arm that actually makes money earns room while a 60%-hit-rate arm that loses money does not. Symmetric: an arm that stops paying loses its tier on the next pass. No tier can reach a safety rail (firewall, Mayhem exclusion, price impact, concurrency, loss cap, fleet ceiling) and a bounded stop-loss survives every tier. Tests: [tests/sniper-autonomy.test.js](tests/sniper-autonomy.test.js), [tests/sniper-optimizer.test.js](tests/sniper-optimizer.test.js), [tests/sniper-judge-knowledge.test.js](tests/sniper-judge-knowledge.test.js). See [docs/sniper-autonomy.md](docs/sniper-autonomy.md) |
| Autonomous trading experiment | policy [scripts/trading-experiment-setup.mjs](scripts/trading-experiment-setup.mjs), laddered exit [workers/agent-sniper/exit-logic.js](workers/agent-sniper/exit-logic.js) (`decideLadderedExit`), no-Mayhem gate [workers/agent-sniper/mayhem-gate.js](workers/agent-sniper/mayhem-gate.js), journal [workers/agent-sniper/journal.js](workers/agent-sniper/journal.js) → [api/sniper/journal.js](api/sniper/journal.js) | In-repo | One agent, ~10 SOL, newer pump.fun launches ($10k–$100k mcap, no Mayhem). Take-initials-at-2× laddered exit keeps a moon bag (never a 100% exit up), hard stop-loss underneath. Every decision journaled with its reasoning. UI-funded, simulate-first. See [docs/trading-experiment.md](docs/trading-experiment.md) |
+| Never sell 100% of a winner (moon-bag policy) | rule [workers/agent-sniper/exit-logic.js](workers/agent-sniper/exit-logic.js) (`moonbagExitFraction`, `moonbagAlways`), retained-bag booking [workers/agent-sniper/executor.js](workers/agent-sniper/executor.js), position fields [api/_lib/migrations/20260725100000_sniper_moonbag_always.sql](api/_lib/migrations/20260725100000_sniper_moonbag_always.sql), board [api/sniper/experiments.js](api/sniper/experiments.js) + [src/sniper-experiments.js](src/sniper-experiments.js) `→ /sniper/experiments` | Live | Fleet-wide owner rule: a terminal exit that is IN PROFIT sells down to the moon-bag floor (default 15%) instead of to zero, and the retained tokens ride indefinitely. Once the cost basis is back the remainder is free, so a bag that goes to zero costs nothing and a bag that runs is the whole upside; selling the last slice for a rounding error gives that up. Applies with or without the proactive 2x ladder. A loss exit with the stake still at risk is still a FULL exit and the hard stop-loss is never overridden. The position still books `closed`, so realized P&L and the `max_concurrent_positions` slot are unaffected and a held bag can never stop an arm trading; only the tokens stay behind (`moonbag_base_amount`). Per-strategy opt-out `moonbag_always = false`. Tests: [tests/sniper-laddered-exit.test.js](tests/sniper-laddered-exit.test.js), [tests/trading-experiment-e2e.test.js](tests/trading-experiment-e2e.test.js). See [docs/trading-experiment.md](docs/trading-experiment.md) |
| Sniper Experiments (rules vs LLM A/B fleet) | [pages/sniper-experiments.html](pages/sniper-experiments.html) + [src/sniper-experiments.js](src/sniper-experiments.js) `→ /sniper/experiments`, aggregate [api/sniper/experiments.js](api/sniper/experiments.js), LLM judge [workers/agent-sniper/llm-judge.js](workers/agent-sniper/llm-judge.js), fleet seeding [scripts/seed-sniper-experiments.mjs](scripts/seed-sniper-experiments.mjs) | Live | The sniper fleet runs labeled rule-set variants side by side (strict shields, oracle-gated, and `decision_mode=llm` arms judged per-launch by Grok / Claude / OpenRouter auto with no shields), all behind the same safety rails. The page is the live scoreboard of which entry conditions actually make money; real on-chain fills only. |
| Trading Copilot (conversational) | client [src/agent-copilot.js](src/agent-copilot.js), hub tab [src/agent-wallet-hub/tabs/copilot.js](src/agent-wallet-hub/tabs/copilot.js), server [api/agents/copilot.js](api/agents/copilot.js) `→ POST /api/agents/:id/copilot` (SSE) | In-repo | Owner-only chat over an agent's Solana wallet: text/voice in, markdown replies, live **data cards** (portfolio, firewall, quote, smart-money, intel) and **confirm-before-execute** trade/limits cards. Read-only tools run server-side; state-changing intents return as proposals the browser re-quotes and runs through the existing spend guards + firewall + custody audit. Slash commands, copy/regenerate, localStorage persistence. See [docs/trading-copilot.md](docs/trading-copilot.md) |
| Real-funds risk acknowledgment | gate [public/risk-ack.js](public/risk-ack.js) `→ /legal/risk`, app wrapper [src/shared/risk-ack.js](src/shared/risk-ack.js), record endpoint [api/legal/risk-ack.js](api/legal/risk-ack.js), disclosure [public/legal/risk.html](public/legal/risk.html) | In-repo | Versioned, once-per-browser acceptance dialog every money-committing surface awaits before executing (trade, snipe, withdraw, swap, launch, x402, onramp — devnet exempt). Acceptances persist in `audit_log` (`risk-ack-accept`). See [docs/risk-acknowledgment.md](docs/risk-acknowledgment.md) |
diff --git a/data/changelog.json b/data/changelog.json
index d70af954d..02bf50acd 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,26 @@
{
"$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-07-25",
+ "title": "The KOL Tracker is now reachable, and its numbers are real",
+ "summary": "The KOL Tracker page shipped listed in the sitemap but with no route behind it, so three.ws/tracker returned a 404 for everyone who followed the link, and the API behind it was answering with three placeholder rows left over from a test fixture. Both are fixed. The page is served, and it now ranks real Solana traders from the live kolscan board: realized profit, win rate and trade count for the 24h, 7d and 30d windows, enriched with our own on-chain FIFO profit calculation wherever we have the trades for a wallet. Every row states where its number came from, and when a source is unreachable the board shows an honest empty state instead of inventing traders. A new test blocks the whole class of mistake: any page advertised in the site index that has no route, or that never gets built, now fails the suite before it can reach production.",
+ "tags": [
+ "fix",
+ "feature"
+ ],
+ "link": "/tracker"
+ },
+ {
+ "date": "2026-07-25",
+ "title": "The trading fleet never sells 100% of a winner again",
+ "summary": "New rule across every autonomous trading strategy: once a position has earned back what it cost, we never sell all of it. Any exit taken in profit now sells just enough to recover the original stake (or banks the gain down to a floor if the stake is already home) and keeps the rest, which then rides indefinitely. The logic is simple: after the cost is recovered the leftover position is free, so it is worth nothing at worst and has no ceiling at best. Selling that last slice to lock in a few thousandths of a SOL gives up every large outcome for a rounding error, and large outcomes are the entire reason to hold. Concretely: a position that ran to 1.4x and then hit its trailing stop used to be dumped completely for about +0.003 SOL; it now sells 71% to return the stake and keeps 29% riding at zero cost. Losses are unchanged and still exit completely, because nothing is free until the stake is back, and the hard stop-loss still overrides everything while real money is at risk. Held positions are booked as closed for accounting the moment the profit is banked, so they never occupy a slot that would stop a strategy from taking its next trade. Each strategy's held bags and their current value are now shown on the experiments board, tracked separately from realized profit since nothing counts as profit until it is sold. This also repairs the take-initials ladder, which could never actually fire: the exit settings lived on the strategy but were missing from the query the position loop reads, so every position silently fell back to selling everything no matter how it was configured.",
+ "tags": [
+ "feature",
+ "fix"
+ ],
+ "link": "/sniper/experiments"
+ },
{
"date": "2026-07-25",
"title": "Trading arms now earn their freedom from their own track record",
diff --git a/public/changelog.json b/public/changelog.json
index 15b294e17..e3dad8b3a 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-25T08:25:10.042Z",
+ "generated_at": "2026-07-25T08:47:56.177Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -46,6 +46,28 @@
"launch"
]
},
+ {
+ "date": "2026-07-25",
+ "type": "update",
+ "title": "The KOL Tracker is now reachable, and its numbers are real",
+ "summary": "The KOL Tracker page shipped listed in the sitemap but with no route behind it, so three.ws/tracker returned a 404 for everyone who followed the link, and the API behind it was answering with three placeholder rows left over from a test fixture. Both are fixed. The page is served, and it now ranks real Solana traders from the live kolscan board: realized profit, win rate and trade count for the 24h, 7d and 30d windows, enriched with our own on-chain FIFO profit calculation wherever we have the trades for a wallet. Every row states where its number came from, and when a source is unreachable the board shows an honest empty state instead of inventing traders. A new test blocks the whole class of mistake: any page advertised in the site index that has no route, or that never gets built, now fails the suite before it can reach production.",
+ "link": "/tracker",
+ "tags": [
+ "fix",
+ "feature"
+ ]
+ },
+ {
+ "date": "2026-07-25",
+ "type": "update",
+ "title": "The trading fleet never sells 100% of a winner again",
+ "summary": "New rule across every autonomous trading strategy: once a position has earned back what it cost, we never sell all of it. Any exit taken in profit now sells just enough to recover the original stake (or banks the gain down to a floor if the stake is already home) and keeps the rest, which then rides indefinitely. The logic is simple: after the cost is recovered the leftover position is free, so it is worth nothing at worst and has no ceiling at best. Selling that last slice to lock in a few thousandths of a SOL gives up every large outcome for a rounding error, and large outcomes are the entire reason to hold. Concretely: a position that ran to 1.4x and then hit its trailing stop used to be dumped completely for about +0.003 SOL; it now sells 71% to return the stake and keeps 29% riding at zero cost. Losses are unchanged and still exit completely, because nothing is free until the stake is back, and the hard stop-loss still overrides everything while real money is at risk. Held positions are booked as closed for accounting the moment the profit is banked, so they never occupy a slot that would stop a strategy from taking its next trade. Each strategy's held bags and their current value are now shown on the experiments board, tracked separately from realized profit since nothing counts as profit until it is sold. This also repairs the take-initials ladder, which could never actually fire: the exit settings lived on the strategy but were missing from the query the position loop reads, so every position silently fell back to selling everything no matter how it was configured.",
+ "link": "/sniper/experiments",
+ "tags": [
+ "feature",
+ "fix"
+ ]
+ },
{
"date": "2026-07-25",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 2a5b7266d..30408d348 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -38,6 +38,22 @@
<category>launch</category>
<description>three.ws has been named an OpenAI Select Partner within the OpenAI Partner Network. What we ship on OpenAI surfaces today: a free 3D Studio MCP connector for ChatGPT, custom GPT Actions, the open Spatial MCP response shape, and one-tap AR.</description>
</item>
+ <item>
+ <title>The KOL Tracker is now reachable, and its numbers are real</title>
+ <link>https://three.ws/tracker</link>
+ <guid isPermaLink="false">2026-07-25:The KOL Tracker is now reachable, and its numbers are real</guid>
+ <pubDate>Sat, 25 Jul 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>The KOL Tracker page shipped listed in the sitemap but with no route behind it, so three.ws/tracker returned a 404 for everyone who followed the link, and the API behind it was answering with three placeholder rows left over from a test fixture. Both are fixed. The page is served, and it now ranks real Solana traders from the live kolscan board: realized profit, win rate and trade count for the 24h, 7d and 30d windows, enriched with our own on-chain FIFO profit calculation wherever we have the trades for a wallet. Every row states where its number came from, and when a source is unreachable the board shows an honest empty state instead of inventing traders. A new test blocks the whole class of mistake: any page advertised in the site index that has no route, or that never gets built, now fails the suite before it can reach production.</description>
+ </item>
+ <item>
+ <title>The trading fleet never sells 100% of a winner again</title>
+ <link>https://three.ws/sniper/experiments</link>
+ <guid isPermaLink="false">2026-07-25:The trading fleet never sells 100% of a winner again</guid>
+ <pubDate>Sat, 25 Jul 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>New rule across every autonomous trading strategy: once a position has earned back what it cost, we never sell all of it. Any exit taken in profit now sells just enough to recover the original stake (or banks the gain down to a floor if the stake is already home) and keeps the rest, which then rides indefinitely. The logic is simple: after the cost is recovered the leftover position is free, so it is worth nothing at worst and has no ceiling at best. Selling that last slice to lock in a few thousandths of a SOL gives up every large outcome for a rounding error, and large outcomes are the entire reason to hold. Concretely: a position that ran to 1.4x and then hit its trailing stop used to be dumped completely for about +0.003 SOL; it now sells 71% to return the stake and keeps 29% riding at zero cost. Losses are unchanged and still exit completely, because nothing is free until the stake is back, and the hard stop-loss still overrides everything while real money is at risk. Held positions are booked as closed for accounting the moment the profit is banked, so they never occupy a slot that would stop a strategy from taking its next trade. Each strategy's held bags and their current value are now shown on the experiments board, tracked separately from realized profit since nothing counts as profit until it is sold. This also repairs the take-initials ladder, which could never actually fire: the exit settings lived on the strategy but were missing from the query the position loop reads, so every position silently fell back to selling everything no matter how it was configured.</description>
+ </item>
<item>
<title>three.ws is an OpenAI Select Partner</title>
<link>https://three.ws/openai</link>
diff --git a/public/features.json b/public/features.json
index 9572ca321..2a7e68dc2 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-25T08:25:10.036Z",
+ "generated_at": "2026-07-25T08:47:56.171Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/scripts/.scratch/check-rig.mjs b/scripts/.scratch/check-rig.mjs
new file mode 100644
index 000000000..1d6fa8184
--- /dev/null
+++ b/scripts/.scratch/check-rig.mjs
@@ -0,0 +1,37 @@
+import {
+ ANCHORS, Pose, boneAxis, boneLength, curlAxis, palmAxis, radialAxis, restDirWorld,
+ restPalmWorld, restRadialWorld, signPoint, solveArm, splayAxis, vLen, vSub, qRotate, restWorld,
+} from '../../src/sign-rig.js';
+
+const f = (v) => (Array.isArray(v) ? v.map((n) => n.toFixed(3)).join(', ') : v.toFixed(3));
+
+console.log('--- derived hand frames ---');
+for (const side of ['Right', 'Left']) {
+ console.log(side, 'palmWorld=', f(restPalmWorld(side)), 'radialWorld=', f(restRadialWorld(side)));
+}
+console.log('\n--- bone axes (local) / lengths ---');
+for (const b of ['RightArm', 'RightForeArm', 'RightHand', 'RightHandIndex1', 'RightHandThumb1', 'LeftArm', 'LeftHand']) {
+ console.log(b.padEnd(16), 'axis=', f(boneAxis(b)), 'len=', f(boneLength(b)), 'restDir=', f(restDirWorld(b)));
+}
+console.log('\n--- finger axes ---');
+for (const b of ['RightHandIndex1', 'RightHandIndex2', 'LeftHandIndex1', 'RightHandThumb1', 'LeftHandThumb1']) {
+ console.log(b.padEnd(18), 'palm=', f(palmAxis(b)), 'radial=', f(radialAxis(b)), 'curl=', f(curlAxis(b)), 'splay=', f(splayAxis(b)));
+}
+console.log('\n--- anchors ---');
+for (const k of ['forward', 'shoulderSpan', 'head', 'chin', 'sternum', 'belly']) console.log(k.padEnd(14), f(ANCHORS[k]));
+console.log('shoulder R', f(ANCHORS.shoulder.Right));
+
+console.log('\n--- IK: fingerspelling position (right hand beside the chin, palm out) ---');
+const target = signPoint('chin', { out: 0.20, up: -0.05, forward: 0.16, side: 'Right' });
+const pose = new Pose();
+solveArm(pose, 'Right', { wrist: target, fingers: [0, 1, 0], palm: [0, 0, 1] });
+const report = (p, side) => {
+ for (const b of [`${side}Arm`, `${side}ForeArm`, `${side}Hand`, `${side}HandMiddle3`]) {
+ console.log(b.padEnd(17), 'pos=', f(p.worldPos(b)), 'dir=', f(p.worldDir(b)), 'palm→', f(qRotate(p.worldQuat(b), palmAxis(b.includes('Hand') && !b.endsWith('Arm') ? b : `${side}Hand`))));
+ }
+};
+console.log('target wrist ', f(target));
+report(pose, 'Right');
+console.log('elbow below wrist?', pose.worldPos('RightForeArm')[1] < pose.worldPos('RightHand')[1]);
+console.log('hand in front (z>0)?', pose.worldPos('RightHand')[2] > 0);
+console.log('wrist error', f(vLen(vSub(pose.worldPos('RightHand'), target))));
diff --git a/scripts/build-canonical-rest.mjs b/scripts/build-canonical-rest.mjs
index fff5a03a3..359734e9a 100644
--- a/scripts/build-canonical-rest.mjs
+++ b/scripts/build-canonical-rest.mjs
@@ -18,7 +18,7 @@
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { Quaternion } from 'three';
+import { Quaternion, Vector3 } from 'three';
import { canonicalizeBoneName } from '../src/glb-canonicalize.js';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
@@ -64,18 +64,52 @@ function worldQuat(i) {
return q;
}
+// Each glTF node's local translation (zero when omitted).
+const localPos = (i) => {
+ const t = Array.isArray(nodes[i]?.translation) ? nodes[i].translation : [0, 0, 0];
+ return new Vector3(t[0], t[1], t[2]);
+};
+
+// World bind POSITION of node i, composed the same way as worldQuat. Humanoid
+// glTF rigs carry no per-node scale on the bone chain, so rotation+translation
+// composition is exact.
+const posCache = new Map();
+function worldPos(i) {
+ if (posCache.has(i)) return posCache.get(i);
+ let p = localPos(i);
+ const parent = parentOf[i];
+ if (parent !== -1) p = p.clone().applyQuaternion(worldQuat(parent)).add(worldPos(parent));
+ posCache.set(i, p);
+ return p;
+}
+
// First occurrence wins, matching canonicalRestMapFromObject's traversal order.
const rest = new Map();
const restWorld = new Map();
+const restPosition = new Map();
+const canonicalOf = new Map(); // node index → canonical name (first-wins)
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
if (!node?.name) continue;
const canonical = canonicalizeBoneName(node.name);
if (!canonical || rest.has(canonical)) continue;
+ canonicalOf.set(i, canonical);
// glTF node rotation defaults to identity [0,0,0,1] when omitted.
rest.set(canonical, Array.isArray(node.rotation) ? node.rotation : [0, 0, 0, 1]);
const w = worldQuat(i);
restWorld.set(canonical, [w.x, w.y, w.z, w.w]);
+ const p = worldPos(i);
+ restPosition.set(canonical, [p.x, p.y, p.z]);
+}
+
+// Nearest CANONICAL ancestor of each canonical bone. Bones the canonicalizer
+// doesn't name (helper/twist joints an artist inserted) are skipped, so the
+// chain a pose solver walks is the canonical one the clips address.
+const parent = new Map();
+for (const [i, canonical] of canonicalOf) {
+ let p = parentOf[i];
+ while (p !== -1 && !canonicalOf.has(p)) p = parentOf[p];
+ parent.set(canonical, p === -1 ? null : canonicalOf.get(p));
}
if (rest.size === 0) throw new Error(`${REFERENCE_RIG}: no canonical bones found`);
@@ -88,6 +122,12 @@ const body = sorted
const worldBody = sorted
.map(([bone]) => `\t${bone}: [${restWorld.get(bone).map((n) => +n).join(', ')}],`)
.join('\n');
+const positionBody = sorted
+ .map(([bone]) => `\t${bone}: [${restPosition.get(bone).map((n) => +n.toFixed(6)).join(', ')}],`)
+ .join('\n');
+const parentBody = sorted
+ .map(([bone]) => `\t${bone}: ${parent.get(bone) ? `'${parent.get(bone)}'` : 'null'},`)
+ .join('\n');
const out = `// GENERATED by scripts/build-canonical-rest.mjs from public/avatars/cz.glb.
// Do not edit by hand — re-run the generator instead.
@@ -110,8 +150,23 @@ ${body}
export const CANONICAL_REST_WORLD = Object.freeze({
${worldBody}
});
+
+// CANONICAL_REST_POSITION — each bone's WORLD (model-space) bind position in
+// metres, and CANONICAL_PARENT — its nearest canonical ancestor. Together with
+// the rotations above they describe the reference skeleton completely enough to
+// run forward and inverse kinematics in plain JS (src/sign-rig.js), which is how
+// the signing lane authors poses by anatomical target instead of by hand-tuned
+// joint angles.
+
+export const CANONICAL_REST_POSITION = Object.freeze({
+${positionBody}
+});
+
+export const CANONICAL_PARENT = Object.freeze({
+${parentBody}
+});
`;
fs.writeFileSync(OUT, out);
-console.log(`wrote ${path.relative(ROOT, OUT)} — ${rest.size} canonical bones (local + world)`);
+console.log(`wrote ${path.relative(ROOT, OUT)} — ${rest.size} canonical bones (local + world + position + parent)`);
console.log('bones:', sorted.map(([b]) => b).join(', '));
diff --git a/src/animation-canonical-rest.js b/src/animation-canonical-rest.js
index a1f1ecbd2..467b4b593 100644
--- a/src/animation-canonical-rest.js
+++ b/src/animation-canonical-rest.js
@@ -121,3 +121,120 @@ export const CANONICAL_REST_WORLD = Object.freeze({
Spine1: [-0.055396652424023016, -5.997624651397324e-8, 3.32759956947242e-9, 0.9984644264570511],
Spine2: [-0.11221710079276989, 7.513757486198981e-8, -8.485311473269302e-9, 0.9936837134066652],
});
+
+// CANONICAL_REST_POSITION — each bone's WORLD (model-space) bind position in
+// metres, and CANONICAL_PARENT — its nearest canonical ancestor. Together with
+// the rotations above they describe the reference skeleton completely enough to
+// run forward and inverse kinematics in plain JS (src/sign-rig.js), which is how
+// the signing lane authors poses by anatomical target instead of by hand-tuned
+// joint angles.
+
+export const CANONICAL_REST_POSITION = Object.freeze({
+ Head: [0, 1.644459, -0.02811],
+ Hips: [0, 0.984089, 0.005022],
+ LeftArm: [0.204124, 1.50826, -0.034115],
+ LeftFoot: [0.095793, 0.088025, -0.010018],
+ LeftForeArm: [0.458234, 1.508259, -0.045252],
+ LeftHand: [0.725837, 1.508259, -0.050352],
+ LeftHandIndex1: [0.815413, 1.499602, -0.024435],
+ LeftHandIndex2: [0.847794, 1.497747, -0.020782],
+ LeftHandIndex3: [0.872293, 1.496601, -0.017998],
+ LeftHandMiddle1: [0.820067, 1.500491, -0.048839],
+ LeftHandMiddle2: [0.854745, 1.498698, -0.047572],
+ LeftHandMiddle3: [0.881683, 1.49736, -0.046832],
+ LeftHandPinky1: [0.810112, 1.495569, -0.08743],
+ LeftHandPinky2: [0.8359, 1.495002, -0.089537],
+ LeftHandPinky3: [0.856018, 1.494638, -0.091171],
+ LeftHandRing1: [0.81666, 1.499944, -0.069059],
+ LeftHandRing2: [0.850313, 1.498728, -0.071468],
+ LeftHandRing3: [0.87354, 1.497943, -0.072665],
+ LeftHandThumb1: [0.761831, 1.487283, -0.024616],
+ LeftHandThumb2: [0.783931, 1.477329, -0.003377],
+ LeftHandThumb3: [0.806009, 1.466616, 0.003515],
+ LeftLeg: [0.09541, 0.505427, 0.007362],
+ LeftShoulder: [0.056656, 1.508576, -0.035092],
+ LeftToeBase: [0.096919, 0.022281, 0.128921],
+ LeftUpLeg: [0.095072, 0.936186, 0.005482],
+ Neck: [0, 1.516499, -0.057245],
+ RightArm: [-0.204124, 1.50826, -0.034115],
+ RightFoot: [-0.095793, 0.088025, -0.010018],
+ RightForeArm: [-0.458234, 1.508259, -0.045252],
+ RightHand: [-0.725837, 1.508259, -0.050352],
+ RightHandIndex1: [-0.815413, 1.499602, -0.024435],
+ RightHandIndex2: [-0.847794, 1.497747, -0.020783],
+ RightHandIndex3: [-0.872293, 1.496601, -0.017998],
+ RightHandMiddle1: [-0.820067, 1.500491, -0.048839],
+ RightHandMiddle2: [-0.854745, 1.498698, -0.047572],
+ RightHandMiddle3: [-0.881683, 1.49736, -0.046832],
+ RightHandPinky1: [-0.810112, 1.495569, -0.08743],
+ RightHandPinky2: [-0.8359, 1.495002, -0.089537],
+ RightHandPinky3: [-0.856018, 1.494638, -0.091171],
+ RightHandRing1: [-0.81666, 1.499944, -0.069059],
+ RightHandRing2: [-0.850313, 1.498729, -0.071468],
+ RightHandRing3: [-0.87354, 1.497943, -0.072665],
+ RightHandThumb1: [-0.761831, 1.487283, -0.024615],
+ RightHandThumb2: [-0.783931, 1.477329, -0.003377],
+ RightHandThumb3: [-0.806009, 1.466616, 0.003515],
+ RightLeg: [-0.09541, 0.505427, 0.007362],
+ RightShoulder: [-0.056656, 1.508576, -0.035092],
+ RightToeBase: [-0.096919, 0.022281, 0.128921],
+ RightUpLeg: [-0.095072, 0.936186, 0.005482],
+ Spine: [0, 1.077013, 0.005222],
+ Spine1: [0, 1.184494, 0.00151],
+ Spine2: [0, 1.330917, -0.014788],
+});
+
+export const CANONICAL_PARENT = Object.freeze({
+ Head: 'Neck',
+ Hips: null,
+ LeftArm: 'LeftShoulder',
+ LeftFoot: 'LeftLeg',
+ LeftForeArm: 'LeftArm',
+ LeftHand: 'LeftForeArm',
+ LeftHandIndex1: 'LeftHand',
+ LeftHandIndex2: 'LeftHandIndex1',
+ LeftHandIndex3: 'LeftHandIndex2',
+ LeftHandMiddle1: 'LeftHand',
+ LeftHandMiddle2: 'LeftHandMiddle1',
+ LeftHandMiddle3: 'LeftHandMiddle2',
+ LeftHandPinky1: 'LeftHand',
+ LeftHandPinky2: 'LeftHandPinky1',
+ LeftHandPinky3: 'LeftHandPinky2',
+ LeftHandRing1: 'LeftHand',
+ LeftHandRing2: 'LeftHandRing1',
+ LeftHandRing3: 'LeftHandRing2',
+ LeftHandThumb1: 'LeftHand',
+ LeftHandThumb2: 'LeftHandThumb1',
+ LeftHandThumb3: 'LeftHandThumb2',
+ LeftLeg: 'LeftUpLeg',
+ LeftShoulder: 'Spine2',
+ LeftToeBase: 'LeftFoot',
+ LeftUpLeg: 'Hips',
+ Neck: 'Spine2',
+ RightArm: 'RightShoulder',
+ RightFoot: 'RightLeg',
+ RightForeArm: 'RightArm',
+ RightHand: 'RightForeArm',
+ RightHandIndex1: 'RightHand',
+ RightHandIndex2: 'RightHandIndex1',
+ RightHandIndex3: 'RightHandIndex2',
+ RightHandMiddle1: 'RightHand',
+ RightHandMiddle2: 'RightHandMiddle1',
+ RightHandMiddle3: 'RightHandMiddle2',
+ RightHandPinky1: 'RightHand',
+ RightHandPinky2: 'RightHandPinky1',
+ RightHandPinky3: 'RightHandPinky2',
+ RightHandRing1: 'RightHand',
+ RightHandRing2: 'RightHandRing1',
+ RightHandRing3: 'RightHandRing2',
+ RightHandThumb1: 'RightHand',
+ RightHandThumb2: 'RightHandThumb1',
+ RightHandThumb3: 'RightHandThumb2',
+ RightLeg: 'RightUpLeg',
+ RightShoulder: 'Spine2',
+ RightToeBase: 'RightFoot',
+ RightUpLeg: 'Hips',
+ Spine: 'Hips',
+ Spine1: 'Spine',
+ Spine2: 'Spine1',
+});
diff --git a/src/sign-rig.js b/src/sign-rig.js
new file mode 100644
index 000000000..8d69d6199
--- /dev/null
+++ b/src/sign-rig.js
@@ -0,0 +1,611 @@
+// Sign-rig — forward/inverse kinematics for the canonical skeleton, in plain JS.
+//
+// Signing is a spatial language: a sign is "flat hand, palm out, at the chin,
+// moving down-forward" — a LOCATION and an ORIENTATION, never a list of joint
+// angles. Authoring it as raw quaternions per bone is how the first pass of this
+// feature ended up with the signing arm pointing behind the avatar: it assumed
+// the reference rig aimed its bones down local +X from a T-pose, when cz.glb
+// (like every Mixamo/Avaturn/VRM humanoid) aims them down local +Y through a
+// shoulder whose own rest rotation is ~120° off identity.
+//
+// So this module reads the reference skeleton instead of assuming it. Everything
+// below is derived at load time from the generated bind-pose data
+// (src/animation-canonical-rest.js — rotations, positions, and parent chain of
+// public/avatars/cz.glb):
+//
+// • each bone's axis (the local direction that points at its child),
+// • each hand's palm normal and radial (thumb-side) direction,
+// • bone lengths, so a two-bone IK solver can put the wrist at a POINT.
+//
+// A `Pose` is a mutable FK container: set a bone's world orientation and it
+// stores the local rotation that produces it, given whatever its parents are
+// currently doing. `solveArm` places a wrist at a world-space target with a
+// natural elbow, then orients the hand by (fingers direction, palm direction).
+// The output is the same absolute-local-rotation form the clip library stores,
+// so it retargets onto any rigged avatar through src/animation-retarget.js.
+//
+// Pure module: no three.js, no DOM — it runs in the browser, in Node, and in
+// vitest identically.
+
+import {
+ CANONICAL_PARENT,
+ CANONICAL_REST,
+ CANONICAL_REST_POSITION,
+ CANONICAL_REST_WORLD,
+} from './animation-canonical-rest.js';
+
+// ── vector + quaternion helpers ([x, y, z, w], matching three.js) ───────────
+
+export const IDENTITY = Object.freeze([0, 0, 0, 1]);
+
+export const v3 = (x, y, z) => [x, y, z];
+
+export function vAdd(a, b) {
+ return [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
+}
+
+export function vSub(a, b) {
+ return [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
+}
+
+export function vScale(a, k) {
+ return [a[0] * k, a[1] * k, a[2] * k];
+}
+
+export function vDot(a, b) {
+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
+}
+
+export function vCross(a, b) {
+ return [
+ a[1] * b[2] - a[2] * b[1],
+ a[2] * b[0] - a[0] * b[2],
+ a[0] * b[1] - a[1] * b[0],
+ ];
+}
+
+export function vLen(a) {
+ return Math.hypot(a[0], a[1], a[2]);
+}
+
+export function vNorm(a) {
+ const n = vLen(a);
+ return n < 1e-9 ? [0, 0, 0] : [a[0] / n, a[1] / n, a[2] / n];
+}
+
+export function vLerp(a, b, t) {
+ return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t];
+}
+
+/** Component of `a` perpendicular to unit vector `axis`. */
+export function vReject(a, axis) {
+ const d = vDot(a, axis);
+ return [a[0] - axis[0] * d, a[1] - axis[1] * d, a[2] - axis[2] * d];
+}
+
+export function qMul(a, b) {
+ const [ax, ay, az, aw] = a;
+ const [bx, by, bz, bw] = b;
+ return [
+ aw * bx + ax * bw + ay * bz - az * by,
+ aw * by - ax * bz + ay * bw + az * bx,
+ aw * bz + ax * by - ay * bx + az * bw,
+ aw * bw - ax * bx - ay * by - az * bz,
+ ];
+}
+
+export function qConj(q) {
+ return [-q[0], -q[1], -q[2], q[3]];
+}
+
+export function qNorm(q) {
+ const n = Math.hypot(q[0], q[1], q[2], q[3]);
+ return n < 1e-9 ? [...IDENTITY] : [q[0] / n, q[1] / n, q[2] / n, q[3] / n];
+}
+
+export function qAxisAngle(axis, deg) {
+ const [x, y, z] = vNorm(axis);
+ const half = (deg * Math.PI) / 360;
+ const s = Math.sin(half);
+ return [x * s, y * s, z * s, Math.cos(half)];
+}
+
+/** Rotate vector `v` by quaternion `q`. */
+export function qRotate(q, v) {
+ const [x, y, z, w] = q;
+ // t = 2 * (q.xyz × v); v' = v + w*t + q.xyz × t
+ const tx = 2 * (y * v[2] - z * v[1]);
+ const ty = 2 * (z * v[0] - x * v[2]);
+ const tz = 2 * (x * v[1] - y * v[0]);
+ return [
+ v[0] + w * tx + y * tz - z * ty,
+ v[1] + w * ty + z * tx - x * tz,
+ v[2] + w * tz + x * ty - y * tx,
+ ];
+}
+
+/** Shortest rotation carrying unit vector `from` onto unit vector `to`. */
+export function qBetween(from, to) {
+ const f = vNorm(from);
+ const t = vNorm(to);
+ const d = vDot(f, t);
+ if (d > 1 - 1e-9) return [...IDENTITY];
+ if (d < -1 + 1e-9) {
+ let axis = vCross(f, [1, 0, 0]);
+ if (vLen(axis) < 1e-6) axis = vCross(f, [0, 1, 0]);
+ const [x, y, z] = vNorm(axis);
+ return [x, y, z, 0];
+ }
+ const axis = vCross(f, t);
+ return qNorm([axis[0], axis[1], axis[2], 1 + d]);
+}
+
+export function qSlerp(a, b, t) {
+ let [bx, by, bz, bw] = b;
+ let cos = a[0] * bx + a[1] * by + a[2] * bz + a[3] * bw;
+ if (cos < 0) {
+ cos = -cos;
+ bx = -bx;
+ by = -by;
+ bz = -bz;
+ bw = -bw;
+ }
+ if (cos > 0.9995) return qNorm([
+ a[0] + (bx - a[0]) * t,
+ a[1] + (by - a[1]) * t,
+ a[2] + (bz - a[2]) * t,
+ a[3] + (bw - a[3]) * t,
+ ]);
+ const theta = Math.acos(cos);
+ const sin = Math.sin(theta);
+ const wa = Math.sin((1 - t) * theta) / sin;
+ const wb = Math.sin(t * theta) / sin;
+ return qNorm([a[0] * wa + bx * wb, a[1] * wa + by * wb, a[2] * wa + bz * wb, a[3] * wa + bw * wb]);
+}
+
+// Quaternion from an orthonormal 3×3 basis given as its column vectors.
+function qFromBasis(x, y, z) {
+ const m00 = x[0], m10 = x[1], m20 = x[2];
+ const m01 = y[0], m11 = y[1], m21 = y[2];
+ const m02 = z[0], m12 = z[1], m22 = z[2];
+ const trace = m00 + m11 + m22;
+ if (trace > 0) {
+ const s = 0.5 / Math.sqrt(trace + 1);
+ return qNorm([(m21 - m12) * s, (m02 - m20) * s, (m10 - m01) * s, 0.25 / s]);
+ }
+ if (m00 > m11 && m00 > m22) {
+ const s = 2 * Math.sqrt(1 + m00 - m11 - m22);
+ return qNorm([0.25 * s, (m01 + m10) / s, (m02 + m20) / s, (m21 - m12) / s]);
+ }
+ if (m11 > m22) {
+ const s = 2 * Math.sqrt(1 + m11 - m00 - m22);
+ return qNorm([(m01 + m10) / s, 0.25 * s, (m12 + m21) / s, (m02 - m20) / s]);
+ }
+ const s = 2 * Math.sqrt(1 + m22 - m00 - m11);
+ return qNorm([(m02 + m20) / s, (m12 + m21) / s, 0.25 * s, (m10 - m01) / s]);
+}
+
+// Orthonormal basis from a primary direction and a secondary reference. The
+// primary is preserved exactly; the reference only resolves the roll.
+function basisFrom(primary, reference) {
+ const a = vNorm(primary);
+ let b = vReject(reference, a);
+ if (vLen(b) < 1e-6) {
+ // Reference parallel to the primary: pick any perpendicular so the frame
+ // stays well-defined (the caller's roll is undefined anyway).
+ b = vReject(Math.abs(a[1]) < 0.9 ? [0, 1, 0] : [1, 0, 0], a);
+ }
+ b = vNorm(b);
+ return [a, b, vCross(a, b)];
+}
+
+/**
+ * The rotation that carries the local frame (`axisLocal`, `refLocal`) onto the
+ * world frame (`axisWorld`, `refWorld`). `axisLocal → axisWorld` is exact; the
+ * reference pair only fixes the twist about it.
+ */
+export function orientQuat(axisLocal, refLocal, axisWorld, refWorld) {
+ const [la, lb, lc] = basisFrom(axisLocal, refLocal);
+ const [wa, wb, wc] = basisFrom(axisWorld, refWorld);
+ // Q = W · Lᵀ, expressed as two basis quaternions: Q = qW · qL⁻¹.
+ const qL = qFromBasis(la, lb, lc);
+ const qW = qFromBasis(wa, wb, wc);
+ return qNorm(qMul(qW, qConj(qL)));
+}
+
+// ── the reference skeleton, read from the generated bind pose ───────────────
+
+/** Nearest canonical ancestor of `bone`, or null at the root. */
+export const parentOf = (bone) => CANONICAL_PARENT[bone] ?? null;
+
+/** Local rest (bind) rotation of `bone` on the reference rig. */
+export const restLocal = (bone) => CANONICAL_REST[bone] ?? [...IDENTITY];
+
+/** World (model-space) rest rotation of `bone` on the reference rig. */
+export const restWorld = (bone) => CANONICAL_REST_WORLD[bone] ?? [...IDENTITY];
+
+/** World (model-space) rest position of `bone`, in metres. */
+export const restPos = (bone) => CANONICAL_REST_POSITION[bone] ?? [0, 0, 0];
+
+/** True when the reference rig carries this canonical bone. */
+export const hasBone = (bone) => Object.hasOwn(CANONICAL_REST, bone);
+
+const CHILDREN = (() => {
+ const map = new Map();
+ for (const [bone, parent] of Object.entries(CANONICAL_PARENT)) {
+ if (!parent) continue;
+ if (!map.has(parent)) map.set(parent, []);
+ map.get(parent).push(bone);
+ }
+ return map;
+})();
+
+// Bones with several canonical children need the one that defines the segment's
+// direction: the hand points down the middle finger, the hips up the spine.
+const PREFERRED_CHILD = {
+ Hips: 'Spine',
+ LeftHand: 'LeftHandMiddle1',
+ RightHand: 'RightHandMiddle1',
+};
+
+function segmentChild(bone) {
+ if (PREFERRED_CHILD[bone] && hasBone(PREFERRED_CHILD[bone])) return PREFERRED_CHILD[bone];
+ return (CHILDREN.get(bone) || [])[0] ?? null;
+}
+
+/** World direction `bone` points at rest (toward its child, or along its own segment for a tip). */
+export function restDirWorld(bone) {
+ const child = segmentChild(bone);
+ if (child) return vNorm(vSub(restPos(child), restPos(bone)));
+ const parent = parentOf(bone);
+ if (parent) return vNorm(vSub(restPos(bone), restPos(parent)));
+ return [0, 1, 0];
+}
+
+const _axisCache = new Map();
+
+/**
+ * The bone's own axis: the LOCAL direction that points at its child. ~[0,1,0]
+ * on Mixamo/Avaturn rigs, but measured rather than assumed.
+ * @param {string} bone
+ * @returns {number[]}
+ */
+export function boneAxis(bone) {
+ if (!_axisCache.has(bone)) {
+ _axisCache.set(bone, vNorm(qRotate(qConj(restWorld(bone)), restDirWorld(bone))));
+ }
+ return _axisCache.get(bone);
+}
+
+/** Length of the segment from `bone` to its next canonical joint, in metres. */
+export function boneLength(bone) {
+ const child = segmentChild(bone);
+ return child ? vLen(vSub(restPos(child), restPos(bone))) : 0;
+}
+
+// Per-hand anatomy, measured from the bind pose rather than assumed:
+// radial — from the pinky knuckle toward the index knuckle, i.e. the thumb
+// side of the hand (forward, +Z, on this palms-down T-pose rig),
+// palm — normal to the hand plane, flipped to the side the thumb tip sits
+// on, which is the palm side for any relaxed humanoid hand.
+// Both are stored in WORLD terms; per-bone locals come from each bone's own
+// rest rotation, so the finger joints inherit the frame without mirror hacks.
+function handFrame(side) {
+ const hand = `${side}Hand`;
+ const axis = restDirWorld(hand);
+ let radial = vNorm(vReject(vSub(restPos(`${side}HandIndex1`), restPos(`${side}HandPinky1`)), axis));
+ if (vLen(radial) < 1e-6) radial = vNorm(vReject([0, 0, 1], axis));
+ let palm = vNorm(vCross(radial, axis));
+ const thumbTip = vSub(restPos(`${side}HandThumb3`), restPos(hand));
+ if (vDot(palm, thumbTip) < 0) palm = vScale(palm, -1);
+ return { axis, radial, palm };
+}
+
+const HAND_FRAME = { Left: handFrame('Left'), Right: handFrame('Right') };
+
+/** World direction the `side` palm faces at rest (down, on this rig). */
+export const restPalmWorld = (side) => HAND_FRAME[side].palm;
+
+/** World direction from the pinky toward the thumb side of the `side` hand at rest. */
+export const restRadialWorld = (side) => HAND_FRAME[side].radial;
+
+const sideOf = (bone) => (bone.startsWith('Left') ? 'Left' : 'Right');
+
+/** LOCAL direction in which `bone`'s palm side faces (hand + finger bones). */
+export function palmAxis(bone) {
+ return vNorm(qRotate(qConj(restWorld(bone)), HAND_FRAME[sideOf(bone)].palm));
+}
+
+/** LOCAL direction toward the thumb side of the hand (hand + finger bones). */
+export function radialAxis(bone) {
+ return vNorm(qRotate(qConj(restWorld(bone)), HAND_FRAME[sideOf(bone)].radial));
+}
+
+/**
+ * LOCAL flexion axis of a finger/thumb joint: rotating about it by a POSITIVE
+ * angle curls the bone toward the palm. Derived per bone, so it is correct on
+ * both hands with no mirroring by hand.
+ */
+export function curlAxis(bone) {
+ return vNorm(vCross(boneAxis(bone), palmAxis(bone)));
+}
+
+/**
+ * LOCAL abduction axis of a finger joint: a POSITIVE angle splays the finger
+ * toward the thumb side, a negative one toward the pinky.
+ */
+export function splayAxis(bone) {
+ return vNorm(vCross(boneAxis(bone), radialAxis(bone)));
+}
+
+// ── the signing body: anchors and workspace ────────────────────────────────
+
+/**
+ * Anatomical anchor points in model space, measured off the reference rig, so a
+ * sign can be authored as "at the chin" or "centre chest" instead of as an
+ * arbitrary XYZ. Signs are written against these and stay anatomically placed.
+ */
+export const ANCHORS = (() => {
+ const head = restPos('Head');
+ const neck = restPos('Neck');
+ const chest = restPos('Spine2');
+ const hips = restPos('Hips');
+ const shoulderR = restPos('RightArm');
+ const shoulderL = restPos('LeftArm');
+ // At a palms-down rest the hand's radial (thumb) side points where the body
+ // faces, so the rig gives us "forward" without a hardcoded axis.
+ const forward = restRadialWorld('Right');
+ const up = [0, 1, 0];
+ const chinY = neck[1] + (head[1] - neck[1]) * 0.55;
+ return Object.freeze({
+ forward,
+ up,
+ /** Model-space width between the shoulders — the unit signs scale by. */
+ shoulderSpan: vLen(vSub(shoulderL, shoulderR)),
+ head,
+ neck,
+ chest,
+ hips,
+ shoulder: { Left: shoulderL, Right: shoulderR },
+ forehead: [0, head[1] + 0.07, head[2]],
+ chin: [0, chinY, head[2] + 0.03],
+ mouth: [0, chinY + 0.04, head[2] + 0.04],
+ nose: [0, head[1] + 0.02, head[2] + 0.05],
+ /** Upper chest, where most two-handed signs live. */
+ sternum: [0, chest[1] + 0.06, chest[2] + 0.02],
+ /** Mid torso — the low end of neutral signing space. */
+ belly: [0, (chest[1] + hips[1]) / 2, chest[2]],
+ });
+})();
+
+/**
+ * A point in signing space: an anchor (or explicit point) plus an offset in
+ * body-relative axes — out (toward the signer's dominant side), up, and forward
+ * (toward the receiver). Offsets are in metres on the reference rig.
+ *
+ * @param {number[]|string} anchor ANCHORS key or an explicit [x,y,z]
+ * @param {{ out?: number, up?: number, forward?: number, side?: 'Left'|'Right' }} [offset]
+ * @returns {number[]} model-space point
+ */
+export function signPoint(anchor, offset = {}) {
+ const base = Array.isArray(anchor) ? anchor : ANCHORS[anchor];
+ if (!base) throw new Error(`unknown sign anchor "${anchor}"`);
+ const side = offset.side ?? 'Right';
+ const outSign = side === 'Right' ? -1 : 1; // the right hand's "out" is −X
+ return [
+ base[0] + outSign * (offset.out ?? 0),
+ base[1] + (offset.up ?? 0),
+ base[2] + (offset.forward ?? 0),
+ ];
+}
+
+// ── the pose container ─────────────────────────────────────────────────────
+
+/**
+ * A skeleton pose: per-bone LOCAL rotations (absolute, replacing the rest
+ * rotation exactly like an AnimationClip track does), with forward kinematics
+ * so a caller can ask where a bone ENDED UP and aim bones at world targets.
+ */
+export class Pose {
+ /** @param {Pose|null} [from] copy-construct from another pose */
+ constructor(from = null) {
+ /** @type {Map<string, number[]>} */
+ this.local = new Map(from ? from.local : []);
+ this._worldQ = new Map();
+ this._worldP = new Map();
+ }
+
+ clone() {
+ return new Pose(this);
+ }
+
+ _invalidate() {
+ this._worldQ.clear();
+ this._worldP.clear();
+ }
+
+ /** Local rotation of `bone` — posed if set, otherwise the rig's rest. */
+ getLocal(bone) {
+ return this.local.get(bone) ?? restLocal(bone);
+ }
+
+ /** Set `bone`'s local rotation directly. */
+ setLocal(bone, q) {
+ this.local.set(bone, qNorm(q));
+ this._invalidate();
+ return this;
+ }
+
+ /** Rotate `bone` by `deg` about a LOCAL axis, on top of its current rotation. */
+ rotateLocal(bone, axis, deg) {
+ return this.setLocal(bone, qMul(this.getLocal(bone), qAxisAngle(axis, deg)));
+ }
+
+ /** World (model-space) rotation of `bone` under this pose. */
+ worldQuat(bone) {
+ let q = this._worldQ.get(bone);
+ if (q) return q;
+ const parent = parentOf(bone);
+ q = parent ? qMul(this.worldQuat(parent), this.getLocal(bone)) : this.getLocal(bone);
+ this._worldQ.set(bone, q);
+ return q;
+ }
+
+ /** World (model-space) position of `bone` under this pose. */
+ worldPos(bone) {
+ let p = this._worldP.get(bone);
+ if (p) return p;
+ const parent = parentOf(bone);
+ if (!parent) {
+ p = restPos(bone);
+ } else {
+ // The bone's fixed offset from its parent, carried by the parent's
+ // posed rotation — the rig's own bone lengths, never rescaled.
+ const offsetLocal = qRotate(qConj(restWorld(parent)), vSub(restPos(bone), restPos(parent)));
+ p = vAdd(this.worldPos(parent), qRotate(this.worldQuat(parent), offsetLocal));
+ }
+ this._worldP.set(bone, p);
+ return p;
+ }
+
+ /** World direction `bone` points under this pose (toward its child). */
+ worldDir(bone) {
+ return vNorm(qRotate(this.worldQuat(bone), boneAxis(bone)));
+ }
+
+ /** Set `bone`'s WORLD rotation, storing the local that produces it here. */
+ setWorldQuat(bone, qWorld) {
+ const parent = parentOf(bone);
+ const local = parent ? qMul(qConj(this.worldQuat(parent)), qWorld) : qWorld;
+ return this.setLocal(bone, local);
+ }
+
+ /**
+ * Aim `bone` down `dirWorld`, using `refWorld` to resolve the twist about it.
+ * `refLocal` defaults to the bone's palm axis (hands/fingers) so callers can
+ * say "point the fingers here, face the palm there".
+ */
+ aim(bone, dirWorld, refWorld = null, refLocal = null) {
+ const axisLocal = boneAxis(bone);
+ if (!refWorld) {
+ // No roll requested: rotate the bone's current orientation the short way.
+ const current = this.worldDir(bone);
+ return this.setWorldQuat(bone, qMul(qBetween(current, dirWorld), this.worldQuat(bone)));
+ }
+ const rl = refLocal ?? palmAxis(bone);
+ return this.setWorldQuat(bone, orientQuat(axisLocal, rl, dirWorld, refWorld));
+ }
+
+ /** Plain `{bone: [x,y,z,w]}` of every posed bone — the clip track payload. */
+ locals() {
+ return Object.fromEntries(this.local);
+ }
+}
+
+// ── two-bone arm IK ────────────────────────────────────────────────────────
+
+/**
+ * Place a `side` wrist at a world-space point with a natural elbow, then orient
+ * the hand.
+ *
+ * The elbow lands on the circle of valid solutions, pushed toward `pole` — a
+ * world direction meaning "the elbow points that way". The default drops it
+ * down, back, and slightly out, which is where a signer's elbow actually sits;
+ * signs never lift the elbow to shoulder height unless the sign says so.
+ *
+ * Roll is anatomical, not arbitrary: the upper arm twists so the elbow flexes in
+ * the plane the pole defines, and the forearm carries the pronation the palm
+ * direction implies — so the wrist itself only ever holds the small residual,
+ * which is what stops the "broken wrist" look.
+ *
+ * @param {Pose} pose mutated in place
+ * @param {'Left'|'Right'} side
+ * @param {{
+ * wrist: number[],
+ * fingers?: number[],
+ * palm?: number[],
+ * pole?: number[],
+ * reach?: number,
+ * }} spec `wrist` is the world target for the wrist joint; `fingers`/`palm` are
+ * world directions for the hand; `reach` (0–1) caps how straight the arm may
+ * lock (0.98 default leaves a soft elbow).
+ * @returns {Pose} the same pose
+ */
+export function solveArm(pose, side, spec) {
+ const upper = `${side}Arm`;
+ const lower = `${side}ForeArm`;
+ const hand = `${side}Hand`;
+
+ const shoulder = pose.worldPos(upper);
+ const lu = boneLength(upper);
+ const ll = boneLength(lower);
+ const reach = spec.reach ?? 0.985;
+
+ let toTarget = vSub(spec.wrist, shoulder);
+ let dist = vLen(toTarget);
+ const maxReach = (lu + ll) * reach;
+ const minReach = Math.abs(lu - ll) + 1e-3;
+ if (dist < 1e-6) {
+ toTarget = [0, -1, 0];
+ dist = minReach;
+ }
+ dist = Math.min(maxReach, Math.max(minReach, dist));
+ const toDir = vNorm(toTarget);
+
+ // Elbow direction: default down/back/outward from the shoulder.
+ const outSign = side === 'Right' ? -1 : 1;
+ const pole = spec.pole ?? [outSign * 0.42, -1, -0.30];
+ let polePerp = vReject(pole, toDir);
+ if (vLen(polePerp) < 1e-6) polePerp = vReject([0, -1, 0], toDir);
+ polePerp = vNorm(polePerp);
+
+ // Law of cosines: how far along the shoulder→target line the elbow sits.
+ const cosShoulder = Math.min(1, Math.max(-1, (lu * lu + dist * dist - ll * ll) / (2 * lu * dist)));
+ const sinShoulder = Math.sqrt(Math.max(0, 1 - cosShoulder * cosShoulder));
+ const elbow = vAdd(shoulder, vAdd(vScale(toDir, lu * cosShoulder), vScale(polePerp, lu * sinShoulder)));
+
+ const upperDir = vNorm(vSub(elbow, shoulder));
+ const wristPoint = vAdd(shoulder, vScale(toDir, dist));
+ const lowerDir = vNorm(vSub(wristPoint, elbow));
+
+ // The direction the forearm swings toward as the elbow closes — the anterior
+ // side of the arm. Falls back to the pole when the arm is nearly straight.
+ let flexDir = vReject(lowerDir, upperDir);
+ if (vLen(flexDir) < 1e-4) flexDir = vScale(polePerp, -1);
+ flexDir = vNorm(flexDir);
+
+ // On this rest pose (T-pose, palms down) elbow flexion carries the hand
+ // toward the hand's radial side, so that rest direction is the upper arm's
+ // flexion reference. Measured, not assumed.
+ const radialWorld = restRadialWorld(side);
+ const upperRefLocal = vNorm(qRotate(qConj(restWorld(upper)), radialWorld));
+ pose.setWorldQuat(upper, orientQuat(boneAxis(upper), upperRefLocal, upperDir, flexDir));
+
+ // The forearm carries pronation: aim its palm side where the hand's palm is
+ // going, so the wrist holds only the residual.
+ const palmTarget = spec.palm ? vNorm(spec.palm) : null;
+ const lowerRefLocal = vNorm(qRotate(qConj(restWorld(lower)), restPalmWorld(side)));
+ const lowerRefWorld = palmTarget ?? flexDir;
+ pose.setWorldQuat(lower, orientQuat(boneAxis(lower), lowerRefLocal, lowerDir, lowerRefWorld));
+
+ // Hand: fingers down `fingers`, palm facing `palm`. Default carries the
+ // forearm's own direction through, i.e. a straight wrist.
+ const fingersDir = spec.fingers ? vNorm(spec.fingers) : lowerDir;
+ if (palmTarget) {
+ pose.setWorldQuat(hand, orientQuat(boneAxis(hand), palmAxis(hand), fingersDir, palmTarget));
+ } else {
+ pose.aim(hand, fingersDir);
+ }
+ return pose;
+}
+
+/**
+ * Where the wrist actually landed for a solved arm — the reachability check the
+ * tests assert against, since IK clamps targets outside the arm's range.
+ * @param {Pose} pose
+ * @param {'Left'|'Right'} side
+ * @returns {number[]}
+ */
+export function wristPosition(pose, side) {
+ return pose.worldPos(`${side}Hand`);
+}
diff --git a/src/sniper-experiments.css b/src/sniper-experiments.css
index e49891f5d..271bc4733 100644
--- a/src/sniper-experiments.css
+++ b/src/sniper-experiments.css
@@ -108,7 +108,10 @@
}
/* ── conditions cell ─────────────────────────────────────────────────────── */
-.xp-cond { max-width: 300px; color: var(--cv-text-2); font-size: 0.8125rem; }
+/* `width` rather than `max-width`: table auto-layout treats max-width on a cell
+ * as a suggestion it is free to ignore, which is how this column ended up wider
+ * than its own cap. A width acts as the preferred size the algorithm honours. */
+.xp-cond { width: 300px; color: var(--cv-text-2); font-size: 0.8125rem; }
.xp-cond-sub {
margin-top: 3px;
@@ -138,17 +141,33 @@
font-size: 0.6875rem;
font-weight: 600;
color: var(--cv-green);
- white-space: nowrap;
cursor: help;
}
+/* The record cell stacks up to four lines (W/L, open, moon bags, paper). Give it
+ * a floor so none of them overflow into the conditions column beside it. */
+.xp-table td:nth-child(3) { min-width: 130px; }
+
/* ── P&L ─────────────────────────────────────────────────────────────────── */
.xp-pos { color: var(--cv-green); font-weight: 600; }
.xp-neg { color: var(--cv-red); font-weight: 600; }
/* ── table + rows ────────────────────────────────────────────────────────── */
.xp-table { width: 100%; font-size: 0.875rem; }
-.xp-table td { vertical-align: top; padding: 10px 12px; }
+
+/* The shared .cv-table sets `white-space: nowrap` and right-aligns every cell,
+ * which suits a grid of figures but not this board: the first three columns hold
+ * prose that then refuses to wrap and spills across the column beside it. Reset
+ * them to normal flow and re-apply the numeric treatment only where it belongs. */
+.xp-table td {
+ vertical-align: top;
+ padding: 10px 12px;
+ text-align: left;
+ white-space: normal;
+ overflow-wrap: anywhere;
+}
+
+.xp-table th:nth-child(-n + 3) { text-align: left; }
/* The strategy cell carries four stacked lines (label + tier, agent + mode,
* ledger link, wallet + balance). Without a floor it collapses to the width of
@@ -156,8 +175,13 @@
.xp-table th:first-child,
.xp-table td:first-child { min-width: 250px; }
+/* The record cell stacks up to four lines (W/L, open, moon bags, paper). */
+.xp-table td:nth-child(3) { min-width: 140px; }
+
/* Numeric columns read as a column of figures, not ragged text. */
-.xp-table td:nth-child(n + 4) { white-space: nowrap; font-variant-numeric: tabular-nums; }
+.xp-table th:nth-child(n + 4),
+.xp-table td:nth-child(n + 4) { white-space: nowrap; text-align: right; }
+.xp-table td:nth-child(n + 4) { font-variant-numeric: tabular-nums; }
.xp-table tbody tr { transition: background 0.15s ease; }
.xp-table tbody tr:hover { background: var(--cv-surface-2); }
diff --git a/src/sniper-experiments.js b/src/sniper-experiments.js
index 1b0e58b8d..2c9518d7e 100644
--- a/src/sniper-experiments.js
+++ b/src/sniper-experiments.js
@@ -197,7 +197,7 @@ function renderBoard(experiments) {
.map((x) => {
const record = x.closed > 0 ? `${x.wins}W · ${x.losses}L` : 'no fills';
const bags = Number(x.moonbags) > 0
- ? `<div class="xp-moonbag" title="Free moon bags still riding from this arm's winners. Cost basis already recovered, so worth zero at worst.">🌙 ${x.moonbags} moon bag${x.moonbags === 1 ? '' : 's'} · ${Number(x.moonbag_value_sol || 0).toFixed(4)} SOL</div>`
+ ? `<div class="xp-moonbag" title="Free moon bags still riding from this arm's winners. The cost basis already came back, so each one is worth zero at worst and uncapped at best. Not counted as profit until sold.">🌙 ${x.moonbags} bag${x.moonbags === 1 ? '' : 's'} · ${Number(x.moonbag_value_sol || 0).toFixed(4)} SOL</div>`
: '';
const paper = x.paper_closed > 0 || x.paper_open > 0
? `<div class="xp-paper" title="Simulate-mode record: real quotes, no broadcast">paper: ${x.paper_wins}W · ${x.paper_closed - x.paper_wins}L${x.paper_open ? ` · ${x.paper_open} open` : ''} · ${esc(sol(x.paper_pnl_sol))}</div>`
diff --git a/tests/pages-routes.test.js b/tests/pages-routes.test.js
new file mode 100644
index 000000000..ea0bc225f
--- /dev/null
+++ b/tests/pages-routes.test.js
@@ -0,0 +1,83 @@
+// Every static page we advertise must actually be built and routed.
+//
+// data/pages.json is the source of truth for the sitemap, llms.txt, features.json
+// and the changelog — a path listed there is published to search engines and to
+// agents. Twice now a page has landed with a pages.json entry, an HTML source
+// file and a changelog line, but no wiring to serve it (/timeline, /tracker), so
+// the advertised URL 404'd in production while every index claimed it existed.
+//
+// A static page needs both halves to reach a visitor:
+// 1. a Vite rollup input in vite.config.js, or its HTML never lands in dist/
+// 2. a vercel.json route rewriting the clean URL to that HTML file
+//
+// Only paths backed by a pages/<name>.html source are checked. Most declared
+// paths (docs/*, tutorials/*, .well-known/*) are rendered at request time by
+// api/** handlers, so a blanket "every path needs a route" sweep would
+// false-flag them — the same reasoning as scripts/check-dist.mjs.
+
+import { describe, it, expect } from 'vitest';
+import { readFileSync, existsSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const read = (rel) => readFileSync(path.join(ROOT, rel), 'utf8');
+
+const pagesConfig = JSON.parse(read('data/pages.json'));
+const vercelConfig = JSON.parse(read('vercel.json'));
+const viteConfigSource = read('vite.config.js');
+
+const declaredPaths = pagesConfig.sections.flatMap((section) =>
+ (section.pages || []).map((page) => page.path),
+);
+
+// Declared paths whose HTML is authored under pages/ — i.e. pure static build
+// output, the class of page this guard covers.
+const staticPages = declaredPaths
+ .map((pagePath) => ({ pagePath, source: `pages${pagePath.replace(/\/$/, '')}.html` }))
+ .filter(({ source }) => existsSync(path.join(ROOT, source)));
+
+// Rewrites only: routes carrying a status are redirects or the 404 fallback
+// (which rewrites to /404.html and would otherwise "serve" every path).
+const rewrites = vercelConfig.routes.filter(
+ (route) => typeof route.src === 'string' && route.dest && !route.status,
+);
+
+// The dest need not be the page's own filename — /ar renders ar-forge.html and
+// /events/<slug> uses a captured dest — so the rule is that some rewrite claims
+// the path and lands on an HTML document, not on the identity catch-all.
+const hasRoute = (pagePath) =>
+ rewrites.some((route) => route.dest.endsWith('.html') && new RegExp(`^${route.src}$`).test(pagePath));
+
+// A page reaches dist/ either as a rollup input or through one of the verbatim
+// copy plugins (pages/ibm/*). Both name the source file in vite.config.js; a
+// page it never mentions cannot be built at all.
+const isBuilt = (source) => viteConfigSource.includes(source);
+
+describe('data/pages.json static page wiring', () => {
+ it('finds the static pages to check', () => {
+ expect(staticPages.length).toBeGreaterThan(50);
+ });
+
+ it('routes every advertised static page to its HTML', () => {
+ const unrouted = staticPages.filter(({ pagePath }) => !hasRoute(pagePath));
+ expect(
+ unrouted.map((p) => p.pagePath),
+ 'advertised in data/pages.json with no vercel.json route to their HTML',
+ ).toEqual([]);
+ });
+
+ it('builds every advertised static page into dist/', () => {
+ const unbuilt = staticPages.filter(({ source }) => !isBuilt(source));
+ expect(
+ unbuilt.map((p) => p.pagePath),
+ 'advertised in data/pages.json but never emitted into dist/ (missing vite.config.js rollup input)',
+ ).toEqual([]);
+ });
+
+ it('declares each path exactly once', () => {
+ const seen = new Set();
+ const dupes = declaredPaths.filter((p) => (seen.has(p) ? true : (seen.add(p), false)));
+ expect(dupes).toEqual([]);
+ });
+});
diff --git a/workers/agent-sniper/executor.js b/workers/agent-sniper/executor.js
index 25fe6617d..7064ba269 100644
--- a/workers/agent-sniper/executor.js
+++ b/workers/agent-sniper/executor.js
@@ -531,9 +531,9 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {
export async function executeSell({ cfg, position, reason, fraction = 1, recoversInitials = false, keepsMoonbag = false }) {
return withAgentLock(position.agent_id, async () => {
// Laddered exits sell only PART of the bag. Two different partials exist:
- // recoversInitials — the take-initials leg; the position stays OPEN and the
+ // recoversInitials: the take-initials leg; the position stays OPEN and the
// moon bag keeps trading under the exit rules.
- // keepsMoonbag — a terminal exit that still refuses to sell the last
+ // keepsMoonbag: a terminal exit that still refuses to sell the last
// slice; the position CLOSES for accounting (its P&L is
// booked and its concurrency slot is freed) while the
// remaining tokens are retained and ride indefinitely.
@@ -628,7 +628,6 @@ export async function executeSell({ cfg, position, reason, fraction = 1, recover
// remainder keeps its own proportional basis.
const soldCostBasis = partial ? (entryFull * ppm) / 1_000_000n : entryFull;
const legPnl = expectedOut - soldCostBasis;
- const legPnlPct = soldCostBasis > 0n ? (Number(legPnl) / Number(soldCostBasis)) * 100 : 0;
const priorRealized = BigInt(position.realized_pnl_lamports || '0');
const cumRealized = priorRealized + legPnl;