Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
chore: remove task/prompt specs for verified-shipped work
miniaturizationa9f97e60a96d
diff --git a/prompts/agent-wallets/04-ownership-fork-to-own.md b/prompts/agent-wallets/04-ownership-fork-to-own.mddeleted file mode 100644index 546a631f3..000000000--- a/prompts/agent-wallets/04-ownership-fork-to-own.md+++ /dev/null@@ -1,103 +0,0 @@-# Task 04 — Ownership clarity & "Fork to own your wallet"--> **Read [00-README-orchestration.md](./00-README-orchestration.md) first** for the-> ownership model, tokens, real APIs, hard rules, definition of done, and the-> "improve then delete this file" close-out. Builds on the shared wallet component-> (**task 01**) and the HUD (**task 02**).--## Mission--This is the user's core mental model made visible: **you own the wallet of the-avatar you created; if you take someone else's avatar, you get your own brand-new-wallet.** The backend already enforces this (`agent_identities.user_id`, fork mints-fresh wallets, `meta.forked_from` lineage). Your job is to make it **obvious,-trustworthy, and delightful** in the UI everywhere — and to make "fork to get your-own wallet" a first-class, conversion-driving flow.--## What "ownership clarity" means on screen--Everywhere an agent/avatar + wallet appears, the viewer instantly understands their-relationship to it:--- **Owner:** a clean "Yours" marker on the wallet, full controls (deposit, withdraw,- vanity, limits, trade, snipe). No ambiguity that these funds are theirs.-- **Visitor (public agent they don't own):** read-only wallet, a clear "owned by- @creator" attribution that links to the creator, a **Tip** action, and a- prominent, well-designed **"Fork to get your own"** CTA explaining: forking gives- you your own copy *with its own wallet you control* — the original owner keeps- theirs.-- **Forked agent:** show lineage — "Forked from @creator's <name>" (from- `meta.forked_from`) with a link to the original. Attribution is a feature- (provenance), not fine print.-- **Logged-out:** read-only + a sign-in / connect prompt before any owner action.--Derive role from `agent_identities.user_id === auth.userId`-([api/_lib/auth.js](../../api/_lib/auth.js)). Never trust the client — owner-controls must also be enforced server-side (they already are; keep it that way).--## The Fork-to-own flow (the headline of this task)--When a visitor wants an avatar, the path to *owning it with their own wallet* must-be one tap and crystal clear:--1. From the wallet chip/HUD or the avatar's profile, a **"Fork & get my wallet"**- action calls `POST /api/agents/fork` ([api/agents/fork.js](../../api/agents/fork.js)).-2. Show what happens, honestly and beautifully: a new agent owned by you, the GLB- copied into your namespace, **a fresh Solana + EVM wallet generated and- controlled by you**, lineage credited to the original creator. No wallet secrets- are ever copied — say so; it builds trust.-3. On success, drop the user into **their** new agent with **their** new wallet HUD- open, ready to fund/vanity/trade. The moment of ownership should feel great.-4. Surface fork lineage both ways: the original shows its fork count / network- (`GET /api/agents/fork?of=:id`); the fork shows its parent.--## Auto-provision on avatar creation (verify + surface)--When a user creates/uploads a 3D avatar, the agent + wallet are auto-provisioned-([api/_lib/avatar-agent.js](../../api/_lib/avatar-agent.js)). Make sure the **first-time a creator sees their new avatar, they also see "your wallet is ready"** — a-real moment that introduces the wallet, its address, and how to fund it. If the-provision is async/best-effort, the UI must handle the brief "provisioning…" state-honestly and then show the real address (poll for the real value; never show a fake-placeholder address).--## Innovation mandate--- **Ownership as status** — an owner's wallet across the app subtly signals "this is- mine" (a consistent marker/treatment) so a creator feels their portfolio of agents- is *theirs*. A "My agents & wallets" portfolio roll-up (total value across all- agents the user owns) is a natural, high-value addition — build it real from the- owner's agent rows + real balances.-- **Provenance graph** — the fork network is real social/financial lineage. A small,- tasteful "forked from / forks of" visualization turns attribution into a feature- people explore. Real data from `meta.forked_from` + the fork-lineage endpoint.-- **Trust copy** — the single most important sentence in this whole program is some- version of "fork it and you control your own wallet; the creator keeps theirs."- Make that promise legible at exactly the moment it matters.-- Invent beyond this where it strengthens the ownership story — but never fake a- wallet, balance, or lineage edge.--## States & edge cases--- Forking your own agent, a private agent (should be blocked/owner-only per the- endpoint), an agent with no avatar, a deeply-nested fork chain, an agent that's- been deleted mid-flow.-- Fork while logged-out → prompt sign-in, then resume the fork.-- Provision latency on a brand-new fork → honest "setting up your wallet…" then the- real address; never block the success screen on a fake value.-- Visitor must never see owner controls; owner must never see a "fork to own" CTA on- an agent they already own (offer "duplicate" semantics if relevant, but don't- confuse the two).--## Definition of done--Per the orchestration README. Plus: owner / visitor / forked / logged-out states are-each correct and visible across profile + at least one feed surface; a real fork-end-to-end produces a new agent with a **new, real, distinct** wallet address owned-by the caller (verify the addresses differ from the source and the source is-untouched); lineage attribution renders on both sides; auto-provision moment shows a-real address. No console errors. Responsive.--When done: self-review + improvement pass, changelog entry, commit (explicit paths-only), then **delete this file**-(`prompts/agent-wallets/04-ownership-fork-to-own.md`).diff --git a/prompts/agent-wallets/05-sniper-trading-copilot.md b/prompts/agent-wallets/05-sniper-trading-copilot.mddeleted file mode 100644index 8230dd93d..000000000--- a/prompts/agent-wallets/05-sniper-trading-copilot.md+++ /dev/null@@ -1,117 +0,0 @@-# Task 05 — The Sniper / Trading Co-pilot (the agent that trades for you)--> **Read [00-README-orchestration.md](./00-README-orchestration.md) first** for the-> ownership model, design tokens, real APIs, hard rules, definition of done, and the-> "improve then delete this file" close-out. Builds on the shared wallet component-> (**task 01**) and opens from the Wallet HUD (**task 02**). This task ships the-> **execution engine** that the invention layer (`08`/`09`/`10`) reuses — get the-> trade path, the spend-guard, and the audit trail right and shared.--## Mission--Every agent has a real, funded, self-custodial Solana wallet. Turn it into a-**best-in-class on-chain trading + launch-sniping cockpit** that lives inside the-agent. Faster than a Telegram sniper bot, clearer than Jupiter, safer than handing a-bot your seed phrase — because the keys never leave the server and every trade is-gated by the owner's spend policy and written to the custody trail.--The bar: a degen who snipes for a living tries it once and never goes back to their-bot. The reason they can't get this anywhere else: the wallet is welded to a real,-ownable, talking 3D agent, and the spend policy makes autonomous execution trustable.--## What exists (read it before building)--- Custodial signing: `recoverSolanaAgentKeypair(encryptedSecret, audit)` in- [api/_lib/agent-wallet.js](../../api/_lib/agent-wallet.js) — the **only** way to- sign; every recovery is audit-logged with a reason. Reuse it. Never expose a key.-- Withdraw path (your model for a safe money-moving endpoint):- `POST /api/agents/:id/solana/withdraw` in- [api/agents/solana-wallet.js](../../api/agents/solana-wallet.js) — owner auth, CSRF,- destination validation, **spend-policy enforcement** (daily USD cap, per-tx ceiling,- allowlist, freeze), build -> simulate -> sign -> send -> confirm, audit every step.- Your trade endpoint must follow the same skeleton.-- Spend policy: `GET/PUT /api/agents/:id/solana/limits`. Trades consume the **same**- daily/per-tx budget as withdrawals — one wallet, one policy, no bypass.-- Holdings + balances: `GET /api/agents/:id/solana/holdings`,- `GET /api/agents/:id/solana` — what you can sell, valued in real USD.-- Launch feed: [api/_lib/agent-pumpfun.js](../../api/_lib/agent-pumpfun.js) and the- pump.fun feed already in use — the real source of fresh launches to snipe.-- Solana RPC + price helpers already wired in `api/_lib/agent-wallet.js`.--## The execution engine (build it real — this is the shared deliverable)--Build `POST /api/agents/:id/solana/trade` (owner-only, CSRF, audited) that executes a-**real** swap on Solana via the **Jupiter aggregator** (real public quote/swap API)-for SPL<->SPL / SOL<->SPL, and a snipe path for fresh pump.fun launches via the-existing pump integration. Requirements, non-negotiable:--1. **Real quotes.** Fetch a real Jupiter quote (input mint, output mint, amount,- slippage bps). Show the real price, price impact, minimum received, and route. No- estimated/fake numbers.-2. **Spend-guard, server-side.** Before signing, value the trade in USD and enforce- the agent's spend policy exactly as withdraw does (per-tx ceiling, remaining daily- budget, freeze, allowlist where relevant). Reject over-limit with an honest,- actionable error. The guard is the product — never bypass it for "speed."-3. **Build -> simulate -> sign -> send -> confirm.** Sign with- `recoverSolanaAgentKeypair` (reason: `trade` / `snipe`). Simulate when possible.- Return the real signature + explorer link. Handle partial fills / failed sends- with a real status, never an optimistic fake.-4. **Slippage & priority fees** are real, user-set, and explained. Reserve rent +- fees. Never strand SOL.-5. **Audit.** Every trade writes a custody-trail row (reason, mints, amounts in/out,- USD, signature) so the owner sees exactly what their agent did.--`$THREE` is the only coin you ever **name, feature, default, or recommend**. The-trade UI may accept an **arbitrary runtime mint** the user pastes/snipes (the-coin-agnostic exception in CLAUDE.md) and the launches feed renders launch records —-but you never hardcode, suggest, or market any specific non-`$THREE` mint.--## The UI (cockpit, opened from the HUD)--- **Buy / Sell panel** — token in/out, amount with MAX (from real holdings), live- real quote (price, impact, min-received, route), slippage + priority controls, a- clear confirm. Real USD on everything. The agent's avatar is visibly the one- acting — "Nova is buying..." — not a faceless form.-- **Snipe panel** — live fresh-launch feed from the real pump.fun source; one-tap- snipe with a pre-set size and slippage, gated by the spend policy. Show real- launch age, liquidity, and the real fill. Honest about MEV/slippage risk.-- **Positions** — current holdings valued live, with real unrealized P&L derived from- real entry data (persist fills to compute cost basis; if no basis exists yet, show- the honest "no entry data" state, never a fake P&L).-- **Order history** — every real fill with signature links, from the custody trail.--## Innovation mandate--- **The agent trades as a character.** The avatar reacts to a fill (a real,- event-driven micro-animation — only on a real confirmed tx). This is the weld that- no DEX has: a face on the trade.-- **Pre-flight, not regret.** Before any trade, a crisp, real risk read: price impact,- remaining daily budget after this trade, honeypot / mint-authority checks where the- data is real and available. Protect the user with truth.-- **One-tap, fully-gated snipe** — the speed of a sniper bot with the safety of a- server-side spend policy. That combination is the moat; make it feel instant.-- Invent beyond this where it raises the bar — but every quote, fill, position, and- P&L number traces to a real chain call you can see in the Network tab.--## States & edge cases (all designed)--Empty wallet (warm "fund me to trade" -> deposit); insufficient balance; over per-tx-or daily limit (show remaining budget, link to limits); slippage exceeded / failed-route; tx not confirmed / dropped (real retry or honest failure, funds reconciled-against real chain state); frozen wallet; expired session mid-trade; a launch that-rugs between quote and fill; dust; 0 / 1 / 1000 positions; very long token names;-network failure mid-send (re-check real on-chain state before reporting outcome).-Visitor / logged-out never see trade controls — UI **and** server enforce it.--## Definition of done--Per the orchestration README. Plus: a **real swap executes end-to-end** (devnet-acceptable) returning a real signature + explorer link; the spend policy genuinely-blocks an over-limit trade; positions/P&L reflect real holdings; the snipe panel-shows the real launch feed; owner-only enforced in UI and server; the-`POST .../trade` endpoint is reusable by tasks 08/09/10; no console errors;-responsive at 320/768/1440.--When done: self-review + improvement pass, changelog entry, commit (explicit paths-only, push to **both** remotes if asked), then **delete this file**-(`prompts/agent-wallets/05-sniper-trading-copilot.md`).diff --git a/prompts/monetization-prompts/10-creator-dashboard-earnings-ui.md b/prompts/monetization-prompts/10-creator-dashboard-earnings-ui.mddeleted file mode 100644index 58daef31f..000000000--- a/prompts/monetization-prompts/10-creator-dashboard-earnings-ui.md+++ /dev/null@@ -1,81 +0,0 @@-# Prompt 10: Creator Dashboard UI for Earnings--## Objective-Create a new page in the creator dashboard to display total earnings, a list of recent transactions, and other relevant monetization analytics.--## Explanation-To create a complete ecosystem, creators must be able to track their sales. This prompt outlines the creation of a new "Earnings" tab in the dashboard that provides an overview of their revenue from skill sales.--## Instructions-1. **Create New Dashboard Page:**- * Create a new HTML file: `dashboard/earnings.html`.- * Create a corresponding JavaScript file: `src/dashboard-earnings.js`.- * Add a link to this new page in the main dashboard navigation (`dashboard/index.html`).--2. **Design the Earnings UI:**- * The `earnings.html` page should contain placeholders for:- * A "Total Revenue" card.- * A "Withdrawable Balance" card.- * A table or list for "Recent Sales".- * (Optional) A chart to show earnings over time.--3. **Fetch Earnings Data:**- * In `src/dashboard-earnings.js`, make a request to a new API endpoint (to be created in the next prompt) that returns the creator's earnings data.- * Use the fetched data to populate the UI elements.--4. **Structure the "Recent Sales" Table:**- * The table should display information for each purchase of the creator's skills.- * Columns should include: Skill Name, Agent Name, Date, Price, and Status.--## HTML Example (`dashboard/earnings.html`)--```html-<!-- Main content area -->-<div class="dashboard-content">- <h2>Earnings</h2>-- <div class="stats-cards">- <div class="card">- <h4>Total Revenue</h4>- <p id="total-revenue">$0.00</p>- </div>- <div class="card">- <h4>Withdrawable Balance</h4>- <p id="withdrawable-balance">$0.00</p>- <button class="btn-secondary">Withdraw</button>- </div>- </div>-- <h3>Recent Sales</h3>- <table id="sales-table">- <thead>- <tr>- <th>Date</th>- <th>Skill</th>- <th>Agent</th>- <th>Price</th>- <th>Status</th>- </tr>- </thead>- <tbody>- <!-- Rows will be inserted by JS -->- </tbody>- </table>-</div>--<script src="/src/dashboard-earnings.js" type="module"></script>-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "prompts/monetization-prompts/10-creator-dashboard-earnings-ui.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/monetization-prompts/10-creator-payout-logic.md b/prompts/monetization-prompts/10-creator-payout-logic.mddeleted file mode 100644index 0fef08463..000000000--- a/prompts/monetization-prompts/10-creator-payout-logic.md+++ /dev/null@@ -1,82 +0,0 @@-# Prompt 10: Logic for Creator Payouts and Platform Fees--**Status:** - [ ] Not Started--## Objective-Implement the logic, both on-chain and off-chain, for splitting payments between the agent creator and the platform.--## Explanation-To create a sustainable business model, the platform will likely take a small fee from each skill purchase. This requires a system to automatically split the incoming funds. This can be done either on-chain with a smart contract or off-chain by having payments go to a platform wallet which then distributes the funds. An on-chain approach is more transparent.--## Instructions-1. **Design the Payout Flow:**- * Decide on the fee structure (e.g., a 5% platform fee).- * Decide on the mechanism:- * **On-chain (preferred):** A smart contract (or a simple wallet acting as an escrow) receives the payment, then immediately splits it between the creator and the platform treasury.- * **Off-chain:** Payment goes to a platform-controlled wallet. A backend process then periodically calculates and sends the creator's share to their wallet.--2. **Implement On-Chain Split (if chosen):**- * This is a more advanced task involving Solana smart contract development (e.g., using Anchor).- * The frontend transaction would change to call this new smart contract instead of a direct SPL transfer.- * The smart contract would require two instructions in the transaction: one to transfer the total amount to the contract, and another to trigger the split.--3. **Implement Off-Chain Split (simpler alternative):**- * Modify the SPL transfer logic from Prompt 5. Instead of transferring to the creator's address, transfer to a platform-owned treasury address. This address should be configured per-skill or per-agent in the `agent_skill_prices` table.- * Create a backend cron job or batch process (`/api/cron/process-payouts.js`).- * This job runs periodically (e.g., daily), queries all purchase records since the last run, calculates the creator's share for each, and queues up the payout transactions.- * Use a secure backend wallet to sign and send these payout transactions.--## Code Example (Off-chain Payout Cron Job - `/api/cron/process-payouts.js`)--```javascript-// This is a conceptual example of a cron job for Vercel-import { getDB } from './_lib/db';-import { Connection, Keypair, SystemProgram, Transaction } from '@solana/web3.js';-// And SPL token transfer functions--const PLATFORM_FEE_PERCENT = 5;--export default async function handler(req, res) {- // Secure this endpoint, e.g., with a secret key-- const db = getDB();- const pendingPurchases = await db.getUnprocessedPurchases();-- const creatorPayouts = {}; // { [creator_address]: amount_to_pay }-- for (const purchase of pendingPurchases) {- const creatorShare = purchase.amount * (1 - PLATFORM_FEE_PERCENT / 100);- const creator = purchase.creator_address;- creatorPayouts[creator] = (creatorPayouts[creator] || 0) + creatorShare;- }-- // Use a secure way to load your backend wallet- const platformWallet = Keypair.fromSecretKey(...);- const connection = new Connection('your_rpc_url');-- for (const [creator, amount] of Object.entries(creatorPayouts)) {- // Construct and send transaction to pay out `amount` to `creator`- // This involves creating and sending an SPL token transfer from the platform's wallet- // ...- }-- // Mark purchases as processed in the DB- await db.markPurchasesAsProcessed(pendingPurchases.map(p => p.id));-- res.status(200).json({ success: true, message: 'Payouts processed.' });-}-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "prompts/monetization-prompts/10-creator-payout-logic.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/monetization-prompts/11-api-creator-earnings.md b/prompts/monetization-prompts/11-api-creator-earnings.mddeleted file mode 100644index 2e3acb3b6..000000000--- a/prompts/monetization-prompts/11-api-creator-earnings.md+++ /dev/null@@ -1,89 +0,0 @@-# Prompt 11: API Endpoint for Creator Earnings Data--## Objective-Create a secure API endpoint that calculates and returns a creator's earnings data for their dashboard.--## Explanation-The creator dashboard needs data to display. This endpoint will query the database to aggregate sales data for the currently authenticated user, providing them with their total revenue, balance, and a list of recent transactions.--## Instructions-1. **Create the API Endpoint File:**- * Create a new file, e.g., `api/dashboard/earnings.js`.--2. **Implement the Endpoint Logic:**- * **Authentication:** Get the current user via `getSessionUser`.- * **Query for Total Revenue:**- * Write a SQL query that `SUM`s the `amount` from `user_skill_purchases` where the `creator_id` matches the current user and the `status` is `'confirmed'`.- * **Query for Recent Transactions:**- * Write a SQL query that fetches the last 50-100 confirmed purchases for the creator.- * Join with `agent_identities` and `agent_skill_prices` to get agent names, skill names, and prices.- * **Calculate Withdrawable Balance:**- * For now, this can be the same as total revenue. In a future prompt, this will be adjusted for payouts.- * **Return Data:** Combine all the data into a single JSON response.--## SQL Query Example--```sql--- Query to get recent sales for a specific creator-SELECT- p.created_at,- p.skill_id,- a.name as agent_name,- pr.amount,- pr.currency_mint,- p.status-FROM- user_skill_purchases p-JOIN- agent_skill_prices pr ON p.price_id = pr.id-JOIN- agent_identities a ON p.agent_id = a.id-WHERE- pr.creator_id = $1 -- creator's user_id- AND p.status = 'confirmed'-ORDER BY- p.created_at DESC-LIMIT 50;-```--## Code Example (`api/dashboard/earnings.js`)--```javascript-import { sql } from '../_lib/db.js';-import { getSessionUser } from '../_lib/auth.js';-import { error, json, wrap } from '../_lib/http.js';--export default wrap(async (req, res) => {- const user = await getSessionUser(req);- if (!user) return error(res, 401, 'unauthorized');-- const [total] = await sql`- SELECT SUM(pr.amount) as total_revenue- FROM user_skill_purchases p- JOIN agent_skill_prices pr ON p.price_id = pr.id- WHERE pr.creator_id = ${user.id} AND p.status = 'confirmed'- `;-- const sales = await sql` /* ... Use the SQL query from above ... */ `;-- return json(res, {- totalRevenue: total.total_revenue || 0,- withdrawableBalance: total.total_revenue || 0, // Placeholder for now- recentSales: sales,- });-});-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "prompts/monetization-prompts/11-api-creator-earnings.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/monetization-prompts/12-on-chain-receipts-as-nfts.md b/prompts/monetization-prompts/12-on-chain-receipts-as-nfts.mddeleted file mode 100644index d0095b2df..000000000--- a/prompts/monetization-prompts/12-on-chain-receipts-as-nfts.md+++ /dev/null@@ -1,91 +0,0 @@-# Prompt 12: Generate On-Chain Receipts as NFTs--**Status:** - [ ] Not Started--## Objective-Issue a unique, non-transferable NFT to the user upon a successful skill purchase, serving as an on-chain receipt and proof of ownership.--## Explanation-Using NFTs as receipts provides a permanent, verifiable, and user-owned record of their purchase on the blockchain. This can unlock future possibilities like community-gated access or special privileges for skill owners. We can use a service like Metaplex for this.--## Instructions-1. **Set up NFT Minting Infrastructure:**- * This is a significant step. You can use Metaplex's Candy Machine or their newer Core standards. For simple receipts, a direct mint via the Metaplex Umi library might be sufficient.- * You'll need a backend wallet with SOL to pay for minting fees.--2. **Modify the Purchase Verification Endpoint:**- * In `/api/marketplace/purchase-skill.js`, after successfully verifying the transaction and recording the purchase in the database, trigger the NFT minting process.- * The metadata for the NFT should include:- * Name: e.g., "Skill Receipt: 'sentiment-analysis'"- * Symbol: e.g., "3WS-SKILL"- * Description: "This NFT represents ownership of the 'sentiment-analysis' skill for the agent 'AI Market Analyst'."- * Attributes: Agent Name, Skill Name, Purchase Date.- * Image: A custom image for skill receipts, or maybe the agent's thumbnail.--3. **Mint and Send the NFT:**- * The backend will construct and sign the transaction to create the mint account, create the token account for the user, and mint the NFT to that account.- * The NFT should ideally be non-transferable to act as a "soul-bound" token representing access, not a speculative asset. This can be set with Metaplex's standards.--4. **Update Database Record:**- * After minting, store the NFT's mint address in the `user_agent_skills` table. This links the off-chain record to the on-chain asset.--## Code Example (Conceptual Backend - adding to `purchase-skill.js`)--```javascript-import { createUmi } from '@metaplex-foundation/umi-bundle-defaults';-import { mplCore, createV1, mintV1 } from '@metaplex-foundation/mpl-core';-import { keypairIdentity, Pda } from '@metaplex-foundation/umi';--// After successfully recording purchase in DB...-async function mintReceiptNFT(userAddress, agent, skillName) {- const umi = createUmi('your_rpc_url').use(mplCore());-- // Use a secure way to load your backend/minter wallet- const minterKeypair = ...;- umi.use(keypairIdentity(minterKeypair));-- const newMint = Pda.find(umi.context, 'core-mint', [minterKeypair.publicKey, 0]);-- await createV1(umi, {- mint: newMint,- name: `Skill: ${skillName}`,- uri: `https://your-api.com/api/nft-metadata/${agent.id}/${skillName}`,- plugins: [- // This is conceptual - the exact non-transferable implementation- // depends on the Metaplex standard you choose (e.g., locking delegates).- ]- }).sendAndConfirm(umi);-- await mintV1(umi, {- mint: newMint.publicKey,- authority: minterKeypair,- assetOwner: new PublicKey(userAddress),- }).sendAndConfirm(umi);-- return newMint.publicKey;-}--// In the main handler:-if (verificationSuccess) {- await db.recordSkillPurchase(userId, agentId, skillName);- const nftMintAddress = await mintReceiptNFT(userWalletAddress, agent, skillName);- await db.updatePurchaseWithNftAddress(purchaseId, nftMintAddress);-- return res.status(200).json({ success: true, message: 'Purchase successful!', receiptNft: nftMintAddress });-}-```-*Note: This is a highly simplified example. NFT minting with Metaplex requires careful setup and handling of accounts and authorities.*--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "prompts/monetization-prompts/12-on-chain-receipts-as-nfts.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/monetization-prompts/16-on-chain-nft-license.md b/prompts/monetization-prompts/16-on-chain-nft-license.mddeleted file mode 100644index 1e1d1a306..000000000--- a/prompts/monetization-prompts/16-on-chain-nft-license.md+++ /dev/null@@ -1,46 +0,0 @@-# Prompt 16: On-Chain License as an NFT (Optional)--## Objective-Optionally, extend the purchase flow to mint an NFT (Non-Fungible Token) that represents the user's license to use a skill, and store the mint address in the purchase record.--## Explanation-Minting a skill license as an NFT provides true on-chain ownership for the user. They can hold it, trade it, or use it as a verifiable credential. This transforms a simple database entry into a persistent, user-owned digital asset, aligning with Web3 principles. This would likely use the Metaplex standard on Solana.--## Instructions-1. **Design the NFT Metadata:**- * Define a metadata standard for the skill license NFT. It should include attributes for the `agent_id`, `skill_id`, `purchase_date`, etc.--2. **Create a Server-Side Minting Service:**- * This is a complex task that requires a secure backend wallet (a "minter") with funds to pay for transaction fees.- * Create a new API endpoint, e.g., `api/minter/mint-skill-license.js`.- * This endpoint will be called *after* a purchase is confirmed by the webhook.- * **Logic:**- * Take a `purchaseId` as input.- * Load the secure minter keypair.- * Use the Metaplex Umi or Helio SDK to create and mint a new NFT to the purchaser's wallet address.- * Use the metadata standard defined in step 1.- * The user's wallet address should be stored in your `users` table.--3. **Update Purchase Table:**- * Add a new nullable column to the `user_skill_purchases` table: `license_nft_mint` (TEXT).- * After successfully minting the NFT, save the NFT's mint address to this column for the corresponding purchase record.--4. **Display NFT on Frontend:**- * On the "My Purchased Skills" page, if a `license_nft_mint` exists, provide a link to a Solana explorer (like Solscan or X-Ray) to view the NFT.--## Note-This is an advanced feature. It requires secure key management on the backend, knowledge of a Solana SDK like Umi, and handling of on-chain transaction statuses.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "prompts/monetization-prompts/16-on-chain-nft-license.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/monetization-prompts/21-gifting-skills.md b/prompts/monetization-prompts/21-gifting-skills.mddeleted file mode 100644index 66993e2e6..000000000--- a/prompts/monetization-prompts/21-gifting-skills.md+++ /dev/null@@ -1,76 +0,0 @@-# Prompt 21: Gifting Skills to Other Users--**Status:** - [ ] Not Started--## Objective-Allow users to purchase a skill as a gift for another user on the platform.--## Explanation-Gifting is a great way to introduce new users to the platform and can be a fun social feature. It allows users to share their favorite skills with friends.--## Instructions-1. **Modify the Purchase Flow:**- * In the purchase confirmation modal, add a checkbox or button: "Purchase as a gift?".- * If checked, reveal an input field for the recipient's username or wallet address.--2. **Backend Logic for Gifting:**- * Modify the `purchase-skill` backend endpoint to handle an optional `recipient_user_id`.- * If a recipient is specified, the transaction verification remains the same (the buyer pays).- * However, when recording the ownership in the `user_agent_skills` table, the record should be created for the `recipient_user_id`, not the buyer's ID.- * You may want to add a `gifted_by_user_id` column to the table to track this.--3. **Notifications:**- * Implement a notification system (if one doesn't exist) to inform the recipient that they have received a gift.- * The notification should specify the skill, the agent, and who sent the gift.--4. **On-Chain Receipt (NFT):**- * If you are minting NFTs as receipts (Prompt 12), the NFT should be minted to the recipient's wallet, not the buyer's. The metadata could include a "Gifted By" attribute.--## Code Example (Conceptual - Backend `purchase-skill` modification)--```javascript-export default async function handler(req, res) {- const buyerUserId = req.user.id;- const { agentId, skillName, transactionSignature, recipientUsername } = req.body;- let finalOwnerId = buyerUserId;-- const db = getDB();-- if (recipientUsername) {- const recipient = await db.findUserByUsername(recipientUsername);- if (!recipient) {- return res.status(404).json({ error: 'Recipient not found.' });- }- finalOwnerId = recipient.id;- }-- // ... (Verify transaction was paid by buyerUserId)-- if (verificationSuccess) {- // Record purchase for the final owner (recipient or buyer)- await db.recordSkillPurchase(finalOwnerId, agentId, skillName, buyerUserId); // buyerUserId is the gifter-- // Trigger a notification to the recipient- if (recipientUsername) {- await sendNotification(finalOwnerId, `You received the skill ${skillName} as a gift!`);- }-- res.status(200).json({ success: true, message: 'Gift purchase successful!' });- }- // ...-}-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "prompts/monetization-prompts/21-gifting-skills.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/monetization-prompts/21-skill-subscription-model-backend.md b/prompts/monetization-prompts/21-skill-subscription-model-backend.mddeleted file mode 100644index 962cf7c5b..000000000--- a/prompts/monetization-prompts/21-skill-subscription-model-backend.md+++ /dev/null@@ -1,82 +0,0 @@-----status: not-started------# Prompt 21: Skill Subscription Model - Backend--## Objective-Implement the backend infrastructure for a subscription model, where users pay a recurring fee for access to all of an agent's paid skills.--## Explanation-Subscriptions provide predictable revenue for creators and value for active users. This is a significant feature requiring new database tables and logic for managing subscription status and recurring payments. We'll focus on the backend setup first. For payments, we could use a service like Helio to manage recurring Solana payments.--## Instructions-- [ ] **Database Schema Changes:**- - [ ] Create a new table: `agent_subscriptions`.- - [ ] Columns: `id`, `user_id`, `agent_id`, `status` (e.g., 'active', 'cancelled', 'past_due'), `expires_at` (Timestamp), `payment_provider_subscription_id` (String).- - [ ] Add a new table `agent_subscription_plans`: `id`, `agent_id`, `amount`, `currency_mint`, `interval` (e.g., 'month', 'year').--- [ ] **API for Subscription Plans:**- - [ ] Create CRUD APIs for creators to manage their subscription plans (`/api/agents/:id/subscription-plans`). A creator might offer monthly and yearly tiers.--- [ ] **API for Creating a Subscription:**- - [ ] Create an endpoint `POST /api/subscriptions/create`.- - [ ] This endpoint would interact with a recurring payment provider (e.g., Helio). It would create a payment link or subscription plan with the provider and return it to the frontend.--- [ ] **Webhook for Payment Events:**- - [ ] Create a webhook endpoint `POST /api/webhooks/payments`.- - [ ] The payment provider will call this webhook to notify your app of events like `subscription.created`, `subscription.payment_succeeded`, `subscription.payment_failed`.- - [ ] When a `payment_succeeded` event is received, you should:- - [ ] Find the corresponding subscription in your `agent_subscriptions` table.- - [ ] Update its `status` to 'active'.- - [ ] Set the `expires_at` to the end of the new billing period (e.g., now + 30 days).--- [ ] **Update Skill Gating Logic:**- - [ ] Modify the skill gating logic from Prompt 19.- - [ ] Before checking for individual skill ownership in `unlocked_skills`, it should first check for an active subscription.- - [ ] Query the `agent_subscriptions` table for the `user_id` and `agent_id`. If an active subscription exists (`status` = 'active' and `expires_at` > now), allow skill execution.--## Webhook Logic Example--```javascript-// POST /api/webhooks/payments-export default async function handler(req, res) {- // 1. Verify the webhook signature to ensure it's from the payment provider- if (!isSignatureValid(req)) {- return res.status(403).send('Invalid signature');- }-- const event = req.body;-- // 2. Handle the event- switch (event.type) {- case 'subscription.payment_succeeded':- const subId = event.data.subscription_id;- const newExpiry = new Date(event.data.new_expiry_timestamp);-- // Find subscription in DB by payment_provider_subscription_id- await db.updateSubscriptionStatus(subId, 'active', newExpiry);- break;- case 'subscription.payment_failed':- // ... handle failed payments, maybe set status to 'past_due'- break;- }-- // 3. Acknowledge receipt- res.status(200).send('Acknowledged');-}-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "prompts/monetization-prompts/21-skill-subscription-model-backend.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/monetization-prompts/22-unit-tests-monetization-service.md b/prompts/monetization-prompts/22-unit-tests-monetization-service.mddeleted file mode 100644index b275d80ca..000000000--- a/prompts/monetization-prompts/22-unit-tests-monetization-service.md+++ /dev/null@@ -1,85 +0,0 @@-# Prompt 22: Unit Tests for Monetization Service--## Objective-Write unit tests for the `MonetizationService` class to ensure its logic is correct, robust, and reliable.--## Explanation-The `MonetizationService` will contain critical business logic related to user purchases and creator payouts. Unit tests are essential to verify that this logic works as expected, especially for edge cases like insufficient funds or duplicate purchases. This prevents bugs and provides confidence when refactoring.--## Instructions-1. **Set Up Testing Environment:**- * The project appears to use `vitest`. Ensure it's configured to work with your database. You may need a separate test database and a library for mocking database calls (like `pg-mem`).--2. **Create a Test File:**- * Create a new test file: `tests/monetization-service.test.js`.--3. **Write Test Cases for Each Method:**- * Import the `MonetizationService`.- * For each public method in the service, write one or more `it` blocks.- * **Test Scenarios:**- * **`initiatePurchase`:** Test the successful creation of a pending purchase. Test that it fails if the skill is not priced. Test that it fails if the user has already bought the skill.- * **`confirmPurchase`:** Test that a 'pending' purchase moves to 'confirmed'.- * **`requestWithdrawal`:** Test a successful request. Test that it fails if the creator's balance is too low.- * **`gateSkillAccess`:** Test that it returns `true` for free skills, `true` for purchased skills, and `false` for un-purchased paid skills.--4. **Run the Tests:**- * Use the `npm test` command to run the test suite.--## Code Example (`tests/monetization-service.test.js`)--```javascript-import { it, expect, describe, beforeEach } from 'vitest';-import { MonetizationService } from '../api/_lib/monetization-service.js';-// You'll need a way to mock your database, e.g., using an in-memory postgres instance-import { getMockDb } from './test-helpers.js';--describe('MonetizationService', () => {- let service;- let db;-- beforeEach(async () => {- db = await getMockDb(); // Resets the mock db for each test- service = new MonetizationService(db);- // Seed the mock db with necessary data (users, agents, etc.)- });-- it('should initiate a purchase successfully', async () => {- // Setup: create a priced skill in the mock db-- const result = await service.initiatePurchase({- userId: 'user-1',- agentId: 'agent-1',- skillId: 'skill-1'- });-- expect(result.purchaseId).toBeDefined();-- // Verify that a 'pending' record was created in the mock db- const purchase = await db.findPurchaseById(result.purchaseId);- expect(purchase.status).toBe('pending');- });-- it('should fail to request a withdrawal with insufficient funds', async () => {- // Setup: set a creator's balance to 50 in the mock db-- await expect(service.requestWithdrawal({- userId: 'creator-1',- amount: 100- })).rejects.toThrow('Insufficient funds');- });-});-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "prompts/monetization-prompts/22-unit-tests-monetization-service.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/monetization/17-subscription-payment-activation.md b/prompts/monetization/17-subscription-payment-activation.mddeleted file mode 100644index 2d0569dd6..000000000--- a/prompts/monetization/17-subscription-payment-activation.md+++ /dev/null@@ -1,81 +0,0 @@-----status: not-started------# Prompt 17: Subscription Payment and Activation--## Objective-Implement the backend and frontend logic to handle a new subscription payment using Solana Pay and activate the subscription in the database.--## Explanation-This process is similar to a one-time skill purchase but involves creating a `user_subscriptions` record instead. For simplicity in this initial implementation, we will treat the first subscription payment as a one-time charge. True recurring payments on Solana are more complex and can be implemented later.--## Instructions-1. **Create a Subscription Transaction Endpoint:**- * Create a new backend endpoint, e.g., `GET /api/subscribe/transaction?tierId=...`.- * This endpoint will be called when a user clicks a "Subscribe" button.- * It should look up the tier details (price, currency) from the `agent_subscription_tiers` table.- * Generate a `reference` keypair for tracking this specific subscription activation.- * Before returning the transaction URL, it should create a new record in the `user_subscriptions` table with a status of `'incomplete'` and store the `reference` key. This "locks in" the intent to subscribe.--2. **Create the Solana Pay Details Endpoint:**- * Similar to the one-time purchase, create the `POST /api/subscribe/details` endpoint that the wallet will call.- * This endpoint should build and serialize a transaction to transfer the correct subscription price from the user's wallet to the agent owner's wallet.--3. **Create a Subscription Verification Endpoint:**- * Create an endpoint like `GET /api/subscribe/status?reference=...`.- * This endpoint will be polled by the frontend after the user is shown the QR code.- * Its logic should:- * Find the transaction using the `reference` public key.- * Thoroughly validate the transaction details (amount, recipient, etc.).- * If valid, find the `'incomplete'` record in `user_subscriptions` associated with this `reference`.- * Update the record's status to `'active'`.- * Set the `current_period_start` to `NOW()` and `current_period_end` to the appropriate future date (e.g., 1 month from now).- * Store the transaction signature.- * Return `{ status: 'confirmed' }` to the frontend.--4. **Update Frontend Logic:**- * The `initiateSubscription('tierId')` function should call the `/api/subscribe/transaction` endpoint.- * It should then display the QR code and start polling the `/api/subscribe/status` endpoint.- * Upon confirmation, it should refresh the UI to show the user's new "Current Plan".--## Key Difference from One-Time Purchase-The main difference is the database interaction. Instead of inserting into `user_unlocked_skills`, we are creating and then updating a record in `user_subscriptions`. This sets the foundation for managing the subscription lifecycle (renewals, cancellations, etc.) in the future.--## Code Example (Backend - Creating 'incomplete' subscription)--```javascript-// Inside GET /api/subscribe/transaction-// ... after fetching tier details-const reference = new solanaWeb3.Keypair();-const userId = await getUserIdFromRequest(req);--// Create an initial record to track this attempt-const subResult = await db.query(- `INSERT INTO user_subscriptions (user_id, tier_id, status, payment_reference)- VALUES ($1, $2, 'incomplete', $3) RETURNING id`,- [userId, tierId, reference.publicKey.toBase58()]-);-const subscriptionId = subResult.rows[0].id;--// Now construct the Solana Pay URL, perhaps including the subscriptionId for context-const url = new URL(`${req.protocol}://${req.get('host')}/api/subscribe/details`);-url.searchParams.set('subId', subscriptionId); // Pass the new ID to the details endpoint--const solanaPayUrl = `solana:${encodeURIComponent(url.toString())}`;-res.json({ url: solanaPayUrl, reference: reference.publicKey.toBase58() });-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "prompts/monetization/17-subscription-payment-activation.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/monetization/17-subscription-purchase-flow.md b/prompts/monetization/17-subscription-purchase-flow.mddeleted file mode 100644index 7f304f10a..000000000--- a/prompts/monetization/17-subscription-purchase-flow.md+++ /dev/null@@ -1,45 +0,0 @@-# Prompt 17: Subscription Purchase Flow--## Objective-Implement the UI and backend logic for purchasing a monthly subscription to an agent, which grants access to all its skills.--## Explanation-This prompt builds on the subscription database schema by creating the user-facing flow to purchase a subscription. This will involve presenting subscription tiers, handling payment, and creating the `user_subscriptions` record.--## Instructions-1. **Display Subscription Tiers:**- * On the agent detail page in the marketplace, if an agent offers subscriptions, display the available tiers (from the `subscription_tiers` table).- * Each tier should show its name, price, interval (e.g., "$10/month"), and description.- * Add a "Subscribe" button to each tier.--2. **Create Subscription Checkout API:**- * Create a new endpoint, e.g., `/api/subscriptions/purchase`.- * This endpoint will handle the payment logic. Since subscriptions are recurring, a simple transfer is not enough. You need to use a Solana protocol designed for recurring payments, like Solana Pay or a custom smart contract.- * For this prompt, we can simulate the first payment: the endpoint should behave like the skill purchase endpoint, processing a one-time payment for the first month.--3. **Create `user_subscriptions` Record:**- * After the first payment is successfully processed, the backend must:- * Create a new record in the `user_subscriptions` table.- * Set the `user_id`, `tier_id`, and `status` to 'active'.- * Set the `start_date` to the current time.- * Calculate and set the `end_date` (e.g., `start_date` + 1 month).--4. **Connect UI to API:**- * Wire the "Subscribe" button to call the purchase endpoint and handle the transaction with the user's wallet.--## Note on Recurring Payments-True on-chain recurring payments are complex. They often require users to deposit funds into an escrow contract or use token streaming protocols. This prompt simplifies the task to focus on the initial purchase and record creation, which is the first step in any subscription system. A later, more advanced prompt would cover the on-chain automation for renewals.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "prompts/monetization/17-subscription-purchase-flow.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/monetization/18-tip-jar-feature.md b/prompts/monetization/18-tip-jar-feature.mddeleted file mode 100644index e2710bce5..000000000--- a/prompts/monetization/18-tip-jar-feature.md+++ /dev/null@@ -1,110 +0,0 @@-----status: not-started------# Prompt 18: Tip Jar Feature--## Objective-Add a simple "Tip" button and flow to the agent detail page, allowing users to send a custom amount of SOL or USDC to the agent's creator.--## Explanation-A tip jar is a straightforward way to let appreciative users support creators without the commitment of a subscription. This feature leverages the existing Solana Pay infrastructure for a simple, one-off payment.--## Instructions-1. **Add UI Elements:**- * On the agent detail page (`marketplace.html`), add a "Send a Tip" button, perhaps near the agent's name or creator details.- * Clicking this button should open a small modal.- * The modal should contain:- * An input field for the amount.- * A dropdown to select the currency (e.g., SOL, USDC).- * A "Generate Payment QR" button.--2. **Create a Backend Endpoint for Tip Transactions:**- * Create a new endpoint, e.g., `GET /api/tip/transaction`.- * This endpoint will take `agentId`, `amount`, and `currency` as query parameters.- * The logic will be very similar to the skill purchase endpoint:- * Fetch the agent owner's wallet address.- * Generate a `reference` keypair for tracking.- * Construct the Solana Pay details URL.- * Return the `solana:...` URL and the `reference` public key.--3. **Create the Solana Pay Details Endpoint:**- * Create the corresponding `POST /api/tip/details` endpoint.- * This will receive the user's wallet and build the appropriate transaction (either a `SystemProgram.transfer` for SOL or an `splToken.createTransferInstruction` for USDC).- * The amount will be read from the query parameters passed along in the details URL.- * Return the serialized transaction in the Solana Pay format.--4. **Implement Frontend Logic:**- * Wire up the "Send a Tip" button to open the modal.- * When the user clicks "Generate Payment QR" inside the modal:- * Read the amount and currency from the form.- * Call the `/api/tip/transaction` endpoint with these parameters.- * Receive the Solana Pay URL and display it as a QR code in the modal.- * You can optionally add a polling mechanism to confirm the tip was received and show a "Thank you" message.--## Code Example (Tip Modal HTML)--```html-<div id="tip-modal" class="modal-backdrop">- <div class="modal-content">- <div class="modal-header"><h3>Send a Tip</h3></div>- <div class="modal-body">- <div class="form-group">- <label>Amount</label>- <input type="number" id="tip-amount" placeholder="1.0">- </div>- <div class="form-group">- <label>Currency</label>- <select id="tip-currency">- <option value="SOL">SOL</option>- <option value="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7uP3">USDC</option>- </select>- </div>- <button id="generate-tip-qr-btn" class="cta-button">Generate Payment Code</button>- <div id="tip-qr-container" style="margin-top: 16px;"></div>- </div>- </div>-</div>-```--## Code Example (Frontend JavaScript)--```javascript-document.getElementById('generate-tip-qr-btn').addEventListener('click', async () => {- const amount = document.getElementById('tip-amount').value;- const currency = document.getElementById('tip-currency').value;- const agentId = /* get current agent ID */;-- if (!amount || parseFloat(amount) <= 0) {- showToast('Please enter a valid amount.', 'error');- return;- }-- try {- const response = await fetch(`/api/tip/transaction?agentId=${agentId}&amount=${amount}¤cy=${currency}`);- const { url } = await response.json();-- const qrContainer = document.getElementById('tip-qr-container');- qrContainer.innerHTML = '';- const qr = SolanaPay.createQR(url, 250);- qrContainer.appendChild(qr.canvas);-- } catch (e) {- showToast('Could not generate payment code.', 'error');- }-});-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "prompts/monetization/18-tip-jar-feature.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/monetization/19-backend-record-earnings.md b/prompts/monetization/19-backend-record-earnings.mddeleted file mode 100644index c26eecfe9..000000000--- a/prompts/monetization/19-backend-record-earnings.md+++ /dev/null@@ -1,91 +0,0 @@-# Prompt 19: Backend Logic to Record Earnings--## Objective-After a payment is confirmed, implement the backend logic to calculate and record the creator's earnings and the platform fee in the `skill_payment_earnings` table.--## Explanation-This is the accounting step of the monetization flow. It connects the confirmed payment to the creator's ledger. This logic must run immediately after payment confirmation to ensure that revenue is tracked in real-time.--## Instructions-1. **File to Edit:**- * Open the backend endpoint for payment confirmation: `POST /api/payments/confirm-skill-payment`.--2. **Integrate Earnings Calculation:**- * Locate the spot in your code inside the database transaction, immediately after you have updated the `skill_payments` table to `completed` and created the `skill_access_grants` record.- * **Define Platform Fee:** Get the current platform fee. It's best practice to have this as a configurable value (e.g., in an environment variable or a configuration file). For example, `PLATFORM_FEE_BPS = 500` (for 5%).- * **Calculate Amounts:**- * `gross_amount`: This is the `amount` from the `paymentIntent` record.- * `platform_fee_amount`: `Math.floor(gross_amount * PLATFORM_FEE_BPS / 10000)`. Use floor to be safe.- * `net_amount`: `gross_amount - platform_fee_amount`.- * **Get Creator ID:** You'll need the ID of the agent's creator, which should be available on the `agent` object.--3. **Insert the Earnings Record:**- * Within the same database transaction, insert a new row into the `skill_payment_earnings` table with all the calculated values.--## Code Example (Backend - `confirm-skill-payment` logic)--This refines the example from Prompt 14, adding the earnings logic to the transaction.--```javascript-// Inside your /api/payments/confirm-skill-payment endpoint handler--// ... after successfully verifying the on-chain transaction ...--const PLATFORM_FEE_BPS = 500; // 5%--try {- // Use a database transaction to ensure atomicity- await db.transaction(async (trx) => {- // 1. Update Payment Status- await trx.update('skill_payments', { status: 'completed', signature: signature })- .where({ id: paymentId });-- // 2. Grant Skill Access- const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000);- await trx.insert({- user_id: user.id,- agent_id: paymentIntent.agentId,- skill_name: paymentIntent.skillName,- payment_id: paymentId,- expires_at: expiresAt,- }).into('skill_access_grants');-- // 3. NEW: Record Earnings- const agent = await trx.select('creator_id').from('agents').where({ id: paymentIntent.agentId }).first();- const gross_amount = paymentIntent.amount;- const platform_fee_amount = Math.floor(gross_amount * PLATFORM_FEE_BPS / 10000);- const net_amount = gross_amount - platform_fee_amount;-- await trx.insert({- payment_id: paymentId,- agent_id: paymentIntent.agentId,- creator_id: agent.creator_id,- gross_amount,- platform_fee_bps: PLATFORM_FEE_BPS,- platform_fee_amount,- net_amount,- currency_mint: paymentIntent.currency_mint,- }).into('skill_payment_earnings');- });-- res.status(200).json({ success: true, message: 'Payment confirmed and access granted.' });--} catch (error) {- console.error('Error in confirmation transaction:', error);- res.status(500).json({ error: 'Failed to finalize payment.' });-}-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "prompts/monetization/19-backend-record-earnings.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/monetization/19-creator-revenue-dashboard.md b/prompts/monetization/19-creator-revenue-dashboard.mddeleted file mode 100644index dd7ce116b..000000000--- a/prompts/monetization/19-creator-revenue-dashboard.md+++ /dev/null@@ -1,107 +0,0 @@-----status: not-started------# Prompt 19: Creator Revenue Dashboard--## Objective-Create a new, dedicated "Creator Dashboard" page where agent owners can view their earnings from skill sales and subscriptions.--## Explanation-To empower creators, they need a clear and transparent view of their revenue. This dashboard is the central hub for creators to track their monetization success on the platform. This prompt focuses on the initial structure and UI of the dashboard.--## Instructions-1. **Create a New HTML File:**- * Create a new file, `creator-dashboard.html`.- * This page should be protected and only accessible to logged-in users.--2. **Design the Dashboard Layout:**- * The layout should include several key components:- * **Summary Stats:** A section at the top for key metrics like "Total Revenue," "30-Day Earnings," "Total Subscribers," and "Total Sales."- * **Revenue Chart:** A placeholder for a chart that will visualize earnings over time (e.g., daily or monthly).- * **Breakdown Section:** A section to show revenue broken down by source (e.g., "Skill Sales" vs. "Subscriptions").- * **Recent Transactions:** A table or list showing the most recent sales and subscription payments.- * **Top Performing Agents/Skills:** A list of the creator's agents or skills that are generating the most revenue.--3. **Add Placeholders:**- * For this initial step, populate the dashboard with static HTML and placeholder values. The goal is to build the structure first.- * Use clear IDs for all elements that will be populated with dynamic data later.--## Code Example (HTML Structure for `creator-dashboard.html`)--```html-<!DOCTYPE html>-<html lang="en">-<head>- <title>Creator Dashboard</title>- <!-- Link to your standard CSS files -->-</head>-<body>- <header>- <!-- Your standard site header -->- </header>- <main class="container">- <h1>Creator Dashboard</h1>-- <!-- Summary Stats -->- <div class="stats-grid">- <div class="stat-card">- <div class="label">Total Revenue (USDC)</div>- <div class="value" id="total-revenue">$0.00</div>- </div>- <div class="stat-card">- <div class="label">Last 30 Days</div>- <div class="value" id="revenue-30-days">$0.00</div>- </div>- <div class="stat-card">- <div class="label">Total Subscribers</div>- <div class="value" id="total-subscribers">0</div>- </div>- <div class="stat-card">- <div class="label">Total Sales</div>- <div class="value" id="total-sales">0</div>- </div>- </div>-- <!-- Revenue Chart -->- <div class="panel">- <div class="panel-header"><h2>Revenue Over Time</h2></div>- <div class="panel-body">- <div id="revenue-chart-container" class="empty">Chart loading...</div>- </div>- </div>-- <!-- Recent Transactions -->- <div class="panel">- <div class="panel-header"><h2>Recent Transactions</h2></div>- <div class="panel-body no-pad">- <table id="transactions-table">- <thead>- <tr><th>Date</th><th>Type</th><th>Agent/Skill</th><th>Amount</th><th>Status</th></tr>- </thead>- <tbody>- <tr><td colspan="5" class="empty">No transactions yet.</td></tr>- </tbody>- </table>- </div>- </div>- </main>-</body>-</html>-```--**Next Steps:** The following prompts will focus on creating the backend APIs to populate this dashboard with real data.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "prompts/monetization/19-creator-revenue-dashboard.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/monetization/19-platform-fee-integration.md b/prompts/monetization/19-platform-fee-integration.mddeleted file mode 100644index e2700cff2..000000000--- a/prompts/monetization/19-platform-fee-integration.md+++ /dev/null@@ -1,73 +0,0 @@-# Prompt 19: Platform Fee Integration--## Objective-Implement a platform fee on all transactions (both individual skill sales and subscription payments).--## Explanation-To create a sustainable business model, the platform needs to take a small percentage of each transaction. This requires modifying the on-chain payment logic to split the payment between the agent creator and the platform's treasury wallet.--## Instructions-1. **Store Platform Wallet Address:**- * Store the platform's main treasury wallet address in a secure place, like an environment variable (`PLATFORM_TREASURY_WALLET`).--2. **Modify Transaction Logic:**- * Locate the backend code that constructs the payment transaction (from Prompt 5 and Prompt 17).- * Instead of a single `SystemProgram.transfer` instruction, the transaction must now include **two** transfer instructions.--3. **Calculate and Split Payment:**- * Define the platform fee percentage (e.g., 5%).- * When a payment is made, calculate the fee amount and the creator's share.- * `platform_fee = total_price * 0.05`- * `creator_share = total_price * 0.95`- * The first transfer instruction will send `creator_share` to the `creator_wallet_address`.- * The second transfer instruction will send `platform_fee` to the `PLATFORM_TREASURY_WALLET`.--4. **Update Database and UI:**- * Ensure your `sales` table has columns to record the `platform_fee` and `creator_payout` amounts for transparent accounting.- * The UI should clearly state that the price includes a platform fee.--## Code Example (Updated Solana Transaction)-```javascript-// ...inside the purchase logic-const PLATFORM_FEE_PERCENT = 0.05; // 5%-const platformTreasury = new PublicKey(process.env.PLATFORM_TREASURY_WALLET);-const creatorWallet = new PublicKey(agent.creator_wallet_address);-const totalLamports = price.amount;--const platformFeeLamports = Math.round(totalLamports * PLATFORM_FEE_PERCENT);-const creatorShareLamports = totalLamports - platformFeeLamports;--const transaction = new Transaction()- .add(- // First instruction: pay the creator- SystemProgram.transfer({- fromPubkey: wallet.publicKey,- toPubkey: creatorWallet,- lamports: creatorShareLamports,- })- )- .add(- // Second instruction: pay the platform- SystemProgram.transfer({- fromPubkey: wallet.publicKey,- toPubkey: platformTreasury,- lamports: platformFeeLamports,- })- );--// Send and confirm the transaction as before...-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "prompts/monetization/19-platform-fee-integration.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/monetization/22-marketplace-analytics-dashboard.md b/prompts/monetization/22-marketplace-analytics-dashboard.mddeleted file mode 100644index a0afcc46b..000000000--- a/prompts/monetization/22-marketplace-analytics-dashboard.md+++ /dev/null@@ -1,97 +0,0 @@-# Prompt 22: Marketplace Analytics Dashboard--## Objective-Create a dedicated analytics page for the marketplace that displays key metrics about agent and skill performance.--## Explanation-To create a healthy and competitive marketplace, creators and the platform administrators need data. This analytics dashboard will provide insights into which agents are most popular, which skills are selling the most, and overall revenue trends. This helps creators understand what the market wants and helps administrators monitor the health of the economy.--## Instructions-1. **Create a New Page:**- * Create a new route and page, e.g., `marketplace/analytics.html`.- * Design the layout with charts and data tables.--2. **Backend Analytics Endpoint:**- * Create a new API endpoint, `/api/marketplace/analytics`.- * This endpoint will perform aggregation queries to calculate stats. It should be restricted to administrators or perhaps a subset of stats could be public.- * **Metrics to compute:**- * Total marketplace volume (in USD).- * Number of unique buyers.- * Number of unique sellers (creators with at least one sale).- * A time-series chart of daily/weekly sales volume.- * Top 10 best-selling agents (by revenue).- * Top 10 best-selling skills (by revenue).--3. **Frontend Visualization:**- * On the analytics page, fetch data from the new endpoint.- * Use a charting library (e.g., Chart.js, which is lightweight) to visualize the time-series data.- * Render the "Top 10" lists in styled tables.--## Code Example (Backend Analytics Endpoint - `/api/marketplace/analytics.js`)--```javascript-import { supabase } from '../../_lib/supabase';-import { json, error } from '../../_lib/http';--export default async function handler(req, res) {- // Add admin authentication check here-- // Example: Fetching top selling skills- const { data: topSkills, error: skillsError } = await supabase.rpc('get_top_selling_skills', { limit_count: 10 });-- if (skillsError) {- return error(res, 500, 'Failed to calculate analytics.');- }-- // Example: Fetching sales volume by day- const { data: salesVolume } = await supabase.rpc('get_daily_sales_volume');-- // ...fetch other metrics...-- return json(res, {- topSkills,- salesVolume,- // ...other data...- });-}-```--## Supabase RPC Function Example (`get_top_selling_skills`)--```sql-CREATE OR REPLACE FUNCTION get_top_selling_skills(limit_count INT)-RETURNS TABLE(skill_name TEXT, agent_id UUID, total_revenue BIGINT, total_sales BIGINT) AS $$-BEGIN- RETURN QUERY- SELECT- ups.skill_name,- ups.agent_id,- SUM(asp.amount) as total_revenue,- COUNT(ups.id) as total_sales- FROM- user_purchased_skills ups- JOIN- agent_skill_prices asp ON ups.agent_id = asp.agent_id AND ups.skill_name = asp.skill_name- GROUP BY- ups.skill_name, ups.agent_id- ORDER BY- total_revenue DESC- LIMIT- limit_count;-END;-$$ LANGUAGE plpgsql;-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "prompts/monetization/22-marketplace-analytics-dashboard.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/monetization/22-my-collection-page.md b/prompts/monetization/22-my-collection-page.mddeleted file mode 100644index 0a38e7c43..000000000--- a/prompts/monetization/22-my-collection-page.md+++ /dev/null@@ -1,69 +0,0 @@-# Prompt 22: "My Collection" Page--## Objective-Create a dedicated page where users can view all the premium skills and agent subscriptions they have purchased.--## Explanation-As users begin to acquire assets on the platform, they need a central place to view their collection. This page acts as their personal inventory, reinforcing the value of their purchases and providing easy access to the agents and skills they've unlocked.--## Instructions-1. **Create New Page:**- * Create a new HTML file, `collection.html`, and its corresponding JavaScript file, `src/collection.js`.- * This page must be accessible only to logged-in users.--2. **Backend API for Owned Assets:**- * Create a new backend endpoint, `/api/users/my-collection`.- * This endpoint will fetch all the assets owned by the currently logged-in user.- * It should query the database to find:- * All purchased skills (by looking at the `sales` table or by querying for their skill NFTs on-chain, though the database is faster).- * All active subscriptions from the `user_subscriptions` table.--3. **Frontend UI:**- * On page load, `src/collection.js` should call the `/api/users/my-collection` endpoint.- * The UI should be divided into two sections: "My Skills" and "My Subscriptions."- * For each skill, display its name, the agent it belongs to, and a link to that agent's page.- * For each subscription, display the agent's name, the subscription tier, and the renewal/expiry date.- * Design the page with clean cards or list items to make the collection easy to browse.--## Code Example (HTML Structure for `collection.html`)-```html-<h1>My Collection</h1>--<section>- <h2>My Subscriptions</h2>- <div id="subscriptions-list" class="collection-grid">- <!-- Subscription cards will be populated here -->- <div class="card">- <h3>Agent 'X' - Pro Tier</h3>- <p>Renews on: 2026-06-04</p>- <a href="/agent/x">View Agent</a>- </div>- </div>-</section>--<section>- <h2>My Skills</h2>- <div id="skills-list" class="collection-grid">- <!-- Skill cards will be populated here -->- <div class="card">- <h3>Skill: dance</h3>- <p>From: Agent 'Y'</p>- <a href="/agent/y">View Agent</a>- </div>- </div>-</section>-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "prompts/monetization/22-my-collection-page.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/monetization/24-subscription-model.md b/prompts/monetization/24-subscription-model.mddeleted file mode 100644index e0cff8480..000000000--- a/prompts/monetization/24-subscription-model.md+++ /dev/null@@ -1,96 +0,0 @@-# Prompt 24: Subscription Pricing Model for Skills--## Objective-Extend the monetization system to support a subscription model, where a user pays a recurring fee for access to all of an agent's paid skills.--## Explanation-A one-time payment per skill is a good start, but subscriptions offer creators a predictable revenue stream and users a more convenient way to access a suite of premium skills. This prompt covers the necessary database and backend changes to introduce a subscription option.--## Instructions-1. **Database Schema Changes:**- * **`agents` table:** Add columns to the `agents` table (or a new `agent_subscriptions` table) to store subscription pricing:- * `subscription_amount` (BIGINT)- * `subscription_interval` (VARCHAR, e.g., 'month')- * `subscription_currency_mint` (VARCHAR)- * **`user_agent_subscriptions` table:** Create a new table to track active user subscriptions.- * `id`: Primary key.- * `user_id`: Foreign key to `users`.- * `agent_id`: Foreign key to `agents`.- * `status`: VARCHAR (e.g., 'active', 'cancelled', 'past_due').- * `current_period_ends_at`: TIMESTAMPTZ.- * `created_at`, `updated_at`.--2. **UI for Creators:**- * In `agent-edit.html`, under the new "Earnings" or a dedicated "Monetization" tab, add a form for creators to enable and configure subscriptions for their agent.- * This includes inputs for price, currency, and interval (e.g., a dropdown for "monthly").--3. **Modify Skill Access Check:**- * Update the `checkForValidSkillGrant` logic (from Prompt 15).- * Before checking for individual skill grants in `skill_access_grants`, it must **first** check if the user has an `active` subscription to the agent in the `user_agent_subscriptions` table where `current_period_ends_at` is in the future.- * If an active subscription exists, the check should immediately return `true`, granting access to all of the agent's skills.--4. **Subscription Payment Flow:**- * Create a new "Subscribe" button on the agent's detail page in the marketplace.- * This will trigger a new payment flow, similar to the single-skill payment:- * A new "prepare subscription" endpoint that creates a transaction for the subscription amount.- * A "confirm subscription" endpoint that verifies the payment and creates the initial record in `user_agent_subscriptions`.--5. **Recurring Billing (Advanced):**- * True recurring billing on Solana is complex. For this prompt, the focus is on a manual renewal model. The user's subscription is valid until `current_period_ends_at`.- * A separate, more advanced feature would involve setting up a cron job or on-chain program to handle automatic renewals.--## Code Example (Backend - Skill Access Check Logic)--```javascript-// The updated access check logic--async function checkForAccess({ userId, agentId, skillName }) {- // 1. Check for an active agent-level subscription first- const activeSubscription = await db('user_agent_subscriptions')- .where({- user_id: userId,- agent_id: agentId,- status: 'active',- })- .where('current_period_ends_at', '>', db.fn.now())- .first();-- if (activeSubscription) {- return true; // Subscription grants access to all skills- }-- // 2. If no subscription, check for a specific, single-skill grant- const skillGrant = await db('skill_access_grants')- .where({- user_id: userId,- agent_id: agentId,- skill_name: skillName,- })- .where(builder => {- builder.where('expires_at', '>', db.fn.now())- .orWhere('uses_left', '>', 0);- })- .first();-- if (skillGrant) {- // Decrement uses_left if applicable (as in Prompt 15)- return true;- }-- return false;-}-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "prompts/monetization/24-subscription-model.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/CLEANUP-MANIFEST.md b/tasks/CLEANUP-MANIFEST.mdindex 2d0c64d07..0ee40af3f 100644--- a/tasks/CLEANUP-MANIFEST.md+++ b/tasks/CLEANUP-MANIFEST.md@@ -100,3 +100,33 @@ verifiably present in code:| prompts/avatar-animation-hardening/06-final-qa-and-promote.md | runtime fallen-pose guard in animation-manager.js; regression corpus tests/animation-upright-invariant.test.js green |**KEEP (notable):** all monetization/ + monetization-prompts/ (subscriptions, bundles, NFT receipts, fiat, creator payouts, email, admin — none shipped); all feature-innovation/ (improvement specs, gaps remain); all living-agents/, living-wallet/, wallet-innovation/, inventions/, moonshots/, agent-studio 04-12, vanity-* (named modules absent).++## 2026-06-21 verified-shipped sweep (25 removed)++| spec file | decision | evidence |+|---|---|---|+| tasks/next-gen-trading/01-rug-honeypot-firewall.md | DELETE | api/_lib/trade-firewall.js:assessTradeSafety (round-trip simulateTransaction + mint authority + venue checks), api/pump/safety.js endpoint, migration 20260620045927_trade_firewall.sql (firewall_level/firewall_decisions), executor.js wiring, and src/shared/safety-panel.js gating buy in coin-buy.js/trade.js all shipped. |+| tasks/next-gen-trading/02-mev-execution-engine.md | DELETE | api/_lib/execution-engine.js:submitProtected (Jito sendBundle + dynamic fee/tip + retry), trade-client.js routes signAndSend through it, migration 20260620062600_mev_execution.sql adds exec_route/tip_lamports/landed_ms, persisted in executor.js, and mev_tip_mode editor + exec readout in src/dashboard-next/pages/sniper.js. |+| tasks/next-gen-trading/03-smart-money-graph.md | DELETE | api/_lib/smart-money.js:getSmartMoneyForMint/getWalletReputation, workers/agent-sniper/recompute-wallet-graph.js job, migration 20260620061500_smart_money_graph.sql (smart_wallet_reputation/smart_wallet_clusters), scorer.js min_smart_money_score gate, api/intel/smart-money.js + api/intel/wallet/[address].js, and src/shared/smart-money-panel.js all shipped. |+| tasks/irl-production/10-mobile-responsive-polish.md | DELETE | pages/irl.html: viewport-fit=cover meta (L6), env(safe-area-inset-*) in portrait+landscape (L118-261, L1773-1781), .irl-secondary-row flex-wrap for 320px (L395-401), 44px tap targets (L434-437), #irl-caption-input font:16px (L1096, no iOS zoom), .irl-agent-label-name ellipsis (L1310); changelog entry shipped (data/changelog.json L856). |+| tasks/irl-production/13-security-validation.md | DELETE | api/irl/pins.js: outfit-bake error logs server-side and returns generic 502 (L791-796), isValidPinId gates calibrate/outfit/delete (L1274,1397), isExpiredOrHidden+ownership on mutations (L535-542,768-773), safePaymentEndpoint fail-safe allow-list (L160-193); api/irl/report.js: sanitizeDetail (L66-74) + REPORT_PIN_CAP_24H per-pin 429 (L49,155-169); covered by tests/api/irl-pins-hardening.test.js and irl-report.test.js. |+| tasks/irl-production/14-observability.md | DELETE | api/irl/interactions.js view_count catch logs (L326-327); api/irl/interactions-stream.js poller-health metrics (L112-141); api/irl/report.js auto-hide structured log + sendOpsAlert (L211-225); api/cron/irl-reap.js swept log + isReapSpike/sendOpsAlert (L150-160); multiplayer/src/rooms/IrlRoom.js join/leave/error logs no PII (L108,172,177); reapTotal/isReapSpike unit-tested in tests/api/irl-reap-cron.test.js. |+| prompts/monetization/17-subscription-purchase-flow.md | DELETE | api/subscriptions/subscribe.js + verify.js (activateSubscription in api/_lib/subscription-checkout.js) display tiers (src/marketplace.js renderSubscriptionTiers), process first payment, and create creator_subscriptions/subscription_payments/user_agent_subscriptions records with start/end. |+| prompts/monetization/19-backend-record-earnings.md | DELETE | api/_lib/purchase-confirm.js computes gross/platform_fee/net and inserts the creator earnings ledger row (agent_revenue_events) inside the confirmation transaction after grant creation. |+| prompts/monetization/22-my-collection-page.md | DELETE | pages/collection.html (wired in vite.config.js) + src/collection.js render My Skills + My Subscriptions sections with auth wall, fetching /api/users/me/purchased-skills and /api/subscriptions. |+| prompts/monetization/17-subscription-payment-activation.md | DELETE | api/subscriptions/subscribe.js + verify.js + api/_lib/subscription-checkout.js:activateSubscription build/verify/activate the subscription (creator_subscriptions, subscription_payments, user_agent_subscriptions), wired from src/shared/skill-purchase.js:openSubscribeFlow. |+| prompts/monetization/18-tip-jar-feature.md | DELETE | src/shared/agent-tip.js + src/shared/agent-tip-modal.js (openTipModal) implement a real SOL/USDC tip-an-agent modal, reachable on agent/marketplace detail via the wallet chip (src/shared/agent-wallet-chip.js, used by src/marketplace-detail.js / src/agent-detail.js). |+| prompts/monetization/19-creator-revenue-dashboard.md | DELETE | pages/dashboard-next/monetize.html → src/dashboard-next/pages/monetize.js renders revenue summary, time-range chart, and payment history from /api/billing/revenue, /api/monetization/revenue, /api/users/me/earnings; routed at /dashboard/monetize in src/dashboard-next/nav.js. |+| prompts/monetization/19-platform-fee-integration.md | DELETE | api/_lib/marketplace-platform-fee.js (resolveMarketplaceFee, MARKETPLACE_PLATFORM_FEE_BPS + treasury wallet) appends a real on-chain creator/treasury split, consumed by api/subscriptions/subscribe.js and api/marketplace/purchase-bundle.js. |+| prompts/monetization/22-marketplace-analytics-dashboard.md | DELETE | api/marketplace/analytics.js computes total volume, unique buyers/sellers, daily sales time-series, top-10 skills and top-10 agents; rendered by src/marketplace-analytics.js (pages/marketplace-analytics.html), routed at /marketplace-analytics in data/pages.json. |+| prompts/monetization/24-subscription-model.md | DELETE | user_agent_subscriptions table + activation in api/_lib/subscription-checkout.js:activateSubscription, subscribe/verify endpoints, creator subscribe UI in src/agent-detail-market.js/marketplace.js, and the active-subscription access gate read for skill access. |+| prompts/agent-wallets/04-ownership-fork-to-own.md | DELETE | api/avatars/fork.js mints a fresh custodial wallet per fork (provisionAgentWallets) with forked_from lineage and GET ?of= fork network; public/avatar-actions.js renders owner wallet block, non-owner 'fork' CTA, lineage and provision moment. |+| prompts/agent-wallets/05-sniper-trading-copilot.md | DELETE | api/agents/solana-trade.js#handleTrade does real quote->spend-guard(enforceSpendLimit)->simulate->sign(recoverSolanaAgentKeypair)->confirm with audit, routed via solana-wallet.js action 'trade'; src/agent-wallet-hub/tabs/trade.js + snipe.js give the cockpit with positions/P&L/history. |+| prompts/monetization-prompts/10-creator-dashboard-earnings-ui.md | DELETE | Creator earnings dashboard shipped at src/dashboard-next/pages/monetize.js (Total Revenue/available, Recent Sales via renderPaymentsPanel, withdrawal UI via renderWithdrawals), reachable via /dashboard/monetize wired in src/dashboard-next/nav.js. |+| prompts/monetization-prompts/11-api-creator-earnings.md | DELETE | Creator earnings API shipped: api/monetization/revenue.js aggregates SUM(net_amount) from royalty_ledger and MonetizationService.getCreatorSalesData() returns the recent confirmed sales list with skill/agent names. |+| prompts/monetization-prompts/10-creator-payout-logic.md | DELETE | api/_lib/marketplace-platform-fee.js:resolveMarketplaceFee + api/_lib/purchase-confirm.js:feeLegSatisfied implement the on-chain creator/treasury fee split, verified at confirm and credited via recordRevenueEvent. |+| prompts/monetization-prompts/12-on-chain-receipts-as-nfts.md | DELETE | api/_lib/skill-nft.js:mintSkillNft mints a Metaplex Core receipt NFT to the buyer, wired via api/skills/mint.js and stored in skill_purchases.skill_nft_mint (schema.sql:1452). |+| prompts/monetization-prompts/16-on-chain-nft-license.md | DELETE | api/_lib/skill-nft.js:mintSkillNft + skill_nft_mint column + src/collection.js:nftLine renders the Solscan explorer link on the purchased-skills page. |+| prompts/monetization-prompts/21-gifting-skills.md | DELETE | api/payments/purchase-skill.js + api/_lib/resolve-recipient.js + MonetizationService recipient_user_id path + src/shared/skill-purchase.js gift UI + skill_gift_received notification (purchase-confirm.js:548) fully wire gifting. |+| prompts/monetization-prompts/21-skill-subscription-model-backend.md | DELETE | Full subscription backend: subscription_plans table, api/subscriptions/{plans,subscribe,verify}.js create/activate flow, and gating in api/_lib/skill-access.js (user_agent_subscriptions + creator_subscriptions). |+| prompts/monetization-prompts/22-unit-tests-monetization-service.md | DELETE | tests/api/monetization-service.test.js directly tests MonetizationService methods (setSkillPrices, preparePurchaseTransaction, confirmPurchase, etc.) and tests/monetization-service.test.js covers fee/balance/revenue logic. |diff --git a/tasks/irl-production/10-mobile-responsive-polish.md b/tasks/irl-production/10-mobile-responsive-polish.mddeleted file mode 100644index 0274c126a..000000000--- a/tasks/irl-production/10-mobile-responsive-polish.md+++ /dev/null@@ -1,66 +0,0 @@-# Task 10 — Mobile & responsive polish--**Phase:** 2 (UX / polish) · **Effort:** S · **Files:** `pages/irl.html`, `src/irl.js`--## Why-IRL is a phone-first product. It must be flawless at 320px, on notched devices, in-both orientations, and must not trigger iOS's input-zoom. Today there are gaps in-safe-area handling, small-screen layout, and input sizing that would make a senior-designer wince.--## Read first (verify before fixing)-- Viewport meta — `pages/irl.html` `<meta name="viewport">` (must allow safe-area + no forced zoom)-- Joystick CSS + safe-area — `pages/irl.html` `.irl-joystick` / `#irl-joystick` (~216-234)-- Bottom controls + secondary row layout — the control-row CSS-- Caption textarea font-size — `pages/irl.html` (~1673) — iOS zooms inputs < 16px-- Floating agent labels — `.irl-agent-label` (~990-1061) + `updateLabels()`-- Calibrate readouts — `.irl-cal-*`--## Scope — confirm, then fix--1. **Safe-area insets in both orientations.** Every fixed control (joystick, bottom- controls, topbar, sheets) respects `env(safe-area-inset-*)` in portrait AND- landscape. Nothing hides under the notch, home indicator, or rounded corners.--2. **320px layout.** At the narrowest common width, the secondary control row must- not squish illegibly or clip. Allow wrapping or a horizontal scroll affordance;- ensure all controls remain tappable (min 44×44 target).--3. **iOS input-zoom.** Set the caption textarea (and any input) to `font-size: 16px`- on mobile to stop Safari auto-zooming on focus; scale down on desktop via media- query if desired.--4. **Floating labels on small screens.** Ensure `text-overflow: ellipsis` and- sensible max-width so long agent names don't overflow or overlap neighboring- labels; keep hit areas from overlapping (coordinate with task 05).--5. **Landscape joystick + gestures.** Joystick reachable and not under UI in- landscape; confirm two-finger calibrate gesture direction is correct when the- screen is rotated (coordinate with task 02's `screen.orientation.angle`).--6. **Readout legibility.** Calibrate/height readouts get consistent line-height and- sizing so they're readable in both orientations.--## Out of scope-Camera-coupled FOV/orientation math (task 02); a11y focus/contrast (task 07).--## Definition of done-- [ ] Verified at 320px, a notched device profile, portrait + landscape (real device- or device emulation — document widths/devices tested).-- [ ] No control under a safe-area; no input-zoom on iOS; no label overflow at 320px.-- [ ] All tap targets ≥ 44px.-- [ ] esbuild clean; `npm test` green; changelog entry if visibly improved.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-production/10-mobile-responsive-polish.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-production/13-security-validation.md b/tasks/irl-production/13-security-validation.mddeleted file mode 100644index 54f5ffce0..000000000--- a/tasks/irl-production/13-security-validation.md+++ /dev/null@@ -1,69 +0,0 @@-# Task 13 — Security & validation hardening--**Phase:** 3 (backend) · **Effort:** M · **Files:** `api/irl/pins.js`, `api/irl/report.js`--## Why-The placement/report/calibrate endpoints accept untrusted input from anonymous-devices. They must validate strictly, never leak server internals, enforce-ownership and expiry, and resist abuse — all while preserving the deliberate-location-privacy lockdown (no widening of nearby reads).--## Read first (verify before fixing)-- Outfit bake error response (`detail: err?.message`) — `api/irl/pins.js:~400`-- Calibrate/outfit ownership + id handling — `api/irl/pins.js:~282-372`-- Pin expiry on mutations — `api/irl/pins.js:~285, 372`-- x402 endpoint allow-list parse — `api/irl/pins.js:~109-125`-- Report `detail` sanitization — `api/irl/report.js:~70-73`-- Report abuse caps (per-IP exists; per-pin?) — `api/irl/report.js`--## Scope — confirm, then fix--1. **No internal-detail disclosure.** The outfit-bake error must not echo- `err.message` to the client (it can leak paths/upstream errors). Log full detail- server-side; return a generic message. Sweep other endpoints for the same pattern.--2. **Strict id validation.** Validate pin `id` is a UUID (or the exact expected- format) at the top of calibrate/outfit/delete paths — reject early with `400`.- (SQL is already parameterized; this stops oversized/garbage ids reaching logs.)--3. **Ownership + expiry on mutations.** Calibrate, outfit, and delete must verify the- `device_token`/owner AND that the pin is not expired (`expires_at IS NULL OR- expires_at > NOW()`) before mutating. Confirm and add what's missing.--4. **Report input sanitization.** Sanitize/escape the `detail` field (strip control- chars/null bytes, bound length) before storing, so the moderation console renders- it safely.--5. **Report abuse caps.** In addition to per-IP limits, add a per-pin ceiling (e.g.- reject once a pin exceeds N reports in 24h) so a distributed report flood can't- hide a legitimate pin faster than intended. Keep the distinct-reporter dedup.--6. **Config validation.** If `IRL_X402_ALLOWED_HOSTS` is empty/malformed, fail safe- (reject external x402 endpoints) rather than silently accepting a relative/blank- host. Validate the parsed allow-list.--## Constraints-- **Do not widen the nearby read, add a location feed, or re-add pin broadcast.** The- privacy lockdown stands.-- **Do not edit `data/changelog.json`** — return the proposed line in your summary.--## Definition of done-- [ ] No client response leaks internal error detail (coordinate with task 11).-- [ ] id/expiry/ownership/allow-list/report-detail validation covered by- `tests/api/irl-*.test.js`.-- [ ] Per-pin report cap covered by a test.-- [ ] `npm test` green.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-production/13-security-validation.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-production/14-observability.md b/tasks/irl-production/14-observability.mddeleted file mode 100644index 615c83166..000000000--- a/tasks/irl-production/14-observability.md+++ /dev/null@@ -1,64 +0,0 @@-# Task 14 — Observability: log the right things, alert on what matters--**Phase:** 3 (backend) · **Effort:** S · **Files:** `api/irl/*.js`, `api/cron/irl-reap.js`, `multiplayer/src/rooms/IrlRoom.js`--## Why-"Zero error" requires *knowing* when something breaks in production. Today several-IRL failure paths swallow errors silently and key moderation events leave no audit-trail. Wire IRL into the platform's existing observability so operators see failures-and moderation actions.--## Read first (verify before fixing)-- Existing ops/error pipeline — search the repo for `sendOpsAlert`, `[client-error]`,- and the Telegram alerts wiring (memory `observability-stack`); reuse it, don't invent.-- Silent catches — `api/irl/interactions.js:~251`, `api/irl/interactions-stream.js:~163`-- Moderation hide path — `api/irl/report.js:~129-140`-- Reaper cron — `api/cron/irl-reap.js`-- Realtime room — `multiplayer/src/rooms/IrlRoom.js`--## Scope — confirm, then fix--1. **No silent swallows.** Replace bare `.catch(() => {})` on meaningful operations- (view_count increment, SSE send, etc.) with a structured `console.error`/`warn`- that includes endpoint + context. Keep truly-ignorable best-effort calls cheap but- logged at `warn`.--2. **Moderation audit + alert.** When a pin is auto-hidden after crossing the report- threshold, log a structured event AND fire an ops alert (`sendOpsAlert`) with the- pin id, report count, and timestamp, so the review team has visibility.--3. **SSE + poller metrics.** Periodically log connection count, dispatch rate, error- count, and current delay for the interactions-stream poller, so a stuck poller is- diagnosable.--4. **Reaper cron telemetry.** The IRL reaper should log how many pins it expired per- run (and alert on an anomalous spike or repeated failures).--5. **Realtime room health.** Confirm `IrlRoom` logs join/leave/error at a useful- level without leaking PII (presence is anonymous — keep it that way).--## Constraints-- Reuse the existing alert/log pipeline and respect privacy (no precise coordinates,- no device identifiers in logs/alerts).-- **Do not edit `data/changelog.json`** — return the proposed line (observability is- usually internal-only; include a line only if there's a user-visible effect).--## Definition of done-- [ ] No meaningful error path is silently swallowed; all log with context.-- [ ] Pin auto-hide fires a structured log + ops alert.-- [ ] Poller + reaper emit periodic health/telemetry lines.-- [ ] Any pure helper (e.g. log-sampling) unit-tested; `npm test` green.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-production/14-observability.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/next-gen-trading/01-rug-honeypot-firewall.md b/tasks/next-gen-trading/01-rug-honeypot-firewall.mddeleted file mode 100644index f65a95499..000000000--- a/tasks/next-gen-trading/01-rug-honeypot-firewall.md+++ /dev/null@@ -1,118 +0,0 @@-# Task 01 — Rug/Honeypot Simulation Firewall (pre-trade safety engine)--> **Operating bar (applies to the whole task).** You are a senior engineer + product-> thinker building three.ws to beat the best in the world. Be genuinely innovative — this-> must be something users can't get elsewhere, not a clone. No mocks, no fake/sample data,-> no placeholders, no TODO/stubs, no `setTimeout` fake-loading. Wire it 100% end-to-end with-> REAL APIs and real on-chain data. Every state designed (loading/empty/error/populated).-> The only coin is **$THREE** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) — never name,-> hardcode, or recommend any other token; runtime-supplied mints in generic trade plumbing-> are the only exception and must never be promoted. When the build works, do a self-review-> pass and ship what would make it 10× better. Add a `data/changelog.json` entry for every-> user-visible change. Run the **completionist** subagent on your diff. Stage only the paths-> you changed (never `git add -A`); re-check `git status` before committing.--## The invention--Every pump.fun sniper buys blind and prays. We will **never let an agent buy a coin it-cannot sell.** Before any buy — discretionary, sniper, or copy — run a real on-chain-*simulated round-trip* and authority audit, and refuse trades that fail. This is a shared-safety kernel that every trade path in the platform calls. The differentiator is that it is-(a) real RPC `simulateTransaction` of an actual buy→sell in one pass, not a heuristic, and-(b) wired into the autonomous worker, not just a UI badge.--## Context (real, verified)--- Buy/sell instruction builders: `api/_lib/pump-swap-ix.js` (`buildPumpSwapInnerIx`),- `api/_lib/pump.js` (`getPumpSdk`, `getPumpSwapSdk`, `getAmmPoolState`, `getConnection`).-- Worker execution that must call the firewall before broadcast: `workers/agent-sniper/executor.js`- (`executeBuy`, ~L138-192) and `workers/agent-sniper/trade-client.js` (`signAndSend`).-- Discretionary buy paths: `api/agents/agent-trade.js`, `api/agents/solana-trade.js`- (`resolveCustodialQuote`), `src/game/coin-buy.js`, wallet-hub `src/agent-wallet-hub/tabs/trade.js`.-- Shared guard module to extend (do NOT fork): `api/_lib/agent-trade-guards.js`.-- RPC with failover: `api/_lib/solana/connection.js` (`solanaConnection`). Helius is available- (`HELIUS_API_KEY`) for `simulateTransaction` with `sigVerify:false` + account-state diffs.-- Intel already computes structural risk for graduated/observed coins:- `pump_coin_intel.risk_flags`, `concentration_top1`, `fresh_wallet_ratio` — reuse as inputs,- don't recompute.--## Goal--A single `assessTradeSafety({ network, mint, side, payer, quoteAmount, connection })` kernel in-`api/_lib/trade-firewall.js` that returns a structured verdict-`{ verdict: 'allow'|'warn'|'block', score, checks: [...], simulated, reasons[] }`, backed by-real on-chain reads, called by **every** buy path and exposed read-only via API + UI.--## What to build--1. **`api/_lib/trade-firewall.js`** — the kernel. Run these real checks (each a named function,- each returning a typed sub-result; never throw past the boundary — degrade to `warn` with a- reason if a data source is unavailable):- - **Mint authority** — fetch the SPL mint account; flag if `mintAuthority` is non-null- (infinite-supply risk) and whether `freezeAuthority` is set (can freeze your tokens).- - **Round-trip simulation** — build a buy instruction for `quoteAmount` and a sell of the- resulting base amount, pack into one v0 message, and `connection.simulateTransaction`- with `sigVerify:false`, `replaceRecentBlockhash:true`. Parse logs + balance deltas to- confirm the sell would actually return SOL (honeypot detection). BLOCK if the sell leg- fails or returns ~0.- - **LP / curve state** — pre-graduation: read bonding-curve account (real reserves,- `complete` flag). Post-graduation: `getAmmPoolState` and verify a live pool with- non-trivial liquidity. BLOCK if no tradable venue.- - **Concentration / bundle** — pull `pump_coin_intel` if present; WARN on- `concentration_top1` over a sane threshold, dev-dump flags, or extreme `bundle_score`.- - **Price-impact ceiling** — reuse `checkPriceImpact` math from `agent-trade-guards.js`.- - Compose a 0–100 safety score + verdict with explicit human-readable reasons.-2. **Wire it into every buy path** (this is the point — not just a badge):- - `workers/agent-sniper/executor.js#executeBuy` — call the firewall after the quote, before- `signAndSend`; on `block`, abort the buy, write the reason to the position `error` field /- `agent_custody_events`, and continue the loop. Respect a per-strategy- `firewall_level` (`block`|`warn`|`off`, default `block`) added to `agent_sniper_strategies`.- - `api/agents/agent-trade.js` + `api/agents/solana-trade.js` — block server-signed buys that- fail; return a structured 4xx via the existing `tradeGuardResponse` shape with the verdict.- - Discretionary preview endpoints must include the verdict so the UI can show it pre-trade.-3. **Read-only API** — `GET /api/pump/safety?mint=<mint>&network=<net>&amount=<sol>` (rate-limited,- public, cached briefly) returning the verdict for any mint. No auth needed to read.-4. **UI** — a compact, reusable **Safety** panel: render the verdict (color-coded allow/warn/block),- each check with pass/warn/fail + plain-language explanation, and a "what this means" tooltip.- Surface it in `src/agent-wallet-hub/tabs/trade.js` and `src/game/coin-buy.js` *before* the buy- button; disable the buy button on `block` (with an explicit override only for `warn`). Use the- existing design tokens. Designed loading/empty/error states.-5. **Migration** — dated file under `api/_lib/migrations/` adding `firewall_level` to- `agent_sniper_strategies` and a `firewall_decisions` audit table (mint, network, verdict,- score, checks jsonb, agent_id nullable, created_at) so blocks are observable/learnable.--## Constraints--- Real `simulateTransaction` against real RPC only — never fabricate a verdict. If RPC is- unavailable after failover, return `warn` with reason `simulation_unavailable`, never a fake- `allow`. Honest degradation is the rule.-- Performance: the worker is latency-sensitive at block-0. Cache mint-authority + curve reads- briefly per mint; run checks concurrently; keep added latency to a few hundred ms and make the- worker path configurable so a strategy can opt into `warn` (log-only) if it wants raw speed.-- Use the $THREE mint or a clearly-synthetic placeholder in any test fixture; never a real- third-party mint.-- Extend `agent-trade-guards.js` patterns; don't duplicate spend-limit logic.--## Success criteria--- `assessTradeSafety` is called by the sniper worker, both discretionary endpoints, and the- read-only API; a known-honeypot-shaped simulation is BLOCKED on a real RPC.-- `firewall_decisions` rows accrue for real blocks/warns; `firewall_level` is honored per strategy.-- Safety panel renders in trade + coin-buy with all states; buy button disabled on `block`.-- `npm run build` + `npm run typecheck` + `npm test` clean. Changelog entry (tags: feature,- security). Completionist passes.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built,-wired, verified, and committed**, remove it in the same change:--```bash-git rm "tasks/next-gen-trading/01-rug-honeypot-firewall.md"-```--A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.diff --git a/tasks/next-gen-trading/02-mev-execution-engine.md b/tasks/next-gen-trading/02-mev-execution-engine.mddeleted file mode 100644index 7791f0b1b..000000000--- a/tasks/next-gen-trading/02-mev-execution-engine.md+++ /dev/null@@ -1,98 +0,0 @@-# Task 02 — MEV-Aware Execution Engine (Jito bundles, dynamic fees, atomic protection)--> **Operating bar (applies to the whole task).** Senior engineer + product thinker building-> three.ws to beat the best in the world. Genuinely innovative, not a clone. No mocks, no-> fake/sample data, no placeholders, no TODO/stubs, no `setTimeout` fake-loading. Wire 100%-> end-to-end with REAL APIs and real on-chain data. Every state designed. Only coin is **$THREE**-> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime-supplied mints in generic trade-> plumbing are the only exception and are never promoted. After it works, self-review and ship-> the 10× improvement. `data/changelog.json` entry for every user-visible change. Run the-> **completionist** subagent. Stage only changed paths (never `git add -A`); re-check `git status`.--## The invention--Snipers win or lose in the first block. Today our `signAndSend` (`workers/agent-sniper/trade-client.js`)-sends a single raw tx with a fixed compute budget — at the mercy of public mempool ordering and-sandwich bots. We build a real **MEV-aware execution layer**: Jito bundle submission with a-dynamic tip, priority-fee modeling from recent blocks, simulate-then-send with adaptive retry,-and atomic anti-sandwich protection. The edge: better fills, fewer reverts, measurable.--## Context (real, verified)--- Current broadcast: `workers/agent-sniper/trade-client.js#signAndSend` (~L29) — blockhash →- v0 message → sign → `sendRawTransaction(skipPreflight:false, maxRetries:3)` → confirm race.-- Discretionary broadcast paths: `api/agents/agent-trade.js`, `api/agents/solana-trade.js`- (`_solRpcWithBackoffFallback`). Tx serialization helper: `api/_lib/pump.js#buildUnsignedTxBase64`.-- RPC failover + cooldowns: `api/_lib/solana/connection.js`. Helius (`HELIUS_API_KEY`) supports- `getPriorityFeeEstimate`.-- Slippage/impact config lives on `agent_sniper_strategies` (`slippage_bps`, `max_price_impact_pct`)- and trade limits (`api/_lib/agent-trade-guards.js`).-- SDK has compute-unit/priority-fee helpers: `solana-agent-sdk` (`estimatePriorityFee`,- `estimateComputeUnits`) — reuse rather than reinvent where sensible.--## Goal--A single `api/_lib/execution-engine.js` (`submitProtected({ network, connection, payer,-instructions, opts })`) used by the sniper worker AND the discretionary endpoints, that:-chooses the cheapest viable inclusion path, sets a data-driven priority fee + compute limit,-optionally routes a Jito bundle with a tip, simulates before send, and retries adaptively —-returning `{ signature, slot, route, tipLamports, priorityFeeMicroLamports, attempts, landedMs }`.--## What to build--1. **Dynamic compute budget** — prepend `ComputeBudgetProgram.setComputeUnitLimit` (from a real- `simulateTransaction` unit estimate, not a guess) and `setComputeUnitPrice` from a real- priority-fee estimate (Helius `getPriorityFeeEstimate`, falling back to a recent-blocks- percentile via `getRecentPrioritizationFees`). Cache estimates briefly.-2. **Jito bundle route** — integrate the Jito Block Engine REST API- (`JITO_BLOCK_ENGINE_URL`, default `https://mainnet.block-engine.jito.wtf`): fetch tip-floor,- append a real SOL tip transfer to a Jito tip account as the last instruction, and submit via- `sendBundle`. Poll bundle status for landing. Tip sizing is **adaptive**: scale with a- per-strategy `mev_tip_mode` (`off`|`economy`|`turbo`) and back off if bundles aren't landing.- Devnet/no-Jito → transparently fall back to the protected single-tx route.-3. **Atomic protection** — when the firewall (task 01) is present, optionally pack the safety- round-trip check inline; always set tight, honest slippage from strategy config so a sandwich- makes the tx revert rather than fill at a terrible price (fail-closed, not fill-at-any-cost).-4. **Adaptive retry + landing telemetry** — simulate first; on blockhash-expiry or not-landed,- refresh blockhash and re-submit up to a bounded count with escalating fee/tip; record- `landedMs`, route, attempts. Never silently double-spend — dedupe by the worker's existing- idempotency lock.-5. **Wire it in** — replace the body of `workers/agent-sniper/trade-client.js#signAndSend` to call- `submitProtected` (keep the signature stable for callers); route the discretionary buy/sell in- `agent-trade.js`/`solana-trade.js` through it too. Persist execution telemetry onto- `agent_sniper_positions` (new nullable columns: `exec_route`, `tip_lamports`,- `priority_fee_microlamports`, `landed_ms`) via a dated migration.-6. **Surface it** — add an "Execution" readout to the sniper/positions UI and the trade result- toast: route used (Jito turbo / protected), tip paid, time-to-land. Add `mev_tip_mode` +- `firewall_level` (if task 01 merged) to the strategy editor. All states designed.--## Constraints--- Real RPC + real Jito only — no simulated landings, no fabricated fee numbers. If Jito is- unreachable, fall back and say so in telemetry; never claim a bundle landed that didn't.-- Tips are real SOL leaving the agent wallet — count them in the spend guards- (`agent-trade-guards.js`) and the `agent_custody_events` ledger (category `mev_tip`), and- respect the daily budget / kill switch. A tip must never bypass spend limits.-- Keep the hot path fast: estimates cached, single simulate, bounded retries.-- $THREE-only rule; synthetic placeholder mints in any fixtures.--## Success criteria--- Sniper + discretionary buys flow through `submitProtected`; on mainnet a buy can land via a- real Jito bundle with a real tip, with graceful fallback on devnet.-- Execution telemetry (route/tip/fee/landed_ms) is persisted and shown in the UI.-- Tips are spend-guarded and audited; kill switch halts them.-- Build/typecheck/test clean. Changelog entry (tags: feature, improvement, infra).- Completionist passes.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--```bash-git rm "tasks/next-gen-trading/02-mev-execution-engine.md"-```--A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.diff --git a/tasks/next-gen-trading/03-smart-money-graph.md b/tasks/next-gen-trading/03-smart-money-graph.mddeleted file mode 100644index 31f45524b..000000000--- a/tasks/next-gen-trading/03-smart-money-graph.md+++ /dev/null@@ -1,96 +0,0 @@-# Task 03 — Smart-Money Wallet Graph & Cluster Intelligence--> **Operating bar (applies to the whole task).** Senior engineer + product thinker building-> three.ws to beat the best in the world. Genuinely innovative, not a clone. No mocks, no-> fake/sample data, no placeholders, no TODO/stubs, no `setTimeout` fake-loading. Wire 100%-> end-to-end with REAL APIs and real on-chain data. Every state designed. Only coin is **$THREE**-> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime-supplied mints in generic trade-> plumbing are the only exception and are never promoted. After it works, self-review and ship-> the 10× improvement. `data/changelog.json` entry for every user-visible change. Run the-> **completionist** subagent. Stage only changed paths (never `git add -A`); re-check `git status`.--## The invention--We already record, per launch, every buyer wallet and its **funder** (`pump_coin_wallets`),-plus eventual **outcomes** (`pump_coin_outcomes`: graduated/pumped/rugged/ath_multiple). Nobody-has stitched this into a persistent, self-updating **wallet reputation graph**. Build it: derive-a rolling "smart money" score per wallet from its realized hit-rate across launches, cluster-wallets that share a common funder (sybil/insider detection), and emit a **live "smart money is-buying X" signal** that the sniper, the firewall, and Mission Control all consume. This is the-on-chain alpha layer competitors fake with vanity lists; ours is computed from outcomes.--## Context (real, verified)--- Per-coin per-wallet ledger: `pump_coin_wallets` (buy/sell counts, volumes, `is_creator`,- `funder`) — written by `workers/agent-sniper/intel/store.js`.-- Outcome labels: `pump_coin_outcomes` (`outcome`, `ath_multiple`, `ath_market_cap_usd`,- graduated/rugged) — the ground truth for scoring wallets.-- Signal computation patterns: `workers/agent-sniper/intel/signals.js` (concentration, entropy,- funder graph) and the learning loop `intel/learn.js` (per-signal conditional win-rates) — mirror- this style for wallet scoring.-- Existing conviction surface to enrich (don't duplicate): `oracle_conviction.smart_wallet_count`,- `oracle_agent_watch.require_smart_money` — feed real numbers into these.-- DB: Neon HTTP (`api/_lib/db.js`); migrations in `api/_lib/migrations/`.--## Goal--A maintained `wallet_reputation` table + `wallet_clusters` table, a recompute job, and a-`getSmartMoneyForMint(mint, network)` / `getWalletReputation(addr)` API used by the worker-(scoring + oracle), the firewall, and the UI — all derived from real observed buys and outcomes.--## What to build--1. **Migration** — `wallet_reputation` (address, network, scored_at, trades_seen, winners,- losers, win_rate, avg_ath_multiple, realized_score 0–100, first_seen, last_seen, labels[]) and- `wallet_clusters` (cluster_id, address, funder_root, size, confidence, network). Indexes for- lookup by mint-join and by score.-2. **Recompute job** — a worker entrypoint (extend `workers/agent-sniper/` or a sibling under- `workers/`, runnable standalone, env-gated) that, on an interval, joins `pump_coin_wallets` ⋈- `pump_coin_outcomes` to compute each active wallet's hit-rate and ATH-weighted score, and- clusters wallets by shared `funder` (union-find over funder edges) with a confidence from- co-occurrence frequency. Fire-and-forget DB writes; never block the live feed. Honest about- sample size — regress new wallets toward neutral until N observed launches (mirror the- confidence regression in `trader-stats.js`).-3. **Live signal** — `getSmartMoneyForMint(mint, network)` returns the count + list of- reputable, non-clustered wallets currently net-buying this mint (from the in-flight intel- watcher + `pump_coin_wallets`), with a `smart_money_score` and `sybil_flag` when buyers are- dominated by one cluster. Cache briefly.-4. **Wire into trading** — add an optional strategy gate `min_smart_money_score` /- `require_smart_money` to `agent_sniper_strategies`; have `scorer.js` (`scoreIntel`) and- `oracle-gate.js` add the smart-money signal to their score, and feed the real- `smart_wallet_count` into `oracle_conviction`. The firewall (task 01) WARNs when a buy is- dominated by a single sybil cluster.-5. **API + UI** — `GET /api/intel/smart-money?mint=…&network=…` (public, rate-limited, cached) and- `GET /api/intel/wallet/:address`. Build a **Smart-Money** panel: a compact, accessible mini- wallet-graph (reputable buyers, clusters highlighted, links to Solscan), shown on the coin/- trade surfaces and consumed by Mission Control (task 09). All states designed; zero-data state- explains "not enough on-chain history yet."--## Constraints--- Scores derive only from real observed buys + real outcomes — no hand-curated wallet lists, no- invented "famous trader" names. If there isn't enough data, say so; don't fabricate confidence.-- Never expose or store private keys; this is public on-chain address analytics only.-- Respect Neon HTTP limits — batch the recompute, paginate, and keep the live lookup O(small).-- $THREE-only rule; synthetic placeholder addresses in fixtures (e.g. `THREEsynthetic1111…`),- never a real third-party wallet.--## Success criteria--- `wallet_reputation` + `wallet_clusters` populate from real data on a real network; recompute- is re-runnable and idempotent.-- `scoreIntel`/`oracle-gate` incorporate smart-money; `min_smart_money_score` gate works.-- Smart-Money panel + APIs render with all states; sybil clusters are flagged.-- Build/typecheck/test clean. Changelog entry (tags: feature, improvement). Completionist passes.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--```bash-git rm "tasks/next-gen-trading/03-smart-money-graph.md"-```--A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.