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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(sniper): exit replay engine and exit lab page
nirholas4191f6b31ba6
diff --git a/api/_lib/exit-replay.js b/api/_lib/exit-replay.jsnew file mode 100644index 000000000..4d7fe6d68--- /dev/null+++ b/api/_lib/exit-replay.js@@ -0,0 +1,540 @@+/**+ * Exit Lab — counterfactual replay of REAL closed positions under a different+ * exit policy.+ *+ * What this is, and why it is not the backtester+ * ----------------------------------------------+ * `api/_lib/strategy-backtest.js` answers "would this strategy have entered+ * profitably?" by replaying hypothetical entries over captured launch intel. It+ * models exits with `decideExit`, the single-shot decider, and it never sees a+ * position the fleet actually opened.+ *+ * This module answers the opposite, and much sharper, question: **the fleet+ * already spent this SOL. Were the exits right?** It takes positions that were+ * genuinely entered and closed on-chain and re-runs each one through+ * `decideLadderedExit` — the SAME function the live position loop calls — with a+ * different set of exit parameters, mirroring the live partial-sell bookkeeping+ * leg for leg. Nothing here is synthesized: every input is a recorded price+ * point from a position that cost real money.+ *+ * The price path we actually have+ * -------------------------------+ * A closed position records three honest points and a duration:+ *+ * entry_quote_lamports the SOL spent (cost basis)+ * peak_value_lamports the high-water mark of the bag's quoted SOL value+ * last_value_lamports the bag's quoted value at the moment the exit fired+ * opened_at → closed_at how long it was held+ *+ * The replay walks 1x → peak → terminal. That is a real path, not a synthetic+ * one, but it is truncated at the point the actual policy sold. So:+ *+ * - A counterfactual that exits EARLIER than the live policy did is fully+ * determined by the recorded path. Those results are exact.+ * - A counterfactual that would have HELD LONGER runs out of observations at+ * the terminal price. Its result is a LOWER BOUND, never an upper one.+ *+ * `replayFleet` reports how many trades fall in each bucket so a reader can+ * weigh the answer instead of trusting a single number. Overstating a+ * counterfactual is the whole failure mode of a tool like this, and the bound+ * direction is stated rather than buried.+ *+ * Which positions are replayable+ * ------------------------------+ * A position whose initials were already taken has had its `entry_quote_lamports`+ * scaled down and its `peak_value_lamports` reset to the remaining bag (see the+ * partial-sell branch in workers/agent-sniper/executor.js). Its recorded points+ * are therefore bag-relative and the original price path cannot be recovered.+ * Those positions are EXCLUDED with a stated reason rather than replayed against+ * numbers that no longer mean what they look like.+ *+ * Pure: no I/O, no clock, no Node built-ins. Imported by both the API handler+ * and the browser console at /exit-lab, so the two can never disagree about what+ * a parameter set is worth.+ */++import { decideLadderedExit, moonbagFraction, ladderMultiple, pct } from '../../workers/agent-sniper/exit-logic.js';++export const LAMPORTS_PER_SOL = 1_000_000_000;++/** The live fleet defaults, as shipped in the strategy schema. */+export const DEFAULT_PARAMS = Object.freeze({+ stopLossPct: 35,+ trailingStopPct: 25,+ takeProfitPct: null,+ initialsOutMultiple: 2,+ moonbagMinPct: 15,+});++/**+ * The tunable surface, as data. The console builds its controls from this and+ * the sweep builds its grid from it, so a new knob is added in exactly one place.+ *+ * `nullable: true` means "off" is a legal value and is expressed as null, not 0+ * (see the `pct` contract in exit-logic.js: 0 would fire immediately).+ */+export const PARAM_SPECS = Object.freeze([+ {+ key: 'stopLossPct',+ label: 'Hard stop-loss',+ unit: '%',+ min: 5,+ max: 90,+ step: 5,+ nullable: true,+ help: 'Sell everything once the position is this far below cost. It outranks every other rule, so it is the one number that caps a loss. Off means a losing bag rides to the timeout.',+ },+ {+ key: 'trailingStopPct',+ label: 'Trailing stop',+ unit: '%',+ min: 5,+ max: 90,+ step: 5,+ nullable: true,+ help: 'Sell after the price falls this far from its high-water mark. It only arms once the position has been green, so it protects a gain and never converts a dip into a locked loss.',+ },+ {+ key: 'takeProfitPct',+ label: 'Take-profit ceiling',+ unit: '%',+ min: 25,+ max: 1000,+ step: 25,+ nullable: true,+ help: 'A hard ceiling that closes the remainder once the position is this far up. With the ladder armed it only applies after the initials are already out, so it can never pre-empt the ladder.',+ },+ {+ key: 'initialsOutMultiple',+ label: 'Take initials at',+ unit: 'x',+ min: 1.25,+ max: 10,+ step: 0.25,+ nullable: true,+ help: 'The multiple at which the stake comes back off the table. At 2x that is a half sell; at 5x a fifth. Fires once per position. Off means no ladder and the classic all-or-nothing exit.',+ },+ {+ key: 'moonbagMinPct',+ label: 'Moon-bag floor',+ unit: '%',+ min: 0,+ max: 90,+ step: 5,+ nullable: false,+ help: 'The share of the bag that always keeps riding on a profitable exit. This is why a winner is never fully sold: once the cost is recovered the remainder is free, and a free bag that runs is the whole point.',+ },+]);++const REASONS = Object.freeze([+ 'take_initials',+ 'take_profit',+ 'trailing_stop',+ 'stop_loss',+ 'timeout',+]);++/** Every exit reason the replay can emit, for stable chart ordering. */+export function exitReasons() {+ return REASONS.slice();+}++function num(v) {+ if (v == null || v === '') return null;+ const n = Number(v);+ return Number.isFinite(n) ? n : null;+}++/**+ * Normalize a raw payload into the parameter shape the replay consumes.+ * Out-of-range values are clamped to the spec rather than rejected, so a URL a+ * user hand-edited degrades to the nearest legal policy instead of a stack trace.+ */+export function normalizeParams(raw) {+ const src = raw && typeof raw === 'object' ? raw : {};+ const out = {};+ for (const spec of PARAM_SPECS) {+ const v = num(src[spec.key]);+ if (v == null) {+ out[spec.key] = spec.nullable ? null : DEFAULT_PARAMS[spec.key];+ continue;+ }+ out[spec.key] = Math.min(spec.max, Math.max(spec.min, v));+ }+ return out;+}++/** True when two parameter sets describe the same policy. */+export function sameParams(a, b) {+ const x = normalizeParams(a);+ const y = normalizeParams(b);+ return PARAM_SPECS.every((s) => x[s.key] === y[s.key]);+}++/**+ * Build the position-like object `decideLadderedExit` reads. The field names are+ * the live column names on purpose: this is fed to production code unchanged.+ */+function posLike(params, entryRemaining, recovered) {+ return {+ entry_quote_lamports: String(Math.max(0, Math.round(entryRemaining))),+ stop_loss_pct: params.stopLossPct,+ trailing_stop_pct: params.trailingStopPct,+ take_profit_pct: params.takeProfitPct,+ initials_out_multiple: params.initialsOutMultiple,+ moonbag_min_pct: params.moonbagMinPct,+ initials_recovered: recovered,+ moonbag_always: true,+ max_hold_seconds: null,+ opened_at: 0,+ };+}++// A replay can never produce more legs than this. The ladder fires once and the+// terminal exit closes the walk, so 6 is already generous; the cap exists so a+// pathological parameter set cannot spin.+const MAX_LEGS = 6;++/**+ * Replay one real closed position under an alternative exit policy.+ *+ * @param {{entryLamports: number, peakLamports: number, terminalLamports: number,+ * holdSeconds?: number, actualPnlLamports?: number|null,+ * mint?: string, symbol?: string}} trade+ * @param {object} params exit policy (see PARAM_SPECS)+ * @returns {{ok: boolean, skip?: string, legs: Array, realizedLamports: number,+ * openValueLamports: number, totalLamports: number,+ * pnlLamports: number, pnlPct: number, exitReason: string|null,+ * keptMoonbag: boolean, bounded: boolean}}+ * `bounded` is true when the counterfactual was still holding at the end of the+ * recorded path, i.e. the result is a lower bound on what it could have made.+ */+export function replayPosition(trade, params) {+ const p = normalizeParams(params);+ const entry0 = num(trade?.entryLamports);+ const peakAbs = num(trade?.peakLamports);+ const termAbs = num(trade?.terminalLamports);+ if (!(entry0 > 0)) return skipped('no_entry_basis');+ if (peakAbs == null || termAbs == null) return skipped('no_price_path');++ // The peak is a high-water mark, so it can never be below the terminal price+ // or below cost. A row that says otherwise was written by a sweep that raced+ // the exit; clamp rather than replay a path that never existed.+ const peakMult = Math.max(1, peakAbs / entry0, termAbs / entry0);+ const termMult = Math.max(0, termAbs / entry0);++ const moonbag = moonbagFraction(p.moonbagMinPct);+ const ladder = ladderMultiple(p.initialsOutMultiple);+ const tp = pct(p.takeProfitPct);+ const sl = pct(p.stopLossPct);+ const ts = pct(p.trailingStopPct);++ let bag = 1; // fraction of the originally-bought tokens still held+ let entryRemaining = entry0; // our money still at risk+ let peakRef = entry0; // high-water of the CURRENT bag's value (live semantics)+ let recovered = false;+ let realized = 0;+ let m = 1; // current price multiple relative to the original entry+ const legs = [];++ const valueAt = (mult) => entry0 * mult * bag;++ // Book one sell leg, mirroring the live partial-sell bookkeeping exactly+ // (executor.js: scale the basis by the sold fraction, reset the high-water to+ // the remaining bag, flag initials recovered).+ const sell = (mult, reason, fraction, recoversInitials) => {+ const f = Math.max(0, Math.min(1, fraction));+ if (!(f > 0)) return false;+ const value = valueAt(mult);+ const proceeds = value * f;+ const soldBasis = entryRemaining * f;+ realized += proceeds;+ entryRemaining -= soldBasis;+ bag *= 1 - f;+ if (recoversInitials) recovered = true;+ peakRef = valueAt(mult);+ legs.push({+ atMultiple: round(mult, 4),+ reason,+ sellFraction: round(f, 4),+ proceedsLamports: Math.round(proceeds),+ pnlLamports: Math.round(proceeds - soldBasis),+ });+ return bag <= 1e-9;+ };++ // ── Rising phase: 1x up to the recorded peak. Only take-initials and the+ // take-profit ceiling can fire while price climbs; both are monotone in+ // price, so the next event is whichever triggers at the lower multiple.+ for (let i = 0; i < MAX_LEGS; i += 1) {+ if (bag <= 1e-9) break;+ const candidates = [];+ if (ladder != null && !recovered) candidates.push(triggerMult(entryRemaining * ladder, entry0, bag));+ if (tp != null && (recovered || ladder == null)) {+ candidates.push(triggerMult(entryRemaining * (1 + tp / 100), entry0, bag));+ }+ const next = candidates.filter((c) => c != null && c > m + 1e-12 && c <= peakMult).sort((a, b) => a - b)[0];+ if (next == null) break;+ const decision = decideLadderedExit(posLike(p, entryRemaining, recovered), valueAt(next), Math.max(peakRef, valueAt(next)), 0, null);+ if (!decision) break;+ m = next;+ if (sell(m, decision.reason, decision.sellFraction, decision.recoversInitials === true)) break;+ }++ // The bag rode to the peak; that is its high-water mark for the descent.+ if (bag > 1e-9) {+ peakRef = Math.max(peakRef, valueAt(peakMult));+ m = peakMult;+ }++ // ── Falling phase: peak down to the terminal price. Whichever protective+ // trigger sits HIGHEST is the one hit first on the way down.+ let exitReason = null;+ let keptMoonbag = false;+ let bounded = false;+ if (bag > 1e-9) {+ const down = [];+ if (sl != null) down.push(triggerMult(entryRemaining * (1 - sl / 100), entry0, bag));+ if (ts != null && peakRef > entryRemaining) down.push(triggerMult(peakRef * (1 - ts / 100), entry0, bag));+ const hit = down.filter((c) => c != null && c <= peakMult + 1e-12 && c >= termMult - 1e-12).sort((a, b) => b - a)[0];+ const at = hit == null ? termMult : hit;+ const decision = decideLadderedExit(posLike(p, entryRemaining, recovered), valueAt(at), peakRef, 0, null);+ if (decision) {+ exitReason = decision.reason;+ m = at;+ const emptied = sell(at, decision.reason, decision.sellFraction, decision.recoversInitials === true);+ keptMoonbag = !emptied && bag > 1e-9;+ } else {+ // Nothing fired anywhere on the recorded path: this policy was still+ // holding when the observations ran out.+ exitReason = 'timeout';+ bounded = true;+ m = termMult;+ }+ }++ // Whatever still rides is valued at the last price we actually observed.+ const openValue = bag > 1e-9 ? entry0 * termMult * bag : 0;+ if (bag > 1e-9) bounded = true;++ const total = realized + openValue;+ return {+ ok: true,+ legs,+ realizedLamports: Math.round(realized),+ openValueLamports: Math.round(openValue),+ totalLamports: Math.round(total),+ pnlLamports: Math.round(total - entry0),+ pnlPct: round(((total - entry0) / entry0) * 100, 2),+ exitReason: exitReason ?? (legs.length ? legs[legs.length - 1].reason : null),+ keptMoonbag,+ bounded,+ peakMultiple: round(peakMult, 3),+ terminalMultiple: round(termMult, 3),+ };+}++/** The price multiple at which a bag of `bag` size is worth `targetValue`. */+function triggerMult(targetValue, entry0, bag) {+ if (!(bag > 0) || !(entry0 > 0)) return null;+ const m = targetValue / (entry0 * bag);+ return Number.isFinite(m) ? Math.max(0, m) : null;+}++function skipped(reason) {+ return {+ ok: false,+ skip: reason,+ legs: [],+ realizedLamports: 0,+ openValueLamports: 0,+ totalLamports: 0,+ pnlLamports: 0,+ pnlPct: 0,+ exitReason: null,+ keptMoonbag: false,+ bounded: false,+ };+}++function round(n, places) {+ const f = 10 ** places;+ return Math.round(n * f) / f;+}++/**+ * Replay a whole corpus and aggregate it.+ *+ * @param {Array<object>} trades replayable trades from /api/sniper/exit-lab+ * @param {object} params exit policy+ * @returns {object} aggregate metrics plus the per-trade rows+ */+export function replayFleet(trades, params) {+ const rows = [];+ let staked = 0;+ let total = 0;+ let wins = 0;+ let losses = 0;+ let boundedCount = 0;+ let ridingCount = 0;+ let skipped = 0;+ const byReason = Object.create(null);+ for (const r of REASONS) byReason[r] = { trades: 0, pnlLamports: 0 };++ const list = Array.isArray(trades) ? trades : [];+ for (const t of list) {+ const res = replayPosition(t, params);+ if (!res.ok) {+ skipped += 1;+ continue;+ }+ const entry = Number(t.entryLamports);+ staked += entry;+ total += res.totalLamports;+ if (res.pnlLamports > 0) wins += 1;+ else if (res.pnlLamports < 0) losses += 1;+ if (res.bounded) boundedCount += 1;+ if (res.keptMoonbag) ridingCount += 1;+ if (res.exitReason && byReason[res.exitReason]) {+ byReason[res.exitReason].trades += 1;+ byReason[res.exitReason].pnlLamports += res.pnlLamports;+ }+ rows.push({+ mint: t.mint,+ symbol: t.symbol,+ agentName: t.agentName,+ agentId: t.agentId,+ entryLamports: entry,+ peakMultiple: res.peakMultiple,+ terminalMultiple: res.terminalMultiple,+ actualPnlLamports: t.actualPnlLamports ?? null,+ actualReason: t.actualReason ?? null,+ pnlLamports: res.pnlLamports,+ pnlPct: res.pnlPct,+ exitReason: res.exitReason,+ keptMoonbag: res.keptMoonbag,+ bounded: res.bounded,+ legs: res.legs,+ });+ }++ const counted = rows.length;+ const pnl = total - staked;+ // Equity curve in trade order, for the drawdown read and the sparkline.+ let equity = 0;+ let peak = 0;+ let maxDrawdown = 0;+ const curve = [];+ for (const row of rows) {+ equity += row.pnlLamports;+ curve.push(Math.round(equity));+ if (equity > peak) peak = equity;+ const drop = peak - equity;+ if (drop > maxDrawdown) maxDrawdown = drop;+ }++ // The actual policy's result over the SAME corpus, so the delta is apples to+ // apples. A row whose realized P&L was never booked (an unreconcilable exit)+ // is left out of the actual total rather than counted as zero.+ let actualPnl = 0;+ let actualKnown = 0;+ for (const row of rows) {+ if (row.actualPnlLamports == null) continue;+ actualPnl += Number(row.actualPnlLamports);+ actualKnown += 1;+ }++ return {+ trades: counted,+ skipped,+ wins,+ losses,+ winRate: counted ? round((wins / counted) * 100, 1) : 0,+ stakedLamports: Math.round(staked),+ pnlLamports: Math.round(pnl),+ roiPct: staked > 0 ? round((pnl / staked) * 100, 2) : 0,+ maxDrawdownLamports: Math.round(maxDrawdown),+ boundedTrades: boundedCount,+ ridingTrades: ridingCount,+ byReason,+ curve,+ actual: {+ pnlLamports: Math.round(actualPnl),+ knownTrades: actualKnown,+ roiPct: staked > 0 ? round((actualPnl / staked) * 100, 2) : 0,+ },+ deltaLamports: Math.round(pnl - actualPnl),+ rows,+ };+}++/**+ * Search the parameter space for the policy that would have done best over the+ * recorded corpus, and return the ranked leaders.+ *+ * This is a full grid, not a heuristic: the space is small enough to enumerate+ * exactly, and an exact answer over 200 real trades beats a clever answer nobody+ * can reproduce. The caller supplies the axes, so the console can sweep two+ * knobs finely or all five coarsely without a second implementation.+ *+ * A grid result is an in-sample optimum over the trades that happened. That is+ * a real finding about the fleet's past, not a promise about its future, and+ * `overfitRisk` flags the case where the corpus is too thin to lean on.+ *+ * @param {Array<object>} trades+ * @param {Record<string, Array<number|null>>} axes parameter key → values to try+ * @param {{limit?: number, baseline?: object}} [opts]+ * @returns {{combos: number, leaders: Array, baseline: object, overfitRisk: boolean}}+ */+export function sweepParams(trades, axes, { limit = 8, baseline = DEFAULT_PARAMS } = {}) {+ const keys = Object.keys(axes || {}).filter((k) => PARAM_SPECS.some((s) => s.key === k));+ const grids = keys.map((k) => (Array.isArray(axes[k]) && axes[k].length ? axes[k] : [DEFAULT_PARAMS[k]]));+ const combos = grids.reduce((acc, g) => acc * g.length, 1);++ const base = replayFleet(trades, baseline);+ const results = [];+ const idx = new Array(keys.length).fill(0);+ for (let n = 0; n < combos; n += 1) {+ const params = { ...normalizeParams(baseline) };+ for (let k = 0; k < keys.length; k += 1) params[keys[k]] = grids[k][idx[k]];+ const r = replayFleet(trades, params);+ results.push({+ params,+ pnlLamports: r.pnlLamports,+ roiPct: r.roiPct,+ winRate: r.winRate,+ maxDrawdownLamports: r.maxDrawdownLamports,+ boundedTrades: r.boundedTrades,+ deltaLamports: r.pnlLamports - base.actual.pnlLamports,+ });+ // odometer increment+ for (let k = keys.length - 1; k >= 0; k -= 1) {+ idx[k] += 1;+ if (idx[k] < grids[k].length) break;+ idx[k] = 0;+ }+ }++ results.sort((a, b) => b.pnlLamports - a.pnlLamports || a.maxDrawdownLamports - b.maxDrawdownLamports);+ return {+ combos,+ leaders: results.slice(0, Math.max(1, limit)),+ baseline: {+ params: normalizeParams(baseline),+ pnlLamports: base.pnlLamports,+ roiPct: base.roiPct,+ winRate: base.winRate,+ maxDrawdownLamports: base.maxDrawdownLamports,+ },+ actual: base.actual,+ // Under ~30 closed trades a grid this size will find a flattering corner+ // of noise. Say so rather than let a leader row read as a recommendation.+ overfitRisk: base.trades < 30,+ };+}++/** SOL from lamports, for display. */+export function toSol(lamports) {+ const n = Number(lamports);+ return Number.isFinite(n) ? n / LAMPORTS_PER_SOL : 0;+}diff --git a/api/sniper/exit-lab.js b/api/sniper/exit-lab.jsnew file mode 100644index 000000000..615a289cb--- /dev/null+++ b/api/sniper/exit-lab.js@@ -0,0 +1,165 @@+// @ts-check+/**+ * Exit Lab — the replayable corpus of REAL closed sniper positions.+ *+ * GET /api/sniper/exit-lab?network=mainnet&window=90&limit=400+ *+ * Returns every closed position whose recorded price path can honestly be+ * replayed under a different exit policy, in the compact shape+ * `api/_lib/exit-replay.js` consumes. The browser console at /exit-lab does the+ * replay itself against the same kernel, so moving a slider is instant and the+ * server is not asked to re-derive an answer it has no better claim to.+ *+ * Every row is a position the fleet actually opened with real SOL and closed+ * on-chain: `buy_sig` is present and is not the 'SIMULATED' sentinel, so a paper+ * fill can never enter the corpus. Public + IP rate-limited, exactly like the+ * leaderboard: the tx signatures are the proof, and the point is that anyone can+ * check the fleet's homework.+ *+ * Exclusions are returned, not hidden. A position whose initials were already+ * taken has had its cost basis scaled down and its high-water mark reset by the+ * partial-sell path (workers/agent-sniper/executor.js), so its recorded points+ * are bag-relative and the original path is unrecoverable. Replaying it anyway+ * would produce a confident number computed from figures that no longer mean+ * what they look like. It is dropped with a stated reason and counted, so the+ * console can tell the reader exactly how much of the fleet's history the answer+ * covers.+ */++import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { sql } from '../_lib/db.js';++const NETWORKS = new Set(['mainnet', 'devnet']);+const WINDOWS = new Set(['7', '30', '90', 'all']);+const MAX_LIMIT = 500;+const DEFAULT_LIMIT = 400;++/** Why a closed position could not enter the replay corpus. */+const EXCLUSIONS = {+ laddered: 'Initials were already taken, so the recorded cost basis and high-water mark describe the moon bag, not the original position.',+ no_path: 'No high-water mark or final quote was recorded, so there is no price path to replay.',+ no_basis: 'No entry cost was recorded.',+};++function solscan(sig, network) {+ if (!sig || sig === 'SIMULATED') return null;+ return network === 'devnet' ? `https://solscan.io/tx/${sig}?cluster=devnet` : `https://solscan.io/tx/${sig}`;+}++function numOrNull(v) {+ if (v == null || v === '') return null;+ const n = Number(v);+ return Number.isFinite(n) ? n : null;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.mcpIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const url = new URL(req.url, 'http://localhost');+ const network = NETWORKS.has(url.searchParams.get('network') || '') ? url.searchParams.get('network') : 'mainnet';+ const windowRaw = url.searchParams.get('window') || '90';+ const win = WINDOWS.has(windowRaw) ? windowRaw : '90';+ const limitRaw = Number(url.searchParams.get('limit'));+ const limit = Number.isFinite(limitRaw) ? Math.min(MAX_LIMIT, Math.max(1, Math.floor(limitRaw))) : DEFAULT_LIMIT;++ const start = win === 'all' ? new Date(0) : new Date(Date.now() - Number(win) * 86_400_000);++ let rows = [];+ try {+ rows = await sql`+ SELECT p.mint, p.symbol, p.exit_reason, p.agent_id,+ p.entry_quote_lamports, p.peak_value_lamports, p.last_value_lamports,+ p.exit_quote_lamports, p.realized_pnl_lamports, p.initials_recovered,+ p.opened_at, p.closed_at, p.buy_sig, p.sell_sig,+ a.name AS agent_name+ FROM agent_sniper_positions p+ LEFT JOIN agent_identities a ON a.id = p.agent_id AND a.is_public IS NOT FALSE+ WHERE p.network = ${network}+ AND p.status = 'closed'+ AND p.buy_sig IS NOT NULL+ AND p.buy_sig <> 'SIMULATED'+ AND p.closed_at IS NOT NULL+ AND p.closed_at >= ${start.toISOString()}+ ORDER BY p.closed_at DESC+ LIMIT ${limit}+ `;+ } catch (err) {+ // A read failure is reported as an empty corpus with the reason attached,+ // so the console renders its honest error state instead of a blank page+ // that looks like "the fleet has never traded".+ return json(+ res,+ { ok: false, error: 'corpus_unavailable', detail: err?.message || 'database read failed', network, window: win, trades: [], excluded: [] },+ { 'cache-control': 'no-store' },+ );+ }++ const trades = [];+ const excludedCounts = { laddered: 0, no_path: 0, no_basis: 0 };++ for (const r of rows) {+ const entry = numOrNull(r.entry_quote_lamports);+ if (!(entry > 0)) {+ excludedCounts.no_basis += 1;+ continue;+ }+ if (r.initials_recovered === true) {+ excludedCounts.laddered += 1;+ continue;+ }+ const peak = numOrNull(r.peak_value_lamports);+ // The last live quote is the terminal price. When the sweep never wrote one+ // (an exit that fired on its very first tick), the realized proceeds are the+ // same observation from the other side, so the path is still recoverable.+ const terminal = numOrNull(r.last_value_lamports) ?? numOrNull(r.exit_quote_lamports);+ if (peak == null || terminal == null) {+ excludedCounts.no_path += 1;+ continue;+ }+ const opened = r.opened_at ? new Date(r.opened_at).getTime() : null;+ const closed = r.closed_at ? new Date(r.closed_at).getTime() : null;+ trades.push({+ mint: r.mint,+ symbol: r.symbol || null,+ agentId: r.agent_id,+ agentName: r.agent_name || null,+ entryLamports: entry,+ peakLamports: peak,+ terminalLamports: terminal,+ holdSeconds: opened != null && closed != null ? Math.max(0, Math.round((closed - opened) / 1000)) : null,+ actualPnlLamports: numOrNull(r.realized_pnl_lamports),+ actualReason: r.exit_reason || null,+ closedAt: r.closed_at ?? null,+ buyUrl: solscan(r.buy_sig, network),+ sellUrl: solscan(r.sell_sig, network),+ });+ }++ const excluded = Object.entries(excludedCounts)+ .filter(([, n]) => n > 0)+ .map(([key, n]) => ({ key, count: n, reason: EXCLUSIONS[key] }));++ return json(+ res,+ {+ ok: true,+ network,+ window: win,+ trades,+ // The reader deserves the denominator: how many closed positions the+ // window held, and how many the replay can actually speak to.+ scanned: rows.length,+ replayable: trades.length,+ excluded,+ generatedAt: new Date().toISOString(),+ },+ // The corpus only grows when a position closes; a minute of shared cache+ // absorbs a page reload without ever staling a trade out of view.+ { 'cache-control': 'public, max-age=60' },+ );+});diff --git a/pages/exit-lab.html b/pages/exit-lab.htmlnew file mode 100644index 000000000..679dfbd65--- /dev/null+++ b/pages/exit-lab.html@@ -0,0 +1,185 @@+<!doctype html>+<html lang="en" class="cv-page">+ <head>+ <script>+ /* three.ws theme boot, no-flash; runtime in /theme-switcher.js */ (function () {+ try {+ var m = localStorage.getItem('twx_theme');+ var l =+ m === 'auto'+ ? window.matchMedia &&+ window.matchMedia('(prefers-color-scheme: light)').matches+ : m === 'light';+ document.documentElement.setAttribute('data-theme', l ? 'light' : 'dark');+ } catch (e) {+ document.documentElement.setAttribute('data-theme', 'dark');+ }+ })();+ </script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Exit Lab · three.ws</title>+ <meta+ name="description"+ content="Replay the fleet's real closed trades under a different exit policy. Move the stop-loss, the trailing stop, the take-initials ladder and the moon-bag floor, and see what the fleet would have made on the SOL it already spent. Real positions, real on-chain fills, no synthetic data."+ />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/exit-lab" />+ <meta property="og:title" content="Exit Lab · three.ws" />+ <meta+ property="og:description"+ content="Replay the fleet's real closed trades under a different exit policy and see what the SOL it already spent would have returned."+ />+ <meta+ property="og:image"+ content="https://three.ws/api/page-og?s=crypto&t=Exit+Lab&d=Replay+the+fleet%27s+real+closed+trades+under+a+different+exit+policy.+Real+positions%2C+real+on-chain+fills%2C+no+synthetic+data.&p=%2Fexit-lab"+ />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta property="og:image:alt" content="Exit Lab on three.ws" />+ <meta property="og:locale" content="en_US" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Exit Lab · three.ws" />+ <meta+ name="twitter:description"+ content="Replay the fleet's real closed trades under a different exit policy and see what the SOL it already spent would have returned."+ />+ <meta+ name="twitter:image"+ content="https://three.ws/api/page-og?s=crypto&t=Exit+Lab&d=Replay+the+fleet%27s+real+closed+trades+under+a+different+exit+policy.&p=%2Fexit-lab"+ />+ <meta name="theme-color" content="#09090b" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/manifest.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/coin-pages.css" />+ <link rel="stylesheet" href="/src/exit-lab.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="canonical" href="https://three.ws/exit-lab" />+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <script type="application/ld+json">+ {"@context":"https://schema.org","@graph":[{"@type":"WebApplication","name":"Exit Lab","applicationCategory":"FinanceApplication","operatingSystem":"Any","description":"Replay the three.ws agent fleet's real closed positions under a different exit policy and compare the result against what the fleet actually booked.","url":"https://three.ws/exit-lab","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"offers":{"@type":"Offer","price":"0","priceCurrency":"USD"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://three.ws/"},{"@type":"ListItem","position":2,"name":"Autonomous Trading","item":"https://three.ws/trading"},{"@type":"ListItem","position":3,"name":"Exit Lab","item":"https://three.ws/exit-lab"}]}]}+ </script>+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="cv-container xl-page">+ <nav class="cv-crumbs" aria-label="Breadcrumb">+ <a href="/">Home</a><span class="sep">/</span><a href="/trading">Autonomous Trading</a+ ><span class="sep">/</span><span class="here">Exit Lab</span>+ </nav>++ <section class="xl-hero">+ <div id="xl-corpus-pill" class="xl-pill xl-pill-loading" role="status" aria-live="polite">+ <span class="xl-dot" aria-hidden="true"></span>+ <span class="xl-pill-text">Loading the fleet's closed trades</span>+ </div>+ <h1 class="cv-h1">Exit Lab</h1>+ <p class="cv-sub">+ The fleet already spent this SOL. This replays every real closed position+ through the exact exit code the live worker runs, with the rules changed to+ whatever you choose, and shows what those same trades would have returned.+ Nothing here is simulated: every entry, peak and final price is a recorded+ quote from a position that cost real money and settled on-chain.+ </p>+ </section>++ <!-- The console. Controls are generated from PARAM_SPECS so the knobs, the+ sweep axes and the docs can never drift apart. -->+ <section class="cv-section xl-console" aria-labelledby="xl-console-h">+ <h2 id="xl-console-h" class="xl-h2">Exit policy</h2>+ <div class="xl-console-grid">+ <div class="xl-controls">+ <div class="xl-presets" role="group" aria-label="Policy presets">+ <span class="xl-presets-label">Start from</span>+ <div id="xl-presets" class="xl-preset-row"></div>+ </div>+ <div id="xl-params" class="xl-params"></div>+ <div class="xl-control-actions">+ <button type="button" id="xl-reset" class="xl-btn xl-btn-ghost">+ Reset to the live policy+ </button>+ <button type="button" id="xl-share" class="xl-btn xl-btn-ghost">+ Copy a link to this policy+ </button>+ </div>+ </div>++ <div class="xl-results" id="xl-results" aria-live="polite" aria-busy="true"></div>+ </div>+ </section>++ <!-- Where the money came from and went, by exit reason. -->+ <section class="cv-section" aria-labelledby="xl-reasons-h">+ <h2 id="xl-reasons-h" class="xl-h2">Which rule did the selling</h2>+ <p class="xl-section-sub">+ Every closed trade is attributed to the one rule that fired. A policy that+ books its profit through a single rule is a policy resting on a single+ assumption.+ </p>+ <div id="xl-reasons" class="xl-reasons"></div>+ </section>++ <!-- The grid search. Real work, real progress. -->+ <section class="cv-section" aria-labelledby="xl-sweep-h">+ <div class="xl-section-head">+ <div>+ <h2 id="xl-sweep-h" class="xl-h2">Search for a better policy</h2>+ <p class="xl-section-sub">+ Replays the whole corpus against every combination on a grid and ranks+ the results. This is an exact search over trades that already happened,+ not a prediction: it tells you what the fleet's past would have paid,+ which is the only thing this data can honestly say.+ </p>+ </div>+ <button type="button" id="xl-sweep-run" class="xl-btn xl-btn-primary">+ Run the search+ </button>+ </div>+ <div id="xl-sweep" class="xl-sweep"></div>+ </section>++ <!-- Trade by trade, with the on-chain proof. -->+ <section class="cv-section" aria-labelledby="xl-trades-h">+ <div class="xl-section-head">+ <div>+ <h2 id="xl-trades-h" class="xl-h2">Trade by trade</h2>+ <p class="xl-section-sub">+ The positions where this policy diverges most from what the fleet+ actually did. Every row links to the buy and the sell on Solscan.+ </p>+ </div>+ <div class="xl-trade-sort" role="group" aria-label="Sort trades">+ <button type="button" class="xl-chip is-active" data-sort="divergence">+ Biggest divergence+ </button>+ <button type="button" class="xl-chip" data-sort="best">Best under this policy</button>+ <button type="button" class="xl-chip" data-sort="worst">Worst under this policy</button>+ </div>+ </div>+ <div id="xl-trades" class="xl-trades" aria-busy="true"></div>+ </section>++ <!-- The caveats, in the page rather than in a footnote nobody reads. -->+ <section class="cv-section" aria-labelledby="xl-honesty-h">+ <h2 id="xl-honesty-h" class="xl-h2">What this can and cannot tell you</h2>+ <ul class="xl-honesty" id="xl-honesty"></ul>+ </section>++ <p class="cv-updated" id="xl-updated"></p>+ </main>++ <script type="module" src="/src/exit-lab.js"></script>+ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ <script type="module" src="/i18n.js"></script>+ </body>+</html>diff --git a/src/exit-lab.css b/src/exit-lab.cssnew file mode 100644index 000000000..45f19004d--- /dev/null+++ b/src/exit-lab.css@@ -0,0 +1,935 @@+/* /exit-lab — the counterfactual exit console.+ *+ * Layered on /src/coin-pages.css (.cv-container, .cv-h1, .cv-sub, .cv-section,+ * .cv-crumbs). Everything is namespaced .xl-* so it cannot leak into the shared+ * coin-page surfaces.+ *+ * Colour, spacing, radius and type come from public/tokens.css per+ * docs/DESIGN-TOKENS.md. The only literals are alpha overlays derived from+ * currentColor and geometry with no token (the curve viewbox, grid tracks).+ *+ * --accent is #ffffff in the dark theme, so a primary button MUST take its text+ * colour from --btn-primary-fg with a --color-bg fallback; hardcoding white text+ * on it produced an invisible CTA on the sibling /trading page.+ */++.xl-page {+ --xl-gap: var(--space-5);+}++/* ── hero ─────────────────────────────────────────────────────────────────── */++.xl-hero {+ padding: var(--space-6) 0 var(--space-5);+ border-bottom: 1px solid var(--color-hairline);+ max-width: 72ch;+}++.xl-hero .cv-h1 {+ margin: var(--space-3) 0 var(--space-3);+}++.xl-pill {+ display: inline-flex;+ align-items: center;+ gap: var(--space-2);+ padding: var(--space-1) var(--space-3);+ border-radius: var(--radius-pill);+ border: 1px solid var(--color-border);+ background: var(--color-surface);+ font-family: var(--font-mono);+ font-size: var(--text-2xs);+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: var(--color-text-dim);+}++.xl-dot {+ width: 6px;+ height: 6px;+ border-radius: var(--radius-pill);+ background: currentColor;+ flex: none;+}++.xl-pill-live {+ color: var(--color-success);+ border-color: color-mix(in srgb, var(--color-success) 35%, transparent);+ background: color-mix(in srgb, var(--color-success) 10%, transparent);+}++.xl-pill-down {+ color: var(--color-danger);+ border-color: color-mix(in srgb, var(--color-danger) 35%, transparent);+ background: color-mix(in srgb, var(--color-danger) 10%, transparent);+}++.xl-pill-loading .xl-dot {+ animation: xl-pulse 1.4s var(--ease-standard) infinite;+}++@keyframes xl-pulse {+ 0%,+ 100% {+ opacity: 0.35;+ }+ 50% {+ opacity: 1;+ }+}++/* ── headings ─────────────────────────────────────────────────────────────── */++.xl-h2 {+ font-family: var(--font-display);+ font-size: var(--text-xl);+ font-weight: var(--weight-semibold);+ line-height: var(--leading-tight);+ margin: 0 0 var(--space-2);+ color: var(--color-text-bright);+}++.xl-section-sub {+ margin: 0 0 var(--space-4);+ max-width: 68ch;+ color: var(--color-text-dim);+ font-size: var(--text-ui);+ line-height: var(--leading-normal);+}++.xl-section-head {+ display: flex;+ flex-wrap: wrap;+ align-items: flex-start;+ justify-content: space-between;+ gap: var(--space-4);+ margin-bottom: var(--space-4);+}++.xl-note {+ margin: var(--space-3) 0 0;+ color: var(--color-text-faint);+ font-size: var(--text-md);+ line-height: var(--leading-normal);+}++.xl-warn {+ margin: 0 0 var(--space-4);+ padding: var(--space-3) var(--space-4);+ border-radius: var(--radius-md);+ border: 1px solid color-mix(in srgb, var(--color-warning) 35%, transparent);+ background: color-mix(in srgb, var(--color-warning) 8%, transparent);+ color: var(--color-text);+ font-size: var(--text-md);+ line-height: var(--leading-normal);+}++.xl-sr {+ position: absolute;+ width: 1px;+ height: 1px;+ padding: 0;+ margin: -1px;+ overflow: hidden;+ clip: rect(0, 0, 0, 0);+ white-space: nowrap;+ border: 0;+}++/* ── buttons ──────────────────────────────────────────────────────────────── */++.xl-btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ padding: var(--space-2) var(--space-4);+ border-radius: var(--radius-control);+ border: 1px solid var(--color-border);+ background: transparent;+ color: var(--color-text);+ font-family: var(--font-body);+ font-size: var(--text-ui);+ font-weight: var(--weight-semibold);+ cursor: pointer;+ text-decoration: none;+ transition:+ background-color var(--duration-fast) var(--ease-standard),+ border-color var(--duration-fast) var(--ease-standard),+ transform var(--duration-fast) var(--ease-standard);+}++.xl-btn:hover {+ background: var(--color-surface-2);+ border-color: var(--color-border-strong);+}++.xl-btn:active {+ transform: translateY(1px);+}++.xl-btn:focus-visible {+ outline: var(--focus-ring-width) solid var(--focus-ring-color);+ outline-offset: var(--focus-ring-offset);+}++.xl-btn[disabled] {+ opacity: var(--disabled-opacity);+ cursor: var(--disabled-cursor);+}++.xl-btn-primary {+ background: var(--accent);+ color: var(--btn-primary-fg, var(--color-bg));+ border-color: var(--accent);+}++.xl-btn-primary:hover {+ background: var(--btn-primary-bg-hover, var(--accent-soft, var(--accent)));+ color: var(--btn-primary-fg-hover, var(--color-text-bright));+}++.xl-btn-small {+ padding: var(--space-1) var(--space-3);+ font-size: var(--text-sm);+}++.xl-btn-ghost {+ color: var(--color-text-dim);+ font-weight: var(--weight-medium);+}++.xl-chip {+ padding: var(--space-1) var(--space-3);+ border-radius: var(--radius-pill);+ border: 1px solid var(--color-border);+ background: transparent;+ color: var(--color-text-dim);+ font-family: var(--font-body);+ font-size: var(--text-sm);+ cursor: pointer;+ transition:+ background-color var(--duration-fast) var(--ease-standard),+ color var(--duration-fast) var(--ease-standard),+ border-color var(--duration-fast) var(--ease-standard);+}++.xl-chip:hover {+ color: var(--color-text-bright);+ border-color: var(--color-border-strong);+}++.xl-chip:focus-visible {+ outline: var(--focus-ring-width) solid var(--focus-ring-color);+ outline-offset: var(--focus-ring-offset);+}++.xl-chip.is-active {+ color: var(--color-text-bright);+ border-color: var(--color-border-strong);+ background: var(--color-surface-2);+}++/* ── console layout ───────────────────────────────────────────────────────── */++.xl-console-grid {+ display: grid;+ grid-template-columns: minmax(0, 5fr) minmax(0, 6fr);+ gap: var(--space-6);+ align-items: start;+}++.xl-controls {+ display: flex;+ flex-direction: column;+ gap: var(--space-4);+ padding: var(--space-5);+ border-radius: var(--radius-lg);+ border: 1px solid var(--color-border);+ background: var(--color-surface);+}++.xl-presets-label {+ display: block;+ margin-bottom: var(--space-2);+ color: var(--color-text-faint);+ font-family: var(--font-mono);+ font-size: var(--text-2xs);+ letter-spacing: 0.06em;+ text-transform: uppercase;+}++.xl-preset-row {+ display: flex;+ flex-wrap: wrap;+ gap: var(--space-2);+}++.xl-params {+ display: flex;+ flex-direction: column;+ gap: var(--space-4);+ padding-top: var(--space-4);+ border-top: 1px solid var(--color-hairline);+}++.xl-param-head {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ margin-bottom: var(--space-2);+}++.xl-param-label {+ font-size: var(--text-ui);+ font-weight: var(--weight-medium);+ color: var(--color-text-bright);+ cursor: pointer;+}++.xl-param-value {+ margin-left: auto;+ font-family: var(--font-mono);+ font-size: var(--text-md);+ color: var(--color-text);+ font-variant-numeric: tabular-nums;+}++.xl-param.is-off .xl-param-value {+ color: var(--color-text-faint);+}++.xl-help {+ width: 1.15rem;+ height: 1.15rem;+ flex: none;+ display: inline-grid;+ place-items: center;+ border-radius: var(--radius-pill);+ border: 1px solid var(--color-border);+ background: transparent;+ color: var(--color-text-faint);+ font-size: var(--text-2xs);+ font-weight: var(--weight-bold);+ line-height: 1;+ cursor: pointer;+ transition:+ color var(--duration-fast) var(--ease-standard),+ border-color var(--duration-fast) var(--ease-standard);+}++.xl-help:hover,+.xl-help[aria-expanded='true'] {+ color: var(--color-text-bright);+ border-color: var(--color-border-strong);+}++.xl-help:focus-visible {+ outline: var(--focus-ring-width) solid var(--focus-ring-color);+ outline-offset: var(--focus-ring-offset);+}++.xl-param-row {+ display: flex;+ align-items: center;+ gap: var(--space-3);+}++.xl-range {+ flex: 1 1 auto;+ min-width: 0;+ accent-color: var(--color-accent);+ cursor: pointer;+}++.xl-range:focus-visible {+ outline: var(--focus-ring-width) solid var(--focus-ring-color);+ outline-offset: var(--focus-ring-offset);+}++.xl-range[disabled] {+ opacity: var(--disabled-opacity);+ cursor: var(--disabled-cursor);+}++.xl-toggle {+ display: inline-flex;+ align-items: center;+ gap: var(--space-1);+ flex: none;+ color: var(--color-text-faint);+ font-size: var(--text-sm);+ cursor: pointer;+}++.xl-param-help {+ margin: var(--space-2) 0 0;+ padding: var(--space-2) var(--space-3);+ border-radius: var(--radius-sm);+ background: var(--color-surface-2);+ color: var(--color-text-dim);+ font-size: var(--text-md);+ line-height: var(--leading-normal);+}++.xl-control-actions {+ display: flex;+ flex-wrap: wrap;+ gap: var(--space-2);+ padding-top: var(--space-4);+ border-top: 1px solid var(--color-hairline);+}++/* ── results ──────────────────────────────────────────────────────────────── */++.xl-results {+ display: flex;+ flex-direction: column;+ gap: var(--space-4);+}++.xl-verdict {+ display: flex;+ flex-wrap: wrap;+ align-items: flex-end;+ justify-content: space-between;+ gap: var(--space-4);+ padding: var(--space-5);+ border-radius: var(--radius-lg);+ border: 1px solid var(--color-border);+ background: var(--color-surface);+}++.xl-verdict-up {+ border-color: color-mix(in srgb, var(--color-success) 30%, transparent);+ background: color-mix(in srgb, var(--color-success) 6%, transparent);+}++.xl-verdict-down {+ border-color: color-mix(in srgb, var(--color-danger) 30%, transparent);+ background: color-mix(in srgb, var(--color-danger) 6%, transparent);+}++.xl-verdict-main {+ display: flex;+ flex-direction: column;+ gap: var(--space-1);+ min-width: 0;+}++.xl-verdict-label {+ color: var(--color-text-faint);+ font-family: var(--font-mono);+ font-size: var(--text-2xs);+ letter-spacing: 0.05em;+ text-transform: uppercase;+}++.xl-verdict-value {+ font-family: var(--font-display);+ font-size: var(--text-2xl);+ font-weight: var(--weight-bold);+ line-height: 1.05;+ color: var(--color-text-bright);+ font-variant-numeric: tabular-nums;+}++.xl-verdict-up .xl-verdict-value {+ color: var(--color-success);+}++.xl-verdict-down .xl-verdict-value {+ color: var(--color-danger);+}++.xl-verdict-roi {+ color: var(--color-text-dim);+ font-size: var(--text-md);+ font-variant-numeric: tabular-nums;+}++.xl-verdict-delta {+ display: flex;+ flex-direction: column;+ align-items: flex-end;+ gap: var(--space-1);+ text-align: right;+ max-width: 22ch;+}++.xl-delta-value {+ font-family: var(--font-mono);+ font-size: var(--text-lg);+ font-weight: var(--weight-semibold);+ font-variant-numeric: tabular-nums;+}++.xl-delta-note {+ color: var(--color-text-faint);+ font-size: var(--text-sm);+ line-height: var(--leading-normal);+}++.xl-delta-up {+ color: var(--color-success);+}++.xl-delta-down {+ color: var(--color-danger);+}++.xl-delta-flat {+ color: var(--color-text-dim);+}++/* equity curve */++.xl-curve {+ margin: 0;+ padding: var(--space-4);+ border-radius: var(--radius-lg);+ border: 1px solid var(--color-border);+ background: var(--color-surface);+}++.xl-curve svg {+ display: block;+ width: 100%;+ height: 72px;+}++.xl-curve-zero {+ stroke: var(--color-border-strong);+ stroke-width: 1;+ stroke-dasharray: 3 4;+ vector-effect: non-scaling-stroke;+}++.xl-curve-line {+ fill: none;+ stroke-width: 2;+ stroke-linejoin: round;+ stroke-linecap: round;+ vector-effect: non-scaling-stroke;+ stroke: var(--color-text-dim);+}++.xl-curve-up {+ stroke: var(--color-success);+}++.xl-curve-down {+ stroke: var(--color-danger);+}++.xl-curve figcaption {+ margin-top: var(--space-2);+ color: var(--color-text-faint);+ font-size: var(--text-sm);+}++/* metrics */++.xl-metrics {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(9rem, 1fr));+ gap: var(--space-3);+}++.xl-metric {+ padding: var(--space-4);+ border-radius: var(--radius-md);+ border: 1px solid var(--color-border);+ background: var(--color-surface);+ cursor: help;+}++.xl-metric-label {+ color: var(--color-text-faint);+ font-family: var(--font-mono);+ font-size: var(--text-2xs);+ letter-spacing: 0.05em;+ text-transform: uppercase;+ margin-bottom: var(--space-2);+}++.xl-metric-value {+ font-family: var(--font-display);+ font-size: var(--text-lg);+ font-weight: var(--weight-semibold);+ color: var(--color-text-bright);+ font-variant-numeric: tabular-nums;+}++.xl-metric-sub {+ margin-top: var(--space-1);+ color: var(--color-text-dim);+ font-size: var(--text-sm);+}++.xl-metric-up .xl-metric-value {+ color: var(--color-success);+}++.xl-metric-down .xl-metric-value {+ color: var(--color-danger);+}++.xl-policy-line {+ margin: 0;+ color: var(--color-text-faint);+ font-family: var(--font-mono);+ font-size: var(--text-sm);+ line-height: var(--leading-normal);+ word-break: break-word;+}++/* ── loading / empty / error ──────────────────────────────────────────────── */++.xl-state {+ padding: var(--space-6);+ border-radius: var(--radius-lg);+ border: 1px solid var(--color-border);+ background: var(--color-surface);+}++.xl-state h3 {+ margin: 0 0 var(--space-2);+ font-family: var(--font-display);+ font-size: var(--text-lg);+ color: var(--color-text-bright);+}++.xl-state p {+ margin: 0 0 var(--space-3);+ color: var(--color-text-dim);+ font-size: var(--text-ui);+ line-height: var(--leading-normal);+}++.xl-state-sub {+ color: var(--color-text-faint) !important;+ font-size: var(--text-md) !important;+}++.xl-state-error {+ border-color: color-mix(in srgb, var(--color-danger) 35%, transparent);+ background: color-mix(in srgb, var(--color-danger) 6%, transparent);+}++.xl-skeleton {+ height: 1.25rem;+ border-radius: var(--radius-sm);+ background: linear-gradient(+ 90deg,+ var(--color-surface-2) 25%,+ var(--color-surface) 50%,+ var(--color-surface-2) 75%+ );+ background-size: 200% 100%;+ animation: xl-shimmer 1.6s var(--ease-standard) infinite;+ margin-bottom: var(--space-3);+}++.xl-skeleton-lg {+ height: 4rem;+}++.xl-skeleton-sm {+ height: 0.875rem;+ width: 60%;+ margin-bottom: 0;+}++@keyframes xl-shimmer {+ 0% {+ background-position: 200% 0;+ }+ 100% {+ background-position: -200% 0;+ }+}++/* ── exit reasons ─────────────────────────────────────────────────────────── */++.xl-reasons {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr));+ gap: var(--space-4);+}++.xl-reason {+ padding: var(--space-4);+ border-radius: var(--radius-md);+ border: 1px solid var(--color-border);+ background: var(--color-surface);+}++.xl-reason-head {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: var(--space-2);+ margin-bottom: var(--space-2);+}++.xl-reason-name {+ font-size: var(--text-ui);+ font-weight: var(--weight-medium);+ color: var(--color-text-bright);+}++.xl-reason-count {+ color: var(--color-text-faint);+ font-size: var(--text-sm);+ font-variant-numeric: tabular-nums;+}++.xl-reason-bar {+ height: 6px;+ border-radius: var(--radius-pill);+ background: var(--color-surface-2);+ overflow: hidden;+}++.xl-reason-bar span {+ display: block;+ height: 100%;+ border-radius: var(--radius-pill);+ background: var(--color-text-dim);+ transition: width var(--duration-base) var(--ease-standard);+}++.xl-reason-pnl {+ margin-top: var(--space-2);+ font-family: var(--font-mono);+ font-size: var(--text-md);+ font-variant-numeric: tabular-nums;+}++/* ── sweep ────────────────────────────────────────────────────────────────── */++.xl-progress-bar {+ height: 8px;+ border-radius: var(--radius-pill);+ background: var(--color-surface-2);+ overflow: hidden;+}++.xl-progress-bar span {+ display: block;+ height: 100%;+ border-radius: var(--radius-pill);+ background: var(--color-accent);+ transition: width var(--duration-fast) var(--ease-out);+}++.xl-tag {+ display: inline-block;+ margin: 0 var(--space-1) var(--space-1) 0;+ padding: 2px var(--space-2);+ border-radius: var(--radius-sm);+ background: var(--color-surface-2);+ color: var(--color-text-dim);+ font-size: var(--text-sm);+ white-space: nowrap;+}++.xl-tag b {+ color: var(--color-text-faint);+ font-weight: var(--weight-medium);+}++/* ── tables ───────────────────────────────────────────────────────────────── */++.xl-table-scroll {+ overflow-x: auto;+ border-radius: var(--radius-lg);+ border: 1px solid var(--color-border);+}++.xl-table {+ width: 100%;+ border-collapse: collapse;+ font-size: var(--text-md);+ min-width: 40rem;+}++.xl-table th,+.xl-table td {+ padding: var(--space-3) var(--space-4);+ text-align: left;+ border-bottom: 1px solid var(--color-hairline);+ vertical-align: middle;+}++.xl-table thead th {+ position: sticky;+ top: 0;+ background: var(--color-bg);+ color: var(--color-text-faint);+ font-family: var(--font-mono);+ font-size: var(--text-2xs);+ font-weight: var(--weight-medium);+ letter-spacing: 0.05em;+ text-transform: uppercase;+ white-space: nowrap;+}++.xl-table tbody tr:last-child td {+ border-bottom: 0;+}++.xl-table tbody tr:hover {+ background: var(--color-surface);+}++.xl-table tr.is-current {+ background: var(--color-surface-2);+}++.xl-num {+ text-align: right;+ font-family: var(--font-mono);+ font-variant-numeric: tabular-nums;+ white-space: nowrap;+}++.xl-rank {+ color: var(--color-text-faint);+ font-family: var(--font-mono);+}++.xl-policy {+ min-width: 20rem;+}++.xl-coin {+ display: flex;+ flex-direction: column;+ gap: 2px;+}++.xl-coin-sym {+ font-weight: var(--weight-semibold);+ color: var(--color-text-bright);+}++.xl-coin-agent {+ color: var(--color-text-faint);+ font-size: var(--text-sm);+ text-decoration: none;+}++.xl-coin-agent:hover {+ color: var(--color-text);+ text-decoration: underline;+}++.xl-reason-tag {+ display: inline-block;+ margin-right: var(--space-1);+ padding: 2px var(--space-2);+ border-radius: var(--radius-sm);+ background: var(--color-surface-2);+ color: var(--color-text-dim);+ font-size: var(--text-sm);+ white-space: nowrap;+}++.xl-tag-bag {+ color: var(--color-warning);+ background: color-mix(in srgb, var(--color-warning) 12%, transparent);+}++.xl-proof a {+ margin-right: var(--space-2);+ color: var(--color-text-faint);+ font-size: var(--text-sm);+ text-decoration: none;+ border-bottom: 1px dotted currentColor;+}++.xl-proof a:hover {+ color: var(--color-text-bright);+}++.xl-trade-sort {+ display: flex;+ flex-wrap: wrap;+ gap: var(--space-2);+}++/* ── honesty list ─────────────────────────────────────────────────────────── */++.xl-honesty {+ list-style: none;+ margin: 0;+ padding: 0;+ display: grid;+ gap: var(--space-3);+ max-width: 80ch;+}++.xl-honesty li {+ padding: var(--space-3) var(--space-4);+ border-left: 2px solid var(--color-border-strong);+ color: var(--color-text-dim);+ font-size: var(--text-ui);+ line-height: var(--leading-normal);+}++.xl-honesty b {+ color: var(--color-text-bright);+ font-weight: var(--weight-semibold);+}++.xl-honesty a {+ color: var(--color-text);+}++/* ── responsive ───────────────────────────────────────────────────────────── */++@media (max-width: 900px) {+ .xl-console-grid {+ grid-template-columns: minmax(0, 1fr);+ }+}++@media (max-width: 640px) {+ .xl-verdict {+ flex-direction: column;+ align-items: flex-start;+ }++ .xl-verdict-delta {+ align-items: flex-start;+ text-align: left;+ max-width: none;+ }++ .xl-verdict-value {+ font-size: var(--text-xl);+ }++ .xl-controls {+ padding: var(--space-4);+ }++ .xl-section-head {+ flex-direction: column;+ }+}++@media (prefers-reduced-motion: reduce) {+ .xl-skeleton,+ .xl-pill-loading .xl-dot {+ animation: none;+ }++ .xl-btn,+ .xl-chip,+ .xl-reason-bar span,+ .xl-progress-bar span {+ transition: none;+ }+}diff --git a/src/exit-lab.js b/src/exit-lab.jsnew file mode 100644index 000000000..43cc06c9b--- /dev/null+++ b/src/exit-lab.js@@ -0,0 +1,735 @@+// /exit-lab — counterfactual replay of the fleet's real closed positions.+//+// The corpus comes from /api/sniper/exit-lab (real on-chain closed positions,+// nothing simulated). The replay runs HERE, in the browser, against the same+// pure kernel the server imports, so a slider move is instant and the server is+// never asked to re-derive an answer it has no better claim to than we do.+//+// Everything on this page is computed from that corpus. When the corpus is+// empty the page says so and explains why; it never invents a row to fill a+// layout.++import { escapeHtml as esc } from './shared/coin-format.js';+import {+ PARAM_SPECS,+ DEFAULT_PARAMS,+ normalizeParams,+ sameParams,+ replayFleet,+ sweepParams,+ exitReasons,+ toSol,+} from '../api/_lib/exit-replay.js';++const $ = (id) => document.getElementById(id);+const CORPUS_URL = '/api/sniper/exit-lab?network=mainnet&window=all&limit=500';++/** Named starting points. Each is a real posture, not a decoration. */+const PRESETS = [+ {+ key: 'live',+ label: 'Live fleet policy',+ hint: 'The rules the worker is running right now.',+ params: DEFAULT_PARAMS,+ },+ {+ key: 'tight',+ label: 'Cut losers fast',+ hint: 'A short leash on the downside: exit early and often, keep the drawdown small.',+ params: { stopLossPct: 15, trailingStopPct: 10, takeProfitPct: null, initialsOutMultiple: 2, moonbagMinPct: 15 },+ },+ {+ key: 'ride',+ label: 'Let winners run',+ hint: 'Wide stops and a big moon bag: accept deeper dips to keep the tail.',+ params: { stopLossPct: 50, trailingStopPct: 45, takeProfitPct: null, initialsOutMultiple: 3, moonbagMinPct: 40 },+ },+ {+ key: 'classic',+ label: 'No ladder',+ hint: 'The all-or-nothing exit, with no take-initials and no moon bag.',+ params: { stopLossPct: 35, trailingStopPct: 25, takeProfitPct: 100, initialsOutMultiple: null, moonbagMinPct: 0 },+ },+];++// The grid the search sweeps. Deliberately coarse on the axes that barely move+// the answer and fine on the two that dominate it, so the search stays exact and+// still finishes in well under a second on a phone.+const SWEEP_AXES = {+ stopLossPct: [10, 15, 20, 25, 35, 50, 70, null],+ trailingStopPct: [10, 15, 20, 25, 35, 50, null],+ initialsOutMultiple: [1.5, 2, 3, 5, null],+ moonbagMinPct: [0, 15, 30, 50],+};++const REASON_LABELS = {+ take_initials: 'Take initials',+ take_profit: 'Take-profit ceiling',+ trailing_stop: 'Trailing stop',+ stop_loss: 'Hard stop-loss',+ timeout: 'Held to the end',+};++const state = {+ corpus: null,+ error: null,+ params: normalizeParams(DEFAULT_PARAMS),+ live: null, // replayFleet under the live policy, the comparison baseline+ current: null,+ sweep: null,+ tradeSort: 'divergence',+};++// ── formatting ───────────────────────────────────────────────────────────────++function sol(lamports, { signed = true, places = 4 } = {}) {+ const v = toSol(lamports);+ const sign = signed && v > 0 ? '+' : '';+ return `${sign}${v.toFixed(places)}`;+}++function pctText(n, { signed = true } = {}) {+ if (n == null || !Number.isFinite(Number(n))) return '·';+ const v = Number(n);+ return `${signed && v > 0 ? '+' : ''}${v.toFixed(2)}%`;+}++function toneFor(n) {+ if (!Number.isFinite(Number(n)) || Number(n) === 0) return 'flat';+ return Number(n) > 0 ? 'up' : 'down';+}++function paramText(spec, value) {+ if (value == null) return 'off';+ if (spec.unit === 'x') return `${value}x`;+ return `${value}${spec.unit}`;+}++function policySummary(params) {+ return PARAM_SPECS.map((s) => `${s.label} ${paramText(s, params[s.key])}`).join(' · ');+}++// ── controls ─────────────────────────────────────────────────────────────────++function renderPresets() {+ const el = $('xl-presets');+ if (!el) return;+ el.innerHTML = PRESETS.map(+ (p) => `<button type="button" class="xl-chip${sameParams(p.params, state.params) ? ' is-active' : ''}"+ data-preset="${esc(p.key)}" title="${esc(p.hint)}">${esc(p.label)}</button>`,+ ).join('');+}++function renderControls() {+ const el = $('xl-params');+ if (!el) return;+ el.innerHTML = PARAM_SPECS.map((spec) => {+ const v = state.params[spec.key];+ const off = v == null;+ const slider = off ? spec.min : v;+ const helpId = `xl-help-${spec.key}`;+ return `<div class="xl-param${off ? ' is-off' : ''}" data-param="${esc(spec.key)}">+ <div class="xl-param-head">+ <label class="xl-param-label" for="xl-input-${esc(spec.key)}">${esc(spec.label)}</label>+ <button type="button" class="xl-help" aria-expanded="false" aria-controls="${helpId}"+ aria-label="What does ${esc(spec.label)} do?">?</button>+ <output class="xl-param-value" for="xl-input-${esc(spec.key)}">${esc(paramText(spec, v))}</output>+ </div>+ <div class="xl-param-row">+ <input type="range" id="xl-input-${esc(spec.key)}" class="xl-range"+ min="${spec.min}" max="${spec.max}" step="${spec.step}" value="${slider}"+ aria-label="${esc(spec.label)}"${off ? ' disabled' : ''} />+ ${+ spec.nullable+ ? `<label class="xl-toggle"><input type="checkbox" data-off="${esc(spec.key)}"${off ? ' checked' : ''} /> <span>off</span></label>`+ : ''+ }+ </div>+ <p class="xl-param-help" id="${helpId}" hidden>${esc(spec.help)}</p>+ </div>`;+ }).join('');+}++function bindControls() {+ const el = $('xl-params');+ if (!el) return;+ el.addEventListener('input', (ev) => {+ const range = ev.target.closest('.xl-range');+ if (range) {+ const key = range.id.replace('xl-input-', '');+ state.params = normalizeParams({ ...state.params, [key]: Number(range.value) });+ syncUrl();+ recompute();+ return;+ }+ const off = ev.target.closest('input[data-off]');+ if (off) {+ const key = off.getAttribute('data-off');+ const spec = PARAM_SPECS.find((s) => s.key === key);+ const next = off.checked ? null : Number(document.getElementById(`xl-input-${key}`)?.value ?? spec.min);+ state.params = { ...state.params, [key]: off.checked ? null : normalizeParams({ [key]: next })[key] };+ renderControls();+ syncUrl();+ recompute();+ }+ });+ el.addEventListener('click', (ev) => {+ const help = ev.target.closest('.xl-help');+ if (!help) return;+ const panel = document.getElementById(help.getAttribute('aria-controls'));+ if (!panel) return;+ const open = panel.hidden;+ panel.hidden = !open;+ help.setAttribute('aria-expanded', String(open));+ });++ $('xl-presets')?.addEventListener('click', (ev) => {+ const btn = ev.target.closest('[data-preset]');+ if (!btn) return;+ const preset = PRESETS.find((p) => p.key === btn.getAttribute('data-preset'));+ if (!preset) return;+ applyParams(preset.params);+ });++ $('xl-reset')?.addEventListener('click', () => applyParams(DEFAULT_PARAMS));++ $('xl-share')?.addEventListener('click', async (ev) => {+ const btn = ev.currentTarget;+ syncUrl();+ const before = btn.textContent;+ try {+ await navigator.clipboard.writeText(window.location.href);+ btn.textContent = 'Link copied';+ } catch {+ // Clipboard access can be denied outright; the URL bar already holds the+ // shareable link, so say that rather than fail silently.+ btn.textContent = 'Copy it from the address bar';+ }+ window.setTimeout(() => {+ btn.textContent = before;+ }, 2400);+ });++ $('xl-sweep-run')?.addEventListener('click', runSweep);++ document.querySelector('.xl-trade-sort')?.addEventListener('click', (ev) => {+ const btn = ev.target.closest('[data-sort]');+ if (!btn) return;+ state.tradeSort = btn.getAttribute('data-sort');+ document+ .querySelectorAll('.xl-trade-sort [data-sort]')+ .forEach((b) => b.classList.toggle('is-active', b === btn));+ renderTrades();+ });++ $('xl-sweep')?.addEventListener('click', (ev) => {+ const btn = ev.target.closest('[data-apply]');+ if (!btn) return;+ const idx = Number(btn.getAttribute('data-apply'));+ const leader = state.sweep?.leaders?.[idx];+ if (leader) {+ applyParams(leader.params);+ $('xl-console-h')?.scrollIntoView({ behavior: 'smooth', block: 'start' });+ }+ });+}++function applyParams(params) {+ state.params = normalizeParams(params);+ renderControls();+ renderPresets();+ syncUrl();+ recompute();+}++// ── URL sync, so a finding is linkable ───────────────────────────────────────++function syncUrl() {+ const url = new URL(window.location.href);+ for (const spec of PARAM_SPECS) {+ const v = state.params[spec.key];+ if (v == null) url.searchParams.set(spec.key, 'off');+ else url.searchParams.set(spec.key, String(v));+ }+ window.history.replaceState(null, '', `${url.pathname}${url.search}`);+}++function paramsFromUrl() {+ const url = new URL(window.location.href);+ const out = { ...DEFAULT_PARAMS };+ let touched = false;+ for (const spec of PARAM_SPECS) {+ const raw = url.searchParams.get(spec.key);+ if (raw == null) continue;+ touched = true;+ if (raw === 'off') out[spec.key] = spec.nullable ? null : DEFAULT_PARAMS[spec.key];+ else out[spec.key] = Number(raw);+ }+ return touched ? normalizeParams(out) : null;+}++// ── results ──────────────────────────────────────────────────────────────────++function metric({ label, value, sub, tone, title }) {+ return `<div class="xl-metric${tone ? ` xl-metric-${tone}` : ''}"${title ? ` title="${esc(title)}"` : ''}>+ <div class="xl-metric-label">${esc(label)}</div>+ <div class="xl-metric-value">${esc(value)}</div>+ <div class="xl-metric-sub">${esc(sub)}</div>+ </div>`;+}++/** Equity curve as an SVG path. Empty when there is nothing honest to draw. */+function curvePath(series, w, h) {+ const pts = (Array.isArray(series) ? series : []).filter((n) => Number.isFinite(Number(n))).map(Number);+ if (pts.length < 2) return '';+ const min = Math.min(0, ...pts);+ const max = Math.max(0, ...pts);+ const range = max - min || 1;+ const pad = 3;+ const usable = Math.max(1, h - pad * 2);+ const x = (i) => (i / (pts.length - 1)) * w;+ const y = (v) => pad + usable - ((v - min) / range) * usable;+ return {+ d: pts.map((v, i) => `${i === 0 ? 'M' : 'L'}${x(i).toFixed(2)} ${y(v).toFixed(2)}`).join(' '),+ zero: y(0).toFixed(2),+ };+}++function renderResults() {+ const el = $('xl-results');+ if (!el) return;+ el.removeAttribute('aria-busy');++ if (state.error) {+ el.innerHTML = `<div class="xl-state xl-state-error" role="alert">+ <h3>The trade corpus could not be loaded</h3>+ <p>${esc(state.error)}</p>+ <p class="xl-state-sub">The fleet may still be trading. This page reads closed positions from+ <code>/api/sniper/exit-lab</code>; nothing is cached locally, so there is nothing stale to show instead.</p>+ <button type="button" class="xl-btn xl-btn-primary" id="xl-retry">Try again</button>+ </div>`;+ $('xl-retry')?.addEventListener('click', load);+ return;+ }++ if (!state.corpus) {+ el.innerHTML = `<div class="xl-state xl-state-loading">+ <div class="xl-skeleton xl-skeleton-lg"></div>+ <div class="xl-skeleton"></div>+ <div class="xl-skeleton"></div>+ <div class="xl-skeleton xl-skeleton-sm"></div>+ </div>`;+ return;+ }++ if (!state.current || state.current.trades === 0) {+ el.innerHTML = `<div class="xl-state xl-state-empty">+ <h3>No replayable trades yet</h3>+ <p>The lab needs positions the fleet opened with real SOL and closed on-chain. Once the+ first one settles it appears here, and every slider on this page starts working.</p>+ <p class="xl-state-sub">Watch entries happen live in the+ <a href="/play/arena">agent arena</a>, or read how the fleet decides in the+ <a href="/docs/agent-sniper">sniper docs</a>.</p>+ </div>`;+ return;+ }++ const r = state.current;+ const base = state.live;+ const delta = base ? r.pnlLamports - base.pnlLamports : 0;+ const isLive = sameParams(state.params, DEFAULT_PARAMS);+ const curve = curvePath(r.curve, 320, 72);++ el.innerHTML = `+ <div class="xl-verdict xl-verdict-${toneFor(r.pnlLamports)}">+ <div class="xl-verdict-main">+ <span class="xl-verdict-label">Net result over ${esc(String(r.trades))} real trades</span>+ <span class="xl-verdict-value">${esc(sol(r.pnlLamports))} SOL</span>+ <span class="xl-verdict-roi">${esc(pctText(r.roiPct))} on ${esc(sol(r.stakedLamports, { signed: false, places: 3 }))} SOL staked</span>+ </div>+ <div class="xl-verdict-delta xl-delta-${toneFor(isLive ? 0 : delta)}">+ ${+ isLive+ ? '<span class="xl-delta-note">This is the live fleet policy. Move a slider to compare.</span>'+ : `<span class="xl-delta-value">${esc(sol(delta))} SOL</span>+ <span class="xl-delta-note">versus the live policy over the same trades</span>`+ }+ </div>+ </div>++ ${+ curve+ ? `<figure class="xl-curve">+ <svg viewBox="0 0 320 72" preserveAspectRatio="none" role="img"+ aria-label="Cumulative profit and loss across ${esc(String(r.trades))} replayed trades, ending at ${esc(sol(r.pnlLamports))} SOL">+ <line x1="0" y1="${curve.zero}" x2="320" y2="${curve.zero}" class="xl-curve-zero" />+ <path d="${curve.d}" class="xl-curve-line xl-curve-${toneFor(r.pnlLamports)}" />+ </svg>+ <figcaption>Cumulative P&L, newest trade at the right. The line is the flat zero mark.</figcaption>+ </figure>`+ : ''+ }++ <div class="xl-metrics">+ ${metric({+ label: 'Win rate',+ value: `${r.winRate}%`,+ sub: `${r.wins} up · ${r.losses} down`,+ title: 'Share of replayed positions that finished above their cost basis, counting a moon bag still riding at its last observed price.',+ })}+ ${metric({+ label: 'Max drawdown',+ value: `${sol(r.maxDrawdownLamports, { signed: false })} SOL`,+ sub: 'worst peak-to-trough',+ tone: r.maxDrawdownLamports > 0 ? 'down' : '',+ title: 'The deepest fall of the cumulative P&L curve from a high-water mark. This is the number that decides whether a policy is survivable, not the total.',+ })}+ ${metric({+ label: 'Actually booked',+ value: `${sol(r.actual.pnlLamports)} SOL`,+ sub: `over the same ${r.actual.knownTrades} trades`,+ tone: toneFor(r.actual.pnlLamports),+ title: 'What the fleet really realized on these positions, straight from the ledger. Compare replays to replays: the replay does not model slippage or fees, so it will not reproduce this figure exactly.',+ })}+ ${metric({+ label: 'Still riding',+ value: String(r.ridingTrades),+ sub: 'kept a moon bag',+ title: 'Positions this policy would not have fully sold. Their remaining bag is valued at the last price the fleet observed, never at a guess about what came after.',+ })}+ </div>++ <p class="xl-policy-line">${esc(policySummary(state.params))}</p>+ `;+}++function renderReasons() {+ const el = $('xl-reasons');+ if (!el) return;+ const r = state.current;+ if (!r || r.trades === 0) {+ el.innerHTML = '';+ return;+ }+ const rows = exitReasons()+ .map((key) => ({ key, ...r.byReason[key] }))+ .filter((row) => row.trades > 0);+ if (!rows.length) {+ el.innerHTML = `<p class="xl-note">No rule fired on any trade under this policy: every position ran to the end of its recorded path.</p>`;+ return;+ }+ const maxTrades = Math.max(...rows.map((row) => row.trades));+ el.innerHTML = rows+ .map(+ (row) => `<div class="xl-reason">+ <div class="xl-reason-head">+ <span class="xl-reason-name">${esc(REASON_LABELS[row.key] || row.key)}</span>+ <span class="xl-reason-count">${row.trades} ${row.trades === 1 ? 'trade' : 'trades'}</span>+ </div>+ <div class="xl-reason-bar"><span style="width:${((row.trades / maxTrades) * 100).toFixed(1)}%"></span></div>+ <div class="xl-reason-pnl xl-delta-${toneFor(row.pnlLamports)}">${esc(sol(row.pnlLamports))} SOL</div>+ </div>`,+ )+ .join('');+}++// ── the grid search ──────────────────────────────────────────────────────────++function renderSweepIdle() {+ const el = $('xl-sweep');+ if (!el) return;+ const combos = Object.values(SWEEP_AXES).reduce((acc, g) => acc * g.length, 1);+ const trades = state.current?.trades ?? 0;+ el.innerHTML = `<p class="xl-note">${combos.toLocaleString()} policies against ${trades.toLocaleString()} real+ trades, replayed exactly. Nothing is sampled and nothing is estimated.</p>`;+}++function renderSweepProgress(done, total) {+ const el = $('xl-sweep');+ if (!el) return;+ const pctDone = total ? Math.round((done / total) * 100) : 0;+ el.innerHTML = `<div class="xl-progress" role="progressbar" aria-valuenow="${pctDone}" aria-valuemin="0" aria-valuemax="100"+ aria-label="Policy search progress">+ <div class="xl-progress-bar"><span style="width:${pctDone}%"></span></div>+ <p class="xl-note">${done.toLocaleString()} of ${total.toLocaleString()} policies replayed</p>+ </div>`;+}++function renderSweepResults() {+ const el = $('xl-sweep');+ if (!el || !state.sweep) return;+ const s = state.sweep;+ const rows = s.leaders+ .map((l, i) => {+ const isCurrent = sameParams(l.params, state.params);+ return `<tr${isCurrent ? ' class="is-current"' : ''}>+ <td class="xl-rank">${i + 1}</td>+ <td class="xl-policy">${PARAM_SPECS.map(+ (spec) => `<span class="xl-tag"><b>${esc(spec.label)}</b> ${esc(paramText(spec, l.params[spec.key]))}</span>`,+ ).join('')}</td>+ <td class="xl-num xl-delta-${toneFor(l.pnlLamports)}">${esc(sol(l.pnlLamports))}</td>+ <td class="xl-num">${esc(pctText(l.roiPct))}</td>+ <td class="xl-num">${l.winRate}%</td>+ <td class="xl-num">${esc(sol(l.maxDrawdownLamports, { signed: false }))}</td>+ <td><button type="button" class="xl-btn xl-btn-small" data-apply="${i}">${isCurrent ? 'Applied' : 'Apply'}</button></td>+ </tr>`;+ })+ .join('');++ el.innerHTML = `+ ${+ s.overfitRisk+ ? `<p class="xl-warn" role="note"><b>Too few trades to lean on.</b> With ${state.current?.trades ?? 0}+ closed positions in the corpus, a grid this size will always find a flattering corner of noise.+ Read the leaders as a hypothesis to test, not a setting to ship.</p>`+ : `<p class="xl-note">${s.combos.toLocaleString()} policies replayed exactly against+ ${state.current?.trades ?? 0} real trades. This is an in-sample optimum over trades that already+ happened: it describes the fleet's past, and the past is not a forecast.</p>`+ }+ <div class="xl-table-scroll">+ <table class="xl-table">+ <caption class="xl-sr">Top exit policies by net profit over the replayed corpus</caption>+ <thead><tr>+ <th scope="col">#</th><th scope="col">Policy</th>+ <th scope="col" class="xl-num">Net SOL</th><th scope="col" class="xl-num">ROI</th>+ <th scope="col" class="xl-num">Win</th><th scope="col" class="xl-num">Drawdown</th>+ <th scope="col"><span class="xl-sr">Apply</span></th>+ </tr></thead>+ <tbody>${rows}</tbody>+ </table>+ </div>`;+}++/**+ * Run the grid. The work is real, so the progress is real: the corpus is+ * replayed in slices across animation frames, which keeps the page responsive+ * and lets the bar report actual completed policies rather than a timer.+ */+async function runSweep() {+ if (!state.corpus?.trades?.length) return;+ const btn = $('xl-sweep-run');+ if (btn) {+ btn.disabled = true;+ btn.textContent = 'Searching';+ }++ const keys = Object.keys(SWEEP_AXES);+ const grids = keys.map((k) => SWEEP_AXES[k]);+ const total = grids.reduce((acc, g) => acc * g.length, 1);+ renderSweepProgress(0, total);++ // Slice the grid by its first axis so each frame does a bounded, honest+ // chunk of the same exact search a single sweepParams() call would do.+ const results = [];+ let done = 0;+ for (const first of grids[0]) {+ const slice = { ...SWEEP_AXES, [keys[0]]: [first] };+ const part = sweepParams(state.corpus.trades, slice, { limit: 40, baseline: DEFAULT_PARAMS });+ results.push(...part.leaders);+ done += total / grids[0].length;+ renderSweepProgress(Math.round(done), total);+ await new Promise((resolve) => requestAnimationFrame(() => resolve()));+ }++ results.sort((a, b) => b.pnlLamports - a.pnlLamports || a.maxDrawdownLamports - b.maxDrawdownLamports);+ state.sweep = {+ combos: total,+ leaders: results.slice(0, 8),+ overfitRisk: (state.current?.trades ?? 0) < 30,+ };+ renderSweepResults();+ if (btn) {+ btn.disabled = false;+ btn.textContent = 'Run the search again';+ }+}++// ── trade by trade ───────────────────────────────────────────────────────────++const TRADE_LIMIT = 25;++function renderTrades() {+ const el = $('xl-trades');+ if (!el) return;+ el.removeAttribute('aria-busy');+ const r = state.current;+ if (!r || !r.rows.length) {+ el.innerHTML = '';+ return;+ }+ const meta = new Map((state.corpus?.trades || []).map((t) => [t.mint, t]));+ const rows = r.rows.slice();+ if (state.tradeSort === 'best') rows.sort((a, b) => b.pnlLamports - a.pnlLamports);+ else if (state.tradeSort === 'worst') rows.sort((a, b) => a.pnlLamports - b.pnlLamports);+ else {+ rows.sort(+ (a, b) =>+ Math.abs(b.pnlLamports - (b.actualPnlLamports ?? 0)) -+ Math.abs(a.pnlLamports - (a.actualPnlLamports ?? 0)),+ );+ }++ const body = rows+ .slice(0, TRADE_LIMIT)+ .map((row) => {+ const t = meta.get(row.mint) || {};+ const label = row.symbol || row.mint?.slice(0, 6) || 'coin';+ const diff = row.actualPnlLamports == null ? null : row.pnlLamports - Number(row.actualPnlLamports);+ return `<tr>+ <td class="xl-coin">+ <span class="xl-coin-sym">${esc(String(label).toUpperCase())}</span>+ ${row.agentName ? `<a class="xl-coin-agent" href="/trader/${esc(row.agentId)}">${esc(row.agentName)}</a>` : ''}+ </td>+ <td class="xl-num" title="High-water mark reached, as a multiple of the entry price">${row.peakMultiple}x</td>+ <td class="xl-num xl-delta-${toneFor(row.actualPnlLamports)}">${+ row.actualPnlLamports == null ? '·' : esc(sol(row.actualPnlLamports))+ }</td>+ <td class="xl-num xl-delta-${toneFor(row.pnlLamports)}">${esc(sol(row.pnlLamports))}</td>+ <td class="xl-num xl-delta-${toneFor(diff)}">${diff == null ? '·' : esc(sol(diff))}</td>+ <td><span class="xl-reason-tag">${esc(REASON_LABELS[row.exitReason] || row.exitReason || '·')}</span>${+ row.keptMoonbag ? '<span class="xl-reason-tag xl-tag-bag" title="A moon bag was still riding at the end of the recorded path">bag riding</span>' : ''+ }</td>+ <td class="xl-proof">${+ t.buyUrl+ ? `<a href="${esc(t.buyUrl)}" target="_blank" rel="noopener noreferrer" title="Buy transaction on Solscan">buy</a>`+ : ''+ }${+ t.sellUrl+ ? `<a href="${esc(t.sellUrl)}" target="_blank" rel="noopener noreferrer" title="Sell transaction on Solscan">sell</a>`+ : ''+ }</td>+ </tr>`;+ })+ .join('');++ el.innerHTML = `<div class="xl-table-scroll">+ <table class="xl-table">+ <caption class="xl-sr">Per-trade comparison of the replayed policy against what the fleet actually booked</caption>+ <thead><tr>+ <th scope="col">Coin</th>+ <th scope="col" class="xl-num">Peak</th>+ <th scope="col" class="xl-num">Booked</th>+ <th scope="col" class="xl-num">Replay</th>+ <th scope="col" class="xl-num">Delta</th>+ <th scope="col">Exit</th>+ <th scope="col">On-chain</th>+ </tr></thead>+ <tbody>${body}</tbody>+ </table>+ </div>+ ${+ rows.length > TRADE_LIMIT+ ? `<p class="xl-note">Showing ${TRADE_LIMIT} of ${rows.length} replayed trades, ranked by the sort above.</p>`+ : ''+ }`;+}++// ── the caveats ──────────────────────────────────────────────────────────────++function renderHonesty() {+ const el = $('xl-honesty');+ if (!el) return;+ const c = state.corpus;+ const r = state.current;+ const items = [+ `<b>Every trade is real.</b> The corpus is closed positions with an on-chain buy signature that is not the+ simulate sentinel. Paper fills cannot enter it. ${+ c ? `${c.replayable} of ${c.scanned} closed positions in this window are replayable.` : ''+ }`,+ `<b>Compare replays to replays, not to the ledger.</b> The replay prices an exit at the quote the fleet+ recorded and does not model slippage, priority fees or the spread actually paid. Replaying the live+ policy will therefore not reproduce the booked number, and the gap between two replays is the signal.`,+ `<b>Exiting earlier is exact; holding longer is a floor.</b> The recorded path stops where the real+ policy sold. A counterfactual that would have kept holding is valued at that last observed price, so its+ result is a lower bound and never an upper one.${+ r && r.boundedTrades ? ` ${r.boundedTrades} of ${r.trades} trades are bounded this way under the current policy.` : ''+ }`,+ ];+ for (const ex of c?.excluded || []) {+ items.push(`<b>${ex.count} position${ex.count === 1 ? '' : 's'} excluded.</b> ${esc(ex.reason)}`);+ }+ items.push(+ `<b>An in-sample optimum is not a forecast.</b> The search finds the policy that would have paid best on+ trades that already happened. Read <a href="/docs/exit-lab">the method</a> before changing anything the+ fleet runs on.`,+ );+ el.innerHTML = items.map((html) => `<li>${html}</li>`).join('');+}++// ── corpus pill + updated line ───────────────────────────────────────────────++function renderPill() {+ const el = $('xl-corpus-pill');+ if (!el) return;+ if (state.error) {+ el.className = 'xl-pill xl-pill-down';+ el.innerHTML = '<span class="xl-dot" aria-hidden="true"></span><span class="xl-pill-text">Corpus unavailable</span>';+ return;+ }+ if (!state.corpus) return;+ const n = state.corpus.replayable;+ el.className = n > 0 ? 'xl-pill xl-pill-live' : 'xl-pill xl-pill-muted';+ el.innerHTML = `<span class="xl-dot" aria-hidden="true"></span><span class="xl-pill-text">${+ n > 0 ? `${n} real closed trades loaded` : 'No closed trades yet'+ }</span>`;+}++function renderUpdated() {+ const el = $('xl-updated');+ if (!el || !state.corpus?.generatedAt) return;+ const d = new Date(state.corpus.generatedAt);+ el.textContent = Number.isFinite(d.getTime())+ ? `Corpus read ${d.toLocaleString()} · mainnet · all closed positions`+ : '';+}++// ── wiring ───────────────────────────────────────────────────────────────────++function recompute() {+ if (!state.corpus) return;+ state.current = replayFleet(state.corpus.trades, state.params);+ renderResults();+ renderReasons();+ renderTrades();+ renderHonesty();+ renderPresets();+ if (state.sweep) renderSweepResults();+ else renderSweepIdle();+}++async function load() {+ state.error = null;+ state.corpus = null;+ renderResults();+ try {+ const res = await fetch(CORPUS_URL, { headers: { accept: 'application/json' } });+ const body = await res.json().catch(() => null);+ const data = body?.data ?? body;+ if (!res.ok || !data || data.ok === false) {+ throw new Error(data?.detail || data?.error || `the corpus endpoint returned ${res.status}`);+ }+ state.corpus = data;+ state.live = replayFleet(data.trades, DEFAULT_PARAMS);+ renderPill();+ renderUpdated();+ recompute();+ } catch (err) {+ state.error = err?.message || 'the request failed';+ renderPill();+ renderResults();+ renderHonesty();+ }+}++function init() {+ const fromUrl = paramsFromUrl();+ if (fromUrl) state.params = fromUrl;+ renderPresets();+ renderControls();+ bindControls();+ renderResults();+ load();+}++if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);+else init();diff --git a/tests/exit-lab-page.test.js b/tests/exit-lab-page.test.jsnew file mode 100644index 000000000..96cd1e89a--- /dev/null+++ b/tests/exit-lab-page.test.js@@ -0,0 +1,159 @@+// /exit-lab page wiring.+//+// A page can be built, styled and correct and still be unreachable. These pin+// the connections that have silently broken before: the route table, the vite+// entry, the sitemap record, the nav link, and every href on the page resolving+// to something that actually exists.++import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import { resolve, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';++const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');+const read = (p) => readFileSync(resolve(ROOT, p), 'utf8');++const html = read('pages/exit-lab.html');+const js = read('src/exit-lab.js');+const css = read('src/exit-lab.css');+const vercel = JSON.parse(read('vercel.json'));+const viteConfig = read('vite.config.js');+const pages = JSON.parse(read('data/pages.json'));+const navData = read('public/nav-data.js');++function pagePaths() {+ const out = new Set();+ const walk = (node) => {+ if (Array.isArray(node)) return node.forEach(walk);+ if (!node || typeof node !== 'object') return;+ if (typeof node.path === 'string') out.add(node.path);+ Object.values(node).forEach(walk);+ };+ walk(pages);+ return out;+}++describe('routing', () => {+ it('serves /exit-lab from the route table', () => {+ const route = vercel.routes.find((r) => r.src === '/exit-lab/?');+ expect(route).toBeDefined();+ expect(route.dest).toBe('/exit-lab.html');+ });++ it('routes the corpus endpoint to its handler', () => {+ const route = vercel.routes.find((r) => r.src === '/api/sniper/exit-lab');+ expect(route).toBeDefined();+ expect(route.dest).toBe('/api/sniper/exit-lab.js');+ });++ it('declares the endpoint route before any broader /api/sniper pattern could swallow it', () => {+ // A catch-all placed earlier has silently shadowed documented endpoints in+ // this repo before. Order in the routes array is what decides the winner.+ const idx = vercel.routes.findIndex((r) => r.src === '/api/sniper/exit-lab');+ const shadow = vercel.routes.findIndex(+ (r, i) => i < idx && typeof r.src === 'string' && /^\/api\/sniper\/\(?\.\*|^\/api\/sniper\/\[/.test(r.src),+ );+ expect(shadow).toBe(-1);+ });++ it('is a build entry, so the static HTML is actually emitted', () => {+ expect(viteConfig).toContain("'exit-lab': resolve(__dirname, 'pages/exit-lab.html')");+ });++ it('resolves in the dev server route map', () => {+ expect(viteConfig).toContain("'/exit-lab': resolve(root, 'pages/exit-lab.html')");+ expect(viteConfig).toContain("'/exit-lab/': resolve(root, 'pages/exit-lab.html')");+ });+});++describe('discovery', () => {+ it('is declared in data/pages.json, which feeds the sitemap and llms.txt', () => {+ expect(pagePaths().has('/exit-lab')).toBe(true);+ });++ it('is linked from the site nav', () => {+ expect(navData).toContain("href: '/exit-lab'");+ });++ it('declares a canonical URL and an OG image', () => {+ expect(html).toContain('<link rel="canonical" href="https://three.ws/exit-lab" />');+ expect(html).toContain('og:image');+ });+});++describe('page structure', () => {+ it('mounts every element the hydration script writes into', () => {+ const ids = [...js.matchAll(/\$\('([a-z0-9-]+)'\)/g)].map((m) => m[1]);+ expect(ids.length).toBeGreaterThan(5);+ for (const id of new Set(ids)) {+ // Ids created by the script itself at render time are exempt.+ if (id === 'xl-retry') continue;+ expect(html, `#${id} is written to but not present in the page`).toContain(`id="${id}"`);+ }+ });++ it('loads its own stylesheet and module', () => {+ expect(html).toContain('/src/exit-lab.css');+ expect(html).toContain('/src/exit-lab.js');+ });++ it('every internal href resolves to a declared page or a docs path', () => {+ const hrefs = [...html.matchAll(/href="(\/[^"#]*)"/g), ...js.matchAll(/href="(\/[^"#$]*)"/g)]+ .map((m) => m[1])+ .filter((h) => !h.startsWith('/src/') && !h.startsWith('/api/'));+ const known = pagePaths();+ for (const href of new Set(hrefs)) {+ if (href === '/') continue;+ if (/\.(css|js|ico|svg|png|webmanifest)$/.test(href)) continue;+ const ok = known.has(href) || known.has(href.replace(/\/$/, '')) || href.startsWith('/docs/');+ expect(ok, `${href} is linked from /exit-lab but matches no route`).toBe(true);+ }+ });++ it('keeps the primary button readable against the accent token', () => {+ // --accent is #ffffff in the dark theme, so a hardcoded white foreground+ // renders an invisible CTA. This exact bug shipped on a sibling page.+ expect(css).toContain('--btn-primary-fg');+ expect(css).not.toMatch(/\.xl-btn-primary\s*\{[^}]*color:\s*#fff/i);+ });++ it('designs a loading, an empty and an error state', () => {+ expect(css).toContain('.xl-state-loading');+ expect(css).toContain('.xl-state-empty');+ expect(css).toContain('.xl-state-error');+ expect(js).toContain('xl-state-error');+ expect(js).toContain('xl-state-empty');+ });++ it('respects a reduced-motion preference', () => {+ expect(css).toContain('@media (prefers-reduced-motion: reduce)');+ });++ it('scrolls a wide table inside its own container rather than the page body', () => {+ expect(css).toMatch(/\.xl-table-scroll\s*\{[^}]*overflow-x:\s*auto/);+ });+});++describe('honesty', () => {+ it('ships no sample or seed corpus', () => {+ expect(js).not.toMatch(/const\s+(sample|demo|fake|mock)[A-Za-z]*\s*=\s*\[/i);+ });++ it('reads its corpus from the real endpoint', () => {+ expect(js).toContain('/api/sniper/exit-lab');+ });++ it('states the slippage caveat on the page rather than only in the docs', () => {+ expect(js).toMatch(/slippage/i);+ });++ it('uses no banned dash characters in user-visible copy', () => {+ for (const [name, src] of [+ ['pages/exit-lab.html', html],+ ['src/exit-lab.js', js],+ ['src/exit-lab.css', css],+ ]) {+ expect(src, `${name} contains a banned dash`).not.toMatch(/[\u2014\u2013]/);+ }+ });+});diff --git a/tests/exit-replay.test.js b/tests/exit-replay.test.jsnew file mode 100644index 000000000..428b78934--- /dev/null+++ b/tests/exit-replay.test.js@@ -0,0 +1,284 @@+// Exit Lab replay kernel.+//+// These pin the properties that make the tool trustworthy rather than merely+// plausible: a replay must never invent value the recorded path did not contain,+// a bounded (still-holding) result must be flagged as a lower bound, and a+// laddered policy must never sell the last of a winner.++import { describe, it, expect } from 'vitest';+import {+ replayPosition,+ replayFleet,+ sweepParams,+ normalizeParams,+ sameParams,+ exitReasons,+ toSol,+ PARAM_SPECS,+ DEFAULT_PARAMS,+ LAMPORTS_PER_SOL,+} from '../api/_lib/exit-replay.js';++const SOL = LAMPORTS_PER_SOL;++/** A position that 3x'd and came back to 1.2x. */+const winner = {+ mint: 'THREEsynthetic1111111111111111111111111111',+ symbol: 'WIN',+ entryLamports: 0.02 * SOL,+ peakLamports: 0.06 * SOL,+ terminalLamports: 0.024 * SOL,+ actualPnlLamports: 0.001 * SOL,+ actualReason: 'trailing_stop',+};++/** A position that never went green and bled out. */+const loser = {+ mint: 'THREEsynthetic2222222222222222222222222222',+ symbol: 'LOSS',+ entryLamports: 0.02 * SOL,+ peakLamports: 0.02 * SOL,+ terminalLamports: 0.01 * SOL,+ actualPnlLamports: -0.01 * SOL,+ actualReason: 'timeout',+};++describe('normalizeParams', () => {+ it('clamps an out-of-range value to the spec instead of throwing', () => {+ const p = normalizeParams({ stopLossPct: 9999, moonbagMinPct: -50 });+ const sl = PARAM_SPECS.find((s) => s.key === 'stopLossPct');+ const mb = PARAM_SPECS.find((s) => s.key === 'moonbagMinPct');+ expect(p.stopLossPct).toBe(sl.max);+ expect(p.moonbagMinPct).toBe(mb.min);+ });++ it('reads a missing nullable knob as off, not as zero', () => {+ // Number(null) === 0 and a 0% stop-loss fires immediately, so this+ // distinction is the difference between "no stop" and "sell everything".+ expect(normalizeParams({}).takeProfitPct).toBeNull();+ expect(normalizeParams({}).stopLossPct).toBeNull();+ });++ it('falls back to the live default for a non-nullable knob', () => {+ expect(normalizeParams({}).moonbagMinPct).toBe(DEFAULT_PARAMS.moonbagMinPct);+ });++ it('treats an unparseable value as absent rather than NaN', () => {+ expect(normalizeParams({ stopLossPct: 'banana' }).stopLossPct).toBeNull();+ });++ it('compares policies by value', () => {+ expect(sameParams(DEFAULT_PARAMS, { ...DEFAULT_PARAMS })).toBe(true);+ expect(sameParams(DEFAULT_PARAMS, { ...DEFAULT_PARAMS, stopLossPct: 10 })).toBe(false);+ });+});++describe('replayPosition', () => {+ it('refuses a position with no cost basis instead of returning a zero', () => {+ const r = replayPosition({ entryLamports: 0, peakLamports: 1, terminalLamports: 1 }, DEFAULT_PARAMS);+ expect(r.ok).toBe(false);+ expect(r.skip).toBe('no_entry_basis');+ });++ it('refuses a position with no recorded price path', () => {+ const r = replayPosition({ entryLamports: SOL, peakLamports: null, terminalLamports: null }, DEFAULT_PARAMS);+ expect(r.ok).toBe(false);+ expect(r.skip).toBe('no_price_path');+ });++ it('takes initials at the ladder multiple and keeps a bag riding', () => {+ const r = replayPosition(winner, { ...DEFAULT_PARAMS, initialsOutMultiple: 2, trailingStopPct: null, stopLossPct: null });+ const initials = r.legs.find((l) => l.reason === 'take_initials');+ expect(initials).toBeDefined();+ expect(initials.atMultiple).toBeCloseTo(2, 2);+ // At 2x the ladder sells exactly enough to recover the stake, capped by the+ // moon-bag floor: half the bag.+ expect(initials.sellFraction).toBeCloseTo(0.5, 2);+ expect(r.openValueLamports).toBeGreaterThan(0);+ });++ it('never sells the whole bag of a position that is in profit', () => {+ const r = replayPosition(winner, DEFAULT_PARAMS);+ const sold = r.legs.reduce((acc, l) => acc + l.sellFraction, 0);+ expect(sold).toBeLessThan(2); // two legs can never both be a full exit+ expect(r.openValueLamports).toBeGreaterThan(0);+ });++ it('exits a full loser at the hard stop and books the loss there', () => {+ const r = replayPosition(loser, { ...DEFAULT_PARAMS, stopLossPct: 35 });+ expect(r.exitReason).toBe('stop_loss');+ // A stop on money still at risk is a full exit; nothing may ride.+ expect(r.openValueLamports).toBe(0);+ expect(r.pnlLamports).toBeLessThan(0);+ // The stop fires at 35% down, so the loss is bounded there and is NOT the+ // full drop to the terminal price.+ expect(r.pnlPct).toBeCloseTo(-35, 0);+ });++ it('holds to the end of the recorded path when nothing fires, and says the result is bounded', () => {+ const r = replayPosition(loser, { stopLossPct: null, trailingStopPct: null, takeProfitPct: null, initialsOutMultiple: null, moonbagMinPct: 0 });+ expect(r.bounded).toBe(true);+ expect(r.totalLamports).toBeCloseTo(loser.terminalLamports, 0);+ });++ it('never values a bag above the last price actually observed', () => {+ const r = replayPosition(winner, DEFAULT_PARAMS);+ // Total proceeds can never exceed selling the entire bag at the peak.+ expect(r.totalLamports).toBeLessThanOrEqual(winner.peakLamports + 1);+ });++ it('clamps an incoherent row where the peak sits below the terminal price', () => {+ // A sweep that raced the exit can write a peak under the final quote. The+ // replay clamps rather than walking a path that never existed.+ const r = replayPosition(+ { entryLamports: SOL, peakLamports: 0.5 * SOL, terminalLamports: 3 * SOL },+ DEFAULT_PARAMS,+ );+ expect(r.ok).toBe(true);+ expect(r.peakMultiple).toBeGreaterThanOrEqual(r.terminalMultiple);+ });++ it('is deterministic: the same inputs replay to the same numbers', () => {+ const a = replayPosition(winner, DEFAULT_PARAMS);+ const b = replayPosition(winner, DEFAULT_PARAMS);+ expect(a).toEqual(b);+ });++ it('takes no clock from the environment', () => {+ // max_hold_seconds is deliberately not part of the replay: the recorded+ // path already ends where the real position ended, so a timeout clock would+ // double-count the hold. A policy therefore cannot depend on Date.now().+ const before = replayPosition(winner, DEFAULT_PARAMS);+ const spy = Date.now;+ Date.now = () => 0;+ const after = replayPosition(winner, DEFAULT_PARAMS);+ Date.now = spy;+ expect(after).toEqual(before);+ });+});++describe('replayFleet', () => {+ const corpus = [winner, loser];++ it('aggregates only replayable rows and counts the rest as skipped', () => {+ const r = replayFleet([...corpus, { entryLamports: 0 }], DEFAULT_PARAMS);+ expect(r.trades).toBe(2);+ expect(r.skipped).toBe(1);+ });++ it('reports the actual booked result over the same corpus for comparison', () => {+ const r = replayFleet(corpus, DEFAULT_PARAMS);+ expect(r.actual.knownTrades).toBe(2);+ expect(r.actual.pnlLamports).toBe(winner.actualPnlLamports + loser.actualPnlLamports);+ });++ it('leaves a position with no booked P&L out of the actual total rather than counting it as zero', () => {+ const unknown = { ...winner, mint: 'THREEsynthetic3333333333333333333333333333', actualPnlLamports: null };+ const r = replayFleet([unknown], DEFAULT_PARAMS);+ expect(r.trades).toBe(1);+ expect(r.actual.knownTrades).toBe(0);+ expect(r.actual.pnlLamports).toBe(0);+ });++ it('builds a cumulative curve with one point per trade', () => {+ const r = replayFleet(corpus, DEFAULT_PARAMS);+ expect(r.curve).toHaveLength(2);+ expect(r.curve[1]).toBe(r.pnlLamports);+ });++ it('reports a non-negative drawdown', () => {+ const r = replayFleet(corpus, DEFAULT_PARAMS);+ expect(r.maxDrawdownLamports).toBeGreaterThanOrEqual(0);+ });++ it('attributes every counted trade to a known exit reason', () => {+ const r = replayFleet(corpus, DEFAULT_PARAMS);+ const attributed = Object.values(r.byReason).reduce((acc, v) => acc + v.trades, 0);+ expect(attributed).toBe(r.trades);+ for (const key of Object.keys(r.byReason)) expect(exitReasons()).toContain(key);+ });++ it('returns an honest zero on an empty corpus instead of throwing', () => {+ const r = replayFleet([], DEFAULT_PARAMS);+ expect(r.trades).toBe(0);+ expect(r.pnlLamports).toBe(0);+ expect(r.winRate).toBe(0);+ expect(r.rows).toEqual([]);+ });++ it('tolerates a non-array corpus', () => {+ expect(replayFleet(null, DEFAULT_PARAMS).trades).toBe(0);+ });++ it('a tighter stop can only reduce the loss on a pure loser', () => {+ const wide = replayFleet([loser], { ...DEFAULT_PARAMS, stopLossPct: 70 });+ const tight = replayFleet([loser], { ...DEFAULT_PARAMS, stopLossPct: 15 });+ expect(tight.pnlLamports).toBeGreaterThan(wide.pnlLamports);+ });+});++describe('sweepParams', () => {+ const corpus = [winner, loser];++ it('enumerates the full grid exactly', () => {+ const s = sweepParams(corpus, { stopLossPct: [10, 20, 30], trailingStopPct: [10, 25] }, { limit: 99 });+ expect(s.combos).toBe(6);+ expect(s.leaders).toHaveLength(6);+ });++ it('ranks leaders by profit, best first', () => {+ const s = sweepParams(corpus, { stopLossPct: [10, 20, 30, 50, 70] }, { limit: 5 });+ const pnls = s.leaders.map((l) => l.pnlLamports);+ expect([...pnls].sort((a, b) => b - a)).toEqual(pnls);+ });++ it('flags overfit risk on a corpus too thin to lean on', () => {+ expect(sweepParams(corpus, { stopLossPct: [10, 20] }).overfitRisk).toBe(true);+ });++ it('does not flag overfit risk once the corpus is deep enough', () => {+ const deep = Array.from({ length: 40 }, (_, i) => ({ ...winner, mint: `mint${i}` }));+ expect(sweepParams(deep, { stopLossPct: [10, 20] }).overfitRisk).toBe(false);+ });++ it('ignores an axis that is not a real parameter', () => {+ const s = sweepParams(corpus, { notAKnob: [1, 2, 3] }, { limit: 5 });+ expect(s.combos).toBe(1);+ });++ it('reports the baseline alongside the leaders so a win is measurable', () => {+ const s = sweepParams(corpus, { stopLossPct: [10, 20] });+ expect(s.baseline.params).toEqual(normalizeParams(DEFAULT_PARAMS));+ expect(typeof s.baseline.pnlLamports).toBe('number');+ });+});++describe('PARAM_SPECS', () => {+ it('gives every knob a range, a step and a plain-language explanation', () => {+ for (const spec of PARAM_SPECS) {+ expect(spec.min).toBeLessThan(spec.max);+ expect(spec.step).toBeGreaterThan(0);+ expect(spec.help.length).toBeGreaterThan(40);+ expect(spec.help).not.toMatch(/—|–/); // the repo's dash ban applies to UI copy+ }+ });++ it('has a live default inside its own declared range for every knob', () => {+ for (const spec of PARAM_SPECS) {+ const v = DEFAULT_PARAMS[spec.key];+ if (v == null) {+ expect(spec.nullable).toBe(true);+ continue;+ }+ expect(v).toBeGreaterThanOrEqual(spec.min);+ expect(v).toBeLessThanOrEqual(spec.max);+ }+ });+});++describe('toSol', () => {+ it('converts lamports and degrades a bad input to zero rather than NaN', () => {+ expect(toSol(SOL)).toBe(1);+ expect(toSol('nope')).toBe(0);+ });+});