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.

sniper: oracle_crossing trigger + breakeven-armed trailing stops

nirholas1241afcb4c75
diff --git a/api/_lib/migrations/20260723060000_sniper_oracle_crossing.sql b/api/_lib/migrations/20260723060000_sniper_oracle_crossing.sql
new file mode 100644
index 000000000..08b5ceed2
--- /dev/null
+++ b/api/_lib/migrations/20260723060000_sniper_oracle_crossing.sql
@@ -0,0 +1,36 @@
+-- Migration: add the "oracle_crossing" trigger to the sniper.
+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260723060000_sniper_oracle_crossing.sql
+-- Idempotent.
+--
+-- Motivation (measured, 2026-07-23, fleet window Jul 20-23): coins whose Oracle
+-- conviction crossed 50 went on to pump or graduate 77.5% of the time (55 of 71
+-- labeled) vs an 11.8% base rate, yet the fleet bought zero of the 110 qualifying
+-- coins: the two conviction-gated arms had bars at 35 (below the band) and 65
+-- (above the highest score ever observed, 61). The crossing happens at a median
+-- of 2 minutes after launch and the median capturable upside from the crossing
+-- candle is 1.23x, with 35% of crossings reaching >=1.5x.
+--
+-- trigger = 'oracle_crossing' — the sniper buys when a coin FIRST crosses the
+-- strategy's min_oracle_score (default 50), driven by a poll on
+-- oracle_conviction rather than the launch firehose, so the entry reacts to
+-- demonstrated conviction instead of gating at minute zero when no signal
+-- exists. Routes through the SAME executeBuy chokepoint (Mayhem gate, trade
+-- firewall round-trip, budgets, concurrency, market-cap clamps) as every
+-- other trigger.
+
+begin;
+
+alter table agent_sniper_strategies drop constraint if exists agent_sniper_strategies_trigger_check;
+alter table agent_sniper_strategies
+ add constraint agent_sniper_strategies_trigger_check
+ check (trigger in ('new_mint', 'first_claim', 'intel_confirmed', 'prelaunch_radar',
+ 'alpha_hunt', 'graduation_ride', 'oracle_crossing'));
+
+alter table agent_sniper_positions drop constraint if exists agent_sniper_positions_entry_trigger_check;
+alter table agent_sniper_positions
+ add constraint agent_sniper_positions_entry_trigger_check
+ check (entry_trigger in ('new_mint', 'first_claim', 'intel_confirmed', 'prelaunch_radar',
+ 'alpha_hunt', 'llm_judge', 'llm_intel', 'swarm_consensus',
+ 'graduation_ride', 'oracle_crossing'));
+
+commit;
diff --git a/blog/all-90-trades-x.md b/blog/all-90-trades-x.md
index 2606176d9..bd805bba0 100644
--- a/blog/all-90-trades-x.md
+++ b/blog/all-90-trades-x.md
@@ -76,7 +76,16 @@ THE ONES THAT GOT AWAY
The biggest skipped winner ran to a $161M ATH cap. Should we feel bad? At the moment our systems observed it, it showed 3 visible buyers and quality 43/100, statistically identical to the 36,000 rugs in the same dataset. Its run started after our observation window closed.
-That is the structural lesson: a minute-zero sniper is blind to every winner whose story starts at minute thirty. No threshold fixes that. A second look at 30 and 60 minutes does.
+That is the structural lesson: a minute-zero sniper is blind to every winner whose story starts at minute thirty. No threshold fixes that. A second look does.
+
+So we measured the second look against full candle histories. If you had bought each of the 102 measurable conviction-50 crossings at the close of the crossing candle:
+
+- the crossing lands a median of 2 MINUTES after launch (sniper-speed, not lagging)
+- median capturable upside: 1.23x. 35% reached 1.5x, 19% reached 2x, best 9.6x
+- zero coins had already topped before crossing
+- but the median crossing coin eventually decays to 0.32x, so the profit only exists for a strategy that takes it
+
+We built that strategy. The sniper now has an oracle_crossing trigger: a watcher buys a coin the first time it crosses the bar, with a sell-the-initials ladder at 1.5x and a protected moonbag. The formerly-unreachable strict arm is re-armed on it at conviction 50. Its trades will publish like everything else.
THE PAPERHANDS AUDIT
@@ -114,7 +123,7 @@ The experiment continues. Budgets now flow toward whatever performs, and the nex
---
-## Version B: thread (16 posts)
+## Version B: thread (17 posts)
**1/**
We gave 11 AI agents their own Solana wallets and real SOL, pointed them at the pump.fun firehose, and stopped touching the keyboard.
@@ -229,10 +238,15 @@ Health is measured by rows in your audit tables, not by your HTTP status codes.
"The cron returns 200" and "the loop is learning" are unrelated statements.
**16/**
+We measured the fix too. Buying each of the 102 conviction-50 crossings at the crossing candle: median 2 minutes after launch, median capturable 1.23x, 35% reach 1.5x, best 9.6x. But median terminal decay is 0.32x: the profit only exists if you TAKE it.
+
+So the crossing arm is built: enters on the first 50-cross, sells initials at 1.5x, keeps a moonbag.
+
+**17/**
All 90 trades published and individually graded, with on-chain receipts, every model thesis verbatim, the 83k-coin counterfactual, the paperhands audit, charts, and the raw dataset as JSON.
No cherry-picking. The ledger does not let us.
https://three.ws/blog/all-90-trades
-Next up: an arm that trades the conviction-50 crossing.
+The crossing arm's trades will publish the same way. Win or lose.
diff --git a/blog/all-90-trades.html b/blog/all-90-trades.html
index 00ed1c61c..74dc8f0d5 100644
--- a/blog/all-90-trades.html
+++ b/blog/all-90-trades.html
@@ -328,7 +328,7 @@ const SYSTEM_PROMPT = [
<li><strong><code>take_profit</code> (13 trades, +0.056 SOL).</strong> The only systematically profitable exit. Every arm that lacked a configured take-profit either got lucky on a timeout or gave its gains back. After the first trade taught us this, every fleet arm shipped with a TP; the data now confirms it with 13 clean examples.</li>
<li><strong><code>timeout</code> (47 trades, -0.036 SOL).</strong> The modal outcome. Most pump.fun launches simply flatline, and a timeout on a flat coin costs a little slippage each way. 11 timeouts closed green, which is luck, not policy: nothing locked those gains in. The real cost of timeouts is invisible: dead coins held for their full configured hold (4 to 30 minutes depending on the arm) tie up a concurrency slot that a live coin could have used.</li>
<li><strong><code>stop_loss</code> (18 trades, -0.086 SOL).</strong> Working as designed in most cases: the median stop landed within a few points of policy. The tail is the problem; see section 8.</li>
- <li><strong><code>trailing_stop</code> (12 trades, -0.037 SOL).</strong> The most misunderstood exit in the ladder. A trailing stop armed while the position is still underwater just converts a small loss into a realized one. Trailing stops earned their keep only on positions that were already green; the fix (arm the trail only above breakeven) is one of the concrete changes this dataset motivates.</li>
+ <li><strong><code>trailing_stop</code> (12 trades, -0.037 SOL).</strong> The most misunderstood exit in the ladder. A trailing stop armed while the position is still underwater just converts a small loss into a realized one. Trailing stops earned their keep only on positions that were already green; the fix (arm the trail only above breakeven) shipped from this dataset and is now how the exit ladder behaves (section 15).</li>
</ul>
<h2 id="vanity">6. Win rate is a vanity metric</h2>
@@ -373,6 +373,7 @@ const SYSTEM_PROMPT = [
<p>Look at the last three columns before feeling bad. Every one of these coins, at the moment our systems watched it, had <strong>a handful of visible buyers, mediocre quality, and low or no conviction</strong>. The $161M ATH winner showed 3 buyers and quality 43 during its observation window. These were not signals anyone ignored; at minute zero, these coins were indistinguishable from the 36,366 rugs in the same dataset. Their runs started minutes to hours <em>after</em> our observation window closed.</p>
<p>That is the actual lesson, and it is structural: <strong>a minute-zero sniper is blind to every winner whose story starts at minute thirty.</strong> No threshold tuning fixes it, because the information does not exist yet at decision time. What fixes it is a second look: re-scoring coins at 30 and 60 minutes and entering on demonstrated, sustained demand rather than launch-second vibes. The Oracle's 50+ band (section 8) is exactly that signal, which is why wiring an arm to it is the top item on the roadmap.</p>
<p>Where the fleet <em>did</em> have the information and skipped anyway, the record is defensible: of the 110 coins that crossed conviction 50, the 16 that later rugged would have cost us, but the 55 that ran would have paid for them roughly 3-to-1. We are careful not to claim a specific PnL for a strategy nobody ran (entry slippage, exit behavior, and fill quality are all unknowable in hindsight), but the direction is not subtle.</p>
+ <p>So we measured how catchable the band actually is, coin by coin, against full candle histories. For each of the 102 measurable crossings, take the close of the first candle at or after the coin's first 50-plus score as a hypothetical entry, and ask what the price did afterward. Three answers matter. First, <strong>the crossing lands at a median of 2 minutes after launch</strong>: this is a sniper-speed signal, not a lagging one. Second, the upside is real: the median crossing offered 1.23x from the entry candle, <strong>35% of crossings reached at least 1.5x and 19% reached 2x</strong>, with the best run at 9.6x, and not a single coin had already topped before crossing. Third, the warning label: the median crossing coin eventually decays to 0.32x its entry, so the profit exists only for a strategy that takes it; buy-and-hope converts this band back into losses. (Method honesty: candle-close entries, no slippage or fill modeling; the live arm's fills will be worse than the candles by some spread we can only learn by trading it.)</p>
<h2 id="paperhands">10. The paperhands audit: did we sell too early?</h2>
<p>Every trader's private fear: the coin you sold kept running. We checked it for all 90 exits, two independent ways.</p>
@@ -1371,8 +1372,9 @@ async function applyProposal(strategyId, field, value) {
<ul>
<li><strong>Rebalance toward what works.</strong> The evolution layer reallocates budget across arms using confidence intervals on realized returns, so the LLM arms earn larger budgets by performing, not by us liking them.</li>
<li><strong>Fix the model routing.</strong> The named-model arms should actually be piloted by their named models; the failover chain answering most calls muddied the model-vs-model comparison this round.</li>
- <li><strong>An arm that trades the conviction-50 crossing.</strong> Section 8's 77%-good band is the strongest signal in this entire dataset and nothing trades it. The new arm enters when a coin first crosses 50, sized small until the live data tells us how much of the band's edge survives entry slippage. The strict arm's unreachable 65 bar drops to the observed score range.</li>
- <li><strong>A second-window scanner.</strong> Re-score surviving coins at 30 and 60 minutes so the fleet can catch the winners whose stories start after minute zero (section 9), instead of judging every coin exactly once at birth.</li>
+ <li><strong>An arm that trades the conviction-50 crossing: built.</strong> Section 8's 77%-good band is the strongest signal in this dataset, so the sniper now has an <code>oracle_crossing</code> trigger: a watcher polls the Oracle and buys a coin the first time it crosses the strategy's bar, instead of gating a launch-second buy on a score that does not exist yet. The formerly-idle strict arm is re-armed on it: bar at 50 (its old 65 was above the highest score ever observed), tiny size, and, because section 9's data says the median crossing coin eventually decays to 0.32x, a sell-the-initials ladder at 1.5x with a protected moonbag. It goes live with the next worker deploy and its trades will publish like everything else.</li>
+ <li><strong>Trailing stops now arm only above breakeven: shipped.</strong> The exit ladder no longer fires a trailing stop on a position that was never green; the hard stop-loss keeps sole custody of the downside. Every below-breakeven trail in this dataset realized a loss that the stop would have capped anyway.</li>
+ <li><strong>A second-window scanner.</strong> The crossing watcher is the first instance of the pattern; the general version re-scores surviving coins at 30 and 60 minutes so the fleet can catch the winners whose stories start after minute zero (section 9), instead of judging every coin exactly once at birth.</li>
<li><strong>Arm trailing stops above breakeven only, and add a liquidity-decay early exit</strong> so dead coins stop squatting on concurrency slots for half an hour.</li>
<li><strong>Keep the optimizer honest.</strong> Every applied tuning now writes an audit row and a ledger entry, and the fleet's tunings will appear in future editions of this dataset.</li>
</ul>
diff --git a/docs/agent-sniper.md b/docs/agent-sniper.md
index 70b7996e7..5e7946ca3 100644
--- a/docs/agent-sniper.md
+++ b/docs/agent-sniper.md
@@ -86,7 +86,7 @@ The strategy row (`agent_sniper_strategies`, armed via `POST /api/sniper/strateg
| Field | What it does |
|---|---|
-| `trigger` | `new_mint`, `first_claim`, `intel_confirmed`, `graduation_ride` (buy at migration, sell into pump.fun's 5-minute BOOST buyback window), alpha/radar variants |
+| `trigger` | `new_mint`, `first_claim`, `intel_confirmed`, `graduation_ride` (buy at migration, sell into pump.fun's 5-minute BOOST buyback window), `oracle_crossing` (buy the first time a coin crosses the strategy's Oracle-conviction bar; see below), alpha/radar variants |
| `per_trade_lamports` / `daily_budget_lamports` | Position size and the hard daily spend ceiling |
| `max_concurrent_positions` | Open-position cap |
| `min_market_cap_usd` / `max_market_cap_usd` | Entry band; tightened by the fleet-wide safety band |
@@ -95,7 +95,7 @@ The strategy row (`agent_sniper_strategies`, armed via `POST /api/sniper/strateg
| `firewall_level` | `block` (abort on a failed simulation) or `warn` |
| `slippage_bps` / `max_price_impact_pct` | Execution guards |
| `stop_loss_pct` | Hard floor below entry, always evaluated first |
-| `trailing_stop_pct` | Percent off the position's high-water mark |
+| `trailing_stop_pct` | Percent off the position's high-water mark. Arms only once the position has been above breakeven; underwater, the stop-loss alone owns the downside (measured across the fleet's first 90 trades: every below-breakeven trail just realized a loss the stop would have capped) |
| `take_profit_pct` | Profit ceiling. **Set this.** Null means winners are only ever closed by the trailing stop or the clock |
| `max_hold_seconds` | The timeout backstop; closes the position regardless of PnL |
| `initials_out_multiple` / `moonbag_min_pct` | The laddered exit: recover cost at N times entry, let the rest ride |
@@ -103,6 +103,10 @@ The strategy row (`agent_sniper_strategies`, armed via `POST /api/sniper/strateg
Exit rules are evaluated in a fixed order (stop-loss, signal-flip, trailing-stop, take-profit, timeout) by a pure, unit-tested function (`workers/agent-sniper/exit-logic.js`), so a backtest and the live worker agree on exactly when a position closes.
+### The `oracle_crossing` trigger
+
+Most triggers judge a coin at launch, when the Oracle has no signal yet. `oracle_crossing` inverts that: a watcher (`workers/agent-sniper/oracle-crossing.js`) polls `oracle_conviction` and buys a coin the **first time** its score crosses the strategy's `min_oracle_score` (default 50), provided the coin is young (`SNIPER_CROSSING_MAX_AGE_MIN`, default 90) and the score is fresh. The empirical case, measured over the fleet's first window (2026-07-20..23): coins that crossed conviction 50 pumped or graduated **77.5%** of the time vs an 11.8% base rate; the crossing lands a **median of 2 minutes after launch**; and the median crossing offered 1.23x from the crossing candle with 35% reaching 1.5x. The same data says the median crossing coin eventually decays to 0.32x of the crossing price, so a crossing strategy should always ship with a reachable take-profit or the initials-out ladder. One attempt per (strategy, mint); candidates route through the same `executeBuy` chokepoint (Mayhem gate, firewall round trip, budgets, market-cap clamps) plus an explicit x402 rugpull veto. Full analysis: [the 90-trade postmortem](/blog/all-90-trades).
+
## How the fleet improves itself
The hard-config sniper is the control group: its constants (band edges, stop percentages, hold time) are frozen at arm time, so it cannot react to regime changes. A band that is right at midnight is wrong at noon, and the only fix used to be a human editing numbers. That is no longer the case. The fleet now improves itself through three layers, each running above the same execution stack and each bounded so it can only ever tune what a human owner already tunes.
diff --git a/public/features.json b/public/features.json
index 1d01e4e38..dca206fc1 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-23T05:06:22.570Z",
+ "generated_at": "2026-07-23T05:53:57.481Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/tests/agent-sniper-oracle-crossing.test.js b/tests/agent-sniper-oracle-crossing.test.js
new file mode 100644
index 000000000..c74e32099
--- /dev/null
+++ b/tests/agent-sniper-oracle-crossing.test.js
@@ -0,0 +1,86 @@
+/**
+ * agent-sniper — oracle_crossing trigger + breakeven-armed trailing stop.
+ *
+ * Two behaviors shipped from the 90-trade postmortem (2026-07-23):
+ *
+ * 1. crossingCandidates() — pure selection of (strategy, coin) pairs when a
+ * coin's Oracle conviction crosses a strategy's threshold. Locks in the
+ * per-strategy threshold, the once-per-pair dedupe, and the default bar.
+ *
+ * 2. decideExit() trailing stop arms ONLY above breakeven. Across the fleet's
+ * first 90 real trades every below-breakeven trail realized a small loss
+ * while the hard stop-loss already capped the downside; the trail's job is
+ * to protect gains, not to front-run the stop.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { crossingCandidates } from '../workers/agent-sniper/oracle-crossing.js';
+import { decideExit } from '../workers/agent-sniper/exit-logic.js';
+
+describe('crossingCandidates', () => {
+ const armA = { id: 'arm-a', min_oracle_score: 50 };
+ const armB = { id: 'arm-b', min_oracle_score: 58 };
+
+ it('selects only coins at or above each strategy threshold', () => {
+ const rows = [
+ { mint: 'M1', score: 61 },
+ { mint: 'M2', score: 55 },
+ { mint: 'M3', score: 49 },
+ ];
+ const picks = crossingCandidates(rows, [armA, armB], new Set());
+ const keys = picks.map((p) => `${p.strat.id}:${p.coin.mint}`).sort();
+ expect(keys).toEqual(['arm-a:M1', 'arm-a:M2', 'arm-b:M1']);
+ });
+
+ it('never selects the same (strategy, mint) pair twice', () => {
+ const attempted = new Set();
+ const rows = [{ mint: 'M1', score: 60 }];
+ expect(crossingCandidates(rows, [armA], attempted)).toHaveLength(1);
+ expect(crossingCandidates(rows, [armA], attempted)).toHaveLength(0);
+ // a different strategy still gets its own attempt
+ expect(crossingCandidates(rows, [armB], attempted)).toHaveLength(1);
+ });
+
+ it('defaults the bar to 50 when a strategy has no min_oracle_score', () => {
+ const bare = { id: 'arm-bare', min_oracle_score: null };
+ const picks = crossingCandidates(
+ [{ mint: 'M1', score: 50 }, { mint: 'M2', score: 49 }],
+ [bare],
+ new Set(),
+ );
+ expect(picks.map((p) => p.coin.mint)).toEqual(['M1']);
+ });
+
+ it('handles string scores from the DB driver', () => {
+ const picks = crossingCandidates([{ mint: 'M1', score: '52' }], [armA], new Set());
+ expect(picks).toHaveLength(1);
+ });
+});
+
+describe('trailing stop arms only above breakeven', () => {
+ const EV = 1_000_000_000; // 1 SOL entry
+ const pos = {
+ entry_quote_lamports: String(EV),
+ stop_loss_pct: 30,
+ trailing_stop_pct: 20,
+ take_profit_pct: null,
+ max_hold_seconds: 3600,
+ opened_at: new Date(Date.now() - 60_000).toISOString(),
+ };
+
+ it('does NOT fire when the peak never exceeded entry', () => {
+ // peak 0.95x (entry-impact typical), value gave back >20% of peak: the old
+ // behavior fired trailing_stop here and locked in a -24% loss.
+ expect(decideExit(pos, 0.75 * EV, 0.95 * EV)).toBe(null);
+ });
+
+ it('still fires on a green position that gives back the trail', () => {
+ // peak 1.5x, trail 20% → exit at or below 1.2x
+ expect(decideExit(pos, 1.19 * EV, 1.5 * EV)).toBe('trailing_stop');
+ expect(decideExit(pos, 1.25 * EV, 1.5 * EV)).toBe(null);
+ });
+
+ it('the hard stop-loss still caps an underwater position', () => {
+ expect(decideExit(pos, 0.69 * EV, 0.95 * EV)).toBe('stop_loss');
+ });
+});
diff --git a/workers/agent-sniper/exit-logic.js b/workers/agent-sniper/exit-logic.js
index fe6dd29bf..5179648aa 100644
--- a/workers/agent-sniper/exit-logic.js
+++ b/workers/agent-sniper/exit-logic.js
@@ -48,7 +48,12 @@ export function decideExit(pos, value, peak, now = Date.now(), sentiment = null)
if (sl != null && value <= ev * (1 - sl / 100)) return 'stop_loss';
if (isBearishFlip(sentiment) && value < ev) return 'signal_flip';
- if (ts != null && peak > 0 && value <= peak * (1 - ts / 100)) return 'trailing_stop';
+ // The trailing stop arms only once the position has been green (peak above
+ // entry). Armed underwater it is a machine for realizing small losses: across
+ // the fleet's first 90 real trades, every below-breakeven trail converted a
+ // recoverable dip into a locked loss while protecting nothing (the hard
+ // stop-loss above still caps the downside). Measured 2026-07-23.
+ if (ts != null && peak > ev && value <= peak * (1 - ts / 100)) return 'trailing_stop';
if (tp != null && value >= ev * (1 + tp / 100)) return 'take_profit';
const heldS = (now - new Date(pos.opened_at).getTime()) / 1000;
diff --git a/workers/agent-sniper/index.js b/workers/agent-sniper/index.js
index fa29d5fad..61d3b45a2 100644
--- a/workers/agent-sniper/index.js
+++ b/workers/agent-sniper/index.js
@@ -21,6 +21,7 @@ import { judgeLaunch } from './llm-judge.js';
import { runPositionSweep } from './positions.js';
import { runSwarmConsensus, runSwarmSettlement } from './swarm.js';
import { startFirstClaimWatch } from './first-claim-watch.js';
+import { startOracleCrossingWatch } from './oracle-crossing.js';
import { startPrelaunchRadar } from './prelaunch-radar.js';
import { startIntelWatcher } from './intel/watcher.js';
import { getLearnedWeights } from './intel/store.js';
@@ -339,6 +340,14 @@ async function main() {
cfg, queue, throttle, isHalted: () => draining || cfg.globalKill,
});
+ // Oracle conviction-crossing entries — buys the FIRST crossing of a
+ // strategy's conviction threshold (median 2 minutes after launch) instead of
+ // gating a launch-second buy on a score that does not exist yet. See
+ // workers/agent-sniper/oracle-crossing.js for the measured rationale.
+ const stopCrossingWatch = startOracleCrossingWatch({
+ cfg, queue, throttle, isHalted: () => draining || cfg.globalKill,
+ });
+
// Autonomous coin launcher — fires pump.fun launches on schedule.
let stopLauncher = () => {};
if (cfg.launcher) {
@@ -475,6 +484,7 @@ async function main() {
clearInterval(watchdogTimer);
try { stopHeartbeat?.(); } catch {}
try { stopClaimWatch?.(); } catch {}
+ try { stopCrossingWatch?.(); } catch {}
try { radar?.stop?.(); } catch {}
try { stopFeed?.(); } catch {}
try { stopIntel?.(); } catch {}
diff --git a/workers/agent-sniper/oracle-crossing.js b/workers/agent-sniper/oracle-crossing.js
new file mode 100644
index 000000000..0723d29a0
--- /dev/null
+++ b/workers/agent-sniper/oracle-crossing.js
@@ -0,0 +1,143 @@
+// agent-sniper — Oracle conviction-crossing entries (trigger = 'oracle_crossing').
+//
+// The measured case for this trigger (fleet window 2026-07-20..23): coins whose
+// conviction crossed 50 pumped or graduated 77.5% of the time vs an 11.8% base
+// rate, the crossing lands a median of 2 minutes after launch, and the median
+// capturable upside from the crossing candle is 1.23x (35% reach >=1.5x). The
+// fleet's launch-time gates could never trade this band: at minute zero the
+// Oracle has no signal yet, and by design the gate fails open or skips. This
+// watcher inverts the flow: instead of gating a launch-second buy on a score
+// that does not exist yet, it polls oracle_conviction and BUYS THE CROSSING.
+//
+// Discipline learned from the same dataset: median terminal decay after a
+// crossing is 0.32x, so a crossing strategy must ship with a reachable
+// take-profit or an initials-out ladder; this module does not soften any exit.
+//
+// Safety: candidates route through the SAME executeBuy chokepoint as every
+// other trigger (Mayhem gate, trade-firewall buy+sell round trip, budgets,
+// concurrency, SOL headroom, market-cap clamps). The x402 rugpull veto is
+// checked here as well so a fresh high/critical verdict never even queues.
+//
+// Dedupe: one attempt per (strategy, mint), remembered in-memory for the
+// watcher's lifetime and bounded; the DB's unique (agent_id, mint, network)
+// position constraint makes retries idempotent at the ledger anyway.
+
+import { sql } from '../../api/_lib/db.js';
+import { log } from './log.js';
+import { cachedStrategies } from './strategy-store.js';
+import { executeBuy } from './executor.js';
+import { rugpullVeto } from './oracle-gate.js';
+
+const POLL_MS = Math.max(5_000, Number(process.env.SNIPER_CROSSING_POLL_MS || 20_000));
+// Only coins this young qualify: the edge is the EARLY crossing (median 2m).
+// A coin that first crosses conviction hours after launch is a different regime
+// than the one we measured.
+const MAX_COIN_AGE_MIN = Math.max(5, Number(process.env.SNIPER_CROSSING_MAX_AGE_MIN || 90));
+// Only act on scores computed recently; a stale row is not a live crossing.
+const MAX_SCORE_AGE_MIN = Math.max(1, Number(process.env.SNIPER_CROSSING_SCORE_AGE_MIN || 10));
+const DEFAULT_MIN_SCORE = 50;
+
+const MAX_ATTEMPTED = 5_000;
+
+/**
+ * Pure candidate selection: which (strategy, coin) pairs should attempt a buy.
+ * Mutates `attempted` (adds each selected pair's key) so a pair is only ever
+ * selected once per watcher lifetime.
+ *
+ * @param {Array<{mint: string, score: number|string}>} rows crossing rows, any order
+ * @param {Array<{id: string, min_oracle_score?: number|null}>} arms oracle_crossing strategies
+ * @param {Set<string>} attempted `${strategyId}:${mint}` pairs already tried
+ * @returns {Array<{coin: object, strat: object}>}
+ */
+export function crossingCandidates(rows, arms, attempted) {
+ const out = [];
+ for (const coin of rows) {
+ for (const strat of arms) {
+ const minScore = Number(strat.min_oracle_score ?? DEFAULT_MIN_SCORE);
+ if (Number(coin.score) < minScore) continue;
+ const key = `${strat.id}:${coin.mint}`;
+ if (attempted.has(key)) continue;
+ attempted.add(key);
+ out.push({ coin, strat });
+ }
+ }
+ return out;
+}
+
+export function startOracleCrossingWatch({ cfg, queue, throttle, isHalted }) {
+ const attempted = new Set(); // `${strategyId}:${mint}`
+ let stopped = false;
+ let timer = null;
+
+ async function tick() {
+ if (stopped || isHalted()) return;
+ const arms = cachedStrategies().filter(
+ (s) => (s.trigger || 'new_mint') === 'oracle_crossing' && s.network === cfg.network,
+ );
+ if (!arms.length) return;
+
+ const floor = Math.min(...arms.map((s) => Number(s.min_oracle_score ?? DEFAULT_MIN_SCORE)));
+ let rows;
+ try {
+ rows = await sql`
+ select mint, symbol, name, score, tier, coin_first_seen_at
+ from oracle_conviction
+ where network = ${cfg.network}
+ and score >= ${floor}
+ and scored_at > now() - make_interval(mins => ${MAX_SCORE_AGE_MIN})
+ and coin_first_seen_at > now() - make_interval(mins => ${MAX_COIN_AGE_MIN})
+ order by score desc
+ limit 25
+ `;
+ } catch (err) {
+ log.warn('crossing watch query failed', { err: err?.message });
+ return;
+ }
+ if (!rows.length) return;
+
+ if (attempted.size > MAX_ATTEMPTED) {
+ // Oldest-first eviction is overkill here; a full clear only risks one
+ // duplicate attempt per pair, which the position ledger dedupes.
+ attempted.clear();
+ }
+ for (const { coin, strat } of crossingCandidates(rows, arms, attempted)) {
+ log.info('crossing candidate', {
+ agent: strat.agent_id, mint: coin.mint, symbol: coin.symbol,
+ score: coin.score, tier: coin.tier, min: strat.min_oracle_score ?? DEFAULT_MIN_SCORE,
+ });
+ queue.push(async () => {
+ if (stopped || isHalted()) return;
+ const rug = await rugpullVeto(coin.mint, cfg.network);
+ if (rug.reject) {
+ log.info('crossing rugpull veto', { agent: strat.agent_id, mint: coin.mint, level: rug.level, score: rug.score });
+ return;
+ }
+ await executeBuy({
+ cfg, strat, throttle,
+ mint: {
+ mint: coin.mint, symbol: coin.symbol, name: coin.name,
+ entry_trigger: 'oracle_crossing',
+ trigger_ref: `score:${coin.score}`,
+ score: Number(coin.score),
+ },
+ });
+ });
+ }
+ }
+
+ function loop() {
+ if (stopped) return;
+ tick()
+ .catch((err) => log.error('crossing watch tick failed', { err: err?.message }))
+ .finally(() => {
+ if (!stopped) timer = setTimeout(loop, POLL_MS);
+ });
+ }
+ timer = setTimeout(loop, POLL_MS);
+ log.info('oracle-crossing watch armed', { network: cfg.network, pollMs: POLL_MS, maxAgeMin: MAX_COIN_AGE_MIN });
+
+ return () => {
+ stopped = true;
+ if (timer) clearTimeout(timer);
+ };
+}