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(strategies): research gates, a price-impact cap and ask-before-buy, edited with sliders, live counts and a gated backtest

nirholas9a77b2c72518
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 6b8d8dbfe..3461781a7 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -89,7 +89,6 @@ bottom.
| Visitor feedback loop | Recorder [@three-ws/witness](packages/witness), capture + panel [src/feedback-companion.js](src/feedback-companion.js) (mounted by [src/walk-companion.js](src/walk-companion.js)), intake [api/feedback/report.js](api/feedback/report.js), queue API [api/feedback/index.js](api/feedback/index.js), scoring [api/_lib/feedback/triage.js](api/_lib/feedback/triage.js), store [api/_lib/feedback/store.js](api/_lib/feedback/store.js), cron [api/cron/feedback-triage.js](api/cron/feedback-triage.js), review page [pages/feedback.html](pages/feedback.html) `→ /feedback` + [src/feedback-page.js](src/feedback-page.js) | Live | The return channel on the corner companion: the visitor tells the avatar what broke and the report carries the route, build SHA, viewport, and the last console errors and failed requests the browser captured, so a vague sentence lands as an actionable row. The companion offers proactively at the one moment worth asking (right after the page actually threw), once per route per session, never in a background tab. **Feedback is data, never an instruction:** the model that reads untrusted visitor text writes six scalars to that report's own row and has no path to the repo, a deploy, or any other write; the admin-only `/feedback` queue groups reports into one row per problem and a person decides. **A report arrives as a runnable failing test:** the recorded session compiles into a Playwright spec asserting the failure is GONE (red until fixed, green after), reachable from the queue's Copy test button, `GET /api/feedback/repro`, `npm run feedback:repro`, and the `get_feedback_repro` MCP tool. Docs: [docs/feedback.md](docs/feedback.md), [docs/witness.md](docs/witness.md). Tests: [tests/feedback-triage.test.js](tests/feedback-triage.test.js) |
| Session-to-test recorder | [packages/witness/](packages/witness) `→ @three-ws/witness`: recorder [recorder.js](packages/witness/src/recorder.js), selector synthesis [selector.js](packages/witness/src/selector.js), capture-time privacy [redact.js](packages/witness/src/redact.js), spec compiler [compile.js](packages/witness/src/compile.js); compiled repros land in [tests/repros/](tests/repros) with [their own Playwright config](tests/repros/playwright.config.mjs) | Published as `@three-ws/witness` (Apache-2.0, zero deps) | Turns a real user session into a runnable failing test. Records INTENT (about 2 KB) rather than DOM mutations (megabytes), so it can be always-on, which is the point: the trace already exists when somebody decides to complain. Every element gets the strongest handle that is unique in the live document (test id > id > aria-label > role+name > text > name > placeholder > class > structural path), framework-generated ids and utility classes refused, and each trace carries a replay confidence equal to its WEAKEST link. The compiled spec asserts the failure is gone, never that it happened, so it locks in the fix rather than the bug; a session with no machine-visible failure emits `test.fail()` and says which assertion a human must add rather than faking green. Privacy is enforced at capture: typed values are never held (only a length and a shape), password/hidden/email/tel/date inputs and `data-witness="off"` subtrees record nothing, URLs lose their credentials before storage. Docs: [docs/witness.md](docs/witness.md). Tests: [packages/witness/test/](packages/witness/test) (36, `npm run test:witness`) |
| Prepaid credits (`/credits`) | [pages/credits.html](pages/credits.html) `→ /credits` + [src/credits.js](src/credits.js), balance/ledger [api/credits/index.js](api/credits/index.js) `→ GET /api/credits`, deposit verifier [api/credits/deposit.js](api/credits/deposit.js) `→ POST /api/credits/deposit` over [api/_lib/credit-deposit.js](api/_lib/credit-deposit.js), ledger engine [api/_lib/credits.js](api/_lib/credits.js), schema [api/_lib/migrations/20260621200000_credits.sql](api/_lib/migrations/20260621200000_credits.sql) | Live | The prepaid balance every metered action on the platform debits. Top up by sending SOL or $THREE to the platform deposit wallet (connect + SIWS-link + sign in the page, or paste a signature you already sent); crediting is server-authoritative and idempotent on the signature, so a signature that is not signed by a wallet linked to the account credits nobody. The page renders the caller's $THREE holder tier from the same `holder` block [api/pricing.js](api/pricing.js) returns ([api/_lib/three-tier.js](api/_lib/three-tier.js)), which is the discount [api/_lib/credits.js](api/_lib/credits.js) already applies to every debit, and lists what credits buy straight from the pricing catalog ([api/_lib/pricing/catalog.js](api/_lib/pricing/catalog.js)). Ledger is keyset-paginated. Docs: [docs/payment-sessions.md](docs/payment-sessions.md). Tests: [tests/credits.test.js](tests/credits.test.js) |
-| Web domains (`/domains`) | [pages/domains.html](pages/domains.html) `→ /domains` + [src/domains/](src/domains), API [api/domains/[action].js](api/domains/%5Baction%5D.js) `→ /api/domains/*`, MCP [api/_mcp/tools/domains.js](api/_mcp/tools/domains.js), service [api/_lib/domains-service.js](api/_lib/domains-service.js) + [api/_lib/cloud-domains.js](api/_lib/cloud-domains.js) + [api/_lib/domain-connect.js](api/_lib/domain-connect.js), renewals [api/cron/domain-renewals.js](api/cron/domain-renewals.js), schema [api/_lib/migrations/20261011000000_web_domains.sql](api/_lib/migrations/20261011000000_web_domains.sql) | Live pending deploy | Search, price, check and register web domains through Google Cloud Domains, paid from credits behind a quote, an explicit confirm and an idempotency key, then serve an agent's public page on the domain. Coin pages carry a live domain suggestion panel. Docs: [docs/domains.md](docs/domains.md). Tests: [tests/domains-service.test.js](tests/domains-service.test.js) |
| Agent payment sessions (`/payments`) | [pages/payments.html](pages/payments.html) `-> /payments`, API [api/pay/session.js](api/pay/session.js) (`POST`/`GET`/`PATCH`/`DELETE /api/pay/session`, `GET /api/pay/session/:id/executions`), spend rail [api/pay/execute.js](api/pay/execute.js) + [api/pay/simulate.js](api/pay/simulate.js), engine [api/_lib/pay/payment-session.js](api/_lib/pay/payment-session.js) + governor [api/_lib/pay/spend-governor.js](api/_lib/pay/spend-governor.js), expiry sweep [api/cron/payment-session-sweep.js](api/cron/payment-session-sweep.js) | Live | The dashboard for platform-managed spend envelopes: fund a budget out of `/credits`, get a one-time `pss_` bearer token, and hand it to an agent that pays x402 endpoints without ever holding a private key (the platform's Solana wallet signs, and the governor enforces budget, host allowlist and per-tx cap atomically on every call). Each card carries the budget bar, remaining balance, expiry countdown, host allowlist, per-tx cap, an inline execution ledger from `GET /api/pay/session/:id/executions` with a Solscan link per settled payment, an env-var-referencing MCP config for [packages/agentcore-payments-mcp](packages/agentcore-payments-mcp), and cancel-and-refund. Press `N` for the create dialog. Docs: [docs/payment-sessions.md](docs/payment-sessions.md), [docs/tutorials/agent-spending-envelope.md](docs/tutorials/agent-spending-envelope.md). Tests: [tests/payment-session-governor.test.js](tests/payment-session-governor.test.js), [tests/payment-session-sweep.test.js](tests/payment-session-sweep.test.js) |
| Skill bundles (seller builder + evidence pricing) | [pages/bundles.html](pages/bundles.html) `→ /bundles`, API [api/agents/[id]/bundles.js](api/agents/%5Bid%5D/bundles.js), arithmetic [api/_lib/bundle-pricing.js](api/_lib/bundle-pricing.js), checkout [api/marketplace/purchase-bundle.js](api/marketplace/purchase-bundle.js) | Live (seller side); no buyer-facing browser view yet | Sell several of one agent's skills as one purchase. The price is derived from the agent's own ledger rather than a rule of thumb: the public `?action=pricing` endpoint finds every buyer who already bought 2+ of the selected skills, suggests the median of what they really paid (`basis: median_basket`), and backtests any candidate price against those same baskets; with no such buyer yet it falls back to 20% off the sum of the parts and labels itself `discount_off_list` so a default is never read as a finding. Every amount is an atomic integer carried as a BigInt end to end, because a 9-decimal mint puts real sums past `Number.MAX_SAFE_INTEGER`. Checkout settles on-chain and writes one `skill_purchases` row per skill (`kind = 'bundle'`, amount 0) so one bundle sale is never counted as N skill sales. Docs: [docs/skill-bundles.md](docs/skill-bundles.md). Tests: [tests/bundle-pricing.test.js](tests/bundle-pricing.test.js), [tests/vercel-agents-subpath-routes.test.js](tests/vercel-agents-subpath-routes.test.js) |
| Marketplace analytics & trial funnel | [pages/marketplace-analytics.html](pages/marketplace-analytics.html) `→ /marketplace/analytics`, renderer [src/marketplace-analytics.js](src/marketplace-analytics.js), backend [api/marketplace/analytics.js](api/marketplace/analytics.js) | Live | Public transparency page for the skill marketplace: paid sales, volume, top skills/agents, and the trial conversion funnel. **Every money aggregate gates on `status = 'confirmed'` alone.** Counting `status IN ('confirmed','trial')` as a sale published 10,454 "sales" and 6.2M $THREE of "volume" on 2026-07-30 against a table holding zero confirmed purchases, because a `trial` row is a free grant whose `amount` is only the list price it would have cost. Free trials now render as their own stat and as a four-stage funnel (granted → used → exhausted → converted), which also names the two shapes that mean a wiring fault rather than weak demand: trials never spent, or trials exhausted with nothing converting. Docs: [docs/marketplace.md](docs/marketplace.md), tutorial [docs/tutorials/sell-a-skill-with-a-trial.md](docs/tutorials/sell-a-skill-with-a-trial.md). Tests: [tests/marketplace-analytics-paid-only.test.js](tests/marketplace-analytics-paid-only.test.js) |
@@ -271,6 +270,7 @@ bottom.
| Trading growth programs (big-win X poster, first-rug softener, early-leader bonus) | engine [api/_lib/growth-programs/](api/_lib/growth-programs) (flags + caps [config.js](api/_lib/growth-programs/config.js), [big-win-x.js](api/_lib/growth-programs/big-win-x.js), [rug-softener.js](api/_lib/growth-programs/rug-softener.js), [early-leaders.js](api/_lib/growth-programs/early-leaders.js), capped payout leg [payouts.js](api/_lib/growth-programs/payouts.js)), crons [api/cron/big-win-x.js](api/cron/big-win-x.js) + [api/cron/growth-payouts.js](api/cron/growth-payouts.js), ops board [api/ops/growth-programs.js](api/ops/growth-programs.js) `→ /api/ops/growth-programs`, claim API [api/sniper/rug-softener.js](api/sniper/rug-softener.js) `→ /api/sniper/rug-softener`, claim banner [src/dashboard-next/rug-softener-banner.js](src/dashboard-next/rug-softener-banner.js) on `/dashboard/sniper`, ledger migration [api/_lib/migrations/20260929120000_growth_program_payouts.sql](api/_lib/migrations/20260929120000_growth_program_payouts.sql), report [scripts/growth-programs-report.mjs](scripts/growth-programs-report.mjs) | Built, disarmed | Roadmap 917 items 3.8, 12.15 and 13.4. Posts notable live wins to @trythreews (never naming the traded coin, linking the `/trade/:id` card, filtered like the changelog X lane), pays $THREE toward a first-timer's first verified rug, and pays a bounded $THREE bonus to the first leaders with a verified, followed record. The selection logic runs on live data and is inspectable at any time; posting and paying only run when `BIG_WIN_X_ENABLED`, `RUG_SOFTENER_ENABLED` or `EARLY_LEADER_ENABLED` is set, under rolling caps with code ceilings, from the Arena prize wallet (`THREE_PRIZE_PAYOUT_KEY`) via a Token-2022-aware transfer. Docs + owner arm steps: [docs/growth-programs.md](docs/growth-programs.md). Tests: [tests/growth-programs.test.js](tests/growth-programs.test.js) |
| Never sell 100% of a winner (moon-bag policy) | rule [workers/agent-sniper/exit-logic.js](workers/agent-sniper/exit-logic.js) (`moonbagExitFraction`, `moonbagAlways`), retained-bag booking [workers/agent-sniper/executor.js](workers/agent-sniper/executor.js), position fields [api/_lib/migrations/20260725100000_sniper_moonbag_always.sql](api/_lib/migrations/20260725100000_sniper_moonbag_always.sql), board [api/sniper/experiments.js](api/sniper/experiments.js) + [src/sniper-experiments.js](src/sniper-experiments.js) `→ /sniper/experiments` | Live | Fleet-wide owner rule: a terminal exit that is IN PROFIT sells down to the moon-bag floor (default 15%) instead of to zero, and the retained tokens ride indefinitely. Once the cost basis is back the remainder is free, so a bag that goes to zero costs nothing and a bag that runs is the whole upside; selling the last slice for a rounding error gives that up. Applies with or without the proactive 2x ladder. A loss exit with the stake still at risk is still a FULL exit and the hard stop-loss is never overridden. The position still books `closed`, so realized P&L and the `max_concurrent_positions` slot are unaffected and a held bag can never stop an arm trading; only the tokens stay behind (`moonbag_base_amount`). Per-strategy opt-out `moonbag_always = false`. Tests: [tests/sniper-laddered-exit.test.js](tests/sniper-laddered-exit.test.js), [tests/trading-experiment-e2e.test.js](tests/trading-experiment-e2e.test.js). See [docs/trading-experiment.md](docs/trading-experiment.md) |
| Autonomous Trading hub (front door) | [pages/trading.html](pages/trading.html) `→ /trading` + [src/trading-hub.js](src/trading-hub.js), pure formatters [src/trading-hub-format.js](src/trading-hub-format.js), surface + doc directory [src/trading-hub-data.js](src/trading-hub-data.js), styles [src/trading-hub.css](src/trading-hub.css) | Live | One entry point for a trading system that had grown to ~20 pages with no front door. Live fleet vitals from `GET /api/sniper/status` (mode, armed strategies, open positions, feed health, funding, uptime), the agent scoreboard from `GET /api/sniper/leaderboard` (realized P&L only, closed trades only, with cumulative sparkline), the five-gate entry-to-exit explainer, and directories of every trading surface and doc. Feed health is reported separately from process health because a beating worker with a silent feed reads as green while seeing nothing. Directory is data, so [tests/trading-hub.test.js](tests/trading-hub.test.js) asserts every link resolves against `data/pages.json` and the docs tree. Docs: [docs/trading-hub.md](docs/trading-hub.md), tutorial [docs/tutorials/read-the-trading-fleet.md](docs/tutorials/read-the-trading-fleet.md) |
+| Strategy Objects (settings, research gates, ask-before-trade) | library and builder [pages/strategies.html](pages/strategies.html) `→ /strategies` (`?editor=new`), form + JSON editor [src/shared/strategy-forms.js](src/shared/strategy-forms.js), live preview, text compiler box and gated backtest [src/shared/strategy-settings.js](src/shared/strategy-settings.js), agent panel with mode switch, approvals and decision log [src/shared/agent-strategy-panel.js](src/shared/agent-strategy-panel.js); schema and gate evaluator [api/_lib/strategy-schema.js](api/_lib/strategy-schema.js), gate report [api/_lib/strategy-research.js](api/_lib/strategy-research.js), approvals and decision log [api/_lib/strategy-approvals.js](api/_lib/strategy-approvals.js), preview [api/_lib/strategy-preview.js](api/_lib/strategy-preview.js), runtime [api/_lib/agent-strategy-runtime.js](api/_lib/agent-strategy-runtime.js), APIs [api/strategies.js](api/strategies.js) `→ /api/strategies` and [api/agents/agent-strategy-objects.js](api/agents/agent-strategy-objects.js) `→ /api/agents/:id/strategies`, migration [api/_lib/migrations/20261010140000_strategy_research_gates.sql](api/_lib/migrations/20261010140000_strategy_research_gates.sql) | Built, ships with the next deploy | Version 2 Strategy Objects: source filter, market cap band, SOL size, a price-impact cap that only tightens the agent breaker, nine research gates (holders, largest holder, liquidity, firewall score, mint and freeze authority, creator launches, graduations, dev sold) that fail closed on unknown data, and `ask` (default) or `auto` mode. Every blocked coin is logged with the check and reason; ask mode files a payload-hash approval that executes once after re-checking every guard. The builder edits one config through sliders, toggles and raw JSON, shows a live count of recent launches the settings would have bought, compiles plain English into the fields, and backtests with the gates applied. Doc: [docs/strategy-objects.md](docs/strategy-objects.md). Tests: [tests/strategy-research-gates.test.js](tests/strategy-research-gates.test.js), [tests/strategy-schema.test.js](tests/strategy-schema.test.js) |
| Sniper Experiments (rules vs LLM A/B fleet) | [pages/sniper-experiments.html](pages/sniper-experiments.html) + [src/sniper-experiments.js](src/sniper-experiments.js) `→ /sniper/experiments`, aggregate [api/sniper/experiments.js](api/sniper/experiments.js), LLM judge [workers/agent-sniper/llm-judge.js](workers/agent-sniper/llm-judge.js), fleet seeding [scripts/seed-sniper-experiments.mjs](scripts/seed-sniper-experiments.mjs) | Live | The sniper fleet runs labeled rule-set variants side by side (strict shields, oracle-gated, and `decision_mode=llm` arms judged per-launch by Grok / Claude / OpenRouter auto with no shields), all behind the same safety rails. The page is the live scoreboard of which entry conditions actually make money; real on-chain fills only. |
| Arm your agent (Oracle conviction on autopilot) | [pages/arm.html](pages/arm.html) + [src/arm.js](src/arm.js) `→ /oracle/arm` (also `/arm`), config + graded ledger API [api/oracle/watch.js](api/oracle/watch.js) `→ /api/oracle/watch`, alert test [api/oracle/test-alert.js](api/oracle/test-alert.js), live stream [api/oracle/feed.js](api/oracle/feed.js), proof of edge [api/oracle/backtest.js](api/oracle/backtest.js) | Live | The rules screen that turns an Oracle score into an agent that acts. Four steps: the conviction floor (Prime / Strong+ / Lean+, each showing its real 30-day win rate, average peak and 3x count for that exact bar), position sizing with hard daily and open-position caps, an optional personal Telegram alert with a send-test button, and simulate-or-live arming. Beside the form is a live preview of every coin clearing the rules as they stand, updated every 20 seconds, with the size the agent would commit to each: tighten the bar and the list shrinks in front of you. The agent spends only from its own custodial Solana wallet, whose balance and remaining trade runway sit in the control bar, and every action it takes is graded against the outcome in the ledger below. The conviction preview and edge readout are public endpoints, so a signed-out visitor sees the product working before being asked for an account. Arming in live mode is gated on the shared risk acknowledgement ([src/shared/risk-ack.js](src/shared/risk-ack.js)). |
| Oracle Lab (the conviction model, published) | [pages/oracle-lab.html](pages/oracle-lab.html) + [src/oracle-lab.js](src/oracle-lab.js) `→ /oracle-lab`, model API [api/oracle/model.js](api/oracle/model.js) `→ /api/oracle/model`, SDK [packages/oracle-model/](packages/oracle-model) `→ @three-ws/oracle-model` | Live | The glass box over the Oracle. Publishes the scoring model itself, not a summary of it: every bucket weight with the number of labeled launches behind it and what happened to them, the held-out reliability curve for each tier claim, the version history of every refit INCLUDING the candidates the promotion gate refused and why, and a scorer that runs the real weights in the visitor's browser. The model is a lookup table (~32KB), so `@three-ws/oracle-model` downloads it once and reproduces any score offline with no key, no rate limit and no telemetry; `verify()` re-measures our published AUC/Brier/reliability against a caller's own labeled outcomes, and `diff()` shows every weight that moved between two versions. `?view=registry` and `?view=diff&from=&to=` serve the same data server-side. Docs: [docs/oracle-model.md](docs/oracle-model.md) `→ /docs/oracle-model`. Tests: [packages/oracle-model/test/](packages/oracle-model/test) (23), [tests/oracle/fit.test.js](tests/oracle/fit.test.js) (43) |
diff --git a/api/_lib/strategy-compiler.js b/api/_lib/strategy-compiler.js
index a008d0ac5..b3a5bed0c 100644
--- a/api/_lib/strategy-compiler.js
+++ b/api/_lib/strategy-compiler.js
@@ -484,7 +484,8 @@ function heuristicCompile(text) {
if (secScore) out.security_min_score = parseInt(secScore[1], 10);
if (/(?:renounced|revoked|no)\s*mint(?:\s*authority)?|mint\s*authority\s*(?:renounced|revoked|disabled)/.test(t)) out.require_no_mint_authority = true;
if (/(?:renounced|revoked|no)\s*freeze(?:\s*authority)?|freeze\s*authority\s*(?:renounced|revoked|disabled)/.test(t)) out.require_no_freeze_authority = true;
- if (/(?:three\.ws|threews|platform)\s*launch/.test(t)) out.sources = ['three_ws_launch'];
+ // The number-word pass above has already turned "three.ws" into "3.ws".
+ if (/(?:three\.ws|3\.ws|threews|platform)\s*launch/.test(t)) out.sources = ['three_ws_launch'];
if (/\bauto(?:matically)?\b|without asking|no approval|don'?t ask/.test(t)) out.mode = 'auto';
else if (/\bask (?:me|first)|approval|approve each|confirm each/.test(t)) out.mode = 'ask';
diff --git a/api/sniper/compile.js b/api/sniper/compile.js
index 827db6271..f65c8347a 100644
--- a/api/sniper/compile.js
+++ b/api/sniper/compile.js
@@ -2,7 +2,11 @@
* Agent Sniper — natural-language strategy compiler.
*
* POST /api/sniper/compile { agent_id, text, network? }
- * → { ok, via, strategy, summary, assumptions, clamped, warnings }
+ * → { ok, via, strategy, summary, strategy_object, explanations, assumptions, clamped, warnings }
+ *
+ * `strategy_object` is the same intent as a version 2 Strategy Object config
+ * (research gates, price-impact cap, ask/auto mode) and `explanations` says, per
+ * field, where each value came from; the /strategies builder fills from it.
*
* Turns a plain-English description ("snipe creators who've graduated at least
* two, market cap under $30k, organic distribution, take profit at 3x, stop loss
diff --git a/data/changelog.json b/data/changelog.json
index 37fcc45d1..fdf240db1 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -17,6 +17,15 @@
"tags": ["feature", "security"],
"link": "/approvals"
},
+ {
+ "date": "2026-10-10",
+ "title": "Strategies now research every coin and ask before they buy",
+ "summary": "Trading strategies can now check a coin before spending anything: minimum holders, how much the largest holder owns, liquidity, the rug and honeypot safety score, whether the creator can still mint or freeze, and the creator's track record. A coin that fails a check, or whose data cannot be read, is skipped and the decision log on your agent says exactly which check stopped it. You can also cap price impact per buy. Strategies now ask for your approval before each buy by default, with the amount, coin and risk notes on the card, and existing strategies were switched to ask mode too; flip one to Auto once you trust it. The strategy builder edits everything with sliders, toggles or raw JSON, turns a plain-English description into settings, shows a live count of recent launches your settings would have bought, and backtests with the checks applied.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/strategies"
+ },
{
"date": "2026-10-10",
"title": "Approve your agents' payments from a notification",
@@ -29476,30 +29485,6 @@
"feature"
],
"link": "/teams"
- },
- {
- "date": "2026-10-10",
- "title": "Agents can find and register web domains",
- "summary": "Search any name across popular extensions with live availability and the exact yearly price, check a single name, and register it from your credits after a quote and an explicit yes. Coin pages now suggest available domains for the project name, and a registered domain can serve your agent's public page. Registration is for one year, renews at the same price, and has no markup.",
- "tags": ["feature"],
- "link": "/domains"
- },
- {
- "date": "2026-10-10",
- "title": "Token ceilings, a spend page, USDC deposits and a way out of the free tier",
- "summary": "Every agent can now carry hourly, daily and per-run token ceilings next to its dollar caps. A ceiling is checked before the model is called; hitting one pauses the agent, tells you, and gives you Resume and Extend once. The new /spend page shows what each agent spends by day, by model and by tool, projects the month end, and alerts at 50, 80 and 100 percent of any cap. Credits can be topped up with USDC at a fixed rate alongside SOL and $THREE, the deposit page lists every accepted asset and its rate from live config, and paying in $THREE earns whatever bonus the owner has set. When the free tier runs out, the error now carries your choices: wait for the reset, top up, bring your own key, or resend the same request with paid_fallback: true to bill it to credits in one step.",
- "tags": ["feature"],
- "link": "/spend"
- },
- {
- "date": "2026-10-10",
- "title": "Agents get their own email inbox",
- "summary": "Every agent can now have an email address on agents.three.ws, with an inbox right on its profile (the Mail button). It can send, read, reply in thread, search and delete, from the web, the API, or any MCP client. Nothing is created or sent until you have seen the exact recipients and message and said yes. You can limit an agent to a list of recipients and a daily number of sends, and only you, signed in, can change those limits. Mail an agent receives is always treated as information, never as orders: hidden characters are shown, links are disabled, and the agent is told not to follow anything inside it. Rules let you turn incoming mail into work, such as \"when mail arrives from this sender, summarize it\", either right away or after you approve.",
- "tags": [
- "feature",
- "security"
- ],
- "link": "/agent-mail"
}
]
}
diff --git a/docs/api-reference.md b/docs/api-reference.md
index 36981a954..fe8edf529 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -4127,6 +4127,75 @@ curl -s 'https://three.ws/api/pipeline?network=devnet' | jq '.stages.recorder'
---
+## Strategy Objects API
+
+Strategy Objects are validated trade rule sets an agent can equip (entry filter,
+research gates, sizing with a price-impact cap, exits, risk caps, and an
+`ask`/`auto` mode). Full guide, schema, and examples:
+[docs/strategy-objects.md](strategy-objects.md).
+
+### Live match preview
+
+```
+POST /api/strategies/preview { config, hours?: 1|6|24, network?: "mainnet"|"devnet" }
+```
+
+Public, read-only, 120 requests per IP per 5 minutes. Replays the recorded
+launches of the last `hours` (default 6) through the live entry filter and
+research gates. The config is normalized, not validated, so a half-edited config
+still previews. Returns `universe`, `passed_entry`, `passed_research`,
+`impact_blocked`, `matched`, `live_check` (cleared everything except
+firewall-only checks that history lacks), `would_buy`, `entry_rejects`,
+`blocked_by` (a map of gate key to how many coins it blocked), `sample`, `sol_usd`,
+`history_at`, and `caveats`. `502 preview_unavailable` when the history cannot be
+read.
+
+### Per-agent strategy runtime
+
+```
+GET /api/agents/:id/strategies equips, live positions, kill state
+POST /api/agents/:id/strategies { strategy_id, network } equip
+POST /api/agents/:id/strategies/unequip { equip_id | strategy_id }
+POST /api/agents/:id/strategies/toggle { equip_id, active }
+POST /api/agents/:id/strategies/kill toggle the owner's kill switch
+POST /api/agents/:id/strategies/sweep evaluate this agent's equips now
+POST /api/agents/:id/strategies/close { position_id } sell one position now
+POST /api/agents/:id/strategies/mode { equip_id, mode: "ask"|"auto" }
+GET /api/agents/:id/strategies/decisions?decision=&limit=
+GET /api/agents/:id/strategies/approvals?status=pending&limit=
+POST /api/agents/:id/strategies/approve { approval_id, payload_hash }
+POST /api/agents/:id/strategies/deny { approval_id }
+```
+
+Owner only (session plus CSRF, or a bearer allowed to spend). On mainnet,
+equipping, resuming, switching to `auto`, sweeping, and approving require the
+real-funds agreement; pausing and switching to `ask` never do.
+
+- **decisions** returns `data.decisions[]`: one row per equip and coin with
+ `decision` (`blocked`, `approval`, `executed`, `skipped`, `failed`),
+ `check_name`, `reason`, `blocked_by`, `signature`, `seen_count`,
+ `strategy_name`, and `updated_at`. Filter with `decision=`.
+- **approvals** returns `data.approvals[]` with the exact `payload` the buy will
+ run, its `payload_hash`, `summary`, `amount`, `amount_usd`, `recipient_label`,
+ `risk_notes`, and `expires_at` (15 minutes after filing).
+- **approve** must carry the `payload_hash` you reviewed. It runs the buy once
+ with the original idempotency key after re-checking every guard, and returns
+ `data: { approval, already, executed, code, message }`. A guard that now
+ refuses answers `422` with `executed: false` and the reason; nothing is bought.
+
+### Compile a strategy from text
+
+```
+POST /api/sniper/compile { agent_id, text, network? }
+```
+
+Session or bearer, agent you own. Returns the sniper rule set (`strategy`) plus
+`strategy_object` (the version 2 Strategy Object config) and `explanations[]`
+(`field`, `value`, `why`), with every money and risk knob clamped to the agent's
+trade guards and listed in `clamped`.
+
+---
+
## Trader Passport API
A trader's daily on-chain score attestation (`threews.tradescore.v1`), served as a
diff --git a/docs/strategy-objects.md b/docs/strategy-objects.md
index b9a4925df..5642829dd 100644
--- a/docs/strategy-objects.md
+++ b/docs/strategy-objects.md
@@ -1,9 +1,9 @@
# Strategy Objects and the Strategy Lab
-A Strategy Object is a trade strategy as a first-class thing you can own: a structured, validated rule set (entry conditions, sizing, take-profit, stop-loss, risk caps) that your agent can equip and run on-chain, ranked on a leaderboard by real live performance and forkable by anyone. The Strategy Lab is the workbench: write a strategy as data, validate it, backtest it against real recorded pump.fun history with the same evaluator its live runs use, and run it live or in simulation, end to end. Both run strategies as additional constraints on top of your agent's server-side spend policy, never a way around it.
+A Strategy Object is a trade strategy as a first-class thing you can own: a structured, validated rule set (entry conditions, research gates, sizing, a price-impact cap, take-profit, stop-loss, risk caps, and whether it asks before each buy) that your agent can equip and run on-chain, ranked on a leaderboard by real live performance and forkable by anyone. The Strategy Lab is the workbench: write a strategy as data, validate it, backtest it against real recorded pump.fun history with the same evaluator its live runs use, and run it live or in simulation, end to end. Both run strategies as additional constraints on top of your agent's server-side spend policy, never a way around it.
Pages: [/strategies](https://three.ws/strategies) (the library and leaderboard), [/strategy-lab](https://three.ws/strategy-lab) (the workbench)
-API: `GET/POST /api/strategies`, `GET /api/strategies/leaderboard`, `GET/PATCH/DELETE /api/strategies/:id`, `POST /api/strategies/:id/{fork,publish}`, `GET/POST/PATCH/DELETE /api/dca-strategies`, the Lab's `POST /api/pump/strategy-{validate,backtest,run,close-all}`, and the sniper backtester `POST /api/sniper/backtest`
+API: `GET/POST /api/strategies`, `POST /api/strategies/preview`, `GET /api/strategies/leaderboard`, `GET/PATCH/DELETE /api/strategies/:id`, `POST /api/strategies/:id/{fork,publish}`, the per-agent runtime under `/api/agents/:id/strategies` (equip, mode, decisions, approvals), `GET/POST/PATCH/DELETE /api/dca-strategies`, the Lab's `POST /api/pump/strategy-{validate,backtest,run,close-all}`, and the sniper backtester `POST /api/sniper/backtest`
## Why it exists
@@ -19,15 +19,74 @@ Third, it makes them safe to run. The strategy's own caps (per-trade size, slipp
### The Strategy Object schema
-Every strategy is normalized and validated by `api/_lib/strategy-schema.js` before it persists. Free text is impossible; a malformed rule set cannot be saved. The config has four sections:
+Every strategy is normalized and validated by `api/_lib/strategy-schema.js` before it persists. Free text is impossible; a malformed rule set cannot be saved. The current config is `version: 2`. It carries a top-level `mode` and five sections:
-- **entry**: trigger (`new_launch`), `max_age_minutes`, optional min/max market cap, min liquidity, `require_socials`, creator-history gates (`max_creator_launches`, `min_creator_graduated`), and `require_sol_quote`.
-- **sizing**: `amount_sol` per trade and `max_slippage_bps`.
+- **mode**: `ask` (the default) or `auto`. See [Ask before each buy](#ask-before-each-buy-or-auto-within-caps) below.
+- **entry**: trigger (`new_launch`), `sources` (`[]` for every launch, or `["three_ws_launch"]` for coins launched through three.ws only), `max_age_minutes`, an optional market cap band (`min_market_cap_usd`, `max_market_cap_usd`), `require_socials`, and `require_sol_quote`.
+- **sizing**: `amount_sol` per trade, `max_slippage_bps`, and an optional `max_price_impact_bps`.
+- **research**: the gates a coin must clear before any buy. See [Research gates](#research-gates) below.
- **exits**: `take_profit_pct`, a mandatory `stop_loss_pct`, optional `trailing_stop_pct`, and `max_hold_minutes`. Validation requires a stop-loss and at least one upside exit.
- **risk**: `max_concurrent_positions` and `cooldown_minutes`.
+Keys are stored snake_case; camelCase (`maxPriceImpactBps`, `devHistory.blockDevSold`) is accepted on the way in and rewritten. Version 1 configs keep working: their `entry.min_liquidity_sol`, `entry.max_creator_launches`, and `entry.min_creator_graduated` fold into the matching research gates, and both halves are written back identical so the two evaluators can never disagree.
+
+```json
+{
+ "version": 2,
+ "mode": "ask",
+ "network": "mainnet",
+ "entry": { "trigger": "new_launch", "sources": [], "max_age_minutes": 10, "max_market_cap_usd": 30000 },
+ "sizing": { "amount_sol": 0.1, "max_slippage_bps": 1000, "max_price_impact_bps": 300 },
+ "research": {
+ "min_holders": 50,
+ "max_top_holder_pct": 20,
+ "min_liquidity_sol": 5,
+ "security_min_score": 60,
+ "require_no_mint_authority": true,
+ "require_no_freeze_authority": true,
+ "dev_history": { "max_launches": 3, "min_graduated": 1, "block_dev_sold": true }
+ },
+ "exits": { "take_profit_pct": 100, "stop_loss_pct": 40 },
+ "risk": { "max_concurrent_positions": 3, "cooldown_minutes": 0 }
+}
+```
+
The schema enforces hard bounds on every field, so a stored config can never carry a nonsense number into the runtime. Two pure, synchronous functions, `matchesEntry` (does this real launch pass the entry gate) and `shouldExit` (should this open position close now), are the same logic the live equipped-strategy runtime (`api/_lib/agent-strategy-runtime.js`) and the assisted scan preview (`POST /api/trading/scan`) both evaluate, so a stored rule means exactly the same thing everywhere it runs. The assisted scan is owner-scoped and rate-limited twice (per IP and per owner, because every match it prices costs an upstream call); when the live launch feed cannot be reached it answers `502 feed_unavailable` rather than an empty scan that looks like "nothing matched".
+### Research gates
+
+A research gate is a question the runtime answers about a candidate coin before it spends anything. Every gate is optional (`null` or `false` means off). The answers come from the platform's existing readers (`api/_lib/strategy-research.js`), never from a guess, and only the sections a strategy actually gates on are fetched:
+
+| Gate | Field | Evidence |
+|---|---|---|
+| Minimum holders | `research.min_holders` | holder count from the indexer |
+| Largest holder ceiling | `research.max_top_holder_pct` | intel engine share of bought supply, or the on-chain top holders with the bonding curve excluded |
+| Minimum liquidity | `research.min_liquidity_sol` | live bonding-curve liquidity from the launch feed |
+| Firewall score | `research.security_min_score` | the same rug and honeypot firewall every buy already passes, run with the agent's real wallet and the strategy's real size |
+| Mint authority renounced | `research.require_no_mint_authority` | the SPL mint account, read by the firewall |
+| Freeze authority renounced | `research.require_no_freeze_authority` | the SPL mint account, read by the firewall |
+| Creator launch ceiling | `research.dev_history.max_launches` | the creator's recorded launch history |
+| Creator graduations | `research.dev_history.min_graduated` | the creator's recorded launch history |
+| Creator has not sold | `research.dev_history.block_dev_sold` | the intel engine's dev-sold flag |
+
+Gates fail closed. A gate you switched on whose data could not be read blocks the buy with an "unknown" reason, because a gate exists to prove something before money moves. Every block is written to the candidate decision log (`strategy_candidate_decisions`, one row per strategy and coin) with the check that stopped it, the actual and required values, a plain-language reason, and the cited report it was decided on. Token names and symbols are untrusted data: they never appear in a reason or a risk note.
+
+**Price impact.** `sizing.max_price_impact_bps` skips a buy whose quote would move the price more than the cap (300 bps is 3%). It can only tighten the agent's own price-impact breaker, never loosen it: the runtime uses the smaller of the two.
+
+### Ask before each buy, or auto within caps
+
+In **ask** mode (the default, and what every strategy saved before version 2 was migrated to) a coin that clears the entry filter and every research gate is dry-run through every spend guard, then filed as an approval request instead of bought. The request carries the exact buy (agent, coin, amount, slippage, impact cap) plus its sha256 payload hash, the risk notes from the gate report, and a 15 minute expiry. It shows on the agent's strategy panel and in the approvals inbox. Approving sends back the hash you reviewed; the buy runs once with the same idempotency key and re-checks every guard at that moment, so an approval can never buy something different from what you saw, and a stale approval that a guard now refuses buys nothing. A coin is asked about once per strategy: a denied or expired request is never re-filed. Pending requests count against the strategy's concurrency cap.
+
+In **auto** mode the runtime buys on its own, still inside every research gate, the strategy's caps, and the agent's spend policy. Switching an equipped strategy to auto requires the real-funds agreement. Switch per equip from the agent's strategy panel or with `POST /api/agents/:id/strategies/mode`.
+
+### Settings, live preview, and the gated backtest
+
+The builder at `/strategies?editor=new` (and the edit modal) edits one config three ways that stay in sync: sliders paired with number boxes and an on/off toggle per gate, plain checkboxes for the yes/no gates, and the raw JSON under **Edit as JSON**. A typed JSON change is parsed as you go and applied to the controls; an invalid edit is flagged and leaves the form untouched.
+
+- **Describe it in words.** The **Describe your strategy** box runs the natural-language compiler (`POST /api/sniper/compile`). It emits every version 2 field, explains each one, clamps the price-impact cap to your agent's breaker, and lists what it assumed. "Buy three.ws launches with at least 150 holders, renounced mint and freeze, 3% price impact, ask me first" fills the form.
+- **Live preview.** The side card replays the last 1, 6, or 24 hours of recorded launches through the same entry filter and research gates (`POST /api/strategies/preview`) and shows how many coins the settings would have bought, a funnel (entry, research, within impact), the gates that blocked the most, and sample coins. Firewall-only checks (score and authorities) are often missing from history, so a coin that clears everything else counts as "checked at buy" rather than blocked. The preview is public, read-only, and refreshes as you edit.
+- **Gated backtest.** **Backtest with these gates** runs the sniper backtester with the research block applied, over 7, 30, or 90 days, and reports which gates skipped how many launches alongside the usual metrics and caveats.
+
### The library, leaderboard, and forking
`/strategies` has three surfaces on one page: the marketplace of published strategies (proven first), the leaderboard ranked by real live ROI, and your own library (create, edit, publish, equip, delete). The full-page builder lives in the URL (`?editor=new` or `?editor=<id>`) so it survives reload and the back button. Forking copies the rules only, credits lineage to the author, and gives you fresh ownership; equipping attaches the strategy to an agent you own, which then runs it under its own spend policy.
@@ -50,11 +109,11 @@ A second, separate backtester serves sniper-style rule sets: `POST /api/sniper/b
## Walkthrough
1. Open [/strategies](https://three.ws/strategies) and browse the published marketplace, or switch to the leaderboard to see strategies ranked by real live ROI.
-2. Click **New strategy**. The full-page builder opens. Set your entry conditions, per-trade size and slippage, a required stop-loss and at least one upside exit, and your risk caps. Save.
+2. Click **New strategy**. The full-page builder opens. Describe the strategy in words, or set the entry conditions, research gates, per-trade size, slippage and price-impact cap, a required stop-loss and at least one upside exit, and your risk caps. Watch the live preview count change as you edit, run the gated backtest, then save.
3. To prove it, open [/strategy-lab](https://three.ws/strategy-lab), paste or write the spec, and **Validate**. Fix any field-tagged errors it returns.
4. **Backtest** it over real recorded launches and trades. For a sniper rule set, `POST /api/sniper/backtest` replays the captured outcome history and reports its own limitations; read the `caveats` before you trust a number.
5. **Run** it in Simulate mode first: watch the live SSE stream of entries, exits, and logs with no funds at risk.
-6. Equip the strategy on an agent you own (or flip the Lab run to Live with that agent), and it trades within that agent's spend policy. Fork, edit, publish, or delete from your library at any time.
+6. Equip the strategy on an agent you own (or flip the Lab run to Live with that agent), and it trades within that agent's spend policy. It starts in ask mode: each buy waits on the agent's strategy panel for your approval. Open **Decision log** on that panel to see which gate blocked which coin, and switch to **Auto** once you trust the gates. Fork, edit, publish, or delete from your library at any time.
## Examples
@@ -68,6 +127,39 @@ curl -s 'https://three.ws/api/strategies/leaderboard?limit=10' \
| jq '.data.leaders[] | {rank, name, roi_pct: .performance.roi_pct}'
```
+Preview how many recent launches a config would have bought (public, no auth):
+
+```bash
+curl -s https://three.ws/api/strategies/preview \
+ -H 'content-type: application/json' \
+ -d '{
+ "hours": 6,
+ "config": {
+ "sizing": { "amount_sol": 0.1, "max_price_impact_bps": 300 },
+ "research": { "min_holders": 50, "max_top_holder_pct": 20 }
+ }
+ }' | jq '.data | {universe, passed_entry, passed_research, would_buy, blocked_by}'
+```
+
+Review and approve an ask-mode buy (owner, auth required). Send back the `payload_hash` you reviewed; a mismatch is refused:
+
+```bash
+curl -s 'https://three.ws/api/agents/YOUR_AGENT_UUID/strategies/approvals?status=pending' \
+ -H 'authorization: Bearer YOUR_TOKEN' | jq '.data.approvals[] | {id, summary, payload_hash, risk_notes, expires_at}'
+
+curl -s https://three.ws/api/agents/YOUR_AGENT_UUID/strategies/approve \
+ -H 'authorization: Bearer YOUR_TOKEN' \
+ -H 'content-type: application/json' \
+ -d '{ "approval_id": "APPROVAL_UUID", "payload_hash": "HASH_FROM_THE_LIST" }' | jq '.data'
+```
+
+Read the decision log to see which gate stopped which coin:
+
+```bash
+curl -s 'https://three.ws/api/agents/YOUR_AGENT_UUID/strategies/decisions?decision=blocked&limit=20' \
+ -H 'authorization: Bearer YOUR_TOKEN' | jq '.data.decisions[] | {mint, check_name, reason}'
+```
+
Backtest a sniper rule set against the real captured pump.fun launch history (auth required; bearer tokens skip CSRF):
```bash
@@ -91,6 +183,9 @@ curl -s https://three.ws/api/sniper/backtest \
- **Strategy caps never override the spend leash.** Per-trade size, slippage, and concurrency are additional constraints on top of the agent's server-side policy. A live run's buys pass `checkBuyAllowed`; a strategy cannot spend past your limits.
- **Simulate versus live.** The Lab defaults to Simulate (no wallet, no funds). Live requires auth, an owned agent with a provisioned Solana wallet, and enforces the spend policy on every buy.
+- **Research gates fail closed.** A gate whose data could not be read blocks the buy and says so; "could not check" is never "passed".
+- **Ask is the default.** A strategy files an approval request for each buy until its owner switches it to auto (which needs the real-funds agreement). An approval executes once, against the exact payload hash the owner reviewed, and re-checks every guard first.
+- **A strategy's impact cap only tightens.** The runtime uses the smaller of the strategy's `max_price_impact_bps` and the agent's breaker.
- **A stop-loss is mandatory.** Validation rejects any strategy without a stop-loss and requires at least one upside exit (take-profit, trailing stop, or max hold). Every field is clamped to hard bounds.
- **Proven, not promised.** Performance is aggregated from real closed on-chain positions. No closed trades means "Unproven", not a synthetic curve. The leaderboard ranks by verified live ROI.
- **Backtest honesty.** Both backtesters replay real recorded history with the same evaluator their live path runs; neither invents launches, outcomes, or price paths. The sniper backtester additionally reports its own limitations in `caveats` and returns an explicit `insufficient_data` verdict on a too-thin window.
diff --git a/src/shared/agent-strategy-panel.js b/src/shared/agent-strategy-panel.js
index eac63f195..762e709ec 100644
--- a/src/shared/agent-strategy-panel.js
+++ b/src/shared/agent-strategy-panel.js
@@ -4,6 +4,9 @@
// • Owner of the viewed agent → manage the strategies THIS agent runs: the global
// kill switch (leash), each equip with its live P&L + positions, pause/unequip,
// "Run now", and "+ Equip a strategy" (from your library or the marketplace).
+// Each equip also carries its buy mode (ask before each buy, or auto within
+// caps), the pending approval requests ask mode files, and a decision log of
+// which research check blocked or bought which coin.
// • Visitor → the strategies THIS agent's creator publishes (equip one with your
// own agent — the sibling primitive to mirroring), or a browse-the-library CTA.
// • Logged-out → the same discovery + a sign-in prompt.
@@ -16,6 +19,7 @@ import {
ensureStrategyStyles, esc, shortAddr, fmtSol, timeAgo, toast, configSummary,
openStrategyEditor, openEquipPicker, VIOLET,
} from './strategy-forms.js';
+import { ensureRiskAck } from './risk-ack.js';
const STYLE_ID = 'sop-panel-styles';
function ensurePanelStyles() {
@@ -78,18 +82,76 @@ function ensurePanelStyles() {
.sop-mp-body { flex: 1 1 auto; min-width: 0; }
.sop-mp-name { font-size: var(--text-sm, .82rem); font-weight: 600; color: var(--ink-bright, #fff); }
.sop-mp-sum { font-size: var(--text-2xs, .62rem); color: var(--ink-dim, #9a9a9a); margin-top: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.sop-mode { display: flex; align-items: center; gap: 8px; margin-top: 8px; font-size: var(--text-2xs, .64rem); color: var(--ink-dim, #9a9a9a); flex-wrap: wrap; }
+.sop-seg { display: inline-flex; border: 1px solid var(--stroke-strong, rgba(255,255,255,.14)); border-radius: 999px; padding: 2px; }
+.sop-seg button { font: inherit; font-size: var(--text-2xs, .64rem); padding: 3px 10px; border: 0; border-radius: 999px; background: transparent; color: var(--ink-dim, #9a9a9a); cursor: pointer; transition: background .16s, color .16s; }
+.sop-seg button:hover:not([aria-pressed="true"]) { color: var(--ink-bright, #fff); }
+.sop-seg button[aria-pressed="true"] { background: var(--wallet-accent-soft, rgba(139,92,246,.18)); color: ${VIOLET}; font-weight: 700; cursor: default; }
+.sop-seg button[data-mode="auto"][aria-pressed="true"] { background: rgba(74,222,128,.14); color: var(--success, #4ade80); }
+.sop-seg button:focus-visible { outline: 2px solid var(--wallet-focus, rgba(139,92,246,.7)); outline-offset: 1px; }
+.sop-seg button:disabled { opacity: .5; cursor: progress; }
+.sop-appr { border: 1px solid var(--warn, #fbbf24); border-radius: var(--radius-md, 10px); background: rgba(251,191,36,.05); padding: var(--space-sm, 10px) var(--space-md, 12px); animation: sop-in .24s ease both; }
+@keyframes sop-in { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } }
+@media (prefers-reduced-motion: reduce) { .sop-appr { animation: none; } }
+.sop-appr + .sop-appr { margin-top: 6px; }
+.sop-appr-h { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
+.sop-appr-sum { font-size: var(--text-sm, .8rem); color: var(--ink-bright, #fff); font-weight: 600; min-width: 0; overflow-wrap: anywhere; }
+.sop-appr-exp { font-family: var(--font-mono, monospace); font-size: var(--text-2xs, .64rem); color: var(--warn, #fbbf24); white-space: nowrap; }
+.sop-appr-tbl { display: grid; grid-template-columns: auto 1fr; gap: 3px 10px; margin: 8px 0; font-size: var(--text-2xs, .66rem); }
+.sop-appr-tbl dt { color: var(--ink-faint, #808080); }
+.sop-appr-tbl dd { margin: 0; color: var(--ink, #ddd); min-width: 0; overflow-wrap: anywhere; }
+.sop-appr-tbl a { color: ${VIOLET}; text-decoration: none; font-family: var(--font-mono, monospace); }
+.sop-appr-tbl a:hover { text-decoration: underline; }
+.sop-appr-notes { margin: 0 0 8px; padding-left: 16px; font-size: var(--text-2xs, .64rem); color: var(--ink-dim, #a8a8a8); line-height: 1.5; }
+.sop-appr-act { display: flex; gap: 6px; justify-content: flex-end; }
+.sop-log { border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md, 10px); padding: 0 var(--space-md, 12px); }
+.sop-log > summary { cursor: pointer; padding: 9px 0; font-size: var(--text-xs, .72rem); color: var(--ink, #ddd); font-weight: 600; }
+.sop-log > summary:focus-visible { outline: 2px solid var(--wallet-focus, rgba(139,92,246,.7)); outline-offset: 2px; border-radius: 4px; }
+.sop-log-body { padding-bottom: 10px; display: flex; flex-direction: column; gap: 4px; }
+.sop-dec { display: grid; grid-template-columns: auto 1fr auto; gap: 2px 8px; align-items: baseline; font-size: var(--text-2xs, .66rem); padding: 5px 8px; border-radius: var(--radius-sm, 6px); background: var(--surface-1, rgba(255,255,255,.025)); }
+.sop-dec .sop-dot { align-self: center; }
+.sop-dec-main { min-width: 0; color: var(--ink, #ddd); overflow-wrap: anywhere; }
+.sop-dec-main a { color: ${VIOLET}; text-decoration: none; font-family: var(--font-mono, monospace); }
+.sop-dec-when { color: var(--ink-faint, #777); white-space: nowrap; }
+.sop-dec-why { grid-column: 2 / -1; color: var(--ink-dim, #9a9a9a); line-height: 1.4; }
+.sop-dot.blocked { background: var(--danger, #f87171); }
+.sop-dot.approval { background: var(--warn, #fbbf24); }
+.sop-dot.executed { background: var(--success, #4ade80); }
+.sop-dot.skipped { background: var(--ink-dim, #888); }
`;
document.head.appendChild(s);
}
const LEASH_SVG = '<svg class="sop-leash-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.7 21a2 2 0 0 1-3.4 0"/></svg>';
+// Devnet equips trade test SOL, so the server waives the real-funds agreement for them.
+const isDevnet = (e) => String(e?.network || '').toLowerCase() === 'devnet';
+// Server errors come back as { error: code, error_description }.
+const errMsg = (j, fallback) => j?.error_description || j?.error?.message || (typeof j?.error === 'string' ? j.error.replace(/_/g, ' ') : '') || fallback;
+
+const DECISION_WORD = { blocked: 'Blocked', approval: 'Asked you', executed: 'Bought', skipped: 'Skipped', failed: 'Failed' };
+const CHECK_LABELS = {
+ min_holders: 'Minimum holders', max_top_holder_pct: 'Largest holder share', min_liquidity_sol: 'Minimum liquidity',
+ security_min_score: 'Firewall security score', require_no_mint_authority: 'Mint authority renounced',
+ require_no_freeze_authority: 'Freeze authority renounced', dev_max_launches: 'Creator launch count',
+ dev_min_graduated: 'Creator graduations', dev_block_sold: 'Creator has not sold', mode_ask: 'Ask mode',
+ approval_unavailable: 'Approval request', price_impact: 'Price impact',
+};
+
+function expiresIn(t) {
+ const ms = new Date(t).getTime() - Date.now();
+ if (!(ms > 0)) return 'expired';
+ const m = Math.floor(ms / 60000), sec = Math.floor((ms % 60000) / 1000);
+ return `${m}:${String(sec).padStart(2, '0')} left`;
+}
+
export function mountStrategyPanel({ mount, agent, isOwner = false }) {
if (!mount) return { destroy() {} };
ensurePanelStyles();
const card = mount.closest('#ad-strategy-objects-card') || mount.parentElement;
const agentId = agent.id;
let alive = true;
+ let countdown = null;
const isLoggedIn = () => window.__authed !== false;
const root = document.createElement('div');
root.className = 'sop';
@@ -146,6 +208,10 @@ export function mountStrategyPanel({ mount, agent, isOwner = false }) {
</div>
</div>
<div class="sop-perf">${perfLine(e.performance)}${e.last_fired_at ? `<span>last fired ${timeAgo(e.last_fired_at)}</span>` : ''}</div>
+ <div class="sop-mode"><span>Buys</span><span class="sop-seg" role="group" aria-label="Buy mode for ${esc(e.strategy_name)}">
+ <button type="button" data-mode="ask" aria-pressed="${modeOf(e) === 'ask'}" title="File an approval request for every match">Ask first</button>
+ <button type="button" data-mode="auto" aria-pressed="${modeOf(e) === 'auto'}" title="Buy every match within the agent's caps">Auto</button>
+ </span><span>${modeOf(e) === 'auto' ? 'buys matches on its own, within caps' : 'waits for your approval on every buy'}</span></div>
${ps.length ? `<div class="sop-pos">${ps.map(positionRow).join('')}</div>` : ''}
</div>`;
}).join('')
@@ -163,9 +229,136 @@ export function mountStrategyPanel({ mount, agent, isOwner = false }) {
<div style="font-size:var(--text-2xs,.64rem);color:var(--ink-dim,#9a9a9a)">${d.equips.length} equipped</div>
<button class="sop-btn" data-act="run" ${d.killed ? 'disabled' : ''} title="Evaluate launches & positions now">↻ Run now</button>
</div>
+ <div id="sop-approvals" aria-live="polite"></div>
<div id="sop-equips">${equipsHtml}</div>
- <div class="sop-add"><button class="sop-btn sop-btn-primary" data-act="equip" style="margin-top:4px">+ Equip a strategy</button> <a class="sop-btn" href="/strategies" style="text-decoration:none;display:inline-block">Open library</a></div>`;
+ <div class="sop-add"><button class="sop-btn sop-btn-primary" data-act="equip" style="margin-top:4px">+ Equip a strategy</button> <a class="sop-btn" href="/strategies" style="text-decoration:none;display:inline-block">Open library</a></div>
+ ${d.equips.length ? '<details class="sop-log" id="sop-log"><summary>Decision log: what each check blocked or bought</summary><div class="sop-log-body" id="sop-log-body"></div></details>' : ''}`;
wireOwner(d);
+ if (d.equips.length) loadApprovals();
+ }
+
+ function modeOf(e) { return e.config?.mode === 'auto' ? 'auto' : 'ask'; }
+
+ // Pending ask-mode buys. Each card shows exactly what will be signed (coin,
+ // amount, chain, where the SOL goes, the research notes) and expires on its own.
+ async function loadApprovals() {
+ const host = root.querySelector('#sop-approvals');
+ if (!host) return;
+ let rows = [];
+ try {
+ const res = await apiFetch(`/api/agents/${agentId}/strategies/approvals?status=pending&limit=10`, { allowAnonymous: true });
+ if (!res.ok) throw new Error(errMsg(await res.json().catch(() => ({})), 'Could not load approval requests'));
+ rows = (await res.json()).data?.approvals || [];
+ } catch (err) {
+ if (err?.redirected || !alive) return;
+ host.innerHTML = `<div class="sop-err">${esc(err.message)} <button class="sop-btn" data-retry-appr>Retry</button></div>`;
+ host.querySelector('[data-retry-appr]')?.addEventListener('click', loadApprovals);
+ return;
+ }
+ if (!alive) return;
+ clearInterval(countdown);
+ if (!rows.length) { host.innerHTML = ''; return; }
+ host.innerHTML = `<div class="sop-h">Waiting for your approval (${rows.length})</div>${rows.map(approvalCard).join('')}`;
+ countdown = setInterval(() => {
+ if (!alive || !host.isConnected) { clearInterval(countdown); return; }
+ let anyLive = false;
+ host.querySelectorAll('[data-expires]').forEach((el) => {
+ const left = expiresIn(el.dataset.expires);
+ el.textContent = left;
+ if (left === 'expired') el.closest('.sop-appr')?.querySelector('[data-approve]')?.setAttribute('disabled', '');
+ else anyLive = true;
+ });
+ if (!anyLive) { clearInterval(countdown); loadApprovals(); }
+ }, 1000);
+ host.querySelectorAll('.sop-appr').forEach((cardEl) => {
+ const a = rows.find((r) => r.id === cardEl.dataset.id);
+ cardEl.querySelector('[data-approve]')?.addEventListener('click', (ev) => approve(a, ev.currentTarget));
+ cardEl.querySelector('[data-deny]')?.addEventListener('click', (ev) => deny(a, ev.currentTarget));
+ });
+ }
+
+ function approvalCard(a) {
+ const mint = a.payload?.mint || a.recipient;
+ const usd = a.amount_usd != null ? ` (about $${Number(a.amount_usd).toFixed(2)})` : '';
+ const notes = Array.isArray(a.risk_notes) ? a.risk_notes : [];
+ return `<div class="sop-appr" data-id="${esc(a.id)}">
+ <div class="sop-appr-h"><div class="sop-appr-sum">${esc(a.summary)}</div><span class="sop-appr-exp" data-expires="${esc(a.expires_at)}">${expiresIn(a.expires_at)}</span></div>
+ <dl class="sop-appr-tbl">
+ <dt>Amount</dt><dd>◎${fmtSol(a.amount)} SOL${usd}</dd>
+ <dt>Token</dt><dd><a href="/coin/${encodeURIComponent(mint)}" title="${esc(mint)}">${esc(shortAddr(mint, 6, 6))}</a></dd>
+ <dt>Chain</dt><dd>Solana ${a.network === 'devnet' ? 'devnet' : 'mainnet'}</dd>
+ <dt>Pays</dt><dd>${esc(a.recipient_label || shortAddr(a.recipient))}</dd>
+ <dt>Limits</dt><dd>${a.payload?.slippage_bps != null ? `${a.payload.slippage_bps / 100}% slippage` : ''}${a.payload?.max_price_impact_pct != null ? ` · ${a.payload.max_price_impact_pct}% max impact` : ''}</dd>
+ </dl>
+ ${notes.length ? `<ul class="sop-appr-notes">${notes.map((n) => `<li>${esc(n)}</li>`).join('')}</ul>` : ''}
+ <div class="sop-appr-act">
+ <button type="button" class="sop-btn" data-deny>Deny</button>
+ <button type="button" class="sop-btn sop-btn-primary" data-approve>Approve and buy</button>
+ </div>
+ </div>`;
+ }
+
+ async function approve(a, btn) {
+ if (!a) return;
+ if (!(await ensureRiskAck({ context: 'strategy' }))) return;
+ const card = btn.closest('.sop-appr');
+ card?.querySelectorAll('button').forEach((b) => { b.disabled = true; });
+ btn.textContent = 'Buying…';
+ try {
+ const res = await apiFetch(`/api/agents/${agentId}/strategies/approve`, {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ approval_id: a.id, payload_hash: a.payload_hash }),
+ });
+ const j = await res.json().catch(() => ({}));
+ if (!res.ok && !j.data) throw new Error(errMsg(j, 'Could not approve'));
+ const r = j.data || {};
+ if (r.executed) toast(r.already ? 'Already approved' : 'Approved: the buy went through within your caps');
+ else toast(`Nothing was bought: ${r.message || r.code || 'the trade did not complete'}`);
+ } catch (err) { if (!err?.redirected) toast(err.message || 'Could not approve'); }
+ load();
+ }
+
+ async function deny(a, btn) {
+ if (!a) return;
+ btn.disabled = true;
+ try {
+ const res = await apiFetch(`/api/agents/${agentId}/strategies/deny`, {
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ approval_id: a.id }),
+ });
+ if (!res.ok) throw new Error(errMsg(await res.json().catch(() => ({})), 'Could not deny'));
+ toast('Denied. This coin will not be asked about again.');
+ } catch (err) { if (!err?.redirected) toast(err.message || 'Could not deny'); }
+ loadApprovals();
+ }
+
+ async function loadDecisions() {
+ const body = root.querySelector('#sop-log-body');
+ if (!body) return;
+ body.innerHTML = '<div class="sop-sk" style="height:30px"></div><div class="sop-sk" style="height:30px"></div>';
+ try {
+ const res = await apiFetch(`/api/agents/${agentId}/strategies/decisions?limit=30`, { allowAnonymous: true });
+ if (!res.ok) throw new Error(errMsg(await res.json().catch(() => ({})), 'Could not load the decision log'));
+ const rows = (await res.json()).data?.decisions || [];
+ if (!alive) return;
+ body.innerHTML = rows.length
+ ? rows.map(decisionRow).join('')
+ : '<div class="sop-empty" style="padding:12px"><strong>No decisions yet</strong>Each sweep (every 2 minutes, or Run now) records why a launch was bought, asked about, or blocked.</div>';
+ } catch (err) {
+ if (err?.redirected || !alive) return;
+ body.innerHTML = `<div class="sop-err">${esc(err.message)} <button class="sop-btn" data-retry-log>Retry</button></div>`;
+ body.querySelector('[data-retry-log]')?.addEventListener('click', loadDecisions);
+ }
+ }
+
+ function decisionRow(r) {
+ const check = r.check_name ? (CHECK_LABELS[r.check_name] || r.check_name.replace(/_/g, ' ')) : '';
+ const seen = r.seen_count > 1 ? ` · seen ${r.seen_count}×` : '';
+ return `<div class="sop-dec">
+ <span class="sop-dot ${esc(r.decision)}"></span>
+ <span class="sop-dec-main"><b>${DECISION_WORD[r.decision] || esc(r.decision)}</b> <a href="/coin/${encodeURIComponent(r.mint)}">${esc(shortAddr(r.mint))}</a>${r.strategy_name ? ` · ${esc(r.strategy_name)}` : ''}${check ? ` · ${esc(check)}` : ''}${r.signature ? ` <a href="https://solscan.io/tx/${esc(r.signature)}" target="_blank" rel="noopener" title="View on Solscan">↗</a>` : ''}</span>
+ <span class="sop-dec-when">${esc(timeAgo(r.updated_at))}${seen}</span>
+ ${r.reason ? `<span class="sop-dec-why">${esc(r.reason)}</span>` : ''}
+ </div>`;
}
function wireOwner(d) {
@@ -175,19 +368,24 @@ export function mountStrategyPanel({ mount, agent, isOwner = false }) {
load();
});
root.querySelector('[data-act="run"]')?.addEventListener('click', async (e) => {
- const btn = e.currentTarget; btn.disabled = true; btn.textContent = 'Running…';
+ const btn = e.currentTarget;
+ // The sweep only needs the real-funds agreement when a mainnet equip is in it.
+ if (d.equips.some((x) => !isDevnet(x)) && !(await ensureRiskAck({ context: 'strategy' }))) return;
+ btn.disabled = true; btn.textContent = 'Running…';
try {
const res = await apiFetch(`/api/agents/${agentId}/strategies/sweep`, { method: 'POST' });
const j = await res.json().catch(() => ({}));
- if (!res.ok) throw new Error(j?.error?.message || 'Run failed');
+ if (!res.ok) throw new Error(errMsg(j, 'Run failed'));
const all = (j.data?.results || []).flatMap((r) => r.results || []);
const exec = all.filter((r) => r.status === 'executed').length;
+ const asked = all.filter((r) => r.status === 'approval' && r.created).length;
const skip = all.filter((r) => r.status === 'skipped').length;
- toast(all.length ? `Evaluated: ${exec} executed, ${skip} skipped` : 'No entries or exits this run');
+ toast(all.length ? `Evaluated: ${exec} bought, ${asked} waiting for you, ${skip} skipped` : 'No entries or exits this run');
} catch (err) { if (!err?.redirected) toast(err.message || 'Run failed'); }
load();
});
root.querySelector('[data-act="equip"]')?.addEventListener('click', () => openEquipFlow());
+ root.querySelector('#sop-log')?.addEventListener('toggle', (ev) => { if (ev.currentTarget.open) loadDecisions(); });
root.querySelectorAll('.sop-equip').forEach((row) => {
const equipId = row.dataset.equip;
const e = d.equips.find((x) => x.equip_id === equipId);
@@ -196,6 +394,17 @@ export function mountStrategyPanel({ mount, agent, isOwner = false }) {
await postAction('toggle', { equip_id: equipId, active: !e.active }, e.active ? 'Strategy paused' : 'Strategy resumed');
load();
});
+ row.querySelectorAll('[data-mode]').forEach((b) => b.addEventListener('click', async () => {
+ const mode = b.dataset.mode;
+ if (mode === modeOf(e)) return;
+ if (mode === 'auto') {
+ if (!confirm(`Switch “${e.strategy_name}” to auto? It will buy every coin that passes its gates without asking, always inside this agent's spend policy.`)) return;
+ if (!isDevnet(e) && !(await ensureRiskAck({ context: 'strategy' }))) return;
+ }
+ row.querySelectorAll('[data-mode]').forEach((x) => { x.disabled = true; });
+ await postAction('mode', { equip_id: equipId, mode }, mode === 'auto' ? 'Auto: buys within caps without asking' : 'Ask first: every buy waits for your approval');
+ load();
+ }));
row.querySelector('[data-act="unequip"]')?.addEventListener('click', async () => {
if (!confirm(`Unequip “${e.strategy_name}”? Open positions stay yours to manage; no new entries start.`)) return;
await postAction('unequip', { equip_id: equipId }, 'Strategy unequipped');
@@ -209,9 +418,10 @@ export function mountStrategyPanel({ mount, agent, isOwner = false }) {
const res = await apiFetch(`/api/agents/${agentId}/strategies/${action}`, {
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body || {}),
});
- if (!res.ok) { const j = await res.json().catch(() => ({})); throw new Error(j?.error?.message || 'Action failed'); }
+ if (!res.ok) throw new Error(errMsg(await res.json().catch(() => ({})), 'Action failed'));
if (okMsg) toast(okMsg);
- } catch (e) { if (!e?.redirected) toast(e.message || 'Action failed'); }
+ return true;
+ } catch (e) { if (!e?.redirected) toast(e.message || 'Action failed'); return false; }
}
// Owner "+ Equip": pick a strategy from your library (or create one), then equip it here.
@@ -325,5 +535,5 @@ export function mountStrategyPanel({ mount, agent, isOwner = false }) {
}
load();
- return { destroy() { alive = false; mount.replaceChildren(); } };
+ return { destroy() { alive = false; clearInterval(countdown); mount.replaceChildren(); } };
}
diff --git a/src/shared/strategy-forms.js b/src/shared/strategy-forms.js
index 39b7b28cf..ea10055ab 100644
--- a/src/shared/strategy-forms.js
+++ b/src/shared/strategy-forms.js
@@ -8,6 +8,7 @@
// /api/agents/:id/strategies. No mock state, no fake preview numbers.
import { apiFetch } from '../api.js';
+import { mountLivePreview, mountCompileBox, mountGatedBacktest } from './strategy-settings.js';
export const VIOLET = 'var(--wallet-accent, #c4b5fd)';
@@ -51,22 +52,37 @@ export function toast(msg, ms = 2800) {
// ── rule summary: a one-line, honest plain-language read of a config ──────────
export function configSummary(config) {
const c = config || {};
- const e = c.entry || {}, s = c.sizing || {}, x = c.exits || {}, k = c.risk || {};
+ const e = c.entry || {}, s = c.sizing || {}, x = c.exits || {}, k = c.risk || {}, r = c.research || {};
+ const dv = r.dev_history || {};
const parts = [];
+ if (Array.isArray(e.sources) && e.sources.length === 1 && e.sources[0] === 'three_ws_launch') parts.push('three.ws launches');
if (e.max_age_minutes != null) parts.push(`launches &lt;${e.max_age_minutes}m old`);
- if (e.min_liquidity_sol != null) parts.push(`liq ≥◎${fmtSol(e.min_liquidity_sol)}`);
+ const liq = r.min_liquidity_sol ?? e.min_liquidity_sol;
+ if (liq != null) parts.push(`liq ≥◎${fmtSol(liq)}`);
if (e.min_market_cap_usd != null || e.max_market_cap_usd != null) {
const lo = e.min_market_cap_usd != null ? `$${fmtUsdShort(e.min_market_cap_usd)}` : '';
const hi = e.max_market_cap_usd != null ? `$${fmtUsdShort(e.max_market_cap_usd)}` : '';
parts.push(`MC ${lo}${lo && hi ? ' to ' : ''}${hi}`);
}
if (e.require_socials) parts.push('has socials');
+ if (r.min_holders != null) parts.push(`≥${r.min_holders} holders`);
+ if (r.max_top_holder_pct != null) parts.push(`top holder ≤${r.max_top_holder_pct}%`);
+ if (r.security_min_score != null) parts.push(`security ≥${r.security_min_score}`);
+ if (r.require_no_mint_authority || r.require_no_freeze_authority) parts.push('authorities renounced');
+ const launches = dv.max_launches ?? e.max_creator_launches;
+ if (launches != null) parts.push(`dev ≤${launches} launches`);
+ const grads = dv.min_graduated ?? e.min_creator_graduated;
+ if (grads != null) parts.push(`dev ≥${grads} grads`);
+ if (dv.block_dev_sold) parts.push('dev holding');
parts.push(`size ◎${fmtSol(s.amount_sol)}`);
+ if (s.max_price_impact_bps != null) parts.push(`impact ≤${Number(s.max_price_impact_bps) / 100}%`);
if (x.take_profit_pct != null) parts.push(`TP +${x.take_profit_pct}%`);
if (x.stop_loss_pct != null) parts.push(`SL −${x.stop_loss_pct}%`);
if (x.trailing_stop_pct != null) parts.push(`trail ${x.trailing_stop_pct}%`);
if (x.max_hold_minutes != null) parts.push(`≤${formatMinutes(x.max_hold_minutes)}`);
if (k.max_concurrent_positions != null) parts.push(`max ${k.max_concurrent_positions} open`);
+ if (c.mode === 'auto') parts.push('auto');
+ else if (c.version >= 2 || c.mode === 'ask') parts.push('asks first');
return parts.join(' · ');
}
function fmtUsdShort(v) {
@@ -132,6 +148,12 @@ export function ensureStrategyStyles() {
.so-compose-grid { display: grid; grid-template-columns: 1fr; gap: var(--space-lg, 20px); }
@media (min-width: 880px) { .so-compose-grid { grid-template-columns: minmax(0, 1fr) 296px; align-items: start; } }
@media (min-width: 880px) { .so-compose-side { position: sticky; top: 84px; } }
+.so-mbar { position: sticky; bottom: 12px; z-index: 5; display: flex; align-items: center; justify-content: space-between; gap: 10px; margin: 14px 0 0; padding: 10px 12px; border: 1px solid var(--wallet-stroke, rgba(139,92,246,.3)); border-radius: var(--radius-lg, 14px); background: color-mix(in srgb, var(--bg-1, #141414) 92%, transparent); backdrop-filter: blur(10px); box-shadow: var(--shadow-2, 0 12px 32px rgba(0,0,0,.4)); }
+.so-mbar-t { min-width: 0; font-size: var(--text-xs, .72rem); color: var(--ink-dim, #9a9a9a); line-height: 1.35; transition: opacity .2s; }
+.so-mbar-t b { color: var(--ink-bright, #fff); font-size: .95rem; font-variant-numeric: tabular-nums; }
+.so-mbar[data-status="loading"] .so-mbar-t { opacity: .6; }
+.so-mbar-go { flex: none; }
+@media (min-width: 880px) { .so-mbar { display: none; } }
.so-side-card { border: 1px solid var(--wallet-stroke, rgba(139,92,246,.3)); border-radius: var(--radius-lg, 14px); background: var(--bg-1, #141414); padding: var(--space-lg, 18px); box-shadow: var(--shadow-2, 0 12px 32px rgba(0,0,0,.4)); }
.so-side-h { font-size: var(--text-2xs, .64rem); text-transform: uppercase; letter-spacing: .08em; color: var(--ink-dim, #9a9a9a); font-weight: 700; margin-bottom: 8px; }
.so-side-card .so-preview { margin-top: 0; }
@@ -142,135 +164,401 @@ export function ensureStrategyStyles() {
.so-side-save { width: 100%; justify-content: center; margin-top: 14px; }
.so-side-cancel { width: 100%; justify-content: center; margin-top: 7px; background: transparent; border-color: transparent; }
.so-side-cancel:hover { background: var(--surface-2, rgba(255,255,255,.05)); }
+.so-gp { font-size: var(--text-2xs, .66rem); color: var(--ink-dim, #9a9a9a); line-height: 1.5; margin: 0 0 10px; }
+.so-seg { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 10px; }
+@media (max-width: 460px) { .so-seg:not(.so-seg-inline) { grid-template-columns: 1fr; } }
+.so-seg-opt { position: relative; display: block; cursor: pointer; }
+.so-seg-opt input { position: absolute; opacity: 0; pointer-events: none; }
+.so-seg-opt > span { display: block; height: 100%; box-sizing: border-box; padding: 10px 12px; border-radius: var(--radius-md, 10px); border: 1px solid var(--stroke-strong, rgba(255,255,255,.14)); background: var(--surface-1, rgba(255,255,255,.03)); transition: border-color .16s, background .16s; }
+.so-seg-opt b { display: block; font-size: var(--text-sm, .8rem); color: var(--ink-bright, #fff); font-weight: 600; }
+.so-seg-opt small { display: block; font-size: var(--text-2xs, .64rem); color: var(--ink-dim, #9a9a9a); line-height: 1.45; margin-top: 3px; }
+.so-seg-inline .so-seg-opt > span { padding: 8px 10px; text-align: center; }
+.so-seg-opt:hover > span { border-color: var(--wallet-stroke, rgba(139,92,246,.35)); }
+.so-seg-opt input:checked + span { border-color: var(--wallet-stroke-strong, rgba(139,92,246,.6)); background: var(--wallet-accent-soft, rgba(139,92,246,.1)); box-shadow: inset 0 0 0 1px var(--wallet-stroke-strong, rgba(139,92,246,.6)); }
+.so-seg-opt input:focus-visible + span { outline: 2px solid var(--wallet-focus, rgba(139,92,246,.7)); outline-offset: 2px; }
+.so-gates { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 6px; }
+@media (max-width: 560px) { .so-gates { grid-template-columns: 1fr; } }
+.so-gate { border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md, 10px); padding: 9px 10px; background: var(--surface-1, rgba(255,255,255,.02)); transition: border-color .16s, background .16s; margin-top: 6px; }
+.so-gates .so-gate { margin-top: 0; }
+.so-gate[data-on="true"] { border-color: var(--wallet-stroke, rgba(139,92,246,.35)); background: var(--wallet-accent-soft, rgba(139,92,246,.06)); }
+.so-gate-head { display: flex; align-items: center; gap: 8px; cursor: pointer; font-size: var(--text-xs, .74rem); color: var(--ink, #ddd); }
+.so-gate-label { flex: 1; min-width: 0; }
+.so-gate-out { font-family: var(--font-mono, monospace); font-size: var(--text-2xs, .66rem); color: var(--ink-faint, #777); white-space: nowrap; }
+.so-gate[data-on="true"] .so-gate-out { color: ${VIOLET}; }
+.so-gate-ctl { display: flex; align-items: center; gap: 8px; margin-top: 7px; }
+.so-gate-ctl input[type="range"] { flex: 1; min-width: 0; accent-color: ${VIOLET}; height: 20px; cursor: pointer; }
+.so-gate-ctl input[type="range"]:disabled { opacity: .35; cursor: not-allowed; }
+.so-gate-ctl input[type="number"] { width: 78px; flex: 0 0 auto; box-sizing: border-box; font: inherit; font-size: var(--text-xs, .76rem); padding: 6px 8px; border-radius: var(--radius-sm, 6px); border: 1px solid var(--stroke-strong, rgba(255,255,255,.14)); background: var(--surface-1, rgba(255,255,255,.03)); color: var(--ink-bright, #fff); }
+.so-gate-ctl input[type="number"]:disabled { opacity: .4; }
+.so-gate-ctl input:focus-visible { outline: 2px solid var(--wallet-focus, rgba(139,92,246,.7)); outline-offset: 2px; }
+.so-gate .so-hint { font-size: var(--text-2xs, .6rem); color: var(--ink-faint, #777); margin-top: 4px; line-height: 1.4; }
+.so-gate-head input, .so-checkrow input { accent-color: ${VIOLET}; width: 15px; height: 15px; flex: 0 0 auto; }
+.so-json { border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md, 10px); padding: 0 var(--space-sm, 12px); margin-bottom: var(--space-sm, 12px); }
+.so-json > summary { cursor: pointer; padding: 11px 0; font-size: var(--text-xs, .74rem); font-weight: 600; color: var(--ink, #ddd); list-style-position: inside; }
+.so-json > summary:focus-visible { outline: 2px solid var(--wallet-focus, rgba(139,92,246,.7)); outline-offset: 2px; border-radius: 4px; }
+.so-json textarea { width: 100%; box-sizing: border-box; min-height: 280px; resize: vertical; font-family: var(--font-mono, monospace); font-size: var(--text-2xs, .68rem); line-height: 1.5; padding: 10px; border-radius: var(--radius-sm, 6px); border: 1px solid var(--stroke-strong, rgba(255,255,255,.14)); background: var(--bg-0, rgba(0,0,0,.25)); color: var(--ink-bright, #fff); tab-size: 2; }
+.so-json textarea:focus { outline: none; border-color: var(--wallet-stroke-strong, rgba(139,92,246,.5)); }
+.so-json-st { font-size: var(--text-2xs, .64rem); min-height: 1.4em; margin: 5px 0 10px; color: var(--ink-faint, #777); }
+.so-json-st[data-kind="err"] { color: var(--danger, #f87171); }
+.so-json-st[data-kind="ok"] { color: var(--success, #4ade80); }
`;
document.head.appendChild(s);
}
const DEFAULTS = {
+ version: 2,
+ mode: 'ask',
network: 'mainnet',
- entry: { trigger: 'new_launch', max_age_minutes: 60, min_market_cap_usd: null, max_market_cap_usd: null, min_liquidity_sol: null, require_socials: false, max_creator_launches: null, min_creator_graduated: null, require_sol_quote: true },
- sizing: { amount_sol: 0.1, max_slippage_bps: 500 },
+ entry: { trigger: 'new_launch', sources: [], max_age_minutes: 60, min_market_cap_usd: null, max_market_cap_usd: null, min_liquidity_sol: null, require_socials: false, max_creator_launches: null, min_creator_graduated: null, require_sol_quote: true },
+ sizing: { amount_sol: 0.1, max_slippage_bps: 500, max_price_impact_bps: null },
exits: { take_profit_pct: 100, stop_loss_pct: 40, trailing_stop_pct: null, max_hold_minutes: null },
risk: { max_concurrent_positions: 3, cooldown_minutes: 0 },
+ research: {
+ min_holders: null, max_top_holder_pct: null, min_liquidity_sol: null, security_min_score: null,
+ require_no_mint_authority: false, require_no_freeze_authority: false,
+ dev_history: { max_launches: null, min_graduated: null, block_dev_sold: false },
+ },
};
const numOrNull = (v) => { const s = String(v ?? '').trim(); if (s === '') return null; const n = Number(s); return Number.isFinite(n) ? n : null; };
+const isObj = (v) => v && typeof v === 'object' && !Array.isArray(v);
// ── shared editor internals ────────────────────────────────────────────────────
// One source of truth for the strategy form, used by both the modal editor
// (openStrategyEditor: in-context editing on an agent profile) and the full-page
// builder (mountStrategyComposer: the /strategies "New strategy" flow). The field
// markup, parsing, live preview, and save all live here so the two surfaces can
-// never drift apart.
-function makeState(existing) {
- const cfg = existing?.config ? structuredCloneSafe(existing.config) : structuredCloneSafe(DEFAULTS);
+// never drift apart. Every control and the JSON view edit the same config object.
+
+// Fold any stored config (v1 or v2, camelCase or snake_case keys) into editor
+// state. Liquidity and creator history live in both `entry` (v1) and `research`
+// (v2); the server treats them as one setting, so the editor does too.
+function stateFromConfig(cfg, base = {}) {
+ const c = isObj(cfg) ? cfg : {};
+ const e = isObj(c.entry) ? c.entry : {};
+ const s = isObj(c.sizing) ? c.sizing : {};
+ const r = isObj(c.research) ? c.research : {};
+ const dvRaw = r.dev_history ?? r.devHistory;
+ const dv = isObj(dvRaw) ? dvRaw : {};
+ const pick = (o, a, b) => (o[a] !== undefined ? o[a] : o[b]);
+ const sources = Array.isArray(e.sources) && e.sources.map(String).includes('three_ws_launch') && !e.sources.map(String).includes('pump_curve') ? ['three_ws_launch'] : [];
return {
- name: existing?.name || '',
- description: existing?.description || '',
- network: cfg.network || 'mainnet',
- entry: { ...DEFAULTS.entry, ...(cfg.entry || {}) },
- sizing: { ...DEFAULTS.sizing, ...(cfg.sizing || {}) },
- exits: { ...DEFAULTS.exits, ...(cfg.exits || {}) },
- risk: { ...DEFAULTS.risk, ...(cfg.risk || {}) },
+ name: base.name ?? '',
+ description: base.description ?? '',
+ mode: c.mode === 'auto' ? 'auto' : 'ask',
+ network: c.network === 'devnet' ? 'devnet' : 'mainnet',
+ entry: { ...DEFAULTS.entry, ...e, sources },
+ sizing: { ...DEFAULTS.sizing, ...s, max_price_impact_bps: numOrNull(pick(s, 'max_price_impact_bps', 'maxPriceImpactBps')) },
+ exits: { ...DEFAULTS.exits, ...(isObj(c.exits) ? c.exits : {}) },
+ risk: { ...DEFAULTS.risk, ...(isObj(c.risk) ? c.risk : {}) },
+ research: {
+ min_holders: numOrNull(pick(r, 'min_holders', 'minHolders')),
+ max_top_holder_pct: numOrNull(pick(r, 'max_top_holder_pct', 'maxTopHolderPct')),
+ min_liquidity_sol: numOrNull(pick(r, 'min_liquidity_sol', 'minLiquiditySol') ?? e.min_liquidity_sol),
+ security_min_score: numOrNull(pick(r, 'security_min_score', 'securityMinScore')),
+ require_no_mint_authority: pick(r, 'require_no_mint_authority', 'requireNoMintAuthority') === true,
+ require_no_freeze_authority: pick(r, 'require_no_freeze_authority', 'requireNoFreezeAuthority') === true,
+ dev_history: {
+ max_launches: numOrNull(pick(dv, 'max_launches', 'maxLaunches') ?? e.max_creator_launches),
+ min_graduated: numOrNull(pick(dv, 'min_graduated', 'minGraduated') ?? e.min_creator_graduated),
+ block_dev_sold: pick(dv, 'block_dev_sold', 'blockDevSold') === true,
+ },
+ },
};
}
+function makeState(existing) {
+ return stateFromConfig(existing?.config ? structuredCloneSafe(existing.config) : DEFAULTS, existing || {});
+}
+
const numVal = (v) => (v == null ? '' : v);
+const getPath = (o, path) => path.split('.').reduce((a, k) => (a == null ? a : a[k]), o);
+function setPath(o, path, v) {
+ const keys = path.split('.');
+ let t = o;
+ for (const k of keys.slice(0, -1)) t = t[k] ??= {};
+ t[keys[keys.length - 1]] = v;
+}
function previewText(state) {
- const c = { entry: state.entry, sizing: state.sizing, exits: state.exits, risk: state.risk };
- return configSummary(c) || 'Define your rules above.';
+ return configSummary(buildConfig(state)) || 'Define your rules above.';
+}
+
+// Plain inputs: one row per control, read and written through its config path.
+const PLAIN_FIELDS = [
+ { id: 'so-name', path: 'name', kind: 'str' },
+ { id: 'so-desc', path: 'description', kind: 'str' },
+ { id: 'so-net', path: 'network', kind: 'str' },
+ { id: 'so-age', path: 'entry.max_age_minutes', kind: 'num' },
+ { id: 'so-mcmin', path: 'entry.min_market_cap_usd', kind: 'num' },
+ { id: 'so-mcmax', path: 'entry.max_market_cap_usd', kind: 'num' },
+ { id: 'so-socials', path: 'entry.require_socials', kind: 'bool' },
+ { id: 'so-size', path: 'sizing.amount_sol', kind: 'num' },
+ { id: 'so-slip', path: 'sizing.max_slippage_bps', kind: 'num' },
+ { id: 'so-tp', path: 'exits.take_profit_pct', kind: 'num' },
+ { id: 'so-sl', path: 'exits.stop_loss_pct', kind: 'num' },
+ { id: 'so-trail', path: 'exits.trailing_stop_pct', kind: 'num' },
+ { id: 'so-hold', path: 'exits.max_hold_minutes', kind: 'num' },
+ { id: 'so-conc', path: 'risk.max_concurrent_positions', kind: 'num' },
+ { id: 'so-cool', path: 'risk.cooldown_minutes', kind: 'num' },
+ { id: 'so-r-mint', path: 'research.require_no_mint_authority', kind: 'bool' },
+ { id: 'so-r-freeze', path: 'research.require_no_freeze_authority', kind: 'bool' },
+ { id: 'so-r-devsold', path: 'research.dev_history.block_dev_sold', kind: 'bool' },
+];
+
+// Gates: an on/off switch plus a slider and a number box. Off stores null, which
+// the runtime reads as "this check is not enforced". `scale` converts the
+// displayed unit to the stored one (price impact shows % and stores bps).
+const GATES = [
+ { id: 'so-impact', path: 'sizing.max_price_impact_bps', label: 'Max price impact', unit: '%', min: 0.5, max: 25, step: 0.5, def: 5, scale: 100, hint: 'skip a buy that would move the price more than this; can only tighten your agent’s own breaker' },
+ { id: 'so-r-holders', path: 'research.min_holders', label: 'Minimum holders', unit: '', min: 0, max: 1000, step: 5, def: 50, hint: 'distinct wallets holding the coin' },
+ { id: 'so-r-top', path: 'research.max_top_holder_pct', label: 'Largest holder share, at most', unit: '%', min: 1, max: 100, step: 1, def: 20, hint: 'excludes the bonding curve itself' },
+ { id: 'so-r-liq', path: 'research.min_liquidity_sol', label: 'Minimum liquidity', unit: ' SOL', min: 0, max: 85, step: 0.5, def: 5, hint: 'SOL in the bonding curve' },
+ { id: 'so-r-score', path: 'research.security_min_score', label: 'Firewall security score, at least', unit: '/100', min: 0, max: 100, step: 5, def: 60, hint: 'the three.ws token firewall, run live before every buy' },
+ { id: 'so-r-launches', path: 'research.dev_history.max_launches', label: 'Creator launches, at most', unit: '', min: 0, max: 50, step: 1, def: 3, hint: 'skip serial deployers' },
+ { id: 'so-r-grad', path: 'research.dev_history.min_graduated', label: 'Creator graduations, at least', unit: '', min: 0, max: 20, step: 1, def: 1, hint: 'coins this creator took off the curve before' },
+];
+
+const fmtGate = (g, v) => (v == null ? 'off' : `${Number(v).toLocaleString('en-US', { maximumFractionDigits: 2 })}${g.unit}`);
+
+function gateHTML(g, state) {
+ const stored = getPath(state, g.path);
+ const on = stored != null;
+ const v = on ? stored / (g.scale || 1) : g.def;
+ return `<div class="so-gate" data-gate="${g.id}" data-on="${on}">
+ <label class="so-gate-head"><input type="checkbox" class="so-gate-on" id="${g.id}-on" ${on ? 'checked' : ''}><span class="so-gate-label">${g.label}</span><output class="so-gate-out" id="${g.id}-out" for="${g.id}">${fmtGate(g, on ? v : null)}</output></label>
+ <div class="so-gate-ctl">
+ <input type="range" id="${g.id}-range" min="${g.min}" max="${g.max}" step="${g.step}" value="${Math.min(g.max, Math.max(g.min, v))}" aria-label="${g.label}" ${on ? '' : 'disabled'}>
+ <input type="number" id="${g.id}" min="${g.min}" step="${g.step}" value="${v}" aria-label="${g.label} value" ${on ? '' : 'disabled'}>
+ </div>
+ <div class="so-hint">${g.hint}</div>
+ </div>`;
}
// The form fields, without any chrome. `preview` controls whether the inline
// preview/error block is emitted here (the modal wants it inline; the page hosts
// them in its sticky side panel instead).
function strategyFieldsHTML(state, { preview = true } = {}) {
- return `<div class="so-field"><label>Name</label><input id="so-name" maxlength="80" placeholder="e.g. Fresh-launch sniper" value="${esc(state.name)}"></div>
- <div class="so-field"><label>Description <span style="color:var(--ink-faint,#777)">(optional)</span></label><input id="so-desc" maxlength="2000" placeholder="What edge does this capture?" value="${esc(state.description)}"></div>
+ const src = state.entry.sources.includes('three_ws_launch') ? 'three_ws_launch' : 'all';
+ return `<div class="so-field"><label for="so-name">Name</label><input id="so-name" maxlength="80" placeholder="e.g. Fresh-launch sniper" value="${esc(state.name)}"></div>
+ <div class="so-field"><label for="so-desc">Description <span style="color:var(--ink-faint,#777)">(optional)</span></label><input id="so-desc" maxlength="2000" placeholder="What edge does this capture?" value="${esc(state.description)}"></div>
+
+ <fieldset class="so-group"><legend>Mode: who pulls the trigger</legend>
+ <div class="so-seg" role="radiogroup" aria-label="Mode">
+ <label class="so-seg-opt"><input type="radio" name="so-mode" value="ask" ${state.mode === 'ask' ? 'checked' : ''}><span><b>Ask before each buy</b><small>You get an approval request with the coin, amount and risk notes. Nothing is bought until you say yes.</small></span></label>
+ <label class="so-seg-opt"><input type="radio" name="so-mode" value="auto" ${state.mode === 'auto' ? 'checked' : ''}><span><b>Auto within caps</b><small>Buys every match on its own, inside your agent’s spend policy and these gates.</small></span></label>
+ </div>
+ </fieldset>
<fieldset class="so-group"><legend>Entry: when to buy</legend>
+ <div class="so-seg so-seg-inline" role="radiogroup" aria-label="Launch sources">
+ <label class="so-seg-opt"><input type="radio" name="so-src" value="all" ${src === 'all' ? 'checked' : ''}><span><b>All launches</b></span></label>
+ <label class="so-seg-opt"><input type="radio" name="so-src" value="three_ws_launch" ${src === 'three_ws_launch' ? 'checked' : ''}><span><b>three.ws launches only</b></span></label>
+ </div>
<div class="so-grid">
- <div class="so-field"><label>Max launch age (min)</label><input type="number" min="1" max="10080" id="so-age" value="${numVal(state.entry.max_age_minutes)}"><div class="so-hint">only act on launches newer than this</div></div>
- <div class="so-field"><label>Min liquidity (◎ SOL)</label><input type="number" min="0" step="0.1" id="so-liq" value="${numVal(state.entry.min_liquidity_sol)}"></div>
- <div class="so-field"><label>Min market cap (USD)</label><input type="number" min="0" id="so-mcmin" value="${numVal(state.entry.min_market_cap_usd)}"></div>
- <div class="so-field"><label>Max market cap (USD)</label><input type="number" min="0" id="so-mcmax" value="${numVal(state.entry.max_market_cap_usd)}"></div>
- <div class="so-field"><label>Max creator launches</label><input type="number" min="0" id="so-claunch" value="${numVal(state.entry.max_creator_launches)}"><div class="so-hint">skip serial deployers</div></div>
- <div class="so-field"><label>Min creator graduations</label><input type="number" min="0" id="so-cgrad" value="${numVal(state.entry.min_creator_graduated)}"></div>
+ <div class="so-field"><label for="so-age">Max launch age (min)</label><input type="number" min="1" max="10080" id="so-age" value="${numVal(state.entry.max_age_minutes)}"><div class="so-hint">only act on launches newer than this</div></div>
+ <div class="so-field"><label for="so-mcmin">Market cap band: min (USD)</label><input type="number" min="0" id="so-mcmin" placeholder="no floor" value="${numVal(state.entry.min_market_cap_usd)}"></div>
+ <div class="so-field"><label for="so-mcmax">Market cap band: max (USD)</label><input type="number" min="0" id="so-mcmax" placeholder="no ceiling" value="${numVal(state.entry.max_market_cap_usd)}"></div>
</div>
<label class="so-checkrow"><input type="checkbox" id="so-socials" ${state.entry.require_socials ? 'checked' : ''}> Require socials (X / Telegram / site)</label>
</fieldset>
<fieldset class="so-group"><legend>Sizing</legend>
+ <div class="so-field"><label for="so-size">Per-trade size</label>
+ <div class="so-gate-ctl"><input type="range" id="so-size-range" min="0.01" max="2" step="0.01" value="${Math.min(2, Math.max(0.01, Number(state.sizing.amount_sol) || 0.1))}" aria-label="Per-trade size"><input type="number" min="0.0001" max="100" step="0.01" id="so-size" value="${numVal(state.sizing.amount_sol)}" aria-label="Per-trade size in SOL"></div>
+ <div class="so-hint">SOL per buy, still capped by your agent’s spend policy</div></div>
<div class="so-grid">
- <div class="so-field"><label>Per-trade size (◎ SOL)</label><input type="number" min="0.0001" step="0.01" id="so-size" value="${numVal(state.sizing.amount_sol)}"><div class="so-hint">still capped by your agent's spend policy</div></div>
- <div class="so-field"><label>Max slippage (bps)</label><input type="number" min="0" max="10000" id="so-slip" value="${numVal(state.sizing.max_slippage_bps)}"><div class="so-hint">500 = 5%</div></div>
+ <div class="so-field"><label for="so-slip">Max slippage (bps)</label><input type="number" min="0" max="10000" id="so-slip" value="${numVal(state.sizing.max_slippage_bps)}"><div class="so-hint">500 = 5%</div></div>
</div>
+ ${gateHTML(GATES[0], state)}
+ </fieldset>
+
+ <fieldset class="so-group"><legend>Research gates: checked before every buy</legend>
+ <p class="so-gp">Each switch adds a check the runtime runs on the coin before buying. A coin that fails one is skipped and the reason lands in your decision log. Data that cannot be read counts as a fail.</p>
+ <div class="so-gates">${GATES.slice(1).map((g) => gateHTML(g, state)).join('')}</div>
+ <label class="so-checkrow"><input type="checkbox" id="so-r-mint" ${state.research.require_no_mint_authority ? 'checked' : ''}> Mint authority renounced (no one can print more)</label>
+ <label class="so-checkrow"><input type="checkbox" id="so-r-freeze" ${state.research.require_no_freeze_authority ? 'checked' : ''}> Freeze authority renounced (no one can freeze your tokens)</label>
+ <label class="so-checkrow"><input type="checkbox" id="so-r-devsold" ${state.research.dev_history.block_dev_sold ? 'checked' : ''}> Skip coins whose creator already sold</label>
</fieldset>
<fieldset class="so-group"><legend>Exits: at least one upside exit + a stop-loss</legend>
<div class="so-grid">
- <div class="so-field"><label>Take-profit (%)</label><input type="number" min="1" id="so-tp" value="${numVal(state.exits.take_profit_pct)}"><div class="so-hint">100 = sell at 2×</div></div>
- <div class="so-field"><label>Stop-loss (%), required</label><input type="number" min="1" max="99" id="so-sl" value="${numVal(state.exits.stop_loss_pct)}"></div>
- <div class="so-field"><label>Trailing stop (%)</label><input type="number" min="1" max="99" id="so-trail" value="${numVal(state.exits.trailing_stop_pct)}"><div class="so-hint">% drop from peak</div></div>
- <div class="so-field"><label>Max hold (min)</label><input type="number" min="1" id="so-hold" value="${numVal(state.exits.max_hold_minutes)}"></div>
+ <div class="so-field"><label for="so-tp">Take-profit (%)</label><input type="number" min="1" id="so-tp" value="${numVal(state.exits.take_profit_pct)}"><div class="so-hint">100 = sell at 2×</div></div>
+ <div class="so-field"><label for="so-sl">Stop-loss (%), required</label><input type="number" min="1" max="99" id="so-sl" value="${numVal(state.exits.stop_loss_pct)}"></div>
+ <div class="so-field"><label for="so-trail">Trailing stop (%)</label><input type="number" min="1" max="99" id="so-trail" value="${numVal(state.exits.trailing_stop_pct)}"><div class="so-hint">% drop from peak</div></div>
+ <div class="so-field"><label for="so-hold">Max hold (min)</label><input type="number" min="1" id="so-hold" value="${numVal(state.exits.max_hold_minutes)}"></div>
</div>
</fieldset>
<fieldset class="so-group"><legend>Risk</legend>
<div class="so-grid">
- <div class="so-field"><label>Max concurrent positions</label><input type="number" min="1" max="50" id="so-conc" value="${numVal(state.risk.max_concurrent_positions)}"></div>
- <div class="so-field"><label>Cooldown between entries (min)</label><input type="number" min="0" id="so-cool" value="${numVal(state.risk.cooldown_minutes)}"></div>
- <div class="so-field"><label>Network</label><select id="so-net"><option value="mainnet" ${state.network === 'mainnet' ? 'selected' : ''}>Mainnet</option><option value="devnet" ${state.network === 'devnet' ? 'selected' : ''}>Devnet</option></select></div>
+ <div class="so-field"><label for="so-conc">Max concurrent positions</label><input type="number" min="1" max="50" id="so-conc" value="${numVal(state.risk.max_concurrent_positions)}"><div class="so-hint">pending approvals count toward this</div></div>
+ <div class="so-field"><label for="so-cool">Cooldown between entries (min)</label><input type="number" min="0" id="so-cool" value="${numVal(state.risk.cooldown_minutes)}"></div>
+ <div class="so-field"><label for="so-net">Network</label><select id="so-net"><option value="mainnet" ${state.network === 'mainnet' ? 'selected' : ''}>Mainnet</option><option value="devnet" ${state.network === 'devnet' ? 'selected' : ''}>Devnet</option></select></div>
</div>
- </fieldset>${preview ? `
+ </fieldset>
+
+ <details class="so-json">
+ <summary>Edit as JSON</summary>
+ <p class="so-gp">The exact Strategy Object the controls above edit. Change it here and the controls follow.</p>
+ <textarea id="so-json" spellcheck="false" aria-label="Strategy Object JSON">${esc(JSON.stringify(buildConfig(state), null, 2))}</textarea>
+ <div class="so-json-st" id="so-json-st" role="status"></div>
+ </details>${preview ? `
<div class="so-preview" id="so-preview">${previewText(state)}</div>
<div class="so-err" id="so-err" hidden></div>` : ''}`;
}
-// Read every field in `root` back into `state` (root is the modal or composer).
+// Read every control in `root` back into `state` (root is the modal or composer).
function readInputs(root, state) {
- const q = (id) => root.querySelector(id);
- state.name = q('#so-name')?.value || '';
- state.description = q('#so-desc')?.value || '';
- state.network = q('#so-net')?.value || 'mainnet';
- state.entry.max_age_minutes = numOrNull(q('#so-age')?.value);
- state.entry.min_liquidity_sol = numOrNull(q('#so-liq')?.value);
- state.entry.min_market_cap_usd = numOrNull(q('#so-mcmin')?.value);
- state.entry.max_market_cap_usd = numOrNull(q('#so-mcmax')?.value);
- state.entry.max_creator_launches = numOrNull(q('#so-claunch')?.value);
- state.entry.min_creator_graduated = numOrNull(q('#so-cgrad')?.value);
- state.entry.require_socials = !!q('#so-socials')?.checked;
- state.sizing.amount_sol = numOrNull(q('#so-size')?.value);
- state.sizing.max_slippage_bps = numOrNull(q('#so-slip')?.value);
- state.exits.take_profit_pct = numOrNull(q('#so-tp')?.value);
- state.exits.stop_loss_pct = numOrNull(q('#so-sl')?.value);
- state.exits.trailing_stop_pct = numOrNull(q('#so-trail')?.value);
- state.exits.max_hold_minutes = numOrNull(q('#so-hold')?.value);
- state.risk.max_concurrent_positions = numOrNull(q('#so-conc')?.value);
- state.risk.cooldown_minutes = numOrNull(q('#so-cool')?.value);
+ const q = (id) => root.querySelector(`#${id}`);
+ for (const f of PLAIN_FIELDS) {
+ const el = q(f.id);
+ if (!el) continue;
+ setPath(state, f.path, f.kind === 'bool' ? !!el.checked : f.kind === 'num' ? numOrNull(el.value) : el.value || (f.path === 'network' ? 'mainnet' : ''));
+ }
+ for (const g of GATES) {
+ const on = q(`${g.id}-on`)?.checked;
+ const v = numOrNull(q(g.id)?.value);
+ setPath(state, g.path, on && v != null ? Math.round(v * (g.scale || 1) * 1e6) / 1e6 : null);
+ }
+ const mode = root.querySelector('input[name="so-mode"]:checked')?.value;
+ state.mode = mode === 'auto' ? 'auto' : 'ask';
+ const src = root.querySelector('input[name="so-src"]:checked')?.value;
+ state.entry.sources = src === 'three_ws_launch' ? ['three_ws_launch'] : [];
+}
+
+// Push `state` into every control (the JSON view and the compiler drive this).
+function writeInputs(root, state) {
+ const q = (id) => root.querySelector(`#${id}`);
+ for (const f of PLAIN_FIELDS) {
+ const el = q(f.id);
+ if (!el) continue;
+ const v = getPath(state, f.path);
+ if (f.kind === 'bool') el.checked = !!v;
+ else el.value = v == null ? '' : v;
+ }
+ for (const g of GATES) {
+ const stored = getPath(state, g.path);
+ const on = stored != null;
+ const v = on ? stored / (g.scale || 1) : g.def;
+ const box = root.querySelector(`[data-gate="${g.id}"]`);
+ if (box) box.dataset.on = String(on);
+ if (q(`${g.id}-on`)) q(`${g.id}-on`).checked = on;
+ if (q(g.id)) { q(g.id).value = v; q(g.id).disabled = !on; }
+ if (q(`${g.id}-range`)) { q(`${g.id}-range`).value = Math.min(g.max, Math.max(g.min, v)); q(`${g.id}-range`).disabled = !on; }
+ if (q(`${g.id}-out`)) q(`${g.id}-out`).textContent = fmtGate(g, on ? v : null);
+ }
+ const sz = q('so-size-range');
+ if (sz) sz.value = Math.min(2, Math.max(0.01, Number(state.sizing.amount_sol) || 0.1));
+ const mode = root.querySelector(`input[name="so-mode"][value="${state.mode}"]`);
+ if (mode) mode.checked = true;
+ const src = root.querySelector(`input[name="so-src"][value="${state.entry.sources.includes('three_ws_launch') ? 'three_ws_launch' : 'all'}"]`);
+ if (src) src.checked = true;
}
-// Live-update the preview as any field changes.
-function wireFormFields(root, state) {
- root.querySelectorAll('input,select').forEach((el) => el.addEventListener('input', () => {
+// Keep a slider and its number box in step, and switch a gate's controls on/off.
+function syncPairs(root, target) {
+ const id = target.id || '';
+ if (id.endsWith('-range')) {
+ const box = root.querySelector(`#${id.slice(0, -6)}`);
+ if (box) box.value = target.value;
+ } else if (target.type === 'number') {
+ const range = root.querySelector(`#${id}-range`);
+ const n = numOrNull(target.value);
+ if (range && n != null) range.value = Math.min(Number(range.max), Math.max(Number(range.min), n));
+ } else if (target.classList?.contains('so-gate-on')) {
+ const gid = id.slice(0, -3);
+ const box = root.querySelector(`[data-gate="${gid}"]`);
+ if (box) box.dataset.on = String(target.checked);
+ root.querySelector(`#${gid}`)?.toggleAttribute('disabled', !target.checked);
+ root.querySelector(`#${gid}-range`)?.toggleAttribute('disabled', !target.checked);
+ if (target.checked) root.querySelector(`#${gid}-range`)?.focus();
+ }
+ for (const g of GATES) {
+ const out = root.querySelector(`#${g.id}-out`);
+ if (!out) continue;
+ const on = root.querySelector(`#${g.id}-on`)?.checked;
+ out.textContent = fmtGate(g, on ? numOrNull(root.querySelector(`#${g.id}`)?.value) : null);
+ }
+}
+
+// Wire every control: each change re-reads the form, refreshes the summary and
+// the JSON view, and notifies `onChange` (the live match preview). Editing the
+// JSON parses it and pushes the result back into the controls.
+function wireFormFields(root, state, { onChange } = {}) {
+ const json = root.querySelector('#so-json');
+ const jsonSt = root.querySelector('#so-json-st');
+ const refreshSummary = () => { const p = root.querySelector('#so-preview'); if (p) p.innerHTML = previewText(state); };
+ const fromControls = (ev) => {
+ if (ev.target === json) return;
+ syncPairs(root, ev.target);
readInputs(root, state);
- const p = root.querySelector('#so-preview'); if (p) p.innerHTML = previewText(state);
- }));
+ refreshSummary();
+ if (json && document.activeElement !== json) json.value = JSON.stringify(buildConfig(state), null, 2);
+ if (jsonSt) { jsonSt.textContent = ''; jsonSt.dataset.kind = ''; }
+ onChange?.(state);
+ };
+ root.querySelectorAll('input,select').forEach((el) => {
+ el.addEventListener('input', fromControls);
+ if (el.type === 'checkbox' || el.type === 'radio') el.addEventListener('change', fromControls);
+ });
+ let jsonTimer = null;
+ json?.addEventListener('input', () => {
+ clearTimeout(jsonTimer);
+ jsonTimer = setTimeout(() => {
+ let parsed;
+ try { parsed = JSON.parse(json.value); } catch (err) {
+ if (jsonSt) { jsonSt.textContent = `Not valid JSON yet: ${err.message}`; jsonSt.dataset.kind = 'err'; }
+ return;
+ }
+ if (!isObj(parsed)) { if (jsonSt) { jsonSt.textContent = 'The Strategy Object must be a JSON object.'; jsonSt.dataset.kind = 'err'; } return; }
+ applyConfig(root, state, parsed);
+ if (jsonSt) { jsonSt.textContent = 'Controls updated from JSON.'; jsonSt.dataset.kind = 'ok'; }
+ onChange?.(state);
+ }, 300);
+ });
+ return {
+ apply(config) {
+ applyConfig(root, state, config);
+ if (json) json.value = JSON.stringify(buildConfig(state), null, 2);
+ onChange?.(state);
+ },
+ };
+}
+
+function applyConfig(root, state, config) {
+ const next = stateFromConfig(config, { name: state.name, description: state.description });
+ Object.assign(state, next);
+ writeInputs(root, state);
+ const p = root.querySelector('#so-preview'); if (p) p.innerHTML = previewText(state);
}
+// The Strategy Object exactly as it is saved. Liquidity and creator history are
+// written to both halves so a gate switched off stays off server-side.
function buildConfig(state) {
+ const r = state.research;
return {
+ version: 2,
+ mode: state.mode,
network: state.network,
- entry: { trigger: 'new_launch', ...state.entry },
- sizing: state.sizing,
- exits: state.exits,
- risk: state.risk,
+ entry: {
+ ...state.entry,
+ trigger: 'new_launch',
+ sources: state.entry.sources,
+ min_liquidity_sol: r.min_liquidity_sol,
+ max_creator_launches: r.dev_history.max_launches,
+ min_creator_graduated: r.dev_history.min_graduated,
+ },
+ sizing: { ...state.sizing },
+ exits: { ...state.exits },
+ risk: { ...state.risk },
+ research: { ...r, dev_history: { ...r.dev_history } },
};
}
function showFieldErr(root, m) { const e = root.querySelector('#so-err'); if (e) { e.textContent = m; e.hidden = false; } }
+function clearFieldErr(root) { const e = root.querySelector('#so-err'); if (e) e.hidden = true; }
// POST (create) or PATCH (edit). Returns the saved strategy, or throws.
async function submitStrategy(state, existing) {
@@ -284,7 +572,7 @@ async function submitStrategy(state, existing) {
if (!res.ok) {
const fieldErrs = j?.error?.errors || j?.errors;
if (Array.isArray(fieldErrs) && fieldErrs.length) throw new Error(fieldErrs.map((e) => e.message).join(' '));
- throw new Error(j?.error?.message || j?.message || 'Could not save');
+ throw new Error(j?.error?.message || j?.error_description || j?.message || 'Could not save');
}
return j.data;
}
@@ -304,13 +592,15 @@ export function openStrategyEditor({ existing = null } = {}) {
<h3>${existing ? 'Edit strategy' : 'New strategy'}</h3>
<p class="so-sub">A strategy is a real, rule-based plan. When equipped, your agent evaluates real launches and executes on-chain, always inside your spend policy.</p>
${strategyFieldsHTML(state)}
+ <div id="so-live"></div>
<div class="so-actions">
<button type="button" class="so-btn" id="so-cancel">Cancel</button>
<button type="button" class="so-btn so-btn-primary" id="so-save">${existing ? 'Save changes' : 'Create strategy'}</button>
</div>
</div>`;
const modal = back.firstElementChild;
- wireFormFields(modal, state);
+ const live = mountLivePreview(modal.querySelector('#so-live'), { getConfig: () => buildConfig(state) });
+ wireFormFields(modal, state, { onChange: () => { clearFieldErr(modal); live.refresh(); } });
modal.querySelector('#so-cancel').addEventListener('click', () => close(null));
const btn = modal.querySelector('#so-save');
btn.addEventListener('click', async () => {
@@ -327,7 +617,7 @@ export function openStrategyEditor({ existing = null } = {}) {
showFieldErr(modal, e.message || 'Could not save');
}
});
- function close(result) { document.removeEventListener('keydown', onKey); back.remove(); resolve(result); }
+ function close(result) { live.destroy(); document.removeEventListener('keydown', onKey); back.remove(); resolve(result); }
function onKey(e) { if (e.key === 'Escape') close(null); }
back.addEventListener('click', (e) => { if (e.target === back) close(null); });
document.addEventListener('keydown', onKey);
@@ -338,10 +628,11 @@ export function openStrategyEditor({ existing = null } = {}) {
// ── the strategy builder (full page) ───────────────────────────────────────────
// Renders the whole builder into `host` as a page: a two-column workspace with
-// the rules on the left and a sticky live summary + Create button on the right.
-// This is the /strategies "New strategy" surface: a complex, multi-section form
-// deserves room to breathe, not a cramped modal. onSaved(saved) fires after a
-// successful create/edit; onCancel() fires on the back link.
+// the rules on the left and a sticky live summary, match preview and Create
+// button on the right. This is the /strategies "New strategy" surface: a complex,
+// multi-section form deserves room to breathe, not a cramped modal.
+// onSaved(saved) fires after a successful create/edit; onCancel() fires on the
+// back link.
export function mountStrategyComposer(host, { existing = null, onSaved, onCancel } = {}) {
ensureStrategyStyles();
const state = makeState(existing);
@@ -352,14 +643,23 @@ export function mountStrategyComposer(host, { existing = null, onSaved, onCancel
<p class="so-compose-lead">A strategy is a real, rule-based plan. When equipped, your agent evaluates real launches and executes on-chain, always inside your spend policy.</p>
</div>
<div class="so-compose-grid">
- <div class="so-compose-main">${strategyFieldsHTML(state, { preview: false })}</div>
+ <div class="so-compose-main">
+ <div id="so-nl"></div>
+ ${strategyFieldsHTML(state, { preview: false })}
+ <div id="so-bt"></div>
+ <div class="so-mbar" id="so-mbar" data-status="loading">
+ <span class="so-mbar-t" aria-live="polite">Counting recent launches…</span>
+ <button type="button" class="so-btn so-mbar-go" id="so-mbar-go">See matches</button>
+ </div>
+ </div>
<aside class="so-compose-side">
<div class="so-side-card">
<div class="so-side-h">Your strategy</div>
<div class="so-preview" id="so-preview">${previewText(state)}</div>
+ <div id="so-live"></div>
<ul class="so-side-points">
+ <li><b>Ask by default</b>: nothing is bought until you approve it</li>
<li><b>Spend-policy gated</b>: every trade is capped by your agent</li>
- <li><b>Real on-chain</b>: no backtested fiction</li>
<li><b>Kill switch</b>: halt everything at once</li>
</ul>
<div class="so-err" id="so-err" hidden></div>
@@ -370,9 +670,29 @@ export function mountStrategyComposer(host, { existing = null, onSaved, onCancel
</div>
</div>`;
const root = host.firstElementChild;
- wireFormFields(root, state);
- root.querySelector('#so-back').addEventListener('click', () => onCancel?.());
- root.querySelector('#so-cancel').addEventListener('click', () => onCancel?.());
+ const getConfig = () => buildConfig(state);
+ const mbar = root.querySelector('#so-mbar');
+ const mbarText = mbar.querySelector('.so-mbar-t');
+ const mbarGo = mbar.querySelector('#so-mbar-go');
+ const live = mountLivePreview(root.querySelector('#so-live'), {
+ getConfig,
+ onState: ({ status, data }) => {
+ mbar.dataset.status = status;
+ if (status === 'error') { mbarText.textContent = 'Preview unavailable.'; mbarGo.textContent = 'Try again'; return; }
+ mbarGo.textContent = 'See matches';
+ if (!data) { mbarText.textContent = 'Counting recent launches…'; return; }
+ mbarText.innerHTML = `<b>${Number(data.would_buy || 0).toLocaleString()}</b> of ${Number(data.universe || 0).toLocaleString()} launches in the last ${Number(data.window_hours) || 24}h would buy`;
+ },
+ });
+ mbarGo.addEventListener('click', () => {
+ if (mbar.dataset.status === 'error') { live.retry(); return; }
+ root.querySelector('#so-live').scrollIntoView({ behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth', block: 'start' });
+ });
+ const form = wireFormFields(root, state, { onChange: () => { clearFieldErr(root); live.refresh(); } });
+ mountCompileBox(root.querySelector('#so-nl'), { getNetwork: () => state.network, onCompiled: (config) => form.apply(config) });
+ mountGatedBacktest(root.querySelector('#so-bt'), { getConfig });
+ root.querySelector('#so-back').addEventListener('click', () => { live.destroy(); onCancel?.(); });
+ root.querySelector('#so-cancel').addEventListener('click', () => { live.destroy(); onCancel?.(); });
const btn = root.querySelector('#so-save');
btn.addEventListener('click', async () => {
readInputs(root, state);
@@ -381,6 +701,7 @@ export function mountStrategyComposer(host, { existing = null, onSaved, onCancel
try {
const saved = await submitStrategy(state, existing);
toast(existing ? 'Strategy updated' : 'Strategy created');
+ live.destroy();
onSaved?.(saved);
} catch (e) {
if (e?.redirected) return;
diff --git a/src/shared/strategy-settings.js b/src/shared/strategy-settings.js
new file mode 100644
index 000000000..29e2b8d96
--- /dev/null
+++ b/src/shared/strategy-settings.js
@@ -0,0 +1,429 @@
+// Strategy settings widgets: the live parts of the strategy builder.
+//
+// mountLivePreview how many recent launches the current config would
+// have bought, with the funnel and the top blocking checks
+// (POST /api/strategies/preview, public, read-only).
+// mountCompileBox "describe it in words": compiles plain language into a
+// Strategy Object, clamped to the agent's guards, and
+// explains every field it set (POST /api/sniper/compile).
+// mountGatedBacktest replays the config, research gates included, over real
+// captured launch history (POST /api/sniper/backtest).
+//
+// All three read the config through a getter so they always see exactly what the
+// form controls and the JSON view hold. Used by src/shared/strategy-forms.js.
+
+import { apiFetch } from '../api.js';
+import { esc, shortAddr, timeAgo, VIOLET } from './strategy-forms.js';
+
+// Plain-language names for every reason a launch can be filtered out. Entry
+// keys come from matchesEntry; research keys mirror RESEARCH_CHECK_LABELS in
+// api/_lib/strategy-schema.js.
+const BLOCK_LABELS = {
+ too_old: 'Older than your launch age',
+ quote_not_sol: 'Not quoted in SOL',
+ source_excluded: 'Not a three.ws launch',
+ mc_below_min: 'Market cap under your floor',
+ mc_above_max: 'Market cap over your ceiling',
+ liq_below_min: 'Liquidity under your minimum',
+ creator_launches: 'Creator launched too many coins',
+ creator_graduated_below: 'Creator graduated too few coins',
+ no_socials: 'No socials',
+ filtered: 'Filtered by entry rules',
+ min_holders: 'Too few holders',
+ max_top_holder_pct: 'Largest holder too big',
+ min_liquidity_sol: 'Liquidity under your minimum',
+ security_min_score: 'Firewall score too low',
+ require_no_mint_authority: 'Mint authority not renounced',
+ require_no_freeze_authority: 'Freeze authority not renounced',
+ dev_max_launches: 'Creator launched too many coins',
+ dev_min_graduated: 'Creator graduated too few coins',
+ dev_block_sold: 'Creator already sold',
+ price_impact: 'Price impact over your limit',
+};
+const blockLabel = (k) => BLOCK_LABELS[k] || String(k).replace(/_/g, ' ');
+const nf = new Intl.NumberFormat('en-US');
+const fmtN = (n) => nf.format(Number(n) || 0);
+const fmtPct = (n, d = 1) => (n == null || !Number.isFinite(Number(n)) ? '-' : `${Number(n) > 0 ? '+' : ''}${Number(n).toFixed(d)}%`);
+
+const STYLE_ID = 'sx-settings-styles';
+function ensureStyles() {
+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;
+ const s = document.createElement('style');
+ s.id = STYLE_ID;
+ s.textContent = `
+.sx-live { margin: 12px 0 0; }
+.sx-live-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-bottom: 8px; }
+.sx-live-h { font-size: var(--text-2xs, .64rem); text-transform: uppercase; letter-spacing: .08em; color: var(--ink-dim, #9a9a9a); font-weight: 700; }
+.sx-win { display: inline-flex; border: 1px solid var(--stroke-strong, rgba(255,255,255,.14)); border-radius: 999px; padding: 2px; }
+.sx-win button { font: inherit; font-size: var(--text-2xs, .64rem); padding: 3px 9px; border: 0; border-radius: 999px; background: transparent; color: var(--ink-dim, #9a9a9a); cursor: pointer; transition: background .16s, color .16s; }
+.sx-win button:hover { color: var(--ink-bright, #fff); }
+.sx-win button[aria-pressed="true"] { background: var(--wallet-accent-soft, rgba(139,92,246,.18)); color: ${VIOLET}; font-weight: 700; }
+.sx-win button:focus-visible { outline: 2px solid var(--wallet-focus, rgba(139,92,246,.7)); outline-offset: 1px; }
+.sx-big { display: flex; align-items: baseline; gap: 6px; flex-wrap: wrap; }
+.sx-big b { font-family: var(--font-display, inherit); font-size: 1.9rem; line-height: 1.1; color: var(--ink-bright, #fff); letter-spacing: -.02em; font-variant-numeric: tabular-nums; }
+.sx-big span { font-size: var(--text-xs, .72rem); color: var(--ink-dim, #9a9a9a); }
+.sx-funnel { list-style: none; padding: 0; margin: 10px 0 0; display: flex; flex-direction: column; gap: 5px; }
+.sx-funnel li { display: grid; grid-template-columns: 1fr auto; gap: 2px 8px; font-size: var(--text-2xs, .66rem); color: var(--ink-dim, #9a9a9a); }
+.sx-funnel li b { color: var(--ink, #ddd); font-variant-numeric: tabular-nums; font-weight: 600; }
+.sx-bar { grid-column: 1 / -1; height: 4px; border-radius: 4px; background: var(--surface-2, rgba(255,255,255,.06)); overflow: hidden; }
+.sx-bar i { display: block; height: 100%; background: ${VIOLET}; border-radius: 4px; transform-origin: left; transition: width .3s ease; }
+.sx-sub { font-size: var(--text-2xs, .64rem); text-transform: uppercase; letter-spacing: .07em; color: var(--ink-faint, #777); font-weight: 700; margin: 12px 0 5px; }
+.sx-blockers { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 4px; }
+.sx-blockers li { display: flex; justify-content: space-between; gap: 8px; font-size: var(--text-2xs, .66rem); color: var(--ink-dim, #a8a8a8); }
+.sx-blockers li b { color: var(--danger, #f87171); font-variant-numeric: tabular-nums; font-weight: 600; }
+.sx-sample { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 3px; }
+.sx-sample a { display: flex; justify-content: space-between; gap: 8px; font-size: var(--text-2xs, .66rem); color: var(--ink, #ddd); text-decoration: none; padding: 4px 6px; margin: 0 -6px; border-radius: 6px; transition: background .16s; }
+.sx-sample a:hover { background: var(--surface-2, rgba(255,255,255,.05)); }
+.sx-sample a:focus-visible { outline: 2px solid var(--wallet-focus, rgba(139,92,246,.7)); }
+.sx-sample code { font-family: var(--font-mono, monospace); color: ${VIOLET}; }
+.sx-sample span { color: var(--ink-faint, #777); white-space: nowrap; }
+.sx-note { font-size: var(--text-2xs, .64rem); color: var(--ink-faint, #808080); line-height: 1.5; margin: 8px 0 0; }
+.sx-det { margin-top: 8px; font-size: var(--text-2xs, .64rem); color: var(--ink-faint, #808080); }
+.sx-det summary { cursor: pointer; color: var(--ink-dim, #9a9a9a); }
+.sx-det ul { margin: 6px 0 0; padding-left: 16px; line-height: 1.5; }
+.sx-skel { display: block; border-radius: 6px; background: linear-gradient(90deg, var(--surface-1, rgba(255,255,255,.04)) 25%, var(--surface-2, rgba(255,255,255,.09)) 50%, var(--surface-1, rgba(255,255,255,.04)) 75%); background-size: 200% 100%; animation: sx-shim 1.2s ease-in-out infinite; }
+@keyframes sx-shim { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }
+@media (prefers-reduced-motion: reduce) { .sx-skel { animation: none; } .sx-bar i { transition: none; } }
+.sx-err { font-size: var(--text-2xs, .68rem); color: var(--danger, #f87171); line-height: 1.5; }
+.sx-link { font: inherit; font-size: var(--text-2xs, .66rem); background: none; border: 0; padding: 0; color: ${VIOLET}; cursor: pointer; text-decoration: underline; text-underline-offset: 2px; }
+.sx-link:focus-visible { outline: 2px solid var(--wallet-focus, rgba(139,92,246,.7)); outline-offset: 2px; }
+.sx-stale { opacity: .55; transition: opacity .2s; }
+.sx-card { border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md, 10px); padding: var(--space-sm, 12px); margin-bottom: var(--space-sm, 12px); background: var(--surface-1, rgba(255,255,255,.02)); }
+.sx-card-h { display: flex; align-items: center; justify-content: space-between; gap: 8px; flex-wrap: wrap; margin-bottom: 4px; }
+.sx-card-h h2 { font-size: var(--text-2xs, .64rem); text-transform: uppercase; letter-spacing: .07em; color: ${VIOLET}; font-weight: 700; margin: 0; }
+.sx-card p { font-size: var(--text-2xs, .66rem); color: var(--ink-dim, #9a9a9a); line-height: 1.5; margin: 0 0 10px; }
+.sx-card textarea { width: 100%; box-sizing: border-box; min-height: 72px; resize: vertical; font: inherit; font-size: var(--text-sm, .82rem); padding: 9px 10px; border-radius: var(--radius-sm, 6px); border: 1px solid var(--stroke-strong, rgba(255,255,255,.14)); background: var(--surface-1, rgba(255,255,255,.03)); color: var(--ink-bright, #fff); }
+.sx-card textarea:focus, .sx-card select:focus { outline: none; border-color: var(--wallet-stroke-strong, rgba(139,92,246,.5)); }
+.sx-row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin-top: 8px; }
+.sx-row select { font: inherit; font-size: var(--text-xs, .76rem); padding: 7px 9px; border-radius: var(--radius-sm, 6px); border: 1px solid var(--stroke-strong, rgba(255,255,255,.14)); background: var(--surface-1, rgba(255,255,255,.03)); color: var(--ink-bright, #fff); max-width: 100%; min-width: 0; }
+.sx-row .so-btn { margin-left: auto; }
+.sx-out { margin-top: 10px; }
+.sx-expl { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 6px; }
+.sx-expl li { font-size: var(--text-2xs, .68rem); color: var(--ink-dim, #a8a8a8); line-height: 1.45; padding-left: 10px; border-left: 2px solid var(--wallet-stroke, rgba(139,92,246,.35)); }
+.sx-expl code { font-family: var(--font-mono, monospace); color: ${VIOLET}; font-size: .95em; }
+.sx-flag { font-size: var(--text-2xs, .66rem); line-height: 1.45; margin: 6px 0 0; padding: 7px 9px; border-radius: 8px; background: var(--surface-2, rgba(255,255,255,.04)); color: var(--ink-dim, #b0b0b0); }
+.sx-flag b { color: var(--ink, #ddd); }
+.sx-flag[data-kind="clamp"] { border-left: 2px solid var(--warning, #fbbf24); }
+.sx-metrics { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; }
+@media (max-width: 560px) { .sx-metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
+.sx-metric { border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: 8px; padding: 8px 9px; min-width: 0; }
+.sx-metric span { display: block; font-size: var(--text-2xs, .6rem); text-transform: uppercase; letter-spacing: .06em; color: var(--ink-faint, #777); }
+.sx-metric b { display: block; margin-top: 2px; font-size: var(--text-md, .95rem); color: var(--ink-bright, #fff); font-variant-numeric: tabular-nums; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.sx-metric b[data-sign="pos"] { color: var(--success, #4ade80); }
+.sx-metric b[data-sign="neg"] { color: var(--danger, #f87171); }
+.sx-cta { font-size: var(--text-2xs, .68rem); color: var(--ink-dim, #a8a8a8); line-height: 1.5; }
+.sx-cta a { color: ${VIOLET}; }
+`;
+ document.head.appendChild(s);
+}
+
+async function readError(res, fallback) {
+ const j = await res.json().catch(() => ({}));
+ return j?.error_description || j?.error?.message || j?.message || fallback;
+}
+
+// ── live match preview ───────────────────────────────────────────────────────
+
+export function mountLivePreview(host, { getConfig, onState }) {
+ ensureStyles();
+ if (!host) return { refresh() {}, destroy() {} };
+ let hours = 24;
+ let seq = 0;
+ let ctrl = null;
+ let timer = null;
+ let last = null;
+ let dead = false;
+ host.className = 'sx-live';
+ host.innerHTML = `<div class="sx-live-head">
+ <span class="sx-live-h" id="sx-live-h">Recent launches it would buy</span>
+ <span class="sx-win" role="group" aria-label="Preview window">${[1, 6, 24].map((h) => `<button type="button" data-h="${h}" aria-pressed="${h === hours}">${h}h</button>`).join('')}</span>
+ </div>
+ <div class="sx-live-body" aria-live="polite" aria-labelledby="sx-live-h"></div>`;
+ const body = host.querySelector('.sx-live-body');
+ host.querySelector('.sx-win').addEventListener('click', (e) => {
+ const b = e.target.closest('button[data-h]');
+ if (!b) return;
+ hours = Number(b.dataset.h);
+ host.querySelectorAll('.sx-win button').forEach((x) => x.setAttribute('aria-pressed', String(x === b)));
+ run();
+ });
+ body.addEventListener('click', (e) => { if (e.target.closest('[data-retry]')) run(); });
+
+ function skeleton() {
+ body.innerHTML = `<span class="sx-skel" style="width:46%;height:30px"></span>
+ <span class="sx-skel" style="width:100%;height:9px;margin-top:12px"></span>
+ <span class="sx-skel" style="width:82%;height:9px;margin-top:8px"></span>
+ <span class="sx-skel" style="width:64%;height:9px;margin-top:8px"></span>`;
+ }
+
+ async function run() {
+ clearTimeout(timer);
+ ctrl?.abort();
+ ctrl = new AbortController();
+ const my = ++seq;
+ if (last) body.classList.add('sx-stale');
+ else skeleton();
+ onState?.({ status: 'loading', data: last });
+ try {
+ const config = getConfig();
+ const res = await apiFetch('/api/strategies/preview', {
+ method: 'POST',
+ allowAnonymous: true,
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ config, hours, network: config.network }),
+ signal: ctrl.signal,
+ timeoutMs: 30_000,
+ });
+ if (my !== seq || dead) return;
+ if (!res.ok) throw new Error(await readError(res, 'The launch history could not be read right now.'));
+ const { data } = await res.json();
+ if (my !== seq || dead) return;
+ last = data;
+ body.classList.remove('sx-stale');
+ body.innerHTML = renderPreview(data);
+ onState?.({ status: 'ready', data });
+ } catch (err) {
+ if (err?.name === 'AbortError' || my !== seq || dead || err?.redirected) return;
+ last = null;
+ body.classList.remove('sx-stale');
+ body.innerHTML = `<div class="sx-err">${esc(err?.message || 'Preview unavailable.')} <button type="button" class="sx-link" data-retry>Try again</button></div>`;
+ onState?.({ status: 'error', data: null });
+ }
+ }
+
+ run();
+ return {
+ refresh() { clearTimeout(timer); if (last) body.classList.add('sx-stale'); onState?.({ status: 'loading', data: last }); timer = setTimeout(run, 400); },
+ retry() { run(); },
+ destroy() { dead = true; clearTimeout(timer); ctrl?.abort(); },
+ };
+}
+
+function topBlockers(d) {
+ const all = [...Object.entries(d.entry_rejects || {}), ...Object.entries(d.blocked_by || {})];
+ if (d.impact_blocked) all.push(['price_impact', d.impact_blocked]);
+ const merged = new Map();
+ for (const [k, n] of all) {
+ const label = blockLabel(k);
+ merged.set(label, (merged.get(label) || 0) + n);
+ }
+ return [...merged.entries()].sort((a, b) => b[1] - a[1]).slice(0, 4);
+}
+
+function renderPreview(d) {
+ const universe = Number(d.universe) || 0;
+ const win = `${d.window_hours}h`;
+ if (!universe) {
+ return `<div class="sx-big"><b>0</b><span>launches recorded in the last ${win}</span></div>
+ <p class="sx-note">No ${d.network === 'devnet' ? 'devnet ' : ''}launch history in this window yet. Try a longer window${d.network === 'devnet' ? ' or switch to mainnet' : ''}.</p>`;
+ }
+ const pct = (n) => `${Math.max(0, Math.min(100, (n / universe) * 100)).toFixed(1)}%`;
+ const step = (label, n) => `<li><span>${label}</span><b>${fmtN(n)}</b><span class="sx-bar"><i style="width:${pct(n)}"></i></span></li>`;
+ const blockers = topBlockers(d);
+ const head = d.would_buy > 0
+ ? `<div class="sx-big"><b>${fmtN(d.would_buy)}</b><span>of ${fmtN(universe)} launches in the last ${win}</span></div>`
+ : `<div class="sx-big"><b>0</b><span>of ${fmtN(universe)} launches in the last ${win}</span></div>
+ <p class="sx-note">Nothing passed. ${blockers.length ? `The biggest filter is <b>${esc(blockers[0][0].toLowerCase())}</b>; loosen it to see matches.` : 'Loosen a rule to see matches.'}</p>`;
+ const sample = (d.sample || []).length
+ ? `<div class="sx-sub">Examples</div><ul class="sx-sample">${d.sample.map((s) => `<li><a href="/coin/${encodeURIComponent(s.mint)}"><code>${esc(shortAddr(s.mint))}</code><span>${s.holders != null ? `${fmtN(s.holders)} holders · ` : ''}◎${s.liquidity_sol}${s.live_check ? ' · live check' : ''} · ${esc(timeAgo(s.seen_at))}</span></a></li>`).join('')}</ul>`
+ : '';
+ return `${head}
+ <ul class="sx-funnel">
+ ${step('Passed entry rules', d.passed_entry)}
+ ${step('Passed research gates', d.passed_research)}
+ ${step('Within price impact', d.would_buy)}
+ </ul>
+ ${blockers.length ? `<div class="sx-sub">Top reasons skipped</div><ul class="sx-blockers">${blockers.map(([l, n]) => `<li><span>${esc(l)}</span><b>${fmtN(n)}</b></li>`).join('')}</ul>` : ''}
+ ${sample}
+ ${d.live_check ? `<p class="sx-note">${fmtN(d.live_check)} of these depend on a check only run at buy time (firewall score or authorities), so the live count can be lower.</p>` : ''}
+ ${(d.caveats || []).length ? `<details class="sx-det"><summary>How this is counted</summary><ul>${d.caveats.map((c) => `<li>${esc(c)}</li>`).join('')}</ul></details>` : ''}`;
+}
+
+// ── owned agents (compile + backtest are scoped to an agent the caller owns) ──
+
+let agentsPromise = null;
+function loadMyAgents() {
+ agentsPromise ??= apiFetch('/api/agents', { allowAnonymous: true })
+ .then(async (res) => {
+ if (res.status === 401) return { signedIn: false, agents: [] };
+ if (!res.ok) throw new Error(await readError(res, 'Could not load your agents.'));
+ const j = await res.json();
+ const list = (j.agents || j.data?.agents || j.data || []).filter((a) => a && a.id);
+ return { signedIn: true, agents: list };
+ })
+ .catch((err) => { agentsPromise = null; throw err; });
+ return agentsPromise;
+}
+
+const agentSelectHTML = (agents, id) => `<select id="${id}" aria-label="Agent">${agents.map((a) => `<option value="${esc(a.id)}">${esc(a.name || shortAddr(a.id))}</option>`).join('')}</select>`;
+
+function noAgentHTML(state) {
+ if (!state.signedIn) return `<div class="sx-cta"><a href="/login?next=${encodeURIComponent(location.pathname + location.search)}">Sign in</a> to use this with one of your agents.</div>`;
+ return '<div class="sx-cta">This runs against one of your agents\' guards. <a href="/create">Create an agent</a> first, then come back.</div>';
+}
+
+// ── describe it in words ─────────────────────────────────────────────────────
+
+export function mountCompileBox(host, { getNetwork, onCompiled }) {
+ ensureStyles();
+ if (!host) return;
+ host.className = 'sx-card';
+ host.innerHTML = `<div class="sx-card-h"><h2>Describe it in words</h2></div>
+ <p>Write the plan in plain language. It becomes the settings below, clamped to your agent's caps, with a reason for every field. Nothing is saved until you press Create.</p>
+ <textarea id="sx-nl-text" aria-label="Describe your strategy" maxlength="2000" placeholder="e.g. Buy 0.2 SOL of new launches with 100+ holders, no wallet over 15%, mint and freeze renounced, max 3% price impact. Take profit at 2x, stop at 30%. Ask me first."></textarea>
+ <div class="sx-row"><span id="sx-nl-agent"></span><button type="button" class="so-btn so-btn-primary" id="sx-nl-go">Build settings</button></div>
+ <div class="sx-out" id="sx-nl-out" aria-live="polite"></div>`;
+ const out = host.querySelector('#sx-nl-out');
+ const go = host.querySelector('#sx-nl-go');
+ const text = host.querySelector('#sx-nl-text');
+ const agentSlot = host.querySelector('#sx-nl-agent');
+ let agents = null;
+
+ loadMyAgents().then((st) => {
+ agents = st;
+ if (st.agents.length > 1) agentSlot.innerHTML = agentSelectHTML(st.agents, 'sx-nl-agent-sel');
+ if (!st.agents.length) { out.innerHTML = noAgentHTML(st); go.disabled = true; }
+ }).catch((err) => { out.innerHTML = `<div class="sx-err">${esc(err.message)}</div>`; });
+
+ text.addEventListener('keydown', (e) => { if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) go.click(); });
+ go.addEventListener('click', async () => {
+ const t = text.value.trim();
+ if (t.length < 3) { out.innerHTML = '<div class="sx-err">Describe the strategy in a sentence or two first.</div>'; text.focus(); return; }
+ if (!agents?.agents.length) return;
+ const agentId = host.querySelector('#sx-nl-agent-sel')?.value || agents.agents[0].id;
+ go.disabled = true; go.textContent = 'Building…';
+ out.innerHTML = '<span class="sx-skel" style="width:100%;height:10px"></span><span class="sx-skel" style="width:72%;height:10px;margin-top:8px"></span>';
+ try {
+ const res = await apiFetch('/api/sniper/compile', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ agent_id: agentId, text: t, network: getNetwork() }),
+ });
+ if (!res.ok) throw new Error(await readError(res, 'Could not build settings from that description.'));
+ const r = await res.json();
+ if (!r.strategy_object) throw new Error('The compiler returned no settings. Try rephrasing.');
+ onCompiled(r.strategy_object);
+ out.innerHTML = renderCompile(r);
+ } catch (err) {
+ if (err?.redirected) return;
+ out.innerHTML = `<div class="sx-err">${esc(err.message || 'Could not build settings.')}</div>`;
+ } finally {
+ go.disabled = false; go.textContent = 'Build settings';
+ }
+ });
+}
+
+function fmtExplValue(v) {
+ if (Array.isArray(v)) return v.map((x) => (x == null ? 'any' : x)).join(' to ');
+ if (v === true) return 'on';
+ return v == null ? 'off' : String(v);
+}
+
+function renderCompile(r) {
+ const ex = (r.explanations || []).map((e) => `<li><code>${esc(e.field)}</code> = <b>${esc(fmtExplValue(e.value))}</b>. ${esc(e.why)}</li>`).join('');
+ const clamped = (r.clamped || []).map((c) => `<div class="sx-flag" data-kind="clamp"><b>Clamped:</b> ${esc(c)}</div>`).join('');
+ const assumed = (r.assumptions || []).map((c) => `<div class="sx-flag"><b>Assumed:</b> ${esc(c)}</div>`).join('');
+ const warned = (r.warnings || []).map((c) => `<div class="sx-flag" data-kind="clamp"><b>Note:</b> ${esc(c)}</div>`).join('');
+ return `<p style="margin:0 0 8px">Applied to the settings below${r.via === 'heuristic' ? ' (parsed by rules; the model was unavailable)' : ''}. Review them, then save.</p>
+ ${ex ? `<ul class="sx-expl">${ex}</ul>` : ''}${clamped}${assumed}${warned}`;
+}
+
+// ── backtest with the gates applied ──────────────────────────────────────────
+
+// Map a Strategy Object onto the sniper rule shape the replay engine reads.
+export function toSniperStrategy(cfg) {
+ const e = cfg.entry || {}, s = cfg.sizing || {}, x = cfg.exits || {}, r = cfg.research || {};
+ return {
+ trigger: 'new_mint',
+ per_trade_lamports: String(Math.round((Number(s.amount_sol) || 0) * 1e9)),
+ slippage_bps: s.max_slippage_bps ?? 500,
+ max_price_impact_pct: s.max_price_impact_bps == null ? null : s.max_price_impact_bps / 100,
+ min_market_cap_usd: e.min_market_cap_usd ?? null,
+ max_market_cap_usd: e.max_market_cap_usd ?? null,
+ max_creator_launches: r.dev_history?.max_launches ?? e.max_creator_launches ?? null,
+ min_creator_graduated: r.dev_history?.min_graduated ?? e.min_creator_graduated ?? null,
+ require_socials: e.require_socials === true,
+ require_sol_quote: e.require_sol_quote !== false,
+ take_profit_pct: x.take_profit_pct ?? null,
+ stop_loss_pct: x.stop_loss_pct ?? null,
+ trailing_stop_pct: x.trailing_stop_pct ?? null,
+ max_hold_seconds: x.max_hold_minutes == null ? null : Math.round(x.max_hold_minutes * 60),
+ avoid_dev_dump: r.dev_history?.block_dev_sold === true,
+ research: r,
+ };
+}
+
+export function mountGatedBacktest(host, { getConfig }) {
+ ensureStyles();
+ if (!host) return;
+ host.className = 'sx-card';
+ host.innerHTML = `<div class="sx-card-h"><h2>Backtest with these gates</h2></div>
+ <p>Replays these exact rules, research gates included, over real launches three.ws recorded, with the same exit order the live runtime uses. It never invents launches.</p>
+ <div class="sx-row">
+ <span id="sx-bt-agent"></span>
+ <select id="sx-bt-win" aria-label="Backtest window"><option value="7">Last 7 days</option><option value="30" selected>Last 30 days</option><option value="90">Last 90 days</option></select>
+ <button type="button" class="so-btn so-btn-primary" id="sx-bt-go">Run backtest</button>
+ </div>
+ <div class="sx-out" id="sx-bt-out" aria-live="polite"></div>`;
+ const out = host.querySelector('#sx-bt-out');
+ const go = host.querySelector('#sx-bt-go');
+ let agents = null;
+
+ loadMyAgents().then((st) => {
+ agents = st;
+ if (st.agents.length > 1) host.querySelector('#sx-bt-agent').innerHTML = agentSelectHTML(st.agents, 'sx-bt-agent-sel');
+ if (!st.agents.length) { out.innerHTML = noAgentHTML(st); go.disabled = true; }
+ }).catch((err) => { out.innerHTML = `<div class="sx-err">${esc(err.message)}</div>`; });
+
+ go.addEventListener('click', async () => {
+ if (!agents?.agents.length) return;
+ const cfg = getConfig();
+ const agentId = host.querySelector('#sx-bt-agent-sel')?.value || agents.agents[0].id;
+ go.disabled = true; go.textContent = 'Replaying…';
+ out.innerHTML = `<div class="sx-metrics">${'<div class="sx-metric"><span class="sx-skel" style="width:60%;height:8px"></span><span class="sx-skel" style="width:80%;height:16px;margin-top:6px"></span></div>'.repeat(4)}</div>`;
+ try {
+ const res = await apiFetch('/api/sniper/backtest', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ agent_id: agentId, strategy: toSniperStrategy(cfg), window_days: Number(host.querySelector('#sx-bt-win').value), network: cfg.network }),
+ timeoutMs: 120_000,
+ });
+ if (!res.ok) throw new Error(await readError(res, 'The backtest could not run right now.'));
+ out.innerHTML = renderBacktest(await res.json());
+ } catch (err) {
+ if (err?.redirected) return;
+ out.innerHTML = `<div class="sx-err">${esc(err.message || 'The backtest could not run.')} <button type="button" class="sx-link" id="sx-bt-retry">Try again</button></div>`;
+ out.querySelector('#sx-bt-retry')?.addEventListener('click', () => go.click());
+ } finally {
+ go.disabled = false; go.textContent = 'Run backtest';
+ }
+ });
+}
+
+function renderBacktest(r) {
+ if (r.insufficient_data) {
+ return `<div class="sx-flag"><b>Not enough history:</b> ${esc(r.message || 'Too few recorded launches matched to give an honest number.')} Try a longer window or loosen a gate.</div>${blockedList(r)}`;
+ }
+ const m = r.metrics || {};
+ const sign = (n) => (n == null ? '' : n > 0 ? 'pos' : n < 0 ? 'neg' : '');
+ const cell = (label, val, s = '') => `<div class="sx-metric"><span>${label}</span><b data-sign="${s}">${val}</b></div>`;
+ return `<div class="sx-metrics">
+ ${cell('Entries', fmtN(m.entries))}
+ ${cell('Win rate', m.win_rate == null ? '-' : `${(m.win_rate * 100).toFixed(0)}%`)}
+ ${cell('Avg return', fmtPct(m.expected_value_pct), sign(m.expected_value_pct))}
+ ${cell('Net P&amp;L', m.net_pnl_sol == null ? '-' : `◎${Number(m.net_pnl_sol).toFixed(2)}`, sign(m.net_pnl_sol))}
+ ${cell('Median', fmtPct(m.roi_median_pct), sign(m.roi_median_pct))}
+ ${cell('Worst 10%', fmtPct(m.roi_p10_pct), sign(m.roi_p10_pct))}
+ ${cell('Best 10%', fmtPct(m.roi_p90_pct), sign(m.roi_p90_pct))}
+ ${cell('Invested', m.total_invested_sol == null ? '-' : `◎${Number(m.total_invested_sol).toFixed(2)}`)}
+ </div>
+ <p class="sx-note">${fmtN(r.sample_size)} of ${fmtN(r.universe_size)} recorded launches over ${r.window_days} days passed your rules${r.cached ? ' (cached result for these exact settings)' : ''}.</p>
+ ${blockedList(r)}
+ ${(r.caveats || []).length ? `<details class="sx-det"><summary>Caveats</summary><ul>${r.caveats.map((c) => `<li>${esc(c)}</li>`).join('')}</ul></details>` : ''}`;
+}
+
+function blockedList(r) {
+ const rows = Object.entries(r.research_blocked_by || {}).sort((a, b) => b[1] - a[1]);
+ if (!rows.length) return '';
+ return `<div class="sx-sub">Skipped by research gates</div><ul class="sx-blockers">${rows.map(([k, n]) => `<li><span>${esc(blockLabel(k))}</span><b>${fmtN(n)}</b></li>`).join('')}</ul>${r.research_live_checked ? `<p class="sx-note">${fmtN(r.research_live_checked)} entries relied on a check only run at buy time.</p>` : ''}`;
+}
diff --git a/tests/strategy-research-gates.test.js b/tests/strategy-research-gates.test.js
new file mode 100644
index 000000000..aa618705a
--- /dev/null
+++ b/tests/strategy-research-gates.test.js
@@ -0,0 +1,434 @@
+/**
+ * Strategy Object v2: research gates, price-impact cap, ask/auto mode.
+ *
+ * Money-adjacent, so the invariants that keep an autonomous buyer honest are
+ * pinned here without a DB or a model:
+ * - every research gate passes, fails, fails closed on unknown data, and
+ * stays out of the way when switched off,
+ * - v1 configs fold into v2 without losing a setting, and mode defaults to ask,
+ * - a strategy's impact cap can only tighten its agent's breaker,
+ * - the approval payload hash is canonical, so an approval cannot be replayed
+ * against a different buy,
+ * - the gate report fetches only the sections a strategy gates on,
+ * - the historical judge treats firewall-only checks as "checked at buy",
+ * - the natural-language compiler emits, explains and clamps the new fields.
+ */
+
+import { describe, it, expect, vi } from 'vitest';
+
+vi.mock('../api/_lib/llm.js', () => ({ llmConfigured: () => false, llmComplete: vi.fn() }));
+
+import {
+ normalizeStrategyConfig,
+ evaluateResearchGates,
+ effectivePriceImpactPct,
+ launchSources,
+ researchGatesActive,
+ matchesEntry,
+ STRATEGY_CONFIG_DEFAULTS,
+} from '../api/_lib/strategy-schema.js';
+import { sectionsNeeded, topHolderPctExcluding, buildGateReport, riskNotesFromReport } from '../api/_lib/strategy-research.js';
+import { canonicalJson, payloadHash, buildStrategyBuyPayload } from '../api/_lib/strategy-approvals.js';
+import { curveMarketCapSol, curveImpactPct, historyToCandidate, judgeHistoricalGates, historicalGateReport } from '../api/_lib/strategy-preview.js';
+import { sanitizeResearch, strategyHash } from '../api/_lib/strategy-backtest.js';
+import { compileStrategyFromText } from '../api/_lib/strategy-compiler.js';
+
+const MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const CREATOR = 'THREEsynthetic11111111111111111111111111111';
+
+function cfg(research = {}, extra = {}) {
+ return normalizeStrategyConfig({ ...extra, research });
+}
+
+function fullReport(over = {}) {
+ return {
+ holders: { count: 120, top_holder_pct: 8 },
+ liquidity: { sol: 12 },
+ security: { score: 82 },
+ authority: { known: true, mint_authority: null, freeze_authority: null },
+ dev: { launches: 2, graduated: 1, sold: false },
+ ...over,
+ };
+}
+
+const statusOf = (ev, check) => ev.checks.find((c) => c.check === check)?.status;
+
+describe('evaluateResearchGates: each gate', () => {
+ const cases = [
+ { check: 'min_holders', research: { min_holders: 100 }, fail: { holders: { count: 40, top_holder_pct: 8 } }, unknown: { holders: { count: null, top_holder_pct: 8 } } },
+ { check: 'max_top_holder_pct', research: { max_top_holder_pct: 20 }, fail: { holders: { count: 120, top_holder_pct: 35 } }, unknown: { holders: { count: 120, top_holder_pct: null } } },
+ { check: 'min_liquidity_sol', research: { min_liquidity_sol: 5 }, fail: { liquidity: { sol: 1.5 } }, unknown: { liquidity: { sol: null } } },
+ { check: 'security_min_score', research: { security_min_score: 60 }, fail: { security: { score: 30 } }, unknown: { security: { score: null } } },
+ { check: 'require_no_mint_authority', research: { require_no_mint_authority: true }, fail: { authority: { known: true, mint_authority: 'Auth111', freeze_authority: null } }, unknown: { authority: { known: false } } },
+ { check: 'require_no_freeze_authority', research: { require_no_freeze_authority: true }, fail: { authority: { known: true, mint_authority: null, freeze_authority: 'Auth111' } }, unknown: { authority: { known: false } } },
+ { check: 'dev_max_launches', research: { dev_history: { max_launches: 3 } }, fail: { dev: { launches: 14, graduated: 1, sold: false } }, unknown: { dev: { launches: null, graduated: 1, sold: false } } },
+ { check: 'dev_min_graduated', research: { dev_history: { min_graduated: 1 } }, fail: { dev: { launches: 2, graduated: 0, sold: false } }, unknown: { dev: { launches: 2, graduated: null, sold: false } } },
+ { check: 'dev_block_sold', research: { dev_history: { block_dev_sold: true } }, fail: { dev: { launches: 2, graduated: 1, sold: true } }, unknown: { dev: { launches: 2, graduated: 1, sold: null } } },
+ ];
+
+ for (const c of cases) {
+ describe(c.check, () => {
+ const config = cfg(c.research);
+
+ it('passes a coin that meets it', () => {
+ const ev = evaluateResearchGates(config, fullReport());
+ expect(statusOf(ev, c.check)).toBe('pass');
+ expect(ev.pass).toBe(true);
+ expect(ev.blocked_by).toEqual([]);
+ });
+
+ it('blocks a failing coin and names the check with a reason', () => {
+ const ev = evaluateResearchGates(config, fullReport(c.fail));
+ expect(ev.pass).toBe(false);
+ expect(ev.blocked_by).toHaveLength(1);
+ const b = ev.blocked_by[0];
+ expect(b.check).toBe(c.check);
+ expect(b.status).toBe('fail');
+ expect(typeof b.reason).toBe('string');
+ expect(b.reason.length).toBeGreaterThan(10);
+ expect(b.label).toBeTruthy();
+ });
+
+ it('fails closed when the data is unknown', () => {
+ const ev = evaluateResearchGates(config, fullReport(c.unknown));
+ expect(ev.pass).toBe(false);
+ expect(ev.blocked_by[0].check).toBe(c.check);
+ expect(ev.blocked_by[0].status).toBe('unknown');
+ expect(ev.blocked_by[0].reason).toMatch(/could not be verified/);
+ });
+
+ it('is ignored when switched off, even with failing or missing data', () => {
+ const off = cfg({});
+ expect(statusOf(evaluateResearchGates(off, fullReport(c.fail)), c.check)).toBe('off');
+ expect(evaluateResearchGates(off, fullReport(c.unknown)).pass).toBe(true);
+ });
+ });
+ }
+
+ it('reports every failing gate, not just the first', () => {
+ const config = cfg({ min_holders: 100, min_liquidity_sol: 5, dev_history: { block_dev_sold: true } });
+ const ev = evaluateResearchGates(config, fullReport({ holders: { count: 3, top_holder_pct: 5 }, liquidity: { sol: 0.2 }, dev: { sold: true } }));
+ expect(ev.blocked_by.map((b) => b.check).sort()).toEqual(['dev_block_sold', 'min_holders', 'min_liquidity_sol']);
+ });
+
+ it('an empty report blocks every enabled gate and passes a gate-free strategy', () => {
+ const all = cfg({
+ min_holders: 1, max_top_holder_pct: 50, min_liquidity_sol: 1, security_min_score: 10,
+ require_no_mint_authority: true, require_no_freeze_authority: true,
+ dev_history: { max_launches: 5, min_graduated: 0, block_dev_sold: true },
+ });
+ expect(evaluateResearchGates(all, {}).blocked_by).toHaveLength(9);
+ expect(evaluateResearchGates(cfg({}), {}).pass).toBe(true);
+ });
+
+ it('the boundary value passes (min is inclusive, ceiling is inclusive)', () => {
+ const config = cfg({ min_holders: 120, max_top_holder_pct: 8, min_liquidity_sol: 12, security_min_score: 82, dev_history: { max_launches: 2, min_graduated: 1 } });
+ expect(evaluateResearchGates(config, fullReport()).pass).toBe(true);
+ });
+});
+
+describe('normalizeStrategyConfig: v2 shape and v1 compatibility', () => {
+ it('defaults mode to ask and stamps version 2', () => {
+ const c = normalizeStrategyConfig({});
+ expect(c.version).toBe(2);
+ expect(c.mode).toBe('ask');
+ expect(STRATEGY_CONFIG_DEFAULTS.mode).toBe('ask');
+ expect(normalizeStrategyConfig({ mode: 'yolo' }).mode).toBe('ask');
+ expect(normalizeStrategyConfig({ mode: 'auto' }).mode).toBe('auto');
+ });
+
+ it('folds legacy entry creator and liquidity filters into the research gates', () => {
+ const c = normalizeStrategyConfig({ entry: { min_liquidity_sol: 4, max_creator_launches: 3, min_creator_graduated: 1 } });
+ expect(c.research.min_liquidity_sol).toBe(4);
+ expect(c.research.dev_history.max_launches).toBe(3);
+ expect(c.research.dev_history.min_graduated).toBe(1);
+ });
+
+ it('the research value wins and both halves are written back identical', () => {
+ const c = normalizeStrategyConfig({
+ entry: { min_liquidity_sol: 4, max_creator_launches: 9 },
+ research: { min_liquidity_sol: 7, dev_history: { max_launches: 2 } },
+ });
+ expect(c.research.min_liquidity_sol).toBe(7);
+ expect(c.entry.min_liquidity_sol).toBe(7);
+ expect(c.research.dev_history.max_launches).toBe(2);
+ expect(c.entry.max_creator_launches).toBe(2);
+ });
+
+ it('accepts camelCase keys and stores snake_case', () => {
+ const c = normalizeStrategyConfig({
+ sizing: { maxPriceImpactBps: 250 },
+ research: { minHolders: 75, maxTopHolderPct: 15, requireNoMintAuthority: true, devHistory: { blockDevSold: true, maxLaunches: 4 } },
+ });
+ expect(c.sizing.max_price_impact_bps).toBe(250);
+ expect(c.research.min_holders).toBe(75);
+ expect(c.research.max_top_holder_pct).toBe(15);
+ expect(c.research.require_no_mint_authority).toBe(true);
+ expect(c.research.dev_history.block_dev_sold).toBe(true);
+ expect(c.research.dev_history.max_launches).toBe(4);
+ });
+
+ it('normalizes sources: unknown dropped, duplicates removed, every source means all', () => {
+ expect(normalizeStrategyConfig({ entry: { sources: ['THREE_WS_LAUNCH', 'three_ws_launch', 'nope'] } }).entry.sources).toEqual(['three_ws_launch']);
+ expect(normalizeStrategyConfig({ entry: { sources: ['pump_curve', 'three_ws_launch'] } }).entry.sources).toEqual([]);
+ expect(normalizeStrategyConfig({ entry: { sources: 'three_ws_launch' } }).entry.sources).toEqual([]);
+ });
+
+ it('researchGatesActive is false until a gate is switched on', () => {
+ expect(researchGatesActive(cfg({}))).toBe(false);
+ expect(researchGatesActive(cfg({ require_no_freeze_authority: true }))).toBe(true);
+ expect(researchGatesActive(cfg({ dev_history: { min_graduated: 0 } }))).toBe(true);
+ });
+
+ it('is idempotent', () => {
+ const once = cfg({ min_holders: 50, dev_history: { max_launches: 3 } }, { mode: 'auto', sizing: { max_price_impact_bps: 400 } });
+ expect(normalizeStrategyConfig(once)).toEqual(once);
+ });
+});
+
+describe('price impact and sources', () => {
+ it('a strategy can only tighten its agent breaker', () => {
+ const tight = normalizeStrategyConfig({ sizing: { max_price_impact_bps: 300 } });
+ const loose = normalizeStrategyConfig({ sizing: { max_price_impact_bps: 2000 } });
+ const none = normalizeStrategyConfig({});
+ expect(effectivePriceImpactPct(tight, 10)).toBe(3);
+ expect(effectivePriceImpactPct(loose, 10)).toBe(10);
+ expect(effectivePriceImpactPct(none, 10)).toBe(10);
+ expect(effectivePriceImpactPct(tight, null)).toBe(3);
+ expect(effectivePriceImpactPct(none, null)).toBe(null);
+ });
+
+ it('tags three.ws launches and filters entry by source', () => {
+ expect(launchSources({})).toEqual(['pump_curve']);
+ expect(launchSources({ three_ws_launch: true })).toEqual(['pump_curve', 'three_ws_launch']);
+ const only = normalizeStrategyConfig({ entry: { sources: ['three_ws_launch'], max_age_minutes: 600 } });
+ const launch = { mint: MINT, created_at: Date.now() - 60_000, liquidity_sol: 10, market_cap_usd: 9000, is_usdc_pair: false };
+ expect(matchesEntry(only, launch, Date.now()).pass).toBe(false);
+ expect(matchesEntry(only, { ...launch, three_ws_launch: true }, Date.now()).pass).toBe(true);
+ });
+});
+
+describe('topHolderPctExcluding', () => {
+ it('excludes the bonding curve and rescales to circulating supply', () => {
+ const top = [{ owner: 'CURVE', pct: 80 }, { owner: 'A', pct: 5 }, { owner: 'B', pct: 2 }];
+ expect(topHolderPctExcluding(top, 'CURVE')).toBeCloseTo(25, 6);
+ });
+
+ it('matches the curve by token account address too', () => {
+ expect(topHolderPctExcluding([{ address: 'CURVE', pct: 50 }, { owner: 'A', pct: 10 }], 'CURVE')).toBeCloseTo(20, 6);
+ });
+
+ it('returns null with no usable rows', () => {
+ expect(topHolderPctExcluding([], 'CURVE')).toBe(null);
+ expect(topHolderPctExcluding(null, 'CURVE')).toBe(null);
+ expect(topHolderPctExcluding([{ owner: 'CURVE', pct: 100 }], 'CURVE')).toBe(null);
+ });
+});
+
+describe('approval payload', () => {
+ it('canonicalJson is key-order independent and drops undefined', () => {
+ expect(canonicalJson({ b: 1, a: { d: 2, c: [3, { y: 1, x: 0 }] }, z: undefined }))
+ .toBe(canonicalJson({ a: { c: [3, { x: 0, y: 1 }], d: 2 }, b: 1 }));
+ expect(canonicalJson({ b: 1, a: 2 })).toBe('{"a":2,"b":1}');
+ });
+
+ it('the payload hash binds every field of the buy', () => {
+ const config = normalizeStrategyConfig({ sizing: { amount_sol: 0.1, max_slippage_bps: 800, max_price_impact_bps: 350 } });
+ const p = buildStrategyBuyPayload({ equip: { id: 'eq1', strategy_id: 's1' }, agentId: 'ag1', config, network: 'mainnet', mint: MINT, idempotencyKey: 'k1' });
+ expect(p).toEqual({
+ kind: 'strategy_buy', agent_id: 'ag1', equip_id: 'eq1', strategy_id: 's1', network: 'mainnet',
+ mint: MINT, side: 'buy', amount_sol: 0.1, slippage_bps: 800, max_price_impact_pct: 3.5, idempotency_key: 'k1',
+ });
+ const h = payloadHash(p);
+ expect(h).toMatch(/^[0-9a-f]{64}$/);
+ expect(payloadHash({ ...p })).toBe(h);
+ expect(payloadHash({ ...p, amount_sol: 0.2 })).not.toBe(h);
+ expect(payloadHash({ ...p, mint: CREATOR })).not.toBe(h);
+ });
+
+ it('a strategy with no impact cap carries null, not NaN', () => {
+ const p = buildStrategyBuyPayload({ equip: { id: 'e', strategy_id: 's' }, agentId: 'a', config: normalizeStrategyConfig({}), network: 'devnet', mint: MINT, idempotencyKey: 'k' });
+ expect(p.max_price_impact_pct).toBe(null);
+ });
+});
+
+function fakeDeps(over = {}) {
+ const calls = { holders: 0, safety: 0, creator: 0, intel: 0 };
+ const deps = {
+ readIntel: async () => { calls.intel++; return { dev_sold: false, signals: {} }; },
+ composeTokenHolders: async () => { calls.holders++; return { status: 'ok', holderCount: 140, sources: ['indexer'], top: [{ owner: 'CURVE', pct: 60 }, { owner: 'W', pct: 8 }] }; },
+ bondingCurveOwner: async () => 'CURVE',
+ assessTradeSafety: async () => {
+ calls.safety++;
+ return { score: 77, verdict: 'allow', reasons: ['Simulated buy succeeded.'], checks: [{ name: 'mint_authority', detail: { mint_authority: null, freeze_authority: null } }] };
+ },
+ enrichCreatorStats: async (l) => { calls.creator++; l.creator_launches = 3; l.creator_graduated = 1; },
+ ...over,
+ };
+ return { deps, calls };
+}
+
+const LAUNCH = { mint: MINT, name: 'Synthetic', symbol: 'SYN', creator: CREATOR, liquidity_sol: 9, market_cap_usd: 12000 };
+
+describe('buildGateReport', () => {
+ it('fetches only the sections a strategy gates on', async () => {
+ expect(sectionsNeeded(cfg({ min_liquidity_sol: 2 }))).toEqual({ holders: false, security: false, dev: false });
+ expect(sectionsNeeded(cfg({ min_holders: 10 })).holders).toBe(true);
+ expect(sectionsNeeded(cfg({ require_no_mint_authority: true })).security).toBe(true);
+ expect(sectionsNeeded(cfg({ dev_history: { block_dev_sold: true } })).dev).toBe(true);
+ expect(sectionsNeeded(cfg({}), { forApproval: true })).toEqual({ holders: true, security: true, dev: true });
+
+ const { deps, calls } = fakeDeps();
+ const { report } = await buildGateReport({ config: cfg({ min_liquidity_sol: 2 }), launch: LAUNCH }, deps);
+ expect(calls).toMatchObject({ holders: 0, safety: 0, creator: 0 });
+ expect(report.liquidity.sol).toBe(9);
+ expect(report.holders.skipped).toBe(true);
+ expect(evaluateResearchGates(cfg({ min_liquidity_sol: 2 }), report).pass).toBe(true);
+ });
+
+ it('assembles every section from the readers and the gates read it', async () => {
+ const config = cfg({ min_holders: 100, max_top_holder_pct: 25, security_min_score: 60, require_no_mint_authority: true, require_no_freeze_authority: true, dev_history: { max_launches: 5, min_graduated: 1, block_dev_sold: true } });
+ const { deps } = fakeDeps();
+ const { report, assessment } = await buildGateReport({ config, launch: LAUNCH, payer: CREATOR }, deps);
+ expect(report.holders.count).toBe(140);
+ expect(report.holders.top_holder_pct).toBe(20);
+ expect(report.security.score).toBe(77);
+ expect(report.authority).toMatchObject({ known: true, mint_authority: null, freeze_authority: null });
+ expect(report.dev).toMatchObject({ launches: 3, graduated: 1, sold: false });
+ expect(assessment.score).toBe(77);
+ const ev = evaluateResearchGates(config, report);
+ expect(ev.pass).toBe(true);
+ const notes = riskNotesFromReport(report, ev);
+ expect(notes.some((n) => /Firewall score 77/.test(n))).toBe(true);
+ expect(notes.join(' ')).not.toMatch(/Synthetic|SYN/);
+ });
+
+ it('a reader that throws leaves its fields unknown, so its gate fails closed', async () => {
+ const config = cfg({ min_holders: 10, security_min_score: 50 });
+ const { deps } = fakeDeps({
+ composeTokenHolders: async () => { throw new Error('indexer down'); },
+ assessTradeSafety: async () => { throw new Error('rpc down'); },
+ });
+ const { report } = await buildGateReport({ config, launch: LAUNCH }, deps);
+ const ev = evaluateResearchGates(config, report);
+ expect(ev.pass).toBe(false);
+ expect(ev.blocked_by.map((b) => [b.check, b.status])).toEqual([['min_holders', 'unknown'], ['security_min_score', 'unknown']]);
+ });
+
+ it('prefers the intel engine top-holder share over the on-chain walk', async () => {
+ const { deps } = fakeDeps({ readIntel: async () => ({ dev_sold: true, signals: { concentration_top1: 0.31 } }) });
+ const { report } = await buildGateReport({ config: cfg({ max_top_holder_pct: 25 }), launch: LAUNCH }, deps);
+ expect(report.holders.top_holder_pct).toBe(31);
+ expect(report.holders.source.top_holder_pct).toBe('pump_coin_intel');
+ expect(evaluateResearchGates(cfg({ max_top_holder_pct: 25 }), report).blocked_by[0].check).toBe('max_top_holder_pct');
+ });
+});
+
+describe('preview and backtest history', () => {
+ it('curve math matches the bonding-curve constant-product formula', () => {
+ expect(curveMarketCapSol(0)).toBeCloseTo((30 * 30 * 1e9) / (30 * 1.073e9), 6);
+ expect(curveMarketCapSol(10)).toBeGreaterThan(curveMarketCapSol(0));
+ expect(curveMarketCapSol(-5)).toBe(curveMarketCapSol(0));
+ expect(curveImpactPct(0.3, 0)).toBeCloseTo(1, 6);
+ expect(curveImpactPct(0.3, 30)).toBeCloseTo(0.5, 6);
+ });
+
+ it('turns a recorded intel row into the live launch and report shapes', () => {
+ const row = {
+ mint: MINT, creator: CREATOR, first_seen_at: '2026-10-10T00:00:00Z',
+ buy_volume_lamports: '6000000000', sell_volume_lamports: '1000000000',
+ unique_buyers: 44, top1: '0.12', dev_sold: false, launches_prior: 2, graduated_prior: 1,
+ fw_score: 70, fw_authority: { mint_authority: null, freeze_authority: null }, three_ws_launch: true,
+ };
+ const { launch, report, netSol } = historyToCandidate(row, 150);
+ expect(netSol).toBe(5);
+ expect(launch.liquidity_sol).toBe(5);
+ expect(launch.creator_launches).toBe(3);
+ expect(launch.market_cap_usd).toBeCloseTo(curveMarketCapSol(5) * 150, 6);
+ expect(launchSources(launch)).toContain('three_ws_launch');
+ expect(report.holders).toEqual({ count: 44, top_holder_pct: 12 });
+ expect(report.authority.known).toBe(true);
+ expect(report.dev).toMatchObject({ launches: 3, graduated: 1, sold: false });
+ });
+
+ it('firewall-only checks missing from history are live, any other unknown blocks', () => {
+ const row = { mint: MINT, unique_buyers: 80, top1: 0.1, dev_sold: false, buy_volume_lamports: 5e9, sell_volume_lamports: 0 };
+ const report = historicalGateReport(row, {});
+ const live = judgeHistoricalGates(cfg({ min_holders: 50, security_min_score: 60, require_no_mint_authority: true }), report);
+ expect(live.blocked).toBe(null);
+ expect(live.live).toBe(true);
+ const hard = judgeHistoricalGates(cfg({ dev_history: { max_launches: 3 } }), report);
+ expect(hard.blocked).toBe('dev_max_launches');
+ const fail = judgeHistoricalGates(cfg({ min_holders: 100, security_min_score: 60 }), report);
+ expect(fail.blocked).toBe('min_holders');
+ const clean = judgeHistoricalGates(cfg({ min_holders: 50 }), report);
+ expect(clean).toMatchObject({ blocked: null, live: false });
+ });
+
+ it('sanitizeResearch is null with no gates, so the backtest cache hash is unchanged', () => {
+ expect(sanitizeResearch(null)).toBe(null);
+ expect(sanitizeResearch({})).toBe(null);
+ expect(sanitizeResearch({ min_holders: null, require_no_mint_authority: false })).toBe(null);
+ const g = sanitizeResearch({ minHolders: 60, devHistory: { blockDevSold: true } });
+ expect(g.min_holders).toBe(60);
+ expect(g.dev_history.block_dev_sold).toBe(true);
+
+ const base = { trigger: 'new_mint', per_trade_lamports: '100000000', stop_loss_pct: 30 };
+ const h0 = strategyHash(base, 30, 'mainnet');
+ expect(strategyHash({ ...base, research: null }, 30, 'mainnet')).toBe(h0);
+ expect(strategyHash({ ...base, research: g }, 30, 'mainnet')).not.toBe(h0);
+ });
+});
+
+describe('compileStrategyFromText: v2 round trip', () => {
+ it('emits and explains research gates, impact, sources and ask mode', async () => {
+ const r = await compileStrategyFromText(
+ 'Buy three.ws launches with at least 150 holders, 5 sol liquidity, security score 70, renounced mint and renounced freeze authority, 3% price impact, 0.2 sol per trade, stop loss 35%, ask me first',
+ );
+ expect(r.ok).toBe(true);
+ const so = r.strategy_object;
+ expect(so.version).toBe(2);
+ expect(so.mode).toBe('ask');
+ expect(so.entry.sources).toEqual(['three_ws_launch']);
+ expect(so.sizing.amount_sol).toBe(0.2);
+ expect(so.sizing.max_price_impact_bps).toBe(300);
+ expect(so.research.min_holders).toBe(150);
+ expect(so.research.min_liquidity_sol).toBe(5);
+ expect(so.research.security_min_score).toBe(70);
+ expect(so.research.require_no_mint_authority).toBe(true);
+ expect(so.research.require_no_freeze_authority).toBe(true);
+ expect(so.exits.stop_loss_pct).toBe(35);
+
+ const fields = r.explanations.map((e) => e.field);
+ for (const f of ['mode', 'entry.sources', 'sizing.amount_sol', 'sizing.max_price_impact_bps', 'research.min_holders', 'research.min_liquidity_sol', 'research.security_min_score', 'research.require_no_mint_authority', 'research.require_no_freeze_authority']) {
+ expect(fields).toContain(f);
+ }
+ for (const e of r.explanations) expect(e.why.length).toBeGreaterThan(10);
+
+ // Round trip: the compiled object is already normalized and evaluates as stored.
+ expect(normalizeStrategyConfig(so)).toEqual(so);
+ const bad = evaluateResearchGates(so, fullReport({ holders: { count: 20, top_holder_pct: 5 } }));
+ expect(bad.blocked_by[0].check).toBe('min_holders');
+ });
+
+ it('defaults to ask and only goes auto when the owner says so', async () => {
+ const ask = await compileStrategyFromText('snipe new launches 0.1 sol each stop loss 30%');
+ expect(ask.strategy_object.mode).toBe('ask');
+ const auto = await compileStrategyFromText('snipe new launches automatically, 0.1 sol each, stop loss 30%');
+ expect(auto.strategy_object.mode).toBe('auto');
+ });
+
+ it('clamps price impact to the agent breaker and says so', async () => {
+ const r = await compileStrategyFromText('snipe with 40% price impact, 0.1 sol per trade, stop loss 30%', { tradeLimits: { max_price_impact_pct: 6 } });
+ expect(r.strategy_object.sizing.max_price_impact_bps).toBe(600);
+ expect(r.clamped.join(' ')).toMatch(/6% safety breaker/);
+ expect(effectivePriceImpactPct(r.strategy_object, 6)).toBe(6);
+ });
+
+ it('carries creator filters into dev_history', async () => {
+ const r = await compileStrategyFromText("creators who've graduated at least 2 coins, no dev dump, stop loss 30%");
+ expect(r.strategy_object.research.dev_history.min_graduated).toBe(2);
+ expect(r.strategy_object.research.dev_history.block_dev_sold).toBe(true);
+ expect(r.strategy_object.entry.min_creator_graduated).toBe(2);
+ });
+});