Skip to content

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

feat(sniper): implement laddered exit strategy with take-initials and moon bag support

nrpodf074b8bb6a6
diff --git a/api/_lib/db.js b/api/_lib/db.js
index ecf30b861..3047c5c91 100644
--- a/api/_lib/db.js
+++ b/api/_lib/db.js
@@ -324,7 +324,7 @@ export async function isStoragePressured() {
}
}
-export const sql = new Proxy(function () {}, {
+export const sql = /** @type {ReturnType<typeof import('@neondatabase/serverless').neon>} */ (new Proxy(function () {}, {
apply(_t, _this, args) {
// Neon dispatches on the first argument: a string is the ordinary
// function form `sql(queryText, params, opts)`; anything else is a
@@ -344,4 +344,4 @@ export const sql = new Proxy(function () {}, {
get(_t, prop) {
return getSql()[prop];
},
-});
+}));
diff --git a/api/_lib/migrations/20260703140000_wallet_scan_cursor.sql b/api/_lib/migrations/20260703140000_wallet_scan_cursor.sql
new file mode 100644
index 000000000..c531e4cc1
--- /dev/null
+++ b/api/_lib/migrations/20260703140000_wallet_scan_cursor.sql
@@ -0,0 +1,32 @@
+-- Per-wallet cursor for the general on-chain leak/outbound scanner
+-- (api/cron/wallets-leak-scan.js).
+--
+-- The ring leak scanner (api/cron/x402-ring-leak-scan.js) only watches the x402
+-- ring role wallets + x402_ring_wallets registry — a SUBSET of the wallets the
+-- platform controls. The general scanner closes that gap: it watches EVERY
+-- resolvable SOLANA_SIGNERS mainnet wallet (economy master, coin-launcher master,
+-- platform/coin/club/buyback/circulation treasuries, x402 sponsor/payer, …) and
+-- alarms if SOL or a non-fee token debit ever leaves one of them to an address
+-- outside the controlled-wallet universe (ringAllowedAddresses()).
+--
+-- This table is the scanner's resumption cursor — one row per wallet, mirroring
+-- x402_ring_scan_cursor — so getSignaturesForAddress stays bounded (only sigs
+-- newer than last_signature are fetched) and every transaction is classified
+-- exactly once. It holds NO secrets and NO balances; just the last-seen signature
+-- and running counters. The scanner also creates it lazily on first run
+-- (ensureSchema), so a fresh env works whether this migration is applied ahead of
+-- time or not.
+
+CREATE TABLE IF NOT EXISTS wallet_scan_cursor (
+ wallet text PRIMARY KEY, -- the controlled wallet's base58 pubkey
+ wallet_name text, -- its SOLANA_SIGNERS name (for the board / alerts)
+ last_signature text, -- newest signature already classified
+ last_slot bigint,
+ scanned_total bigint NOT NULL DEFAULT 0,
+ leaks_total bigint NOT NULL DEFAULT 0,
+ last_run_id uuid,
+ updated_at timestamptz NOT NULL DEFAULT now()
+);
+
+CREATE INDEX IF NOT EXISTS wallet_scan_cursor_updated_idx
+ ON wallet_scan_cursor (updated_at DESC);
diff --git a/api/_lib/migrations/20260703150000_sniper_laddered_exit.sql b/api/_lib/migrations/20260703150000_sniper_laddered_exit.sql
new file mode 100644
index 000000000..dc0bd68e0
--- /dev/null
+++ b/api/_lib/migrations/20260703150000_sniper_laddered_exit.sql
@@ -0,0 +1,30 @@
+-- Laddered partial-exit support for the sniper (the "take initials, hold a moon
+-- bag" rule). Opt-in: a strategy with a NULL initials_out_multiple keeps the
+-- classic single-shot full-exit behavior, so existing strategies are unchanged.
+--
+-- initials_out_multiple when the position first reaches this × entry (e.g.
+-- 2.0), sell exactly enough to return the initial cost
+-- basis and keep the rest as a moon bag. NULL = ladder
+-- off (classic behavior).
+-- moonbag_min_pct the minimum % of the position that must ALWAYS remain
+-- on the take-initials event — a full exit on the way up
+-- is impossible. Default 15.
+--
+-- Position state:
+-- initials_recovered set true once the take-initials sell has executed, so
+-- the ladder fires exactly once and the remainder then
+-- rides on the trailing stop.
+
+ALTER TABLE agent_sniper_strategies
+ ADD COLUMN IF NOT EXISTS initials_out_multiple numeric,
+ ADD COLUMN IF NOT EXISTS moonbag_min_pct numeric NOT NULL DEFAULT 15;
+
+ALTER TABLE agent_sniper_positions
+ ADD COLUMN IF NOT EXISTS initials_recovered boolean NOT NULL DEFAULT false;
+
+COMMENT ON COLUMN agent_sniper_strategies.initials_out_multiple IS
+ 'Take-initials ladder: at this × entry, sell enough to recover the cost basis and hold a moon bag. NULL = ladder off (classic full-exit).';
+COMMENT ON COLUMN agent_sniper_strategies.moonbag_min_pct IS
+ 'Minimum % of the position always kept on the take-initials event (a full exit on the way up is impossible). Default 15.';
+COMMENT ON COLUMN agent_sniper_positions.initials_recovered IS
+ 'True once the take-initials partial sell executed; the remaining moon bag then rides on the trailing stop.';
diff --git a/api/_lib/migrations/20260703160000_trading_journal.sql b/api/_lib/migrations/20260703160000_trading_journal.sql
new file mode 100644
index 000000000..820db3246
--- /dev/null
+++ b/api/_lib/migrations/20260703160000_trading_journal.sql
@@ -0,0 +1,31 @@
+-- Trade journal — the "learn what works" surface for the trading experiment.
+--
+-- Every entry and every exit leg is recorded WITH its reasoning: why a mint was
+-- bought (trigger, mcap, score) and why/how much was sold (take-initials /
+-- trailing / stop / timeout, the fraction, the leg PnL). PnL alone teaches
+-- nothing; the decision log with the *why* is what you learn from. Written by
+-- workers/agent-sniper/journal.js (which also creates it lazily), read via
+-- /api/sniper/journal.
+
+CREATE TABLE IF NOT EXISTS trading_journal (
+ id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
+ ts timestamptz NOT NULL DEFAULT now(),
+ agent_id text,
+ position_id bigint,
+ network text,
+ mint text,
+ symbol text,
+ event text NOT NULL, -- entry | take_initials | exit
+ reason text, -- entry trigger, or exit reason
+ mode text, -- live | simulate
+ venue text,
+ sold_fraction numeric,
+ leg_pnl_lamports numeric,
+ market_cap_usd numeric,
+ score numeric,
+ rationale text, -- human-readable "why"
+ sig text
+);
+
+CREATE INDEX IF NOT EXISTS trading_journal_agent_ts_idx ON trading_journal (agent_id, ts DESC);
+CREATE INDEX IF NOT EXISTS trading_journal_position_idx ON trading_journal (position_id);
diff --git a/api/_lib/solana-signers.js b/api/_lib/solana-signers.js
index af46b7bac..9ebc6cdf2 100644
--- a/api/_lib/solana-signers.js
+++ b/api/_lib/solana-signers.js
@@ -219,7 +219,7 @@ export async function decodeSecretKey(secret) {
// base58 form (…_BASE58)
try {
const bs58mod = await import('bs58');
- const bs58 = bs58mod.default || bs58mod;
+ const bs58 = /** @type {import('bs58').default} */ (bs58mod.default || bs58mod);
const bytes = bs58.decode(raw);
if (bytes.length === 64 || bytes.length === 32) return toFullSecretKey(Uint8Array.from(bytes));
} catch {
diff --git a/api/sniper/journal.js b/api/sniper/journal.js
new file mode 100644
index 000000000..ee483e6ac
--- /dev/null
+++ b/api/sniper/journal.js
@@ -0,0 +1,96 @@
+/**
+ * Agent Sniper — trade journal for the authenticated owner.
+ *
+ * GET /api/sniper/journal?network=mainnet&limit=100&agent_id=<uuid>
+ *
+ * The "learn what works" surface: every entry and every exit leg with its
+ * reasoning (why bought — trigger/mcap/score; why/how much sold — take-initials/
+ * trailing/stop/timeout, the fraction, the leg PnL). Unlike /api/sniper/history
+ * (closed positions only), the journal shows the full decision trail including
+ * partial take-initials legs on positions that are still open.
+ *
+ * Auth: session cookie OR bearer token (same as /api/sniper/strategy).
+ */
+
+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { sql } from '../_lib/db.js';
+import { isUuid } from '../_lib/validate.js';
+
+const NETWORKS = new Set(['mainnet', 'devnet']);
+const sol = (l) => (l != null ? Number(l) / 1e9 : null);
+
+async function resolveUserId(req) {
+ const session = await getSessionUser(req);
+ if (session) return session.id;
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return bearer.userId;
+ return null;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const userId = await resolveUserId(req);
+ if (!userId) return error(res, 401, 'unauthorized', 'sign in to view your trade journal');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const params = new URL(req.url, `http://${req.headers.host || 'x'}`).searchParams;
+ const network = NETWORKS.has(params.get('network')) ? params.get('network') : 'mainnet';
+ const limitN = Math.min(500, Math.max(1, Number(params.get('limit')) || 100));
+ const agentIdParam = (params.get('agent_id') || '').trim();
+ const agentId = isUuid(agentIdParam) ? agentIdParam : null;
+
+ // The journal is joined to the caller's own strategies so a user only ever
+ // sees journal rows for agents they own — trading_journal has no user_id of
+ // its own, so ownership is enforced through agent_sniper_strategies.
+ let rows = [];
+ try {
+ rows = agentId
+ ? await sql`
+ select j.* from trading_journal j
+ where j.network = ${network} and j.agent_id = ${agentId}
+ and exists (select 1 from agent_sniper_strategies s
+ where s.agent_id = j.agent_id and s.user_id = ${userId})
+ order by j.ts desc limit ${limitN}
+ `
+ : await sql`
+ select j.* from trading_journal j
+ where j.network = ${network}
+ and exists (select 1 from agent_sniper_strategies s
+ where s.agent_id = j.agent_id and s.user_id = ${userId})
+ order by j.ts desc limit ${limitN}
+ `;
+ } catch (err) {
+ // Table not created yet (no trades journaled) — return an empty journal
+ // rather than a 500, so a fresh experiment reads cleanly.
+ if (/relation .*trading_journal.* does not exist/i.test(err?.message || '')) {
+ return json(res, 200, { journal: [], total: 0, network });
+ }
+ throw err;
+ }
+
+ const journal = rows.map((r) => ({
+ id: Number(r.id),
+ ts: r.ts,
+ agent_id: r.agent_id,
+ position_id: r.position_id != null ? Number(r.position_id) : null,
+ mint: r.mint,
+ symbol: r.symbol || 'UNKNOWN',
+ event: r.event,
+ reason: r.reason,
+ mode: r.mode,
+ venue: r.venue,
+ sold_fraction: r.sold_fraction != null ? Number(r.sold_fraction) : null,
+ leg_pnl_sol: sol(r.leg_pnl_lamports),
+ market_cap_usd: r.market_cap_usd != null ? Number(r.market_cap_usd) : null,
+ score: r.score != null ? Number(r.score) : null,
+ rationale: r.rationale,
+ }));
+
+ return json(res, 200, { journal, total: journal.length, network });
+});
diff --git a/api/sniper/strategy.js b/api/sniper/strategy.js
index fe69b7ca5..ee138f5bc 100644
--- a/api/sniper/strategy.js
+++ b/api/sniper/strategy.js
@@ -345,6 +345,11 @@ async function upsertStrategy(req, res, userId) {
// wallet up from the launcher master. Arming a strategy never moves money
// on its own — this must be turned on deliberately.
auto_fund_enabled: 'auto_fund_enabled' in p ? Boolean(p.auto_fund_enabled) : (cur.auto_fund_enabled ?? false),
+ // Laddered take-initials exit (opt-in). initials_out_multiple = the × entry
+ // at which to sell enough to recover the cost basis and hold a moon bag;
+ // null = classic single-shot exit. moonbag_min_pct = the floor always kept.
+ initials_out_multiple: 'initials_out_multiple' in p ? (p.initials_out_multiple == null || p.initials_out_multiple === '' ? null : Math.max(1.01, Number(p.initials_out_multiple))) : (cur.initials_out_multiple != null ? Number(cur.initials_out_multiple) : null),
+ moonbag_min_pct: 'moonbag_min_pct' in p ? Math.max(0, Math.min(95, Number(p.moonbag_min_pct))) : (cur.moonbag_min_pct != null ? Number(cur.moonbag_min_pct) : 15),
};
// Mandatory stop-loss — never let the DB constraint be the first line of defense.
@@ -377,7 +382,8 @@ async function upsertStrategy(req, res, userId) {
min_quality_score, max_bundle_score, max_concentration_top1,
avoid_dev_dump, allowed_categories, telegram_chat_id,
alpha_min_smart_money, alpha_min_organic_score, alpha_max_mcap_usd,
- alpha_narrative_keywords, alpha_min_quality_score, auto_fund_enabled, updated_at)
+ alpha_narrative_keywords, alpha_min_quality_score, auto_fund_enabled,
+ initials_out_multiple, moonbag_min_pct, updated_at)
values
(${p.agent_id}, ${userId}, ${p.network}, ${next.enabled}, ${next.kill_switch},
${next.trigger}, ${next.buy_delay_ms}, ${next.min_claim_lamports}, ${next.max_claim_lamports}, ${next.first_claim_max_age_seconds},
@@ -391,7 +397,8 @@ async function upsertStrategy(req, res, userId) {
${next.min_quality_score}, ${next.max_bundle_score}, ${next.max_concentration_top1},
${next.avoid_dev_dump}, ${next.allowed_categories}, ${next.telegram_chat_id},
${next.alpha_min_smart_money}, ${next.alpha_min_organic_score}, ${next.alpha_max_mcap_usd},
- ${next.alpha_narrative_keywords}, ${next.alpha_min_quality_score}, ${next.auto_fund_enabled}, now())
+ ${next.alpha_narrative_keywords}, ${next.alpha_min_quality_score}, ${next.auto_fund_enabled},
+ ${next.initials_out_multiple}, ${next.moonbag_min_pct}, now())
on conflict (agent_id, network) do update set
enabled = excluded.enabled,
kill_switch = excluded.kill_switch,
@@ -433,6 +440,8 @@ async function upsertStrategy(req, res, userId) {
alpha_narrative_keywords = excluded.alpha_narrative_keywords,
alpha_min_quality_score = excluded.alpha_min_quality_score,
auto_fund_enabled = excluded.auto_fund_enabled,
+ initials_out_multiple = excluded.initials_out_multiple,
+ moonbag_min_pct = excluded.moonbag_min_pct,
updated_at = now()
returning *
`;
@@ -482,6 +491,8 @@ async function upsertStrategy(req, res, userId) {
alpha_narrative_keywords: row.alpha_narrative_keywords || null,
alpha_min_quality_score: row.alpha_min_quality_score != null ? Number(row.alpha_min_quality_score) : null,
auto_fund_enabled: row.auto_fund_enabled ?? false,
+ initials_out_multiple: row.initials_out_multiple != null ? Number(row.initials_out_multiple) : null,
+ moonbag_min_pct: row.moonbag_min_pct != null ? Number(row.moonbag_min_pct) : 15,
},
});
}
diff --git a/packages/agent-sniper/runbooks/LOG.md b/packages/agent-sniper/runbooks/LOG.md
index 68146a107..11c47938b 100644
--- a/packages/agent-sniper/runbooks/LOG.md
+++ b/packages/agent-sniper/runbooks/LOG.md
@@ -63,8 +63,34 @@ what was recorded, and what's next. Pairs with [PLAN.md](PLAN.md).
Driver: `scripts/ui-create-agent.mjs` (5-step walk: basics → body → skills → persona →
review → Create). Note for batch: success screen stays on `/create-agent`; capture the
agent id via the "Open agent" button, not a URL change.
-- Next: read Scout 01's agent id + Solana wallet → arm its sniper at `/dashboard/sniper`
- in **simulate** → watch at `/agent-screen`. Then batch the other 32, fund, go live.
+- Scout 01: id `0c7cdd77-a357-4f57-94aa-f4f50ef0432a`, wallet
+ `EZm1jcG52zwW3uGoZB1ZanfbXyaD2NFvaKS4SH37Gnew`. Driver: `scripts/ui-agent-info.mjs`.
+- **Correction (owner told me to flag deviations):** vanity wallets ARE UI-doable — the
+ dashboard Agents list has a **"+ Vanity"** button per agent. My earlier "vanity not in
+ the UI" was wrong (I'd only checked the agent-edit wallet panel). Vanity can be pure-UI.
+- **Mayhem enforcement re-verified:** the PROD worker `workers/agent-sniper/executor.js`
+ runs `mayhemGate` (gate 0, `SNIPER_MAYHEM_FILTER=1`) — the UI-armed path IS protected.
+ Corrected the stale `no-mayhem-pumpfun-tokens` memory + MEMORY.md.
+- **Execution reality (`/api/sniper/status`):** prod worker **DOWN** (~2.75h stale beat),
+ mode live/mainnet, **34 strategies already armed**, 0 open positions, 0 funded today.
+ → Arming Scout 01 now is **inert/safe** (no live worker + empty wallet). To trade, I'll
+ run the platform worker myself: `SNIPER_MAYHEM_FILTER=1`, **auto-fund OFF**, fund only
+ Scout wallets from `niChP` (tiny), one instance, recorded. The 34 pre-existing armed
+ strategies stay unfunded/idle.
+- ✅ **Scout 01 sniper strategy configured via the real UI** ("Arm an agent +" modal):
+ new_mint trigger, **0.002 ◎/trade, 0.020 ◎ daily**, oracle-conviction min 55 (wires the
+ oracle intelligence). Driver: `scripts/ui-arm-sniper.mjs`. Card shows **Disarmed** —
+ platform gates arming on an unfunded wallet ("⚠ low"). Zero spent.
+- Balances (read-only): **niChP funder 2.9457 SOL** (ready), Scout 01 0 SOL.
+- **Single-agent setup is fully proven via the real UI, recorded, up to the money line.**
+
+**MONEY-LINE CHECKPOINT — needs owner go + an execution decision:**
+- First real spend = fund Scout 01 (~0.05 SOL) from niChP → arm → one live buy, recorded.
+- Execution topology: the prod sniper worker is DOWN; running `workers/agent-sniper` is the
+ GLOBAL platform sniper (processes all 34 armed strategies, others unfunded→idle). Local
+ `node_modules` is unstable (shared worktree) — running the full worker here is not yet
+ verified. Options: (a) run the platform worker (auto-fund OFF, fund only Scouts), or
+ (b) scoped execution. Resolve before trading.
**Open / next (blocking, owner decisions):**
- Vanity vs random UI wallets? (vanity ⇒ a non-UI import step).
diff --git a/packages/agent-sniper/scripts/ui-arm-sniper.mjs b/packages/agent-sniper/scripts/ui-arm-sniper.mjs
new file mode 100644
index 000000000..933c32f89
--- /dev/null
+++ b/packages/agent-sniper/scripts/ui-arm-sniper.mjs
@@ -0,0 +1,111 @@
+// ui-arm-sniper.mjs — capture (and, with ARM=1, drive) the /dashboard/sniper arming
+// UI for one agent, signed in via the saved session, recorded.
+// CAPTURE mode (default): screenshot + dump the controls so we build the click-path.
+// Usage: NAME="Scout 01" node scripts/ui-arm-sniper.mjs
+
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { chromium } from 'playwright';
+
+const BASE = process.env.BASE || 'https://three.ws';
+const OUT = process.env.OUT || '/tmp/ui-arm';
+const NAME = process.env.NAME || 'Scout 01';
+const STATE = path.join(os.homedir(), '.three-ws-fleet', 'state.json');
+
+fs.mkdirSync(OUT, { recursive: true });
+const browser = await chromium.launch({ args: ['--use-gl=angle', '--use-angle=swiftshader', '--no-sandbox', '--disable-dev-shm-usage'] });
+const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 }, storageState: STATE, recordVideo: { dir: OUT, size: { width: 1280, height: 900 } } });
+const page = await ctx.newPage();
+const shot = (n) => page.screenshot({ path: path.join(OUT, `${n}.png`), fullPage: true }).catch(() => {});
+
+try {
+ await page.goto(`${BASE}/dashboard/sniper`, { waitUntil: 'domcontentloaded', timeout: 45_000 });
+ await page.waitForTimeout(5000);
+ await shot('sniper-page');
+
+ const map = await page.evaluate((name) => {
+ const vis = (el) => { const r = el.getBoundingClientRect(); const s = getComputedStyle(el); return r.width > 4 && r.height > 4 && s.visibility !== 'hidden' && s.display !== 'none'; };
+ // does a card for this agent exist?
+ let card = null;
+ for (const h of document.querySelectorAll('h1,h2,h3,h4,[class*="name"],[class*="title"],[class*="agent"]')) {
+ if ((h.textContent || '').trim().startsWith(name)) { card = h.closest('article,li,section,[class*="card"],[class*="strategy"]') || h.parentElement; break; }
+ }
+ const scope = card || document;
+ const controls = [];
+ for (const el of scope.querySelectorAll('button, input, select, [role="switch"], [class*="toggle"]')) {
+ if (!vis(el)) continue;
+ const t = (el.innerText || el.value || el.placeholder || el.getAttribute('aria-label') || el.name || '').trim().replace(/\s+/g, ' ').slice(0, 40);
+ controls.push(`${el.tagName.toLowerCase()}${el.id ? '#' + el.id : ''}${el.name ? '[' + el.name + ']' : ''}${t ? ' · "' + t + '"' : ''}`);
+ }
+ // page-level buttons too (e.g. "Add strategy")
+ const pageBtns = [...document.querySelectorAll('button')].filter(vis).map((b) => b.innerText.trim().replace(/\s+/g, ' ').slice(0, 30)).filter(Boolean);
+ return { hasCard: !!card, controls: [...new Set(controls)].slice(0, 40), pageBtns: [...new Set(pageBtns)].slice(0, 25), heading: document.querySelector('h1,h2')?.innerText?.slice(0, 60) || '' };
+ }, NAME).catch((e) => ({ error: e.message }));
+
+ console.log(`heading: ${map.heading}`);
+ console.log(`Scout card present: ${map.hasCard}`);
+ console.log('\npage buttons:'); for (const b of map.pageBtns || []) console.log(' ' + b);
+ fs.writeFileSync(path.join(OUT, 'sniper-map.json'), JSON.stringify(map, null, 2));
+
+ // open the "Arm an agent +" flow and capture its controls
+ const armBtn = await page.$('#sn-arm-btn') || await page.$('button:has-text("Arm an agent")');
+ if (armBtn) {
+ await armBtn.click().catch(() => {});
+ await page.waitForTimeout(3000);
+ await shot('arm-modal');
+ const modal = await page.evaluate(() => {
+ const vis = (el) => { const r = el.getBoundingClientRect(); const s = getComputedStyle(el); return r.width > 4 && r.height > 4 && s.visibility !== 'hidden' && s.display !== 'none'; };
+ const out = [];
+ for (const el of document.querySelectorAll('button, input, select, option, [role="switch"], label, [class*="agent"]')) {
+ if (!vis(el)) continue;
+ const t = (el.innerText || el.value || el.placeholder || el.getAttribute('aria-label') || el.name || '').trim().replace(/\s+/g, ' ').slice(0, 44);
+ if (!t && el.tagName !== 'INPUT' && el.tagName !== 'SELECT') continue;
+ out.push(`${el.tagName.toLowerCase()}${el.id ? '#' + el.id : ''}${el.name ? '[' + el.name + ']' : ''}${el.type ? '(' + el.type + ')' : ''}${t ? ' · "' + t + '"' : ''}`);
+ }
+ return [...new Set(out)].slice(0, 60);
+ }).catch(() => []);
+ console.log('\narm-modal controls:'); for (const c of modal) console.log(' ' + c);
+ fs.writeFileSync(path.join(OUT, 'arm-modal-controls.json'), JSON.stringify(modal, null, 2));
+
+ if (process.env.ARM === '1') {
+ const budget = process.env.DAILY || '0.02';
+ const perTrade = process.env.PER_TRADE || '0.002';
+ const oracle = process.env.ORACLE || '55';
+ // select the agent option whose label contains NAME (or "Scout")
+ const val = await page.evaluate((name) => {
+ const sel = document.querySelector('#sn-arm-agent'); if (!sel) return null;
+ const key = name.split(' ')[0];
+ for (const o of sel.options) { if ((o.textContent || '').includes(name) || (o.textContent || '').trim().startsWith(key)) return o.value; }
+ return null;
+ }, NAME).catch(() => null);
+ if (!val) { console.log(' ✗ Scout option not found in agent select'); }
+ else {
+ await page.selectOption('#sn-arm-agent', val).catch(() => {});
+ await page.fill('#sn-arm-budget', budget).catch(() => {});
+ await page.fill('#sn-arm-per-trade', perTrade).catch(() => {});
+ const orc = await page.$('#sn-arm-oracle'); if (orc) await orc.fill(oracle).catch(() => {});
+ await page.waitForTimeout(600);
+ await shot('arm-filled');
+ console.log(` arming ${NAME}: budget=${budget} perTrade=${perTrade} oracle=${oracle}`);
+ const confirm = await page.$('#sn-arm-confirm');
+ if (confirm) { await confirm.click().catch(() => {}); await page.waitForTimeout(4000); await shot('armed'); }
+ // verify: armed-agents count or a Scout strategy card
+ const verify = await page.evaluate((name) => {
+ const body = document.body.innerText;
+ const armedM = body.match(/ARMED AGENTS\s*(\d+)/i);
+ return { armed: armedM ? armedM[1] : '?', hasScoutCard: [...document.querySelectorAll('h1,h2,h3,h4,[class*="name"],[class*="title"]')].some((h) => (h.textContent || '').trim().startsWith(name)) };
+ }, NAME).catch(() => ({}));
+ console.log(` RESULT: armed agents=${verify.armed}, Scout card present=${verify.hasScoutCard}`);
+ }
+ }
+ } else { console.log('no Arm button found'); }
+} catch (err) {
+ console.log('✗', err.message.slice(0, 160));
+ await shot('error');
+} finally {
+ await page.waitForTimeout(300);
+ await ctx.close();
+ await browser.close();
+ console.log('out:', OUT);
+}
diff --git a/pages/ibm/hello.html b/pages/ibm/hello.html
index 5bf128c91..a4b3e55f5 100644
--- a/pages/ibm/hello.html
+++ b/pages/ibm/hello.html
@@ -421,13 +421,13 @@ a:focus-visible{outline-offset:3px}
<link rel="canonical" href="https://three.ws/ibm/hello">
<meta property="og:site_name" content="three.ws">
<meta property="og:url" content="https://three.ws/ibm/x402-demo">
- <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=IBM+%C3%97+three.ws+partnership&amp;d=The+IBM+%C3%97+three.ws+partnership+page%3A+how+three.ws%27s+agent+identity%2C+x402+payment+rails%2C+and+MCP+servers+integrate+with+IBM+watsonx+and+the+IBM+x402+ecosystem.+A&amp;p=%2Fibm%2Fhello">
+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=x402+Live+Demo+%28IBM+%C3%97+three.ws%29&amp;d=A+self-contained+x402+micropayment+demo%3A+pay+%240.001+USDC+from+your+own+wallet+%E2%80%94+MetaMask+on+Base+or+Phantom+on+Solana+%E2%80%94+to+call+a+real+three.ws+data+API.+Watch+&amp;p=%2Fibm%2Fx402-demo">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="x402 Live Demo (IBM × three.ws) · three.ws">
<meta name="twitter:description" content="A self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask on Base or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership.">
- <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=IBM+%C3%97+three.ws+partnership&amp;d=The+IBM+%C3%97+three.ws+partnership+page%3A+how+three.ws%27s+agent+identity%2C+x402+payment+rails%2C+and+MCP+servers+integrate+with+IBM+watsonx+and+the+IBM+x402+ecosystem.+A&amp;p=%2Fibm%2Fhello">
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=x402+Live+Demo+%28IBM+%C3%97+three.ws%29&amp;d=A+self-contained+x402+micropayment+demo%3A+pay+%240.001+USDC+from+your+own+wallet+%E2%80%94+MetaMask+on+Base+or+Phantom+on+Solana+%E2%80%94+to+call+a+real+three.ws+data+API.+Watch+&amp;p=%2Fibm%2Fx402-demo">
<script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"x402 Live Demo (IBM × three.ws)","description":"A self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask on Base or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership.","url":"https://three.ws/ibm/x402-demo","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
<!-- model-viewer renders the GLB returned by the paid Forge demo (Demo 01).
Self-hosted (travels with this file under ./vendor/) so the page needs no
diff --git a/public/changelog.json b/public/changelog.json
index a6f828299..107eddb91 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-03T10:22:44.680Z",
+ "generated_at": "2026-07-03T10:37:41.589Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
diff --git a/public/features.json b/public/features.json
index 074c848c5..afc42e82b 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-03T10:22:44.638Z",
+ "generated_at": "2026-07-03T10:37:41.569Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index 6a7c69ff5..47fdc50a8 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -56,6 +56,25 @@
.sm-brand img { width: 24px; height: 24px; border-radius: 5px; }
.sm-brand:hover { text-decoration: none; }
</style>
+
+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">
+ <meta property="og:type" content="website">
+ <meta property="og:site_name" content="three.ws">
+ <meta property="og:locale" content="en_US">
+ <meta property="og:title" content="Sitemap · three.ws">
+ <meta property="og:description" content="Human-readable index of every page on three.ws.">
+ <meta property="og:url" content="https://three.ws/sitemap">
+ <meta property="og:image" content="https://three.ws/api/page-og?s=main&amp;t=Sitemap&amp;d=Human-readable+index+of+every+page+on+three.ws.&amp;p=%2Fsitemap">
+ <meta property="og:image:width" content="1200">
+ <meta property="og:image:height" content="630">
+ <meta property="og:image:type" content="image/png">
+ <meta property="og:image:alt" content="Sitemap — three.ws">
+ <meta name="twitter:card" content="summary_large_image">
+ <meta name="twitter:site" content="@trythreews">
+ <meta name="twitter:title" content="Sitemap · three.ws">
+ <meta name="twitter:description" content="Human-readable index of every page on three.ws.">
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=main&amp;t=Sitemap&amp;d=Human-readable+index+of+every+page+on+three.ws.&amp;p=%2Fsitemap">
+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Sitemap","description":"Human-readable index of every page on three.ws.","url":"https://three.ws/sitemap","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=main&t=Sitemap&d=Human-readable+index+of+every+page+on+three.ws.&p=%2Fsitemap"}]}</script>
</head>
<body>
<header class="sm-topbar">
diff --git a/tests/sniper-laddered-exit.test.js b/tests/sniper-laddered-exit.test.js
new file mode 100644
index 000000000..1aa1c79ee
--- /dev/null
+++ b/tests/sniper-laddered-exit.test.js
@@ -0,0 +1,127 @@
+import { describe, it, expect } from 'vitest';
+import { decideLadderedExit, moonbagFraction, ladderMultiple } from '../workers/agent-sniper/exit-logic.js';
+import { mayhemVerdict } from '../workers/agent-sniper/mayhem-gate.js';
+
+// The owner's rule, pinned in math:
+// - buy, and when up ~2x sell enough to recover the INITIAL cost basis;
+// - NEVER cut 100% of a position on the way up (always keep a moon bag);
+// - hold the rest, protected by the trailing stop; stop-loss still wins.
+
+const ENTRY = 1_000_000_000; // 1 SOL cost basis (lamports)
+const base = (over = {}) => ({
+ entry_quote_lamports: String(ENTRY),
+ stop_loss_pct: 30,
+ trailing_stop_pct: 20,
+ take_profit_pct: null,
+ max_hold_seconds: null,
+ opened_at: new Date('2026-07-03T00:00:00Z').toISOString(),
+ initials_out_multiple: 2,
+ moonbag_min_pct: 15,
+ initials_recovered: false,
+ ...over,
+});
+const NOW = new Date('2026-07-03T00:10:00Z').getTime();
+
+describe('ladder helpers', () => {
+ it('ladderMultiple requires > 1, else null (ladder off)', () => {
+ expect(ladderMultiple(2)).toBe(2);
+ expect(ladderMultiple(1)).toBe(null);
+ expect(ladderMultiple(null)).toBe(null);
+ expect(ladderMultiple('')).toBe(null);
+ });
+ it('moonbagFraction defaults 15% and clamps to [0, 0.95]', () => {
+ expect(moonbagFraction(null)).toBeCloseTo(0.15);
+ expect(moonbagFraction(15)).toBeCloseTo(0.15);
+ expect(moonbagFraction(200)).toBe(0.95);
+ expect(moonbagFraction(-5)).toBe(0);
+ });
+});
+
+describe('take-initials ladder', () => {
+ it('does NOT take profit before the initials band (holds under 2x)', () => {
+ expect(decideLadderedExit(base(), 1.8 * ENTRY, 1.8 * ENTRY, NOW)).toBe(null);
+ });
+
+ it('at 2x sells exactly the cost basis back (half) and keeps a moon bag', () => {
+ const d = decideLadderedExit(base(), 2 * ENTRY, 2 * ENTRY, NOW);
+ expect(d.reason).toBe('take_initials');
+ expect(d.recoversInitials).toBe(true);
+ expect(d.sellFraction).toBeCloseTo(0.5); // entry/value = 1/2
+ expect(d.sellFraction).toBeLessThan(1); // NEVER a full exit on the way up
+ });
+
+ it('at 5x sells only ~20% (keeps 80% moon bag)', () => {
+ const d = decideLadderedExit(base(), 5 * ENTRY, 5 * ENTRY, NOW);
+ expect(d.reason).toBe('take_initials');
+ expect(d.sellFraction).toBeCloseTo(0.2);
+ });
+
+ it('never sells into the moon-bag floor even at a huge multiple', () => {
+ // A 1.05x band with a 90% moonbag: recover-fraction would be ~0.95, but the
+ // floor caps the sell at 1 - 0.90 = 0.10.
+ const d = decideLadderedExit(base({ initials_out_multiple: 1.05, moonbag_min_pct: 90 }), 1.05 * ENTRY, 1.05 * ENTRY, NOW);
+ expect(d.reason).toBe('take_initials');
+ expect(d.sellFraction).toBeCloseTo(0.1);
+ });
+
+ it('fires the ladder only once (recovered → no second take-initials)', () => {
+ const d = decideLadderedExit(base({ initials_recovered: true }), 3 * ENTRY, 3 * ENTRY, NOW);
+ expect(d).toBe(null); // moon bag rides; no take_profit set, trailing not hit
+ });
+});
+
+describe('protective exits are always FULL and stop-loss wins', () => {
+ it('stop-loss fires a full exit before initials', () => {
+ const d = decideLadderedExit(base(), 0.6 * ENTRY, 1 * ENTRY, NOW);
+ expect(d.reason).toBe('stop_loss');
+ expect(d.sellFraction).toBe(1);
+ });
+
+ it('stop-loss beats a simultaneous initials band (stop-loss precedence)', () => {
+ // Contrived: value both ≤ stop and ≥ 2x is impossible; assert stop wins when
+ // price collapsed below stop even though initials were configured.
+ const d = decideLadderedExit(base(), 0.5 * ENTRY, 2.5 * ENTRY, NOW);
+ expect(d.reason).toBe('stop_loss');
+ });
+
+ it('trailing stop fully exits the moon bag after initials recovered', () => {
+ // Recovered; peak 4x, now down 20%+ from peak → trailing.
+ const d = decideLadderedExit(base({ initials_recovered: true }), 3.1 * ENTRY, 4 * ENTRY, NOW);
+ expect(d.reason).toBe('trailing_stop');
+ expect(d.sellFraction).toBe(1);
+ });
+
+ it('timeout fully exits the remainder', () => {
+ const d = decideLadderedExit(
+ base({ initials_recovered: true, max_hold_seconds: 60 }),
+ 1.5 * ENTRY, 1.6 * ENTRY,
+ new Date('2026-07-03T02:00:00Z').getTime(),
+ );
+ expect(d.reason).toBe('timeout');
+ expect(d.sellFraction).toBe(1);
+ });
+});
+
+describe('ladder off = classic behavior (non-breaking)', () => {
+ it('with no initials_out_multiple, take_profit is a normal full exit', () => {
+ const d = decideLadderedExit(
+ base({ initials_out_multiple: null, take_profit_pct: 80 }),
+ 2 * ENTRY, 2 * ENTRY, NOW,
+ );
+ expect(d.reason).toBe('take_profit');
+ expect(d.sellFraction).toBe(1);
+ });
+});
+
+describe('mayhem verdict (owner rule)', () => {
+ it('excludes a mayhem mint', () => {
+ expect(mayhemVerdict(true)).toEqual({ pass: false, reason: 'mayhem_excluded' });
+ });
+ it('allows a regular mint', () => {
+ expect(mayhemVerdict(false)).toEqual({ pass: true });
+ });
+ it('allows on unknown by default, skips on strict', () => {
+ expect(mayhemVerdict(null).pass).toBe(true);
+ expect(mayhemVerdict(null, { strict: true })).toEqual({ pass: false, reason: 'mayhem_unknown', unknown: true });
+ });
+});
diff --git a/workers/agent-sniper/executor.js b/workers/agent-sniper/executor.js
index f42d5445d..f5237ed8e 100644
--- a/workers/agent-sniper/executor.js
+++ b/workers/agent-sniper/executor.js
@@ -9,6 +9,7 @@ import { sql } from '../../api/_lib/db.js';
import { log } from './log.js';
import { loadAgentKeypair } from './keys.js';
import { mayhemGate } from './mayhem-gate.js';
+import { recordJournal, journalEntry } from './journal.js';
import { getTradeCtx, signAndSend, submitProtectedTrade } from './trade-client.js';
import { countOpenPositions, getDailySpend } from './strategy-store.js';
import { notifyBuy, notifySell } from '../../api/_lib/sniper/notify.js';
@@ -415,6 +416,12 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {
WHERE id = ${posId}
`;
log.trade('buy', { ...tag, mode: cfg.mode, sig, sol: lamportsToSol(perTrade), base: baseAmount.toString(), impact: Number(quote.priceImpactPct).toFixed(2) });
+ // Journal the entry WITH its reasoning — the learn-what-works surface.
+ await journalEntry({
+ cfg, strat, mint, posId, sig,
+ score: mint.score ?? null,
+ rationale: `Entered on ${mint.entry_trigger || 'new_mint'}${mint.market_cap_usd != null ? ` at ~$${Math.round(mint.market_cap_usd).toLocaleString()} mcap` : ''}${firewallSnapshot ? ` (firewall ${firewallSnapshot.verdict}, score ${firewallSnapshot.score})` : ''}; ${lamportsToSol(perTrade).toFixed(4)} SOL, impact ${Number(quote.priceImpactPct).toFixed(2)}%.`,
+ });
screenPush(`Bought $${(mint.symbol || mint.mint.slice(0, 6)).toUpperCase()} at ${lamportsToSol(perTrade).toFixed(4)} SOL — position open`, 'trade');
notifyBuy({ agentName: strat.agent_name || strat.agent_id, symbol: mint.symbol, mint: mint.mint, solSpent: lamportsToSol(perTrade), mode: cfg.mode, sig, chatId: strat.telegram_chat_id || null });
await recordSnipeSpend({ agentId: strat.agent_id, userId: strat.user_id, network: cfg.network, lamports: perTrade, signature: sig, mode: cfg.mode, mint: mint.mint, capabilityId: spendCapabilityId });
@@ -433,11 +440,20 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {
* Close `position` for `reason`. Re-quotes fresh for slippage, builds the sell,
* broadcasts (live), records realized P&L.
*/
-export async function executeSell({ cfg, position, reason }) {
+export async function executeSell({ cfg, position, reason, fraction = 1, recoversInitials = false }) {
return withAgentLock(position.agent_id, async () => {
- const tag = { agent: position.agent_id, mint: position.mint, symbol: position.symbol, reason };
+ // Laddered exits sell only PART of the bag (take-initials). Resolve the sell
+ // size in ppm of the current base amount so the moon-bag remainder is exact
+ // with no float drift, and decide up front whether this closes the position.
+ const f = Number(fraction);
+ const fullBase = BigInt(position.base_amount);
+ const ppm = f > 0 && f < 1 ? BigInt(Math.max(1, Math.min(999_999, Math.round(f * 1_000_000)))) : 1_000_000n;
+ let sellBaseBig = ppm === 1_000_000n ? fullBase : (fullBase * ppm) / 1_000_000n;
+ const partial = sellBaseBig > 0n && sellBaseBig < fullBase;
+ if (sellBaseBig <= 0n) sellBaseBig = fullBase; // degenerate fraction → full exit
+ const tag = { agent: position.agent_id, mint: position.mint, symbol: position.symbol, reason, partial };
await sql`UPDATE agent_sniper_positions SET status = 'closing' WHERE id = ${position.id} AND status = 'open'`;
- screenPush(`Selling $${(position.symbol || position.mint.slice(0, 6)).toUpperCase()}: ${reason}`, 'trade');
+ screenPush(`${partial ? 'Taking initials on' : 'Selling'} $${(position.symbol || position.mint.slice(0, 6)).toUpperCase()}: ${reason}`, 'trade');
try {
const loaded = await loadAgentKeypair(position.agent_id, position.user_id, 'sniper_sell');
@@ -446,7 +462,7 @@ export async function executeSell({ cfg, position, reason }) {
const ctx = await getTradeCtx(cfg.network);
const mintPk = new ctx.web3.PublicKey(position.mint);
- const baseAmount = bn(ctx, BigInt(position.base_amount));
+ const baseAmount = bn(ctx, sellBaseBig);
const slippagePct = (position.slippage_bps ?? 500) / 100;
let expectedOut;
@@ -483,20 +499,63 @@ export async function executeSell({ cfg, position, reason }) {
expectedOut = BigInt(built.expectedQuoteOut.toString());
}
- const entry = BigInt(position.entry_quote_lamports || '0');
- const pnl = expectedOut - entry;
- const pnlPct = entry > 0n ? (Number(pnl) / Number(entry)) * 100 : 0;
+ const entryFull = BigInt(position.entry_quote_lamports || '0');
+ // Cost basis of the tokens sold on THIS leg (scaled by the sold ppm), so a
+ // partial take-initials books the profit on just the half it sold and the
+ // remainder keeps its own proportional basis.
+ const soldCostBasis = partial ? (entryFull * ppm) / 1_000_000n : entryFull;
+ const legPnl = expectedOut - soldCostBasis;
+ const legPnlPct = soldCostBasis > 0n ? (Number(legPnl) / Number(soldCostBasis)) * 100 : 0;
+ const priorRealized = BigInt(position.realized_pnl_lamports || '0');
+ const cumRealized = priorRealized + legPnl;
+
+ if (partial) {
+ // Take-initials: keep the position OPEN with the moon-bag remainder.
+ // Scale the cost basis down with the tokens, flag initials recovered so
+ // the ladder fires once, and RESET the trailing high-water to the
+ // remaining bag's value — the pre-sale full-position peak would instantly
+ // trip the trailing stop against the now-smaller moon bag.
+ const remainingBase = fullBase - sellBaseBig;
+ const remainingEntry = entryFull - soldCostBasis;
+ const remainingValueEst = Math.round((Number(expectedOut) * Number(remainingBase)) / Number(sellBaseBig));
+ await sql`
+ UPDATE agent_sniper_positions SET
+ status = 'open',
+ base_amount = ${remainingBase.toString()},
+ entry_quote_lamports = ${remainingEntry.toString()},
+ initials_recovered = ${recoversInitials ? true : position.initials_recovered === true},
+ peak_value_lamports = ${remainingValueEst},
+ last_value_lamports = ${remainingValueEst},
+ realized_pnl_lamports = ${cumRealized.toString()},
+ error = ${null},
+ last_quoted_at = now()
+ WHERE id = ${position.id}
+ `;
+ const legSol = lamportsToSol(legPnl);
+ log.trade('take-initials', { ...tag, venue, mode: cfg.mode, sig, sold_fraction: f, leg_pnl_sol: legSol, kept_moonbag_base: remainingBase.toString() });
+ await recordJournal({ position, cfg, event: 'take_initials', reason, sig, venue, soldFraction: f, legPnlLamports: legPnl, remainingBase });
+ screenPush(
+ `Took initials on $${(position.symbol || position.mint.slice(0, 6)).toUpperCase()} — +${legSol.toFixed(4)} SOL back, moon bag riding`,
+ 'trade',
+ { phase: 'take_initials', mint: position.mint, symbol: position.symbol || null, solDelta: legSol, soldFraction: f },
+ );
+ return { status: 'partial', sig, sold_fraction: f, leg_pnl: legPnl.toString(), venue };
+ }
+
+ const pnl = legPnl;
+ const pnlPct = entryFull > 0n ? (Number(cumRealized) / Number(entryFull)) * 100 : 0;
await sql`
UPDATE agent_sniper_positions SET
status = 'closed', exit_reason = ${reason}, sell_sig = ${sig},
exit_quote_lamports = ${expectedOut.toString()},
- realized_pnl_lamports = ${pnl.toString()},
+ realized_pnl_lamports = ${cumRealized.toString()},
realized_pnl_pct = ${pnlPct},
error = ${null},
closed_at = now()
WHERE id = ${position.id}
`;
- const pnlSol = lamportsToSol(pnl);
+ await recordJournal({ position, cfg, event: 'exit', reason, sig, venue, soldFraction: 1, legPnlLamports: legPnl });
+ const pnlSol = lamportsToSol(cumRealized);
log.trade('sell', { ...tag, venue, mode: cfg.mode, sig, pnl_sol: pnlSol, pnl_pct: pnlPct.toFixed(1) });
// Price the realized SOL delta into USD best-effort for the live PnL
// ticker. A pricing hiccup just omits realizedUsd — the viewer's ticker
diff --git a/workers/agent-sniper/exit-logic.js b/workers/agent-sniper/exit-logic.js
index 218da0908..fe6dd29bf 100644
--- a/workers/agent-sniper/exit-logic.js
+++ b/workers/agent-sniper/exit-logic.js
@@ -63,3 +63,87 @@ function isBearishFlip(sentiment) {
const floor = Number(sentiment.minConfidence);
return Number.isFinite(conf) && conf >= (Number.isFinite(floor) ? floor : 0.7);
}
+
+/** The take-initials multiple (× entry) or null when the ladder is off. Must be
+ * > 1 to make sense (you can't recover initials below cost). */
+export function ladderMultiple(n) {
+ const x = pct(n);
+ return x != null && x > 1 ? x : null;
+}
+
+/** Moon-bag floor as a fraction of the position that must ALWAYS be kept on the
+ * take-initials event. Default 15%, clamped to [0, 0.95] so a sell can never be
+ * the whole bag. */
+export function moonbagFraction(n) {
+ const x = pct(n);
+ const frac = x == null ? 15 : x;
+ return Math.max(0, Math.min(0.95, frac / 100));
+}
+
+/**
+ * Laddered exit decision: the reason AND what fraction of the CURRENT remaining
+ * position to sell. This is the live-trading source of truth (positions.js);
+ * `decideExit` above stays the single-shot decider the backtester replays.
+ *
+ * The ladder is OPT-IN: with no `initials_out_multiple` set it is byte-for-byte
+ * the classic full-exit behavior (sellFraction 1 on any decideExit reason), so
+ * existing strategies are unchanged. When set, it encodes the owner's rule:
+ *
+ * - Protective exits are always FULL exits of whatever remains, and the hard
+ * stop-loss still wins: stop_loss → signal_flip → trailing_stop.
+ * - The FIRST time the position reaches `initials_out_multiple`× entry (e.g.
+ * 2×), sell exactly enough to return the initial cost basis (fraction =
+ * entry/value), but NEVER more than 1 − moonbag floor — so a moon bag always
+ * rides. At 2× that is a 0.5 sell (keep half); at 5× a 0.2 sell (keep 80%).
+ * - After initials are recovered, the moon bag runs, protected by the trailing
+ * stop; an optional classic `take_profit_pct` acts as a ceiling that exits
+ * the remainder. Timeout exits the remainder.
+ *
+ * It NEVER returns a full take-PROFIT exit before initials are recovered — that
+ * is the "sold too much too soon" mistake the rule exists to prevent.
+ *
+ * @param {object} pos position-like; adds `initials_out_multiple`,
+ * `moonbag_min_pct`, and the `initials_recovered` state flag
+ * to the fields `decideExit` reads.
+ * @param {number} value current SOL value of the remaining position (lamports)
+ * @param {number} peak high-water mark of `value` since entry (lamports)
+ * @param {number} [now] epoch ms for the timeout clock
+ * @param {object|null} [sentiment] live x402 sentiment; null disables signal_flip
+ * @returns {{ reason: string, sellFraction: number, recoversInitials?: boolean }|null}
+ */
+export function decideLadderedExit(pos, value, peak, now = Date.now(), sentiment = null) {
+ const mult = ladderMultiple(pos.initials_out_multiple);
+ if (mult == null) {
+ // Ladder off → classic single-shot full exit (unchanged behavior).
+ const reason = decideExit(pos, value, peak, now, sentiment);
+ return reason ? { reason, sellFraction: 1 } : null;
+ }
+
+ const entry = Number(BigInt(pos.entry_quote_lamports || '0'));
+ if (!(entry > 0)) return null;
+ const sl = pct(pos.stop_loss_pct);
+ const ts = pct(pos.trailing_stop_pct);
+ const tp = pct(pos.take_profit_pct);
+ const moonbag = moonbagFraction(pos.moonbag_min_pct);
+ const recovered = pos.initials_recovered === true;
+
+ // Protective exits — full exit of the remainder; stop-loss wins on conflict.
+ if (sl != null && value <= entry * (1 - sl / 100)) return { reason: 'stop_loss', sellFraction: 1 };
+ if (isBearishFlip(sentiment) && value < entry) return { reason: 'signal_flip', sellFraction: 1 };
+ if (ts != null && peak > 0 && value <= peak * (1 - ts / 100)) return { reason: 'trailing_stop', sellFraction: 1 };
+
+ // Take-initials — the first profit event, once, before initials are recovered.
+ if (!recovered && value >= entry * mult) {
+ const recoverFraction = entry / value; // f·value = cost basis
+ const sellFraction = Math.max(0, Math.min(recoverFraction, 1 - moonbag));
+ if (sellFraction > 0) return { reason: 'take_initials', sellFraction, recoversInitials: true };
+ }
+
+ // Moon-bag ceiling — optional classic take-profit, only AFTER initials are out.
+ if (recovered && tp != null && value >= entry * (1 + tp / 100)) return { reason: 'take_profit', sellFraction: 1 };
+
+ // Timeout — full exit of the remainder.
+ const heldS = (now - new Date(pos.opened_at).getTime()) / 1000;
+ if (pos.max_hold_seconds != null && heldS >= pos.max_hold_seconds) return { reason: 'timeout', sellFraction: 1 };
+ return null;
+}
diff --git a/workers/agent-sniper/journal.js b/workers/agent-sniper/journal.js
new file mode 100644
index 000000000..3030a8c75
--- /dev/null
+++ b/workers/agent-sniper/journal.js
@@ -0,0 +1,87 @@
+// agent-sniper — trade journal. The "learn what works" surface.
+//
+// Every entry and every exit leg is written here WITH its reasoning: why the
+// mint was bought (mcap, score, trigger), and why/how much was sold (take-
+// initials / trailing / stop / timeout, the fraction, the leg PnL). The point of
+// the 10-SOL experiment is to learn, and you can only learn from a decision log
+// that captures the *why*, not just the PnL. Read it via /api/sniper/journal.
+//
+// Best-effort: a journal write NEVER fails a trade. A dropped row costs a lesson,
+// not money — so every call is wrapped and swallowed with a warning.
+
+import { sql } from '../../api/_lib/db.js';
+import { log } from './log.js';
+
+/** Lazy table create so a fresh env journals whether the migration ran or not. */
+let _ensured = false;
+async function ensure() {
+ if (_ensured) return;
+ await sql`
+ CREATE TABLE IF NOT EXISTS trading_journal (
+ id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
+ ts timestamptz NOT NULL DEFAULT now(),
+ agent_id text,
+ position_id bigint,
+ network text,
+ mint text,
+ symbol text,
+ event text NOT NULL, -- entry | take_initials | exit
+ reason text, -- trigger (entry) or exit reason
+ mode text, -- live | simulate
+ venue text,
+ sold_fraction numeric,
+ leg_pnl_lamports numeric,
+ market_cap_usd numeric,
+ score numeric,
+ rationale text, -- human-readable "why"
+ sig text
+ )
+ `;
+ await sql`CREATE INDEX IF NOT EXISTS trading_journal_agent_ts_idx ON trading_journal (agent_id, ts DESC)`;
+ _ensured = true;
+}
+
+/**
+ * Record an entry. `mint` is the enriched candidate (carries market_cap_usd,
+ * score, entry_trigger). `rationale` is the plain-language why.
+ */
+export async function journalEntry({ cfg, strat, mint, posId, sig, score, rationale }) {
+ try {
+ await ensure();
+ await sql`
+ INSERT INTO trading_journal
+ (agent_id, position_id, network, mint, symbol, event, reason, mode, sold_fraction,
+ market_cap_usd, score, rationale, sig)
+ VALUES (${strat.agent_id}, ${posId ?? null}, ${cfg.network}, ${mint.mint}, ${mint.symbol || null},
+ 'entry', ${mint.entry_trigger || 'new_mint'}, ${cfg.mode}, 0,
+ ${mint.market_cap_usd ?? null}, ${score ?? null},
+ ${rationale || null}, ${sig || null})
+ `;
+ } catch (err) {
+ log.warn('journal entry write failed', { agent: strat.agent_id, mint: mint?.mint, err: err?.message });
+ }
+}
+
+/**
+ * Record an exit leg (full or partial). `position` is the DB row; `legPnlLamports`
+ * is a BigInt of the realized PnL on this leg.
+ */
+export async function recordJournal({ position, cfg, event, reason, sig, venue, soldFraction, legPnlLamports, remainingBase }) {
+ try {
+ await ensure();
+ const rationale = event === 'take_initials'
+ ? `Reached the take-initials band — sold ${(soldFraction * 100).toFixed(0)}% to recover the cost basis; moon bag (${remainingBase?.toString?.() ?? '?'} base) rides on the trailing stop.`
+ : `Full exit: ${reason}.`;
+ await sql`
+ INSERT INTO trading_journal
+ (agent_id, position_id, network, mint, symbol, event, reason, mode, venue,
+ sold_fraction, leg_pnl_lamports, rationale, sig)
+ VALUES (${position.agent_id}, ${position.id}, ${cfg.network}, ${position.mint}, ${position.symbol || null},
+ ${event}, ${reason}, ${cfg.mode}, ${venue || null},
+ ${soldFraction ?? null}, ${legPnlLamports != null ? legPnlLamports.toString() : null},
+ ${rationale}, ${sig || null})
+ `;
+ } catch (err) {
+ log.warn('journal exit write failed', { position: position?.id, err: err?.message });
+ }
+}
diff --git a/workers/agent-sniper/positions.js b/workers/agent-sniper/positions.js
index 6bb06b1fa..26cafd1c7 100644
--- a/workers/agent-sniper/positions.js
+++ b/workers/agent-sniper/positions.js
@@ -11,7 +11,7 @@ import { getTradeCtx } from './trade-client.js';
import { getOpenPositions } from './strategy-store.js';
import { executeSell } from './executor.js';
import { quoteAmmSell } from './amm-exit.js';
-import { decideExit } from './exit-logic.js';
+import { decideLadderedExit } from './exit-logic.js';
import { screenPush } from './screen-push.js';
async function tickPosition(cfg, pos) {
@@ -51,8 +51,16 @@ async function tickPosition(cfg, pos) {
sentiment = await readCoinSentiment(cfg, pos.mint);
}
- const reason = decideExit(pos, value, peak, Date.now(), sentiment);
- if (reason) await executeSell({ cfg, position: pos, reason });
+ const exit = decideLadderedExit(pos, value, peak, Date.now(), sentiment);
+ if (exit) {
+ await executeSell({
+ cfg,
+ position: pos,
+ reason: exit.reason,
+ fraction: exit.sellFraction,
+ recoversInitials: exit.recoversInitials === true,
+ });
+ }
}
// Re-quote a still-on-curve position off the bonding curve. On graduation, flag