Skip to content

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

Improve animation retargeting; finalize IRL location-privacy changelog

nirholas56d017155ce4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d9d26de05..689964634 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,7 +23,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **IRL placements now have guardrails: report a pin, content checks, and area limits** — Now that anyone at a location can see anyone's placed agent on three.ws/irl, we've added the safety layer that makes a public shared space work. Tap any agent that isn't yours and you'll find a Report option — pick a reason (spam, hate, impersonation, scam, sexual content, or something else) and once enough different people flag the same pin it's automatically hidden from everyone, with the reporter seeing it disappear right away. One person can't hide someone else's agent, and repeat reports from the same device don't stack, so the system can't be gamed to silence a legitimate pin. At placement time, captions and agent names are screened for slurs and hateful content and rejected with a clear, fixable message, and a pin can only ever reference $THREE — no other coin can be advertised. Pay buttons are locked to three.ws payment endpoints so a pin can't point you at an off-platform drain. To stop one person from carpet-bombing a plaza, each small area caps how many agents it holds and each person has an active-pin limit — and if you hit a limit you get a plain-language nudge (shorten the text, move, wait a moment, or remove an old pin) instead of a silent failure. Abandoned anonymous pins are now cleaned up automatically; your signed-in permanent pins are never touched. (`/irl`) `[security, feature]`
- **IRL stays smooth at crowded locations** — three.ws/irl now holds a steady frame rate even when a busy spot is packed with placed agents. Only the nearest few load as full 3D avatars; agents further out render as lightweight cardboard-style billboards that cost almost nothing, and ones far past that fade out entirely until you walk closer. As you move, avatars load nearest-first and the ones you leave behind are freed from memory, so a long walk past dozens of agents never piles up. IRL also reads your device on startup and picks a matching quality level — turning down resolution and shadows on lower-end phones — and if the frame rate dips under load it steps quality down on the fly and back up when there's room, so the camera view degrades gracefully instead of stuttering. (`/irl`) `[improvement, infra]`
- **IRL walks you through camera, motion & location — and never dead-ends on a blocked permission** — The first time you open three.ws/irl, a quick setup card explains why each sensor matters and asks for one at a time: the camera to see your agents in the real world, motion to look around, and location to place agents and discover the ones others left nearby. Every outcome is designed — you see why we’re asking, a green check when access is granted, and if you decline you get the exact steps to switch it back on (the precise iOS Settings path on iPhone) with a Try again button, not a toast that vanishes. Sensors your device doesn’t have are handled honestly, with a note on what still works. Block something later and a one-tap ‘Enable camera’ or ‘Enable location’ chip stays in the top bar so recovery is always within reach — and turning on the camera or pinning an agent re-asks through the same clear cards instead of failing silently. Your choices are remembered, so you’re never nagged twice. (`/irl`) `[feature, improvement]`
-- **IRL world: closed a bulk location-scrape path on placed agents** — The /irl world lets you place 3D agents at real GPS spots and discover the ones near you. The 'discover nearby' feed always hid who placed each agent, but an internal bulk window-load endpoint — used only by the live realtime server to hydrate a neighborhood — was reachable from the open web, which in principle let someone download many placements' exact coordinates in one request. That endpoint is now locked to the realtime server with a shared secret, the public nearby feed is rate-limited so it can't be systematically gridded, and the maximum window size was tightened. Live discovery, your own pins, and the realtime map are unchanged. (`/irl`) `[security]`
+- **IRL world: placed agents are private by location — discovered only in person** — We changed how the /irl world reveals where agents are placed, for safety. There is no list, map, or feed of agent locations anywhere: an agent's spot is shared with your device only when you are physically within a short distance of it, so you come across one by walking up and pointing your camera — never by browsing locations from afar. The live realtime server no longer broadcasts a neighborhood's placements to everyone connected; it now carries only presence (how many people are viewing nearby) and ambient reactions, both kept coarse and anonymous. The 'nearby' read is hard-capped to a tight radius and rate-limited so it can't be swept to rebuild a map. Placing agents and the multiplayer presence layer keep working as before. (`/irl`) `[security, improvement]`
- **Jump straight from an agent's profile into IRL or XR** — Every agent profile now has View in IRL and View in XR buttons next to See in 3D. View in IRL drops you into three.ws/irl already wearing that agent's body, and if the same agent is placed nearby it flashes its pin and opens its card so you land right on it. View in XR opens the immersive AR/VR viewer with that agent loaded. Both are real links, so you can open them in a new tab, and every agent has a body to show — its own 3D model or the shared mannequin — so the buttons are never dead ends. This matches the Walk IRL / View in XR buttons avatars already had, so the whole platform now routes into the immersive layer from one surface to the next. (`/irl`) `[feature]`
- **Live trade feed: the time-window filters work on first load** — On the Live Trade Feed, the 1h / 24h / 7d window buttons threw an error as the page set up its controls, which could leave the feed stuck before it finished loading. The control-syncing code was treating a group of buttons as a single element. It now handles the whole group, so the window and min-PnL filters initialize and switch cleanly every time. (`/trades`) `[fix]`
- **Minting an agent's on-chain collectible is reliable under load** — Preparing an agent's on-chain mint sometimes failed when the shared public Solana RPC was rate-limited — the request to fetch a recent blockhash came back 'too many requests' and the whole prep errored out. Minting now builds the transaction through the same multi-endpoint failover the rest of the platform uses, rotating to a healthy Solana provider instead of giving up, so a busy public endpoint no longer blocks a mint. Solana name (.sol) lookups and the signer-balance watchdog were moved onto the same resilient connection. (`/create`) `[fix, improvement]`
diff --git a/data/changelog.json b/data/changelog.json
index eff4e227f..656842235 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -3,9 +3,9 @@
"entries": [
{
"date": "2026-06-17",
- "title": "IRL world: closed a bulk location-scrape path on placed agents",
- "summary": "The /irl world lets you place 3D agents at real GPS spots and discover the ones near you. The 'discover nearby' feed always hid who placed each agent, but an internal bulk window-load endpoint — used only by the live realtime server to hydrate a neighborhood — was reachable from the open web, which in principle let someone download many placements' exact coordinates in one request. That endpoint is now locked to the realtime server with a shared secret, the public nearby feed is rate-limited so it can't be systematically gridded, and the maximum window size was tightened. Live discovery, your own pins, and the realtime map are unchanged.",
- "tags": ["security"],
+ "title": "IRL world: placed agents are private by location — discovered only in person",
+ "summary": "We changed how the /irl world reveals where agents are placed, for safety. There is no list, map, or feed of agent locations anywhere: an agent's spot is shared with your device only when you are physically within a short distance of it, so you come across one by walking up and pointing your camera — never by browsing locations from afar. The live realtime server no longer broadcasts a neighborhood's placements to everyone connected; it now carries only presence (how many people are viewing nearby) and ambient reactions, both kept coarse and anonymous. The 'nearby' read is hard-capped to a tight radius and rate-limited so it can't be swept to rebuild a map. Placing agents and the multiplayer presence layer keep working as before.",
+ "tags": ["security", "improvement"],
"link": "/irl"
},
{
diff --git a/package.json b/package.json
index 4c3417218..e7f81488c 100644
--- a/package.json
+++ b/package.json
@@ -71,7 +71,6 @@
"smoke:onchain:ci": "node scripts/onchain-smoke.mjs --only=parity",
"audit:mcp": "node scripts/audit-mcp-manifests.mjs",
"smoke:mcp": "node scripts/smoke-mcp-remotes.mjs",
- "smoke:irl-d1": "node scripts/irl-d1-smoke.mjs",
"test:mcp": "node scripts/test-mcp-all.mjs",
"audit:pages": "node scripts/audit-page-index.mjs",
"audit:handlers": "node scripts/audit-empty-handlers.mjs",
diff --git a/prompts/monetization/04-backend-price-validation.md b/prompts/monetization/04-backend-price-validation.md
deleted file mode 100644
index e4f88cd74..000000000
--- a/prompts/monetization/04-backend-price-validation.md
+++ /dev/null
@@ -1,88 +0,0 @@
-# Prompt 4: Backend Price Validation Logic
-
-## Objective
-Implement robust server-side validation for skill prices to ensure data integrity and prevent invalid pricing information from being stored.
-
-## Explanation
-While the frontend can guide users, the backend must be the ultimate authority on data validity. This prompt focuses on strengthening the `POST /api/agents/:id/skills/price` endpoint by adding comprehensive validation logic for the incoming price data.
-
-## Instructions
-1. **Locate the API Endpoint:**
- * Open the file for the `POST /api/agents/:id/skills/price` endpoint (e.g., `api/agents/[id]/skills/price.js`).
-
-2. **Enhance Validation Logic:**
- * Before interacting with the database, ensure the request body contains all required fields (`skill_name`, `amount`, `currency_mint`).
- * **Amount Validation:**
- * Verify that `amount` is a non-negative integer. Floating-point numbers or negative values should be rejected with a `400 Bad Request` error.
- * Consider setting a maximum allowed price to prevent abuse or user error (e.g., max 100,000,000,000 lamports or 100,000 USDC).
- * **Currency Mint Validation:**
- * Check if `currency_mint` is a valid Solana public key.
- * For now, you might enforce that it must be the official USDC mint address on the target network (Mainnet or Devnet). Create a whitelist of accepted mints.
- * **Skill Name Validation:**
- * Verify that the `skill_name` provided in the request actually corresponds to a real skill defined in the agent's configuration. If not, reject the request.
-
-3. **Return Specific Error Messages:**
- * Provide clear and specific error messages in the JSON response when validation fails. This helps the frontend display meaningful error feedback to the user.
- * Example error responses:
- * `{ "error": "Amount must be a non-negative integer." }`
- * `{ "error": "Invalid currency mint address." }`
- * `{ "error": "Skill 'invalid-skill' not found for this agent." }`
-
-## Code Example (Backend - API Endpoint)
-
-```javascript
-// Inside your /api/agents/:id/skills/price endpoint handler
-
-// Whitelist of accepted currency mints
-const ALLOWED_CURRENCIES = {
- mainnet: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC Mainnet
- devnet: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', // USDC Devnet
-};
-const MAX_PRICE_LAMPORTS = 100000 * 1e6; // Max 100,000 USDC
-
-// --- Inside the handler function, after auth ---
-
-const { skill_name, amount, currency_mint } = req.body;
-
-// 1. Basic field presence
-if (!skill_name || amount == null || !currency_mint) {
- return res.status(400).json({ error: 'Missing required fields: skill_name, amount, currency_mint' });
-}
-
-// 2. Amount validation
-if (!Number.isInteger(amount) || amount < 0) {
- return res.status(400).json({ error: 'Amount must be a non-negative integer.' });
-}
-if (amount > MAX_PRICE_LAMPORTS) {
- return res.status(400).json({ error: `Price cannot exceed ${MAX_PRICE_LAMPORTS / 1e6} USDC.` });
-}
-
-// 3. Currency mint validation
-const network = process.env.SOLANA_NETWORK || 'mainnet'; // Or however you determine the network
-if (currency_mint !== ALLOWED_CURRENCIES[network]) {
- return res.status(400).json({ error: 'Invalid or unsupported currency.' });
-}
-
-// 4. Skill name validation (assuming agent object has a skills array)
-const agent = await db.getAgentById(agentId); // You should have this from auth step
-const agentSkills = agent.meta?.skills || []; // Adjust based on your agent data structure
-if (!agentSkills.some(s => (typeof s === 'string' ? s : s.name) === skill_name)) {
- return res.status(400).json({ error: `Skill '${skill_name}' is not defined for this agent.` });
-}
-
-// If all checks pass, proceed to database logic...
-```
-
-<!-- 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/04-backend-price-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/prompts/monetization/04-backend-purchase-endpoint.md b/prompts/monetization/04-backend-purchase-endpoint.md
deleted file mode 100644
index 6ed5519d3..000000000
--- a/prompts/monetization/04-backend-purchase-endpoint.md
+++ /dev/null
@@ -1,101 +0,0 @@
-# Prompt 4: Backend Purchase Endpoint
-
-## Objective
-Create a backend API endpoint that generates the necessary Solana transaction for a user to purchase a skill. This endpoint will not execute the transaction but will prepare it for the user to sign on the frontend.
-
-## Explanation
-The purchase process must be secure and initiated by the server. This endpoint (`/api/marketplace/skills/purchase`) will be responsible for fetching the skill's price, identifying the creator's treasury wallet, and constructing an unsigned Solana transfer transaction. This transaction is then sent back to the frontend, which will request the user's signature.
-
-## Instructions
-1. **Create New API File:**
- * Create a new file in `api/marketplace/skills/purchase.js`. This will contain the logic for the new endpoint.
-
-2. **Endpoint Logic:**
- * The endpoint should accept a POST request with the `agentId` and `skillName`.
- * It must also know the `purchaser`'s public key, which should be sent from the frontend.
- * **Security:** The endpoint must verify the agent and skill exist and have a valid price.
- * It needs to look up the agent creator's treasury wallet address.
- * Using the Solana `@solana/web3.js` library, construct a transaction that transfers the correct amount of the specified currency (e.g., USDC) from the `purchaser` to the creator's treasury wallet.
- * The endpoint should serialize the transaction, but *not* sign it, and return it to the frontend as a base64-encoded string.
-
-## Code Example (`api/marketplace/skills/purchase.js`)
-
-```javascript
-import { Connection, PublicKey, SystemProgram, Transaction, clusterApiUrl } from '@solana/web3.js';
-import { supabase } from '../../_lib/supabase'; // Assuming Supabase for DB
-import { json, error } from '../../_lib/http'; // Assuming helper for responses
-
-// Mock get-token-address library for USDC on Solana
-const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6d';
-
-export default async function handler(req, res) {
- if (req.method !== 'POST') {
- return error(res, 405, 'Method Not Allowed');
- }
-
- const { agentId, skillName, purchaserPublicKey } = req.body;
-
- if (!agentId || !skillName || !purchaserPublicKey) {
- return error(res, 400, 'Missing required fields.');
- }
-
- // 1. Fetch skill price and agent creator's treasury wallet from DB
- const { data: priceData, error: priceError } = await supabase
- .from('agent_skill_prices')
- .select('amount, currency_mint, agents(creator_treasury_wallet)')
- .eq('agent_id', agentId)
- .eq('skill_name', skillName)
- .single();
-
- if (priceError || !priceData) {
- return error(res, 404, 'Skill price not found.');
- }
-
- const { amount, currency_mint, agents: { creator_treasury_wallet } } = priceData;
-
- if (!creator_treasury_wallet) {
- return error(res, 500, 'Creator has not configured a payout wallet.');
- }
-
- // For this example, we assume native SOL transfer for simplicity
- // A real implementation would handle SPL tokens like USDC, which is more complex.
- const connection = new Connection(clusterApiUrl('devnet'));
- const purchaser = new PublicKey(purchaserPublicKey);
- const recipient = new PublicKey(creator_treasury_wallet);
-
- const transaction = new Transaction().add(
- SystemProgram.transfer({
- fromPubkey: purchaser,
- toPubkey: recipient,
- lamports: amount, // Assuming amount is in lamports for SOL transfer
- })
- );
-
- // Set the recent blockhash
- transaction.recentBlockhash = (await connection.getLatestBlockhash()).blockhash;
- transaction.feePayer = purchaser;
-
- // Serialize the transaction and convert to base64
- const serializedTransaction = transaction.serialize({
- requireAllSignatures: false, // User will sign it
- }).toString('base64');
-
- return json(res, {
- transaction: serializedTransaction,
- });
-}
-```
-
-<!-- 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/04-backend-purchase-endpoint.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/04-connect-wallet-integration.md b/prompts/monetization/04-connect-wallet-integration.md
deleted file mode 100644
index 0d8e843c5..000000000
--- a/prompts/monetization/04-connect-wallet-integration.md
+++ /dev/null
@@ -1,62 +0,0 @@
-# Prompt 4: Wallet Integration for Payments
-
-## Objective
-Integrate a Solana wallet adapter to allow users to connect their crypto wallets to the platform, a prerequisite for making payments.
-
-## Explanation
-To interact with the Solana blockchain for payments, users must first connect their own wallet (like Phantom, Solflare, etc.). We will use the official Solana Wallet Adapter libraries to provide a standardized, user-friendly way for users to connect.
-
-## Instructions
-1. **Add Dependencies:**
- * Install the necessary Solana Wallet Adapter packages (`@solana/wallet-adapter-base`, `@solana/wallet-adapter-react`, `@solana/wallet-adapter-wallets`, etc., and their peer dependencies like `@solana/web3.js`).
- * This might require refactoring parts of the frontend into a framework like React if not already done, or using the adapter with vanilla JS. For this prompt, assume a vanilla JS setup is possible.
-
-2. **Initialize Wallet Adapter:**
- * In a core JavaScript file (e.g., `src/app.js` or `src/wallet.js`), import and initialize the wallet adapter providers.
- * Create a "Connect Wallet" button in the main UI (e.g., the header).
-
-3. **Implement Connect/Disconnect Logic:**
- * When the "Connect Wallet" button is clicked, present the user with a list of available wallets.
- * Once a wallet is selected and approved by the user, the application should store the connection state and public key.
- * The UI should update to show the user's connected wallet address and change the button to "Disconnect."
-
-## Code Example (JavaScript - `src/wallet.js`)
-```javascript
-// This is a simplified example. Refer to official @solana/wallet-adapter docs for a full implementation.
-import { Connection, PublicKey } from '@solana/web3.js';
-import { WalletAdapter, PhantomWalletAdapter } from '@solana/wallet-adapter-wallets';
-
-// Setup
-const connection = new Connection('https://api.mainnet-beta.solana.com');
-const wallets = [new PhantomWalletAdapter()];
-
-let wallet;
-
-// UI Connection
-document.getElementById('connect-wallet-btn').addEventListener('click', async () => {
- const selectedWallet = await showWalletChoice(); // UI function to let user pick from `wallets`
- wallet = selectedWallet;
- await wallet.connect();
- console.log('Wallet connected:', wallet.publicKey.toBase58());
- updateUIForConnectedState(wallet.publicKey);
-});
-
-wallet.on('connect', (publicKey) => {
- console.log('Connected to ' + publicKey.toBase58());
-});
-```
-This is a complex task. The prompt provides the user with the high-level steps and concepts, guiding them through the official documentation.
-
-<!-- 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/04-connect-wallet-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/04-db-schema-skill-prices.md b/prompts/monetization/04-db-schema-skill-prices.md
deleted file mode 100644
index 8ba241d9f..000000000
--- a/prompts/monetization/04-db-schema-skill-prices.md
+++ /dev/null
@@ -1,56 +0,0 @@
----
-status: not-started
----
-
-# Prompt 4: Database Schema for Skill Prices
-
-## Objective
-Design and implement the necessary database schema to store the prices of agent skills.
-
-## Explanation
-A new table, `agent_skill_prices`, is needed to store the monetization information for each skill. This table will link an agent, a skill, and its price.
-
-## Instructions
-1. **Design the Table:**
- * Create a new table named `agent_skill_prices`.
- * The table should have the following columns:
- * `id`: Primary key.
- * `agent_id`: Foreign key referencing the `agents` table.
- * `skill_name`: The name of the skill being priced.
- * `amount`: The price of the skill in the smallest currency unit (e.g., lamports).
- * `currency_mint`: The mint address of the currency (e.g., the USDC mint on Solana).
- * `created_at`, `updated_at`: Timestamps.
-
-2. **Create a Migration:**
- * Use your database migration tool to create a new migration file.
- * Write the SQL script to create the `agent_skill_prices` table.
- * Apply the migration to your database.
-
-## SQL Example
-
-```sql
-CREATE TABLE agent_skill_prices (
- id SERIAL PRIMARY KEY,
- agent_id UUID NOT NULL REFERENCES agents(id),
- skill_name VARCHAR(255) NOT NULL,
- amount BIGINT NOT NULL,
- currency_mint VARCHAR(255) NOT NULL,
- created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
- updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
- UNIQUE(agent_id, skill_name)
-);
-```
-
-<!-- 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/04-db-schema-skill-prices.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/04-design-database-schema-for-skill-pricing.md b/prompts/monetization/04-design-database-schema-for-skill-pricing.md
deleted file mode 100644
index a9996d15b..000000000
--- a/prompts/monetization/04-design-database-schema-for-skill-pricing.md
+++ /dev/null
@@ -1,60 +0,0 @@
-# Prompt 4: Design Database Schema for Skill Pricing
-
-## Status
-- [ ] Not Started
-
-## Objective
-Design and create the necessary database table(s) to store pricing information for agent skills.
-
-## Explanation
-To make skills purchasable, we need a persistent storage solution for their pricing details. This prompt outlines the creation of an `agent_skill_prices` table that will link skills to their price and currency.
-
-## Instructions
-1. **Define the Schema:**
- * Create a new table named `agent_skill_prices`.
- * The table should include the following columns:
- * `id`: Primary key (e.g., UUID or auto-incrementing integer).
- * `agent_id`: Foreign key referencing the `agents` table.
- * `skill_name`: The name of the skill (e.g., "super-jump"). This should match the skill name defined in the agent's configuration.
- * `amount`: The price of the skill in the smallest unit of the currency (e.g., lamports for SOL, or the base unit for USDC). Use a data type that can handle large numbers (e.g., `BIGINT` or `NUMERIC`).
- * `currency_mint`: The mint address of the SPL token used for payment (e.g., the USDC mint address).
- * `created_at`, `updated_at`: Timestamps for record management.
-
-2. **Write the SQL Migration:**
- * Create a new SQL migration file to apply this schema change to the database.
- * Include `CREATE TABLE` and `CREATE INDEX` statements. It's recommended to create an index on `(agent_id, skill_name)` for quick lookups.
-
-## SQL Example (PostgreSQL)
-```sql
--- migration-002-create-agent-skill-prices.sql
-
-CREATE TABLE agent_skill_prices (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
- skill_name VARCHAR(255) NOT NULL,
- amount BIGINT NOT NULL,
- currency_mint VARCHAR(255) NOT NULL,
- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
-);
-
-CREATE UNIQUE INDEX idx_agent_skill_prices_on_agent_and_skill
-ON agent_skill_prices (agent_id, skill_name);
-
-COMMENT ON COLUMN agent_skill_prices.amount IS 'Price in the smallest currency unit (e.g., lamports)';
-COMMENT ON COLUMN agent_skill_prices.currency_mint IS 'Mint address of the SPL token for 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/04-design-database-schema-for-skill-pricing.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/04-frontend-display-priced-skills.md b/prompts/monetization/04-frontend-display-priced-skills.md
deleted file mode 100644
index 5ccf2d16e..000000000
--- a/prompts/monetization/04-frontend-display-priced-skills.md
+++ /dev/null
@@ -1,98 +0,0 @@
----
-status: not-started
-completed_at: null
----
-# Prompt 4: Frontend UI for Displaying Priced Skills
-
-## Objective
-Modify the agent detail page in the marketplace to visually distinguish between free and paid skills, and display the price for paid skills.
-
-## Explanation
-Currently, the agent detail page lists all skills uniformly. To begin building our monetization feature, users need to be able to see which skills are premium and how much they cost. This involves fetching pricing data along with agent details and updating the UI to render prices and a premium indicator.
-
-## Instructions
-1. **Locate the Frontend Code:**
- * In `src/marketplace.js`, find the `renderDetail` function. This function is responsible for rendering the agent's profile, including its list of skills.
-
-2. **Access Pricing Data:**
- * The `renderDetail` function receives the full agent object from the API. With the backend changes from Prompt #2, this object now includes a `skill_prices` map.
-
-3. **Update the Skill Rendering Logic:**
- * Inside the loop that renders the skills (likely targeting the `d-skills` element), check if a price exists for the current skill in the `skill_prices` object.
- * **If a price exists:** Render a price badge next to the skill name. The amount will be in the smallest unit of the currency (e.g., lamports or 10^-6 for USDC). Convert this to a human-readable format (e.g., `(price.amount / 1e6).toFixed(2)` for a 6-decimal USDC).
- * **If a price does not exist:** Render a "Free" badge to make the distinction clear.
- * Use different CSS classes for paid vs. free badges for distinct styling.
-
-4. **Add CSS for Badges:**
- * Open `/marketplace.css` and add the styles for the new price badges. Make them noticeable but not intrusive.
-
-## Code Example (Frontend - `src/marketplace.js`)
-
-Here's how you might modify the skill rendering part within the `renderDetail` function:
-
-```javascript
-// Inside renderDetail function, assuming 'a' is the agent object
-
-const skillPrices = a.skill_prices || {};
-const skillsArr = a.skills || []; // Assuming skills is an array of strings or objects
-
-$('d-skills').innerHTML = skillsArr.length
- ? skillsArr.map((s) => {
- const name = typeof s === 'string' ? s : (s.name || '');
- if (!name) return ''; // Skip empty skills
-
- const price = skillPrices[name];
- const badge = price
- ? `<span class="price-badge price-paid">${(price.amount / 1e6).toFixed(2)} USDC</span>`
- : `<span class="price-badge price-free">Free</span>`;
-
- return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;
- }).join(' ')
- : '<div>This Agent has no skills defined.</div>';
-```
-
-## CSS Example (`/marketplace.css`)
-
-```css
-.price-badge {
- display: inline-block;
- margin-left: 8px;
- padding: 2px 6px;
- font-size: 10px;
- font-weight: 600;
- border-radius: 4px;
- vertical-align: middle;
- text-transform: uppercase;
-}
-
-.price-free {
- color: #a7f3d0; /* A light green */
- background-color: rgba(52, 211, 153, 0.1);
-}
-
-.price-paid {
- color: #fde047; /* A light yellow/gold */
- background-color: rgba(253, 224, 71, 0.1);
-}
-```
-
-## Definition of Done
-- The agent detail page in the marketplace now displays badges next to each skill.
-- Paid skills show the price in a human-readable format (e.g., "1.00 USDC").
-- Free skills show a "Free" badge.
-- The badges are styled according to the CSS example and look professional.
-- The page handles agents with no skills or a mix of free and paid skills without errors.
-
-<!-- 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/04-frontend-display-priced-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/04-frontend-skill-pricing-ui.md b/prompts/monetization/04-frontend-skill-pricing-ui.md
deleted file mode 100644
index 81ec16d3f..000000000
--- a/prompts/monetization/04-frontend-skill-pricing-ui.md
+++ /dev/null
@@ -1,134 +0,0 @@
----
-status: not-started
----
-
-# Prompt 4: Frontend - Skill Pricing UI in Agent Editor
-
-## Objective
-Build a user interface within the agent editor page (`agent-edit.html`) that allows creators to view, add, and update prices for their agent's skills.
-
-## Explanation
-To make the new pricing API useful, creators need a friendly UI. This task involves adding a new section to the agent editor page. This section will list all of the agent's available skills and provide input fields for creators to set a price and currency for each one. The UI will then call the API endpoint created in the previous step to save the changes.
-
-## Instructions
-1. **Locate the Agent Editor File:**
- * Open the `agent-edit.html` file and its corresponding JavaScript file (e.g., `src/agent-edit.js`).
-
-2. **Design the UI:**
- * In `agent-edit.html`, add a new section titled "Skill Monetization" or "Skill Pricing".
- * This section should dynamically render a list of the agent's skills.
- * For each skill, display:
- * The skill name (read-only).
- * An input field for the price (`amount`).
- * A dropdown or input field for the `currency_mint` (for now, you can default this to USDC's mint address).
- * A "Save" or "Update" button for each skill, or a single "Save All Prices" button for the section.
-
-3. **Implement the Frontend Logic:**
- * In `src/agent-edit.js`, when the agent data is loaded, populate the new UI section. You'll need to fetch the existing skill prices along with the agent details.
- * Attach an event listener to the "Save" button(s).
- * When a creator clicks "Save", gather the `skill_name`, `amount`, and `currency_mint` from the input fields.
- * **Important:** The amount in the UI will be in a human-readable format (e.g., 1.00 USDC), but the API expects lamports. You must convert the UI value to the smallest unit before sending it to the API (e.g., `parseFloat(amountInput.value) * 1e6`).
- * Make a `POST` request to the `/api/agents/[agentId]/skills/prices` endpoint with the data in the request body.
- * Provide user feedback, such as a toast notification ("Price updated successfully!") or by changing the state of the save button (e.g., showing a checkmark).
- * Handle any errors returned from the API and display a helpful message to the user.
-
-## Code Example (HTML in `agent-edit.html`)
-
-```html
-<!-- Inside the agent editor form -->
-<div class="form-section">
- <h3>Skill Pricing</h3>
- <p class="form-section-desc">
- Set prices for your agent's skills. Payments will be handled on Solana.
- </p>
- <div id="skill-pricing-list">
- <!-- Skills will be dynamically rendered here -->
- </div>
-</div>
-```
-
-## Code Example (JavaScript in `src/agent-edit.js`)
-
-```javascript
-// Function to render the pricing UI
-function renderSkillPricing(agent) {
- const skills = agent.skills || []; // Assuming agent.skills is an array of skill objects/names
- const prices = agent.skill_prices || {};
- const container = document.getElementById('skill-pricing-list');
-
- container.innerHTML = skills.map(skill => {
- const skillName = typeof skill === 'string' ? skill : skill.name;
- const price = prices[skillName];
- const amountInUSDC = price ? (price.amount / 1e6).toFixed(2) : '0.00';
-
- return `
- <div class="skill-price-entry" data-skill-name="${escapeHtml(skillName)}">
- <label>${escapeHtml(skillName)}</label>
- <div class="price-inputs">
- <input type="number" step="0.01" min="0" value="${amountInUSDC}" class="price-amount-input">
- <select class="price-currency-select">
- <option value="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6T">USDC</option>
- </select>
- <button class="btn-save-price">Save</button>
- </div>
- </div>
- `;
- }).join('');
-
- // Add event listeners to all save buttons
- container.querySelectorAll('.btn-save-price').forEach(button => {
- button.addEventListener('click', handleSavePrice);
- });
-}
-
-// Event handler for saving a price
-async function handleSavePrice(event) {
- const entry = event.target.closest('.skill-price-entry');
- const skillName = entry.dataset.skillName;
- const amountInput = entry.querySelector('.price-amount-input');
- const currencySelect = entry.querySelector('.price-currency-select');
-
- const amountInUSDC = parseFloat(amountInput.value);
- if (isNaN(amountInUSDC) || amountInUSDC < 0) {
- showToast('Invalid amount', 'error');
- return;
- }
-
- const payload = {
- skill_name: skillName,
- amount: Math.round(amountInUSDC * 1e6), // Convert to lamports
- currency_mint: currencySelect.value
- };
-
- try {
- const response = await fetch(`/api/agents/${currentAgentId}/skills/prices`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json', /* ...auth headers */ },
- body: JSON.stringify(payload)
- });
-
- if (!response.ok) {
- const { error } = await response.json();
- throw new Error(error || 'Failed to save price');
- }
-
- showToast(`${skillName} price updated!`, 'success');
- } catch (err) {
- showToast(err.message, '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/04-frontend-skill-pricing-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/04-premium-indicator-marketplace.md b/prompts/monetization/04-premium-indicator-marketplace.md
deleted file mode 100644
index a3662c7cf..000000000
--- a/prompts/monetization/04-premium-indicator-marketplace.md
+++ /dev/null
@@ -1,100 +0,0 @@
----
-status: not-started
----
-
-# Prompt 4: Premium Indicator in Marketplace
-
-## Objective
-Add a "Premium" indicator or tag to agents that have at least one paid skill in the main marketplace list view.
-
-## Explanation
-To help users quickly identify monetized agents, we need a visual cue on the main marketplace page (`marketplace.html`). This makes premium agents stand out and signals that they offer advanced, paid functionality.
-
-## Instructions
-1. **Modify the Backend API:**
- * Locate the API endpoint that serves the list of agents for the marketplace (e.g., `/api/marketplace/agents`).
- * The query should be modified to check if each agent has any associated entries in the `agent_skill_prices` table.
- * A simple way is to use a `LEFT JOIN` and a `COUNT` or an `EXISTS` subquery.
- * The API response for each agent object should now include a boolean flag, e.g., `has_paid_skills: true`.
-
-2. **Update the Frontend UI:**
- * In the JavaScript file for the marketplace, locate the function that renders the list or grid of agent cards.
- * When iterating through the agents, check for the `has_paid_skills` flag.
- * If `true`, add a "Premium" badge or icon to the agent's card template.
-
-## Code Example (Backend - SQL Query)
-
-A possible SQL modification to get the flag:
-
-```sql
-SELECT
- agents.*,
- EXISTS (
- SELECT 1
- FROM agent_skill_prices
- WHERE agent_skill_prices.agent_id = agents.id
- ) AS has_paid_skills
-FROM
- agents
--- ... add your WHERE clauses, LIMIT, OFFSET etc.
-```
-
-## Code Example (Frontend - Agent Card Rendering)
-
-```javascript
-// Inside the function that renders multiple agent cards
-function renderAgentCard(agent) {
- const premiumBadge = agent.has_paid_skills
- ? `<span class="premium-badge">💎 Premium</span>`
- : '';
-
- return `
- <div class="agent-card">
- <div class="card-header">
- <span class="agent-name">${escapeHtml(agent.name)}</span>
- ${premiumBadge}
- </div>
- <div class="agent-description">${escapeHtml(agent.description)}</div>
- // ... rest of the card
- </div>
- `;
-}
-```
-
-## CSS Example
-
-Add these styles to the marketplace CSS file.
-
-```css
-.premium-badge {
- display: inline-block;
- margin-left: auto; /* Pushes it to the right in a flex container */
- padding: 3px 8px;
- font-size: 10px;
- font-weight: 700;
- border-radius: 99px;
- color: #facc15; /* A gold/yellow color */
- background-color: rgba(250, 204, 21, 0.1);
- border: 1px solid rgba(250, 204, 21, 0.2);
-}
-
-.card-header {
- display: flex;
- align-items: center;
- justify-content: space-between;
-}
-```
-
-<!-- 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/04-premium-indicator-marketplace.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/04-solana-pay-frontend-qr.md b/prompts/monetization/04-solana-pay-frontend-qr.md
deleted file mode 100644
index 12364d3db..000000000
--- a/prompts/monetization/04-solana-pay-frontend-qr.md
+++ /dev/null
@@ -1,113 +0,0 @@
-# Prompt 4: Solana Pay QR Code (Frontend)
-
-## Objective
-Integrate the frontend with the new payment endpoint to display a Solana Pay QR code when a user clicks the "Purchase" button.
-
-## Explanation
-With the backend endpoint ready to generate transactions, we need to update the frontend to request this transaction and display it as a QR code. This allows users to scan the code with their mobile Solana wallet to approve the purchase. We'll use the official `@solana/pay` JavaScript library to generate the QR code.
-
-## Instructions
-1. **Add Frontend Dependency:**
- * Add the `@solana/pay` library to your frontend `package.json` and install it.
-
-2. **Create a Payment Modal:**
- * In `marketplace.html` (or your main HTML file), create the HTML structure for a modal dialog. This modal will be hidden by default and will contain the QR code, transaction details, and a spinner.
-
-3. **Implement the Frontend Logic (`src/marketplace.js`):**
- * Add a delegated event listener to the page that listens for clicks on buttons with the `purchase-skill-btn` class.
- * When a button is clicked:
- * Show the payment modal and a loading spinner.
- * Get the `skillName` and `agentId` from data attributes.
- * Make a `POST` request to your `/api/payments/prepare-skill-purchase` endpoint.
- * On success, use the `createQR` function from `@solana/pay` to generate the QR code from the transaction URL.
- * Mount the QR code SVG element into the modal. Hide the spinner.
- * Display the transaction message and amount.
- * Handle any errors from the API call by showing an error message in the modal.
-
-## Code Example (`src/marketplace.js`)
-
-```javascript
-import { createQR } from '@solana/pay';
-
-// ... other imports
-
-function renderPaymentModal(url) {
- const modal = $('payment-modal'); // Assuming you have a modal element
- const qrCodeContainer = modal.querySelector('.qr-code-container');
- const spinner = modal.querySelector('.spinner');
-
- qrCodeContainer.innerHTML = '';
- spinner.hidden = true;
-
- const qr = createQR(url, 300, 'transparent'); // size, background color
- qr.append(qrCodeContainer);
-
- modal.showModal(); // Using <dialog> element's API
-}
-
-async function handlePurchaseClick(event) {
- const button = event.target.closest('.purchase-skill-btn');
- if (!button) return;
-
- const skillName = button.dataset.skillName;
- const agentId = $('d-id').textContent; // Assuming agent ID is available
-
- const modal = $('payment-modal');
- modal.querySelector('.spinner').hidden = false;
- modal.showModal();
-
- try {
- const response = await fetch('/api/payments/prepare-skill-purchase', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ agentId, skillName }),
- });
-
- if (!response.ok) {
- throw new Error(`API Error: ${response.statusText}`);
- }
-
- const { transaction, message } = await response.json();
-
- // The Solana Pay URL is constructed from the API response
- const url = `solana:${encodeURIComponent(transaction)}`;
-
- renderPaymentModal(url, message);
-
- } catch (error) {
- console.error('Purchase failed:', error);
- modal.querySelector('.error-message').textContent = 'Failed to prepare transaction. Please try again.';
- modal.querySelector('.spinner').hidden = true;
- }
-}
-
-document.body.addEventListener('click', handlePurchaseClick);
-```
-
-## HTML Modal Example
-
-```html
-<!-- Add this to your main HTML file -->
-<dialog id="payment-modal">
- <h2>Complete Your Purchase</h2>
- <div class="spinner"></div>
- <div class="qr-code-container"></div>
- <p class="payment-message"></p>
- <p class="error-message"></p>
- <button class="close-modal-btn">Close</button>
-</dialog>
-```
-
-<!-- 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/04-solana-pay-frontend-qr.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/04-wallet-connection.md b/prompts/monetization/04-wallet-connection.md
deleted file mode 100644
index ea5ff659a..000000000
--- a/prompts/monetization/04-wallet-connection.md
+++ /dev/null
@@ -1,98 +0,0 @@
----
-status: not-started
----
-
-# Prompt 4: Wallet Connection
-
-## Objective
-Integrate a Solana wallet adapter to allow users to connect their wallets, a prerequisite for making payments.
-
-## Explanation
-To purchase skills, users will need to connect their Solana wallet (like Phantom or Solflare). We will use the official Solana wallet-adapter library to handle the complexities of wallet detection and connection. The connection button will be placed inside the purchase modal.
-
-## Instructions
-- [ ] **Add Solana Wallet-Adapter Dependencies:**
- - [ ] Add the necessary Solana wallet-adapter packages to your `package.json`. You'll need `@solana/wallet-adapter-base`, `@solana/wallet-adapter-react` (or a vanilla JS equivalent if not using a framework), and adapters for specific wallets like `@solana/wallet-adapter-wallets`. For a vanilla JS project, you may need to use a CDN version or bundle it.
-- [ ] **Integrate Wallet-Adapter:**
- - [ ] In `src/marketplace.js`, initialize the wallet adapter.
- - [ ] Create a `connectWallet` function. This function will be responsible for presenting the user with a list of available wallets and handling the connection logic.
-- [ ] **Add Connect Button to UI:**
- - [ ] In the purchase modal, instead of a simple "Confirm" button, we'll now have a "Connect Wallet" button if the user's wallet is not already connected.
- - [ ] Display the user's public key (wallet address) once connected, and change the button to "Proceed to Payment".
-
-## Code Example (`src/marketplace.js`)
-
-This example assumes you're able to import or include the wallet-adapter libraries. For simplicity, we'll use psuedo-code for the adapter initialization.
-
-```javascript
-// Assume walletAdapter is initialized somewhere in your app's entry point.
-// This is a simplified example. Refer to wallet-adapter docs for full setup.
-
-let connectedWallet = null;
-
-async function connectWallet() {
- try {
- // This would typically open the wallet adapter's modal
- const wallet = await walletAdapter.connect();
- connectedWallet = wallet;
- console.log('Wallet connected:', wallet.publicKey.toBase58());
- updateModalAfterConnect();
- } catch (error) {
- console.error('Failed to connect wallet:', error);
- // Show an error to the user
- }
-}
-
-function updateModalAfterConnect() {
- const walletAddress = connectedWallet.publicKey.toBase58();
- const truncatedAddress = `${walletAddress.slice(0, 4)}...${walletAddress.slice(-4)}`;
-
- // Update the modal body to show connected status
- const modalBody = $('modal-body');
- modalBody.innerHTML = `
- <p>Wallet Connected: <strong>${truncatedAddress}</strong></p>
- <button id="proceed-to-payment-btn">Proceed to Payment</button>
- `;
-}
-
-// In your event listener for showing the modal:
-function showPurchaseModal(skillName) {
- let content = '';
- if (connectedWallet) {
- content = `
- <p>You are purchasing "${skillName}". Your wallet is connected.</p>
- <button id="proceed-to-payment-btn">Proceed to Payment</button>
- `;
- } else {
- content = `
- <p>You need to connect your wallet to purchase "${skillName}".</p>
- <button id="connect-wallet-btn">Connect Wallet</button>
- `;
- }
- showModal(`Purchase Skill: ${skillName}`, content);
-}
-
-// Add event listener for the new buttons inside the modal
-$('modal-body').addEventListener('click', (e) => {
- if (e.target.id === 'connect-wallet-btn') {
- connectWallet();
- }
- if (e.target.id === 'proceed-to-payment-btn') {
- // Next step: initiate the 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/04-wallet-connection.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/04_api_for_saving_prices.md b/prompts/monetization/04_api_for_saving_prices.md
deleted file mode 100644
index baa2dab82..000000000
--- a/prompts/monetization/04_api_for_saving_prices.md
+++ /dev/null
@@ -1,88 +0,0 @@
----
-status: not-started
-last_updated: 2026-05-04
----
-# Prompt 04: API for Saving Skill Prices
-
-## Objective
-Create a secure backend API endpoint for agent creators to save or update the prices for their skills.
-
-## Explanation
-The UI for setting skill prices needs a backend endpoint to persist the data. This endpoint must be secure, ensuring that only the owner of an agent can modify its skill prices. It will receive a payload of skill prices, validate it, and update the `agent_skill_prices` table.
-
-## Instructions
-1. **Create the API File:**
- * Create a new API file, for example, `api/agents/skill-prices.js` or add a new action to an existing agent-related dispatcher. The route could be `POST /api/agents/:id/skill-prices`.
-
-2. **Implement the Endpoint Logic:**
- * **Authentication:** The endpoint must first authenticate the user and retrieve their ID.
- * **Authorization:** It must verify that the authenticated user is the owner of the agent specified in the URL (`:id`).
- * **Validation:** It should validate the incoming payload. The payload should be a JSON object where keys are skill names and values are objects containing `amount` and `currency_mint`. Use a library like `zod` for robust validation.
- * **Database Operation:** For each skill price in the payload, perform an "upsert" operation on the `agent_skill_prices` table. If a price for that agent and skill already exists, update it. If not, insert a new row. This is a perfect use case for PostgreSQL's `ON CONFLICT` clause.
-
-## Code Example (Vercel Serverless Function)
-
-```javascript
-// Example in: /api/agents/[agentId]/skill-prices.js
-import { z } from 'zod';
-import { sql } from '../../_lib/db.js';
-import { getSessionUser } from '../../_lib/auth.js';
-import { error, json, wrap } from '../../_lib/http.js';
-import { parse } from '../../_lib/validate.js';
-
-// Define the schema for a single price entry
-const PriceSchema = z.object({
- amount: z.number().int().positive(),
- currency_mint: z.string().min(32).max(44), // Solana public key validation
-});
-
-// The incoming body should be a map of skill names to price objects
-const BodySchema = z.record(z.string(), PriceSchema);
-
-export default wrap(async (req, res) => {
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized');
-
- const agentId = req.query.agentId;
- const rawBody = await req.json();
- const pricesToUpdate = parse(BodySchema, rawBody);
-
- // 1. Verify ownership of the agent
- const [agent] = await sql`
- SELECT id FROM agent_identities
- WHERE id = ${agentId} AND user_id = ${user.id} AND deleted_at IS NULL
- `;
- if (!agent) return error(res, 404, 'not_found', 'Agent not found or you do not have permission.');
-
- // 2. Perform the upsert operation for all prices in a single transaction
- await sql.begin(async sql => {
- for (const [skillName, price] of Object.entries(pricesToUpdate)) {
- await sql`
- INSERT INTO agent_skill_prices (agent_id, skill_name, amount, currency_mint)
- VALUES (${agentId}, ${skillName}, ${price.amount}, ${price.currency_mint})
- ON CONFLICT (agent_id, skill_name)
- DO UPDATE SET
- amount = EXCLUDED.amount,
- currency_mint = EXCLUDED.currency_mint,
- updated_at = NOW();
- `;
- }
- });
-
- return json(res, 200, { success: true, message: 'Skill prices updated.' });
-});
-```
-
-<!-- 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/04_api_for_saving_prices.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/05-create-purchase-skill-button.md b/prompts/monetization/05-create-purchase-skill-button.md
deleted file mode 100644
index 317c3a448..000000000
--- a/prompts/monetization/05-create-purchase-skill-button.md
+++ /dev/null
@@ -1,112 +0,0 @@
-# Prompt 5: Create "Purchase Skill" Button
-
-## Status
-- [ ] Not Started
-
-## Objective
-Add a "Purchase" button for priced skills on the agent detail page and a modal to confirm the purchase.
-
-## Explanation
-With the front-end now able to display skill prices, the next step is to provide users with a clear call-to-action to initiate a purchase. This prompt covers adding the button and a confirmation modal.
-
-## Instructions
-1. **Modify the Skill Rendering Logic:**
- * In `src/marketplace.js` within the `renderDetail` function, update the skill rendering logic.
- * For skills that have a price, instead of just a badge, render a "Purchase" button.
- * The button should include `data-` attributes to store the skill name, price, and currency mint, which will be needed to initiate the transaction.
-
-2. **Create a Purchase Confirmation Modal:**
- * Add a hidden modal to your main HTML (`app.html` or `marketplace.html`).
- * The modal should display the details of the skill being purchased (name, price) and include "Confirm" and "Cancel" buttons.
-
-3. **Implement Button Logic:**
- * Add a click event listener to the "Purchase" buttons.
- * When a button is clicked, read the `data-` attributes and populate the confirmation modal with the correct information, then display the modal.
-
-## Code Example (Frontend - `src/marketplace.js`)
-```javascript
-// Inside renderDetail function
-const skillPrices = a.skill_prices || {};
-$('d-skills').innerHTML = skillsArr.length
- ? skillsArr.map((s) => {
- const name = typeof s === 'string' ? s : (s.name || '');
- const price = skillPrices[name];
- let actionElement;
- if (price) {
- const priceDisplay = `${(price.amount / 1e6).toFixed(2)} USDC`;
- actionElement = `<button class="purchase-skill-btn"
- data-skill-name="${escapeHtml(name)}"
- data-price-amount="${price.amount}"
- data-currency-mint="${price.currency_mint}">
- Purchase for ${priceDisplay}
- </button>`;
- } else {
- actionElement = `<span class="price-badge price-free">Free</span>`;
- }
- return `<div class="skill-entry">
- <span>${escapeHtml(name)}</span>
- ${actionElement}
- </div>`;
- }).join('')
- : '<div>This Agent has no skills defined.</div>';
-
-// Add event listeners after rendering
-document.querySelectorAll('.purchase-skill-btn').forEach(button => {
- button.addEventListener('click', handlePurchaseClick);
-});
-```
-
-## Code Example (HTML for Modal)
-```html
-<!-- Add to app.html or marketplace.html -->
-<div id="purchase-confirm-modal" class="modal-hidden">
- <div class="modal-content">
- <h2>Confirm Purchase</h2>
- <p>You are about to purchase the skill: <b id="modal-skill-name"></b></p>
- <p>Price: <b id="modal-skill-price"></b></p>
- <div class="modal-actions">
- <button id="modal-confirm-btn">Confirm</button>
- <button id="modal-cancel-btn">Cancel</button>
- </div>
- </div>
-</div>
-```
-
-## Code Example (Event Handling)
-```javascript
-function handlePurchaseClick(event) {
- const button = event.currentTarget;
- const skillName = button.dataset.skillName;
- const priceAmount = button.dataset.priceAmount;
- const currencyMint = button.dataset.currencyMint;
-
- // Populate and show the modal
- document.getElementById('modal-skill-name').textContent = skillName;
- document.getElementById('modal-skill-price').textContent = `${(priceAmount / 1e6).toFixed(2)} USDC`;
- document.getElementById('purchase-confirm-modal').classList.remove('modal-hidden');
-
- // Store data for the transaction
- document.getElementById('modal-confirm-btn').dataset.skillData = JSON.stringify({
- skillName, priceAmount, currencyMint
- });
-}
-
-// Add event listener for the cancel button to hide the modal
-document.getElementById('modal-cancel-btn').addEventListener('click', () => {
- document.getElementById('purchase-confirm-modal').classList.add('modal-hidden');
-});
-```
-
-<!-- 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/05-create-purchase-skill-button.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/05-creator-ui-for-pricing.md b/prompts/monetization/05-creator-ui-for-pricing.md
deleted file mode 100644
index f8e80a997..000000000
--- a/prompts/monetization/05-creator-ui-for-pricing.md
+++ /dev/null
@@ -1,111 +0,0 @@
----
-status: not-started
-completed_at: null
----
-# Prompt 5: Creator Dashboard UI for Pricing Skills
-
-## Objective
-Create a user interface in the Creator Dashboard that allows an agent creator to view their agent's skills and set prices for them.
-
-## Explanation
-To enable creators to monetize their work, they need a simple and intuitive interface. This task involves building a new section in the agent editing page of the Creator Dashboard. This section will list all of the agent's skills and provide input fields for creators to set a price for each one. The interface will use the API created in Prompt #3 to save these prices.
-
-## Instructions
-1. **Locate the Creator Dashboard Page:**
- * Find the HTML file for the agent editor in the Creator Dashboard (e.g., `agent-edit.html`).
-
-2. **Create the Skill Pricing Section:**
- * Add a new section to the page titled "Skill Monetization" or "Skill Pricing".
- * This section should only be visible to the agent's owner.
- * Fetch the agent's details, including their list of skills and any existing `skill_prices`.
-
-3. **Render the Skill List:**
- * Iterate through the agent's skills. For each skill, render:
- * The skill name (read-only).
- * An input field for the `amount`.
- * A dropdown/select for the `currency_mint` (initially, this can be hardcoded to just show USDC, but it should be designed to be extensible).
- * A "Save" or "Update" button for each skill.
- * A "Make Free" or "Remove Price" button.
-
-4. **Implement the API Interaction:**
- * When the creator clicks "Save", make a `POST` request to the `/api/creator/agents/:agentId/skills/price` endpoint.
- * The request body should include the `skill_name`, `amount` (converted to the smallest unit), and `currency_mint`.
- * When the "Make Free" button is clicked, make a similar `POST` request, but set the `amount` to `0` or `null`.
- * Provide feedback to the user on success (e.g., a "Saved!" message) or failure (e.g., an error message).
- * Use a debounce on the input fields to prevent excessive API calls if you choose to save on input change.
-
-## UI Mockup Idea
-
-```
-+------------------------------------------------------+
-| Skill Pricing |
-+------------------------------------------------------+
-| |
-| translate [ 1.00 ] [ USDC ▼ ] [ Save ] |
-| |
-| summarize-document [ 0.00 ] [ USDC ▼ ] [ Set Price ] |
-| |
-| generate-image [ 5.00 ] [ USDC ▼ ] [ Save ] [ Make Free ] |
-| |
-+------------------------------------------------------+
-```
-
-## Code Example (Frontend JavaScript)
-
-```javascript
-// This is a conceptual example for the event handling
-
-async function saveSkillPrice(agentId, skillName, amount, currency) {
- // Note: Convert amount to smallest unit, e.g., amount * 1e6 for USDC
- const amountInSmallestUnit = Math.round(parseFloat(amount) * 1e6);
-
- const response = await fetch(`/api/creator/agents/${agentId}/skills/price`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- skill_name: skillName,
- amount: amountInSmallestUnit,
- currency_mint: currency,
- }),
- });
-
- if (response.ok) {
- // Show success feedback
- console.log(`Price for ${skillName} saved successfully!`);
- } else {
- // Show error feedback
- const err = await response.json();
- console.error(`Failed to save price:`, err.error);
- }
-}
-
-// Attach this function to the 'click' event of the save buttons
-// e.g., saveButton.addEventListener('click', () => {
-// const amount = amountInput.value;
-// const currency = currencySelect.value;
-// saveSkillPrice('agent-123', 'translate', amount, currency);
-// });
-```
-
-## Definition of Done
-- A new "Skill Pricing" section is visible on the agent editing page for agent owners.
-- The section lists all the agent's skills.
-- Each skill has corresponding input fields for price and currency.
-- The "Save" button correctly calls the API to set/update the price.
-- The "Make Free" button correctly calls the API to remove the price.
-- The UI provides clear feedback to the user upon success or failure of the operation.
-- Existing prices are correctly populated into the input fields when the page loads.
-
-<!-- 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/05-creator-ui-for-pricing.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/05-filter-marketplace-price.md b/prompts/monetization/05-filter-marketplace-price.md
deleted file mode 100644
index 5c37af59e..000000000
--- a/prompts/monetization/05-filter-marketplace-price.md
+++ /dev/null
@@ -1,98 +0,0 @@
----
-status: not-started
----
-
-# Prompt 5: Filter Marketplace by Price
-
-## Objective
-Implement a filter control in the marketplace UI to allow users to view "All", "Free", or "Paid" agents.
-
-## Explanation
-Adding a filter enhances user experience by allowing them to narrow down the agent list based on their interest in free or premium offerings. This requires a small UI addition and logic to re-fetch the agent list with the selected filter.
-
-## Instructions
-1. **Update the Frontend UI (`marketplace.html`):**
- * Add a set of filter buttons or a dropdown menu to the marketplace page, typically above the agent list.
- * The options should be "All", "Free", and "Paid".
-
-2. **Update the Backend API:**
- * Modify the marketplace agent list endpoint (e.g., `/api/marketplace/agents`) to accept a query parameter, such as `pricing`.
- * The backend should interpret `pricing=free`, `pricing=paid`, or no parameter (for "all").
- * If `pricing=free`, the query should be adjusted to only return agents that do NOT have any entries in `agent_skill_prices`.
- * If `pricing=paid`, the query should only return agents that HAVE at least one entry in `agent_skill_prices`.
-
-3. **Update Frontend JavaScript:**
- * Add event listeners to the new filter controls.
- * When a filter is selected, store the chosen value (e.g., 'free', 'paid').
- * Trigger a function to re-fetch the agent list from the API, appending the new query parameter (e.g., `?pricing=paid`).
- * The existing rendering logic should then automatically display the filtered list.
- * Remember to handle pagination correctly if it's implemented.
-
-## Code Example (HTML)
-
-```html
-<div class="marketplace-filters">
- <button class="filter-btn active" data-filter="all">All</button>
- <button class="filter-btn" data-filter="free">Free</button>
- <button class="filter-btn" data-filter="paid">Paid</button>
-</div>
-```
-
-## Code Example (Frontend JavaScript)
-
-```javascript
-let currentPriceFilter = 'all';
-
-document.querySelector('.marketplace-filters').addEventListener('click', (e) => {
- if (e.target.classList.contains('filter-btn')) {
- document.querySelectorAll('.filter-btn').forEach(btn => btn.classList.remove('active'));
- e.target.classList.add('active');
- currentPriceFilter = e.target.dataset.filter;
- fetchAndRenderAgents(); // Your main function to get and display agents
- }
-});
-
-async function fetchAndRenderAgents(page = 1) {
- let apiUrl = `/api/marketplace/agents?page=${page}`;
- if (currentPriceFilter !== 'all') {
- apiUrl += `&pricing=${currentPriceFilter}`;
- }
- // ... rest of the fetch and render logic
-}
-```
-
-## Code Example (Backend - SQL Query Modification)
-
-This demonstrates how to adjust the SQL query based on the filter.
-
-```sql
--- Base Query
-let query = `
- SELECT agents.*, EXISTS (...) AS has_paid_skills
- FROM agents
-`;
-
-// Filtering logic
-if (req.query.pricing === 'paid') {
- query += ` WHERE EXISTS (SELECT 1 FROM agent_skill_prices p WHERE p.agent_id = agents.id)`;
-} else if (req.query.pricing === 'free') {
- query += ` WHERE NOT EXISTS (SELECT 1 FROM agent_skill_prices p WHERE p.agent_id = agents.id)`;
-}
-
-// Add ordering, limit, offset, etc.
-// ...
-```
-
-<!-- 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/05-filter-marketplace-price.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/05-frontend-transaction-signing.md b/prompts/monetization/05-frontend-transaction-signing.md
deleted file mode 100644
index c3b107d4c..000000000
--- a/prompts/monetization/05-frontend-transaction-signing.md
+++ /dev/null
@@ -1,82 +0,0 @@
-# Prompt 5: Frontend Transaction Signing
-
-## Objective
-Implement the frontend logic to take the serialized transaction from the backend, have the user sign it with their connected wallet, and send it to the Solana network.
-
-## Explanation
-This is the crucial step where the user approves the purchase. The frontend receives the base64-encoded transaction from the backend purchase endpoint. It then needs to decode it, present it to the user's wallet for signing, and upon approval, submit the signed transaction to the blockchain for confirmation.
-
-## Instructions
-1. **Add Frontend API Call:**
- * In `src/marketplace.js`, within the event handler for the "Buy Now" button in the purchase modal, make a `fetch` POST request to your new `/api/marketplace/skills/purchase` endpoint.
- * Send the `agentId`, `skillName`, and the connected user's public key in the request body.
-
-2. **Sign and Send Transaction:**
- * On a successful response from the API, you will receive the serialized transaction.
- * You need to deserialize it, request the user's wallet to sign it, and then send the raw, signed transaction to the Solana network.
-
-## Code Example (`src/marketplace.js`)
-
-```javascript
-import { Connection, Transaction, clusterApiUrl } from '@solana/web3.js';
-
-// Inside the confirmPurchaseBtn click listener
-confirmPurchaseBtn.addEventListener('click', async () => {
- const skillName = confirmPurchaseBtn.dataset.skillName;
- // Assume `agent` and `walletPublicKey` are available in this scope
- const agentId = agent.id;
- const purchaserPublicKey = walletPublicKey.toBase58();
-
- try {
- // 1. Get transaction from the backend
- const response = await fetch('/api/marketplace/skills/purchase', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ agentId, skillName, purchaserPublicKey }),
- });
-
- if (!response.ok) {
- const errData = await response.json();
- throw new Error(errData.error || 'Failed to prepare transaction.');
- }
-
- const { transaction: base64Transaction } = await response.json();
-
- // 2. Deserialize, sign, and send
- const provider = getProvider(); // The wallet provider from prompt 2
- const connection = new Connection(clusterApiUrl('devnet'));
-
- const transaction = Transaction.from(Buffer.from(base64Transaction, 'base64'));
-
- // 3. Request user to sign
- const { signature } = await provider.signAndSendTransaction(transaction, connection);
-
- // 4. Confirm transaction
- await connection.confirmTransaction(signature, 'confirmed');
-
- alert(`Purchase successful! Transaction: ${signature}`);
-
- // Next step: Call another backend endpoint to formally unlock the skill
- // This will be covered in another prompt.
- closePurchaseModal();
-
- } catch (error) {
- console.error('Purchase failed:', error);
- alert(`Purchase failed: ${error.message}`);
- }
-});
-```
-
-<!-- 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/05-frontend-transaction-signing.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/05-initiate-payment-api.md b/prompts/monetization/05-initiate-payment-api.md
deleted file mode 100644
index 376569cfd..000000000
--- a/prompts/monetization/05-initiate-payment-api.md
+++ /dev/null
@@ -1,98 +0,0 @@
----
-status: not-started
----
-
-# Prompt 5: Initiate Payment API
-
-## Objective
-Create a backend endpoint that prepares a Solana transaction for a skill purchase and sends it to the frontend.
-
-## Explanation
-For security and reliability, the transaction should be constructed on the backend. The frontend will request a transaction for a specific skill. The backend will look up the skill's price, the creator's payout address, and the platform's fee address, then create an unsigned transaction and send it back to the frontend. The frontend's only job is to get it signed by the user's wallet.
-
-## Instructions
-- [ ] **Create the API Endpoint:**
- - [ ] Create a new API file, e.g., `api/payments/initiate.js`.
- - [ ] This endpoint should accept a `skill_name` and `agent_id` in the request body.
-- [ ] **Implement Transaction Logic:**
- - [ ] The endpoint needs to perform several lookups:
- - [ ] The skill's price from `agent_skill_prices`.
- - [ ] The agent creator's payout address.
- - [ ] The platform's fee/treasury address (this can be a constant for now).
- - [ ] Using the Solana SDK (`@solana/web3.js`), construct a transaction. This will likely be a simple SPL-token transfer (e.g., USDC) from the user to the creator, potentially with a second transfer for the platform fee.
- - [ ] Serialize the unsigned transaction and return it in the response, base64-encoded.
-
-## Code Example (Backend - `api/payments/initiate.js`)
-
-```javascript
-// This is a simplified example. You'll need error handling and more robust data fetching.
-import { Connection, PublicKey, SystemProgram, Transaction } from '@solana/web3.js';
-import { getTokenTransferInstruction } from 'your-token-utils'; // Helper for SPL token transfers
-
-export default async function handler(req, res) {
- if (req.method !== 'POST') {
- return res.status(405).end();
- }
-
- const { skillName, agentId, userWalletAddress } = req.body;
-
- // 1. Fetch skill price, creator payout address, etc. from your database
- const skillPrice = await db.getSkillPrice(agentId, skillName); // e.g., { amount: 1000000, mint: 'EPj...' }
- const creatorAddress = await db.getCreatorPayoutAddress(agentId);
- const platformFeeAddress = process.env.PLATFORM_FEE_WALLET;
- const platformFeeBps = 500; // 5%
-
- // 2. Create a new transaction
- const connection = new Connection(process.env.SOLANA_RPC_URL);
- const transaction = new Transaction({
- feePayer: new PublicKey(userWalletAddress),
- recentBlockhash: (await connection.getLatestBlockhash()).blockhash,
- });
-
- // 3. Calculate amounts
- const creatorAmount = skillPrice.amount * (1 - platformFeeBps / 10000);
- const platformAmount = skillPrice.amount - creatorAmount;
-
- // 4. Add transfer instructions (this part is complex for SPL tokens, pseudo-code shown)
- // You need to find the user's Associated Token Account (ATA) for the mint.
- const userTokenAccount = await findUserATA(userWalletAddress, skillPrice.mint);
-
- transaction.add(
- createTokenTransferInstruction(
- userTokenAccount,
- creatorAddress,
- userWalletAddress, // User is the owner of their ATA
- creatorAmount
- )
- );
- transaction.add(
- createTokenTransferInstruction(
- userTokenAccount,
- platformFeeAddress,
- userWalletAddress,
- platformAmount
- )
- );
-
- // 5. Serialize and return
- const serializedTransaction = transaction.serialize({ requireAllSignatures: false });
-
- res.status(200).json({
- transaction: serializedTransaction.toString('base64'),
- });
-}
-```
-
-<!-- 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/05-initiate-payment-api.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/05-initiate-solana-transaction.md b/prompts/monetization/05-initiate-solana-transaction.md
deleted file mode 100644
index 324b7e22a..000000000
--- a/prompts/monetization/05-initiate-solana-transaction.md
+++ /dev/null
@@ -1,71 +0,0 @@
-# Prompt 5: Initiate Solana Transaction on Purchase
-
-## Objective
-Wire up the "Confirm Purchase" button in the modal to construct and request the user to sign a Solana transaction that transfers the specified amount to the creator's wallet.
-
-## Explanation
-This is where the user's action translates into an on-chain event. After connecting their wallet, clicking "Confirm" should prompt them, via their wallet extension, to approve a transaction that pays for the skill.
-
-## Instructions
-1. **Fetch Creator Wallet:**
- * The agent data from the backend must include the creator's public key (wallet address) where funds should be sent.
- * Modify the `/api/marketplace/agents/:id` endpoint to include `creator_wallet_address`.
-
-2. **Construct Transaction (`src/marketplace.js`):**
- * In the event listener for the `#modal-confirm-purchase` button:
- * Get the connected wallet object from the wallet adapter.
- * Fetch the skill price (amount) and the creator's wallet address.
- * Use `@solana/web3.js` to create a new `Transaction` object.
- * Add a `SystemProgram.transfer` instruction to the transaction, specifying the sender (user's public key), recipient (creator's public key), and amount in lamports.
-
-3. **Send and Confirm Transaction:**
- * Use the wallet adapter's `sendTransaction` method to send the transaction to the network.
- * Await the confirmation of the transaction.
- * Provide feedback to the user based on whether the transaction succeeds or fails.
-
-## Code Example (JavaScript - `src/marketplace.js`)
-```javascript
-import { Connection, SystemProgram, Transaction, PublicKey } from '@solana/web3.js';
-// Assume `wallet` is the connected wallet adapter object and `connection` is a Connection object.
-
-document.getElementById('modal-confirm-purchase').addEventListener('click', async () => {
- const agent = getCurrentAgentData();
- const skillName = document.getElementById('modal-skill-name').textContent;
- const price = agent.skill_prices[skillName];
-
- const recipient = new PublicKey(agent.creator_wallet_address);
- const lamports = price.amount;
-
- const transaction = new Transaction().add(
- SystemProgram.transfer({
- fromPubkey: wallet.publicKey,
- toPubkey: recipient,
- lamports: lamports,
- })
- );
-
- try {
- const signature = await wallet.sendTransaction(transaction, connection);
- await connection.confirmTransaction(signature, 'processed');
- console.log('Transaction successful with signature:', signature);
- // Next step: Mint an NFT to prove ownership.
- } catch (error) {
- console.error('Transaction failed:', error);
- // Show an error message to the user.
- }
-});
-```
-
-<!-- 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/05-initiate-solana-transaction.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/05-transaction-confirmation-backend.md b/prompts/monetization/05-transaction-confirmation-backend.md
deleted file mode 100644
index eaafbb026..000000000
--- a/prompts/monetization/05-transaction-confirmation-backend.md
+++ /dev/null
@@ -1,108 +0,0 @@
-# Prompt 5: Transaction Confirmation (Backend)
-
-## Objective
-Implement a backend mechanism to verify that a Solana Pay transaction has been successfully processed and confirmed on the blockchain.
-
-## Explanation
-After the user approves the transaction in their wallet, we need a reliable way to confirm its success on the backend. The Solana Pay spec provides a mechanism for this. The wallet will make a `GET` request to the same URL it used for the `POST`, and our backend should verify the transaction signature provided by the wallet.
-
-## Instructions
-1. **Modify the Payment Endpoint (`api/payments/prepare-skill-purchase.js`):**
- * Our endpoint needs to handle both `POST` (to create the transaction) and `GET` (to verify it).
- * **For the `POST` request:** When creating the transaction, you must associate it with a unique reference `PublicKey`. This reference key allows you to look up the transaction later. Generate a new keypair for each transaction: `const reference = new Keypair().publicKey;`. Add this reference to the `transfer` instruction. Store this reference in your database, linked to the user, skill, and agent.
- * **For the `GET` request:** The wallet will include the transaction `signature` in the query string. Your handler should:
- * Find the transaction on the blockchain using the `signature`.
- * Verify that the transaction was successful and contains the expected transfers (to the creator and the platform).
- * Crucially, verify that the transaction includes the `reference` public key you generated, proving it's for this specific purchase.
- * If everything checks out, proceed to the next step: granting the user access to the skill.
-
-## Code Example (Backend - `api/payments/prepare-skill-purchase.js`)
-
-This example shows the conceptual additions. You'll need to integrate this with your database logic.
-
-```javascript
-// ... imports including Keypair
-import { Keypair } from '@solana/web3.js';
-import { findTransaction, verifyTransaction } from '@solana/pay';
-
-// ... DB function placeholders
-import { savePurchaseReference, findPurchaseByReference, grantSkillToUser } from '../_lib/db';
-
-export default async function handler(req, res) {
- const connection = new Connection(process.env.SOLANA_RPC_URL);
-
- if (req.method === 'POST') {
- // ... POST logic from prompt 3 ...
-
- // 1. Generate a reference keypair
- const reference = new Keypair().publicKey;
-
- // 2. Add it to the transaction so you can find it later
- // This is a simplified example; typically added to the transfer instruction
- transaction.add(
- SystemProgram.transfer({
- fromPubkey: buyerPublicKey,
- toPubkey: reference, // Using reference here is for lookup
- lamports: 0,
- })
- );
-
- // 3. Save reference to DB before sending tx to user
- await savePurchaseReference(reference.toBase58(), { userId: req.user.id, agentId, skillName });
-
- // ... continue serializing and sending transaction
- } else if (req.method === 'GET') {
- try {
- const { reference, signature } = req.query;
- if (!reference || !signature) {
- return res.status(400).json({ error: 'Missing reference or signature' });
- }
-
- // Find the purchase details from your DB using the reference
- const purchaseDetails = await findPurchaseByReference(reference);
- if (!purchaseDetails) {
- return res.status(404).json({ error: 'Purchase reference not found' });
- }
-
- // Use Solana Pay's helper to find and verify the transaction
- const { transaction, status } = await findTransaction(connection, new PublicKey(signature));
-
- if (status !== 'confirmed') {
- return res.status(400).json({ error: 'Transaction not confirmed' });
- }
-
- // You should add more robust verification here:
- // - Check the amounts transferred
- // - Check the destination addresses
- // - Check that the buyer was the fee payer
- console.log('Transaction verified successfully!');
-
- // Grant access to the skill
- await grantSkillToUser(purchaseDetails.userId, purchaseDetails.skillName);
-
- res.status(200).json({ status: 'ok', message: 'Purchase confirmed!' });
-
- } catch (error) {
- console.error('Verification failed:', error);
- res.status(500).json({ error: 'Verification failed' });
- }
- } else {
- res.status(405).json({ error: 'Method Not Allowed' });
- }
-}
-
-```
-
-<!-- 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/05-transaction-confirmation-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/05-ui-purchase-skill-button.md b/prompts/monetization/05-ui-purchase-skill-button.md
deleted file mode 100644
index ef9ff0055..000000000
--- a/prompts/monetization/05-ui-purchase-skill-button.md
+++ /dev/null
@@ -1,62 +0,0 @@
----
-status: not-started
----
-
-# Prompt 5: UI for "Purchase Skill" Button
-
-## Objective
-Add a "Purchase Skill" button to the agent detail page for skills that are not free.
-
-## Explanation
-To allow users to buy skills, a clear call-to-action is needed. This button will be displayed next to paid skills that the user has not yet purchased, and it will trigger the payment flow.
-
-## Instructions
-1. **Modify the Frontend UI:**
- * In `src/marketplace.js`, in the `renderDetail` function, update the skill rendering logic.
- * For each skill, check if it's paid and if the current user has already purchased it.
- * If the skill is paid and not purchased, display a "Purchase" or "Unlock" button instead of the price badge.
- * If the skill is free or already purchased, display the "Free" or "Owned" badge.
-
-2. **Button State:**
- * The button should be clearly visible and clickable.
- * Add a `data-skill-name` attribute to the button to identify which skill is being purchased.
-
-## Code Example (Frontend - `src/marketplace.js`)
-
-```javascript
-// Inside renderDetail function, an updated version of the skill rendering logic
-const skillPrices = a.skill_prices || {};
-const ownedSkills = user.owned_skills || []; // Assuming this data is available
-
-$('d-skills').innerHTML = skillsArr.map((s) => {
- const name = typeof s === 'string' ? s : (s.name || '');
- const price = skillPrices[name];
-
- let badge;
- if (price) {
- if (ownedSkills.includes(name)) {
- badge = `<span class="price-badge price-owned">Owned</span>`;
- } else {
- badge = `<button class="purchase-btn" data-skill-name="${name}">Purchase</button>`;
- }
- } else {
- badge = `<span class="price-badge price-free">Free</span>`;
- }
-
- return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;
-}).join(' ');
-```
-
-<!-- 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/05-ui-purchase-skill-button.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/05-ui-toggle-for-paid-skills.md b/prompts/monetization/05-ui-toggle-for-paid-skills.md
deleted file mode 100644
index e63ef625d..000000000
--- a/prompts/monetization/05-ui-toggle-for-paid-skills.md
+++ /dev/null
@@ -1,100 +0,0 @@
-# Prompt 5: UI Toggle for Paid Skills
-
-## Objective
-Enhance the skill price management UI with dynamic toggles that intuitively show and hide price input fields.
-
-## Explanation
-This prompt focuses on the frontend user experience for creators. Instead of showing price inputs at all times, we'll use a checkbox or toggle switch for each skill. This makes the interface cleaner and the act of setting a price a more deliberate choice.
-
-## Instructions
-1. **File to Edit:**
- * Continue working in `agent-edit.html` and its associated JavaScript.
-
-2. **Refine the UI Structure:**
- * For each skill listed in the pricing management section, ensure you have the following HTML structure:
- * The skill name.
- * A checkbox/toggle: `<input type="checkbox" class="paid-toggle">`.
- * A container for the price inputs (e.g., a `<div>`) that is initially hidden if the skill is free.
-
-3. **Implement JavaScript Logic:**
- * Add an event listener to all `.paid-toggle` checkboxes.
- * When a checkbox is checked (toggled on):
- * The associated price input container should become visible (e.g., `style.display = 'flex'`).
- * You might want to focus the amount input field to encourage the user to enter a price.
- * When a checkbox is unchecked (toggled off):
- * The price input container should be hidden (`style.display = 'none'`).
-
-4. **Initial State:**
- * When the UI is first rendered, the state of each checkbox and the visibility of the price inputs must reflect the current pricing data fetched from the backend. If a skill has a price, its checkbox should be checked and its price inputs should be visible.
-
-## Code Example (Frontend - `agent-edit.html` script)
-
-This builds upon the example from Prompt 3.
-
-```html
-<!-- Example HTML structure for one skill row within agent-edit.html -->
-<div class="form-group skill-price-row">
- <label class="form-label">summarize-text</label>
- <div class="skill-price-controls">
- <input type="checkbox" class="paid-toggle" id="toggle-summarize-text" data-skill="summarize-text">
- <label for="toggle-summarize-text" class="toggle-label">Paid Skill</label>
-
- <div class="price-inputs" style="display: none;">
- <input type="number" class="price-amount" value="1.00" step="0.01" min="0">
- <span>USDC</span>
- </div>
- </div>
-</div>
-```
-
-```css
-/* Add some basic styling for the toggle and inputs in your CSS */
-.skill-price-controls {
- display: flex;
- align-items: center;
- gap: 10px;
-}
-.price-inputs {
- display: flex;
- align-items: center;
- gap: 5px;
-}
-```
-
-```javascript
-// JavaScript to handle the dynamic visibility
-
-document.addEventListener('DOMContentLoaded', () => {
- // Assume renderSkillPricingUI() has been called and the HTML is on the page
-
- const container = document.getElementById('skill-pricing-container');
-
- container.addEventListener('change', (e) => {
- if (e.target.classList.contains('paid-toggle')) {
- const controls = e.target.closest('.skill-price-controls');
- const priceInputs = controls.querySelector('.price-inputs');
-
- if (e.target.checked) {
- priceInputs.style.display = 'flex';
- priceInputs.querySelector('.price-amount').focus();
- } else {
- priceInputs.style.display = 'none';
- }
- }
- });
-});
-```
-
-<!-- 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/05-ui-toggle-for-paid-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/05-wallet-integration.md b/prompts/monetization/05-wallet-integration.md
deleted file mode 100644
index b235ba2e9..000000000
--- a/prompts/monetization/05-wallet-integration.md
+++ /dev/null
@@ -1,83 +0,0 @@
----
-status: not-started
----
-
-# Prompt 5: Wallet Integration
-
-## Objective
-Integrate a Solana wallet adapter to allow users to connect their wallets (e.g., Phantom, Solflare) to the web application.
-
-## Explanation
-To enable on-chain payments, the first step is allowing users to connect their cryptocurrency wallets. We will use the official Solana wallet-adapter libraries to provide a smooth, standardized connection experience for users. This will add a "Connect Wallet" button to the application's header and make the user's public key available to the frontend.
-
-## Instructions
-1. **Install Dependencies:**
- * Add the required Solana wallet-adapter libraries to your project's `package.json`. You'll need `@solana/wallet-adapter-base`, `@solana/wallet-adapter-react`, `@solana/wallet-adapter-wallets`, and potentially UI components for your framework (e.g., `@solana/wallet-adapter-react-ui`).
- * Run `npm install` or `yarn` to install them.
-
-2. **Set up the Wallet Provider:**
- * In your main application component (e.g., `app.js` or a root-level layout component), wrap your application with the `ConnectionProvider`, `WalletProvider`, and `WalletModalProvider`.
- * The `ConnectionProvider` needs an RPC endpoint for the Solana cluster you're targeting (e.g., mainnet-beta or devnet).
- * The `WalletProvider` needs a list of the wallet adapters you want to support (e.g., `PhantomWalletAdapter`, `SolflareWalletAdapter`).
-
-3. **Add the Connect Button:**
- * In your site's header component (e.g., `nav.js` or `header.html`), add the `WalletMultiButton` component from the UI library. This single component handles all connection states (Connect, Connected, Disconnect).
- * Ensure you style the button to match your site's aesthetic. You will need to import the adapter's CSS file (`@solana/wallet-adapter-react-ui/styles.css`).
-
-4. **Access Wallet State:**
- * Use the `useWallet` hook in your components to access the user's wallet state, such as `publicKey`, `connected`, `signTransaction`, etc.
- * For example, you can now show or hide certain UI elements based on whether `connected` is true or false.
-
-## Code Example (React-like, for `app.js` or similar)
-
-```javascript
-import React, { useMemo } from 'react';
-import { ConnectionProvider, WalletProvider } from '@solana/wallet-adapter-react';
-import { WalletAdapterNetwork } from '@solana/wallet-adapter-base';
-import { PhantomWalletAdapter, SolflareWalletAdapter } from '@solana/wallet-adapter-wallets';
-import { WalletModalProvider, WalletMultiButton } from '@solana/wallet-adapter-react-ui';
-import { clusterApiUrl } from '@solana/web3.js';
-
-// Default styles that can be overridden
-require('@solana/wallet-adapter-react-ui/styles.css');
-
-export const App = () => {
- const network = WalletAdapterNetwork.Mainnet;
- const endpoint = useMemo(() => clusterApiUrl(network), [network]);
- const wallets = useMemo(() => [
- new PhantomWalletAdapter(),
- new SolflareWalletAdapter(),
- ], [network]);
-
- return (
- <ConnectionProvider endpoint={endpoint}>
- <WalletProvider wallets={wallets} autoConnect>
- <WalletModalProvider>
- {/* Your existing app layout */}
- <header>
- {/* ... other header items ... */}
- <WalletMultiButton />
- </header>
- <main>
- {/* ... rest of your app ... */}
- </main>
- </WalletModalProvider>
- </WalletProvider>
- </ConnectionProvider>
- );
-};
-```
-
-<!-- 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/05-wallet-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/05_ui_for_purchasing.md b/prompts/monetization/05_ui_for_purchasing.md
deleted file mode 100644
index b99812a23..000000000
--- a/prompts/monetization/05_ui_for_purchasing.md
+++ /dev/null
@@ -1,130 +0,0 @@
----
-status: not-started
-last_updated: 2026-05-04
----
-# Prompt 05: UI for Purchasing a Skill
-
-## Objective
-On the agent detail page, replace the static price badge for paid skills with an interactive "Purchase" button.
-
-## Explanation
-Displaying the price is the first step. The next is to allow users to initiate a purchase. This involves changing the UI from a passive display to an active one. When a user clicks the "Purchase" button, it should trigger the on-chain purchase flow. For this task, we will focus only on creating the button and its initial states.
-
-## Instructions
-1. **Identify User's Owned Skills:**
- * The API that fetches agent details for the marketplace view should also determine which skills the *currently authenticated user* already owns.
- * This requires a new database query to check the `user_purchased_skills` table (which we will create in a later prompt). For now, you can assume the API returns a list of owned skill names, e.g., `agent.owned_skills: ["skill1", "skill2"]`.
-
-2. **Update the UI in `src/marketplace.js`:**
- * In the `renderDetail` function, where skills are rendered, implement conditional logic for each skill:
- * If the skill is free, show a "Free" badge.
- * If the skill is paid and the user already owns it, show an "Owned" badge or checkmark.
- * If the skill is paid and the user does not own it, show a "Purchase" button with the price.
-
-3. **Button Styling:**
- * Add CSS for the new "Purchase" button and "Owned" badge to make them clear and visually appealing.
-
-## Code Example (Frontend - `src/marketplace.js`)
-
-```javascript
-// Inside renderDetail function
-const skillPrices = a.skill_prices || {};
-const ownedSkills = new Set(a.owned_skills || []); // Assume this is passed from the API
-
-$('d-skills').innerHTML = skillsArr.map(s => {
- const name = typeof s === 'string' ? s : (s.name || '');
- const price = skillPrices[name];
- let badgeHtml = '';
-
- if (price) {
- if (ownedSkills.has(name)) {
- badgeHtml = `<span class="skill-badge owned">✓ Owned</span>`;
- } else {
- const priceInUsdc = (price.amount / 1e6).toFixed(2);
- badgeHtml = `<button class="btn btn-purchase" data-skill-name="${name}" data-agent-id="${a.id}">
- Purchase for ${priceInUsdc} USDC
- </button>`;
- }
- } else {
- badgeHtml = `<span class="skill-badge free">Free</span>`;
- }
-
- return `<div class="skill-entry">
- <span class="skill-name">${escapeHtml(name)}</span>
- ${badgeHtml}
- </div>`;
-}).join('');
-
-// Add event listener for purchase buttons
-document.getElementById('d-skills').addEventListener('click', (e) => {
- if (e.target.matches('.btn-purchase')) {
- const skillName = e.target.dataset.skillName;
- const agentId = e.target.dataset.agentId;
- // The purchase flow logic will be implemented in the next prompt
- console.log(`Initiating purchase for skill '${skillName}' from agent '${agentId}'`);
- e.target.disabled = true;
- e.target.textContent = 'Preparing...';
- }
-});
-```
-
-## CSS Example
-
-```css
-/* Add to marketplace.css */
-.skill-entry {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: 8px;
- border-radius: 6px;
- background-color: #1a1a24; /* var(--panel2) */
- margin-bottom: 6px;
-}
-
-.skill-badge, .btn-purchase {
- flex-shrink: 0;
-}
-
-.btn-purchase {
- font-size: 12px;
- padding: 5px 10px;
- background-color: var(--accent);
- color: white;
- border: none;
- border-radius: 5px;
- cursor: pointer;
-}
-
-.btn-purchase:hover {
- filter: brightness(1.1);
-}
-
-.btn-purchase:disabled {
- opacity: 0.6;
- cursor: not-allowed;
-}
-
-.skill-badge.owned {
- color: #4ade80; /* var(--ok) */
- font-weight: 600;
-}
-
-.skill-badge.free {
- color: #888; /* var(--muted) */
-}
-```
-
-<!-- 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/05_ui_for_purchasing.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/06-backend-payment-transaction-api.md b/prompts/monetization/06-backend-payment-transaction-api.md
deleted file mode 100644
index 618fa74d7..000000000
--- a/prompts/monetization/06-backend-payment-transaction-api.md
+++ /dev/null
@@ -1,113 +0,0 @@
----
-status: not-started
----
-
-# Prompt 6: Backend - Payment Transaction API
-
-## Objective
-Create a backend API endpoint that generates a Solana transaction for a specific skill purchase and returns it to the frontend for signing.
-
-## Explanation
-To securely handle payments, the backend must be responsible for creating the transaction. The frontend will request a transaction for a specific skill, and this API will construct it, including the correct recipient address (the creator), the currency (e.g., USDC), and the amount. Returning the unsigned transaction to the frontend allows the user to sign it with their wallet without ever exposing their private key to our server.
-
-## Instructions
-1. **Create the API Endpoint:**
- * Create a new API file, e.g., `api/payments/create-transaction.js`.
- * This endpoint will accept `POST` requests at `/api/payments/create-transaction`.
-
-2. **Request Body and Validation:**
- * The request body from the frontend must include:
- * `agentId`: The ID of the agent whose skill is being purchased.
- * `skillName`: The name of the skill.
- * `buyerPublicKey`: The public key of the user who is buying the skill.
- * Validate this input.
-
-3. **Fetch Skill and Creator Data:**
- * From your database, fetch the price (`amount`, `currency_mint`) for the given `skillName` and `agentId` from the `agent_skill_prices` table.
- * Fetch the agent creator's payout wallet address from the `creator_payout_wallets` table (or `agent_identities` if stored there). Let's call this `creatorPublicKey`.
-
-4. **Construct the Solana Transaction:**
- * Use the `@solana/web3.js` library.
- * You will create a **Token Transfer** instruction using the `@solana/spl-token` library.
- * The instruction needs:
- * The buyer's associated token account for the currency (`source`).
- * The creator's associated token account for the currency (`destination`).
- * The buyer's main wallet address as the authority (`owner`).
- * The `amount` from the database.
- * The `currency_mint` from the database.
- * **Important:** You may need to create the creator's associated token account if it doesn't exist. Your transaction might need to include the `createAssociatedTokenAccountInstruction`.
- * Create a new `Transaction` and add the transfer instruction(s) to it.
- * Set the `feePayer` to the `buyerPublicKey`.
- * Set a `recentBlockhash`. You can get this from your Solana `Connection` object.
-
-5. **Serialize and Return:**
- * Serialize the transaction *without signing it*.
- * Return the serialized transaction to the frontend, base64-encoded.
-
-## Code Example (`api/payments/create-transaction.js`)
-
-```javascript
-import { Connection, PublicKey, Transaction, SystemProgram } from '@solana/web3.js';
-import { getOrCreateAssociatedTokenAccount, createTransferInstruction } from '@solana/spl-token';
-import { json, wrap } from '../_lib/http.js';
-import { sql } from '../_lib/db.js';
-// ... other imports
-
-const SOLANA_RPC_ENDPOINT = process.env.SOLANA_RPC_ENDPOINT;
-const connection = new Connection(SOLANA_RPC_ENDPOINT);
-
-export default wrap(async (req, res) => {
- // ... authentication and input validation ...
- const { agentId, skillName, buyerPublicKey } = req.body;
- const buyer = new PublicKey(buyerPublicKey);
-
- // 1. Fetch price and creator wallet from DB
- const [priceInfo] = await sql`...`; // Get amount and currency_mint
- const [creatorInfo] = await sql`...`; // Get creator's payout wallet
- if (!priceInfo || !creatorInfo) {
- return json(res, 404, { error: 'Skill or creator wallet not found' });
- }
-
- const creator = new PublicKey(creatorInfo.wallet_address);
- const currencyMint = new PublicKey(priceInfo.currency_mint);
- const amount = BigInt(priceInfo.amount);
-
- // 2. Get the buyer's and creator's token accounts
- const buyerTokenAccount = await getOrCreateAssociatedTokenAccount(connection, buyer, currencyMint, buyer);
- const creatorTokenAccount = await getOrCreateAssociatedTokenAccount(connection, buyer, currencyMint, creator);
-
- // 3. Create the transaction
- const transaction = new Transaction();
- transaction.add(
- createTransferInstruction(
- buyerTokenAccount.address, // from
- creatorTokenAccount.address, // to
- buyer, // owner
- amount
- )
- );
-
- transaction.feePayer = buyer;
- transaction.recentBlockhash = (await connection.getLatestBlockhash()).blockhash;
-
- // 4. Serialize and encode
- const serializedTransaction = transaction.serialize({ requireAllSignatures: false });
- const base64Transaction = serializedTransaction.toString('base64');
-
- return json(res, 200, { transaction: base64Transaction });
-});
-```
-
-<!-- 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/06-backend-payment-transaction-api.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/06-create-backend-api-for-payments.md b/prompts/monetization/06-create-backend-api-for-payments.md
deleted file mode 100644
index 0e1523eae..000000000
--- a/prompts/monetization/06-create-backend-api-for-payments.md
+++ /dev/null
@@ -1,95 +0,0 @@
-# Prompt 6: Create Backend API for Payment Transactions
-
-## Status
-- [ ] Not Started
-
-## Objective
-Create a backend API endpoint that prepares a Solana transaction for a skill purchase and sends it to the frontend for signing.
-
-## Explanation
-For security and reliability, the transaction should be constructed on the backend. The backend will determine the correct accounts (buyer, seller, mint) and amounts, create an unsigned transaction, serialize it, and send it to the frontend. The frontend's only job is to get the user's signature.
-
-## Instructions
-1. **Create a New API Endpoint:**
- * Create a new API route, for example, `POST /api/payments/prepare-transaction`.
- * This endpoint will require authentication to ensure only logged-in users can make purchases.
-
-2. **Implement the Endpoint Logic:**
- * The endpoint should accept a payload containing the `skill_name`, `agent_id`, and the buyer's public key.
- * On the backend, retrieve the skill's price and currency mint from the `agent_skill_prices` table.
- * Fetch the agent creator's wallet address (the seller).
- * Construct a Solana transaction using `@solana/web3.js`. The transaction will be a simple SPL token transfer from the buyer's wallet to the seller's wallet.
- * The transaction should be recent and have a recent blockhash.
- * Serialize the transaction and send it back to the frontend in a base64-encoded format.
-
-## Code Example (Backend - `/api/payments/prepare-transaction.js`)
-```javascript
-// /api/payments/prepare-transaction.js
-import { Connection, PublicKey, Transaction, SystemProgram } from '@solana/web3.js';
-import { getOrCreateAssociatedTokenAccount, createTransferInstruction } from '@solana/spl-token';
-import { getSkillPrice, getAgentCreatorWallet } from './_db.js'; // Placeholder for DB functions
-
-export default async function handler(req, res) {
- if (req.method !== 'POST') {
- return res.status(405).json({ error: 'Method Not Allowed' });
- }
-
- const { skillName, agentId, buyerPublicKey } = req.body;
-
- // 1. Fetch skill price and seller's address
- const priceInfo = await getSkillPrice(agentId, skillName);
- const sellerPublicKey = await getAgentCreatorWallet(agentId);
-
- if (!priceInfo || !sellerPublicKey) {
- return res.status(404).json({ error: 'Skill or seller not found' });
- }
-
- // 2. Setup Solana connection
- const connection = new Connection(process.env.SOLANA_RPC_URL, 'confirmed');
- const buyer = new PublicKey(buyerPublicKey);
- const seller = new PublicKey(sellerPublicKey);
- const mint = new PublicKey(priceInfo.currency_mint);
-
- // 3. Get or create token accounts
- const buyerTokenAccount = await getOrCreateAssociatedTokenAccount(connection, buyer, mint, buyer);
- const sellerTokenAccount = await getOrCreateAssociatedTokenAccount(connection, buyer, mint, seller);
-
- // 4. Create the transaction
- const transaction = new Transaction();
- transaction.add(
- createTransferInstruction(
- buyerTokenAccount.address,
- sellerTokenAccount.address,
- buyer,
- priceInfo.amount
- )
- );
-
- // 5. Set recent blockhash and fee payer
- transaction.recentBlockhash = (await connection.getLatestBlockhash()).blockhash;
- transaction.feePayer = buyer;
-
- // 6. Serialize and send to frontend
- const serializedTransaction = transaction.serialize({
- requireAllSignatures: false, // The buyer's signature is still needed
- });
-
- res.status(200).json({
- transaction: serializedTransaction.toString('base64'),
- });
-}
-```
-
-<!-- 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/06-create-backend-api-for-payments.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/06-granting-skill-access.md b/prompts/monetization/06-granting-skill-access.md
deleted file mode 100644
index 2e7b70865..000000000
--- a/prompts/monetization/06-granting-skill-access.md
+++ /dev/null
@@ -1,83 +0,0 @@
-# Prompt 6: Granting Skill Access (Backend)
-
-## Objective
-Upon successful purchase confirmation, create a database record that grants the user permanent access to the purchased skill.
-
-## Explanation
-This is the final step in the backend purchase flow. After the payment is verified, the system needs to record that the user now owns the skill. This is typically done by adding an entry to a linking table in the database, for example, `user_skill_ownership`. This record will be the source of truth for determining what premium content a user can access.
-
-## Instructions
-1. **Database Schema:**
- * If it doesn't exist, design and create a `user_skill_ownership` table.
- * Essential columns would be `id`, `user_id`, `agent_id`, `skill_name`, and `created_at`.
- * The combination of `user_id` and `skill_name` (and perhaps `agent_id` if skills are not globally unique) should be unique.
-
-2. **Create a Database Function (`_lib/db.js`):**
- * Write a function, `grantSkillToUser(userId, agentId, skillName)`, that inserts a new record into the `user_skill_ownership` table.
- * This function should handle potential errors, such as the user already owning the skill (which shouldn't happen if the purchase button is correctly disabled, but is good for data integrity).
-
-3. **Integrate into Confirmation Flow:**
- * In the `GET` handler of your `api/payments/prepare-skill-purchase.js` endpoint, after the transaction has been successfully verified (as per the previous prompt), call your new `grantSkillToUser` function.
- * Pass the authenticated user's ID and the skill details that you retrieved from your database using the transaction `reference`.
-
-## Database Schema Example (SQL)
-
-```sql
-CREATE TABLE user_skill_ownership (
- id SERIAL PRIMARY KEY,
- user_id UUID NOT NULL REFERENCES users(id),
- agent_id UUID NOT NULL REFERENCES agents(id),
- skill_name VARCHAR(255) NOT NULL,
- created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
- UNIQUE(user_id, agent_id, skill_name)
-);
-
--- Add an index for efficient lookups
-CREATE INDEX idx_user_skill_ownership_user_id ON user_skill_ownership(user_id);
-```
-
-## Code Example (Backend - `_lib/db.js`)
-
-```javascript
-// This is a conceptual example using a generic DB client like 'pg' or 'slonik'
-import { db } from './database-client';
-
-export async function grantSkillToUser(userId, agentId, skillName) {
- try {
- const result = await db.query(
- `
- INSERT INTO user_skill_ownership (user_id, agent_id, skill_name)
- VALUES ($1, $2, $3)
- ON CONFLICT (user_id, agent_id, skill_name) DO NOTHING
- RETURNING id;
- `,
- [userId, agentId, skillName]
- );
-
- if (result.rows.length > 0) {
- console.log(`Granted skill '${skillName}' for agent '${agentId}' to user '${userId}'`);
- return true;
- } else {
- console.warn(`User '${userId}' already owns skill '${skillName}' for agent '${agentId}'`);
- return false; // Already owned
- }
- } catch (error) {
- console.error('Error in grantSkillToUser:', error);
- throw 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/06-granting-skill-access.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/06-solana-pay-endpoint.md b/prompts/monetization/06-solana-pay-endpoint.md
deleted file mode 100644
index 889843ad1..000000000
--- a/prompts/monetization/06-solana-pay-endpoint.md
+++ /dev/null
@@ -1,107 +0,0 @@
----
-status: not-started
-completed_at: null
----
-# Prompt 6: On-Chain Payment API with Solana Pay
-
-## Objective
-Create a backend API endpoint that generates a Solana Pay transaction request for purchasing a specific agent skill.
-
-## Explanation
-To accept payments for skills, we need to integrate with the Solana blockchain. This prompt outlines the creation of an API endpoint that follows the Solana Pay specification. When a user wants to buy a skill, the frontend will call this endpoint. The endpoint will generate the details for a valid SPL Token transfer transaction, which the user's wallet will then use to approve the payment.
-
-## Instructions
-1. **Define the API Endpoint:**
- * Create a new route: `GET /api/purchase/skill/:agentId/:skillName`. This will be the main endpoint for initiating a purchase.
- * Also, create a `POST` handler for the same route, which will be used by the Solana Pay protocol to validate the transaction after the user signs it.
-
-2. **Implement the `GET` Handler (Transaction Request):**
- * **Fetch Skill Price:** From the database, retrieve the `amount` and `currency_mint` for the requested `agentId` and `skillName`. If not found, return a `404 Not Found`.
- * **Fetch Creator's Wallet:** Get the agent creator's destination wallet address. This should be stored securely with the creator's user profile.
- * **Generate a Unique Reference Key:** Create a new, unique keypair (`Keypair.generate()`). The public key of this keypair will serve as a unique reference for the transaction, preventing double-spending. Store this reference in your database or cache temporarily, associating it with the purchase details (user, skill, agent).
- * **Construct the Solana Pay Response:**
- * `label`: The name of your platform.
- * `icon`: A URL to your platform's logo.
- * For the `POST` handler, construct the JSON response which includes the details needed for the wallet to build the transaction:
- * `transaction`: A Base64-encoded, serialized, but **unsigned** transaction.
- * `message` (optional): A descriptive message, e.g., "Purchase 'translate' skill for Agent 'X'".
- * The transaction should be a simple SPL Token transfer from the buyer (the wallet will fill this in) to the creator's wallet address.
- * The transaction must include the unique `reference` public key.
-
-3. **Implement the `POST` Handler (Transaction Validation):**
- * **Receive Transaction:** The wallet will send the user-signed transaction to this endpoint. The body will contain `{ transaction: "..." }`.
- * **Deserialize and Verify:**
- * Deserialize the transaction.
- * Check that the signature is valid for the expected signer (the user).
- * Verify that the transaction details match the expected purchase: correct recipient, correct amount, correct SPL token mint, and the **correct unique reference key**. This is crucial for security.
- * **Record the Purchase:** If verification passes, save the purchase details to your `user_skill_purchases` table, including the transaction signature.
- * **Return Confirmation:** Respond with a success message including the transaction signature.
-
-## Code Example (Backend `GET` Handler)
-
-```javascript
-// Example using Express.js and @solana/web3.js, @solana/spl-token
-
-// GET /api/purchase/skill/:agentId/:skillName
-app.get('/api/purchase/skill/:agentId/:skillName', async (req, res) => {
- // ... fetch skillPrice, creatorWallet from db ...
-
- const { amount, currency_mint } = skillPrice;
- const recipient = new PublicKey(creatorWallet);
- const splToken = new PublicKey(currency_mint);
-
- // Generate a unique reference for this transaction
- const reference = new Keypair().publicKey;
- // Store reference in cache/db to validate it in the POST request
- await cache.set(`ref_${reference.toBase58()}`, { agentId, skillName, userId: req.user.id });
-
- res.status(200).json({
- label: "My 3D Agent Platform",
- icon: "https://my-platform.com/logo.png",
- });
-});
-
-// POST /api/purchase/skill/:agentId/:skillName
-app.post('/api/purchase/skill/:agentId/:skillName', async (req, res) => {
- // This endpoint should return the actual transaction details
- const { account } = req.body;
- if (!account) {
- return res.status(400).json({ error: 'Account is required.' });
- }
- // ... fetch skillPrice, creatorWallet from db ...
- // ... generate reference, etc ...
-
- // Create the unsigned transaction
- const transaction = new Transaction();
- // ... add SPL token transfer instruction ...
- // The instruction needs: source (user's wallet), destination (creator's wallet), amount, mint.
- // The wallet will provide the user's source token account.
-
- res.status(200).json({
- transaction: transaction.serialize({ requireAllSignatures: false, verifySignatures: false }).toString('base64'),
- message: `Purchase skill for ${(amount / 1e6).toFixed(2)} USDC`,
- });
-});
-```
-
-## Definition of Done
-- A `GET` endpoint exists at `/api/purchase/skill/:agentId/:skillName` that returns the `label` and `icon` for a Solana Pay request.
-- A `POST` endpoint exists at the same URL that takes a public key `account` and returns a serialized, unsigned transaction.
-- The transaction is a valid SPL token transfer for the correct amount and token.
-- A unique reference key is generated for each transaction request.
-- The `POST` handler for validating the final signed transaction is implemented and secure.
-- Successful purchases are recorded in the `user_skill_purchases` table.
-
-<!-- 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/06-solana-pay-endpoint.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/06-solana-pay-integration.md b/prompts/monetization/06-solana-pay-integration.md
deleted file mode 100644
index 837f1d1ef..000000000
--- a/prompts/monetization/06-solana-pay-integration.md
+++ /dev/null
@@ -1,105 +0,0 @@
----
-status: not-started
----
-
-# Prompt 6: Solana Pay Integration
-
-## Objective
-Integrate the Solana Pay SDK and set up the basic client-side structure for handling skill purchases.
-
-## Explanation
-To facilitate payments, we will use Solana Pay, a standard for decentralized payments on the Solana blockchain. This prompt covers the initial setup of the Solana Pay JavaScript library and creating placeholder functions for the purchase flow.
-
-## Instructions
-1. **Add Solana Pay SDK:**
- * Include the Solana Pay SDK in your frontend. You can add it via a script tag from a CDN or install it as an npm package if you have a build process.
- * For example: `<script src="https://unpkg.com/@solana/[email protected]/dist/index.iife.js"></script>`
-
-2. **Add Solana Web3.js SDK:**
- * Solana Pay often works in conjunction with the core Solana Web3 library. Include this as well.
- * For example: `<script src="https://unpkg.com/@solana/web3.js@latest/lib/index.iife.js"></script>`
-
-3. **Create a Purchase Module:**
- * In your frontend JavaScript for the agent detail page, create a new section or object to handle the purchase logic.
- * This module will contain functions to initiate a purchase, create a transaction request, display a QR code, and monitor the transaction status.
-
-4. **Implement Placeholder Functions:**
- * Create empty or `console.log` stub functions for the main steps:
- * `initiatePurchase(skillName)`: Called when a user clicks a "Buy" button.
- * `fetchTransactionRequest(skillName)`: Will call our backend to get transaction details.
- * `displayPaymentQR(transactionUrl)`: Will use the Solana Pay SDK to generate and show a QR code.
- * `monitorTransaction(transactionSignature)`: Will poll the blockchain to confirm the payment.
-
-## Code Example (HTML - adding scripts in `marketplace.html`)
-
-```html
-<!-- At the end of your body tag -->
-<script src="https://unpkg.com/@solana/web3.js@latest/lib/index.iife.js"></script>
-<script src="https://unpkg.com/@solana/[email protected]/dist/index.iife.js"></script>
-<script src="/src/marketplace.js"></script> <!-- Your app's script -->
-```
-
-## Code Example (JavaScript - Purchase Module Stub)
-
-```javascript
-// In your marketplace JavaScript file
-
-const PurchaseFlow = {
- async initiatePurchase(agent, skillName) {
- console.log(`Initiating purchase for skill: ${skillName} from agent: ${agent.name}`);
-
- // 1. Fetch transaction details from our backend
- const transactionUrl = await this.fetchTransactionRequest(agent.id, skillName);
- if (!transactionUrl) return;
-
- // 2. Display QR code for payment
- this.displayPaymentQR(transactionUrl);
-
- // 3. Monitor for payment completion (to be fully implemented later)
- // This part requires getting a signature, which is part of the Solana Pay flow.
- // For now, we can just log.
- console.log('Purchase flow started. Waiting for payment...');
- },
-
- async fetchTransactionRequest(agentId, skillName) {
- console.log('Fetching transaction request from backend...');
- // In the next step, this will make a real API call.
- // For now, it's a placeholder.
- // The backend will return a Solana Pay URL like:
- // "solana:https://your-api.com/api/purchase/transaction?agent=...&skill=..."
- // We'll stub this out later.
- showToast('Backend for transactions not implemented yet.', 'error');
- return null;
- },
-
- displayPaymentQR(url) {
- console.log(`Displaying QR code for URL: ${url}`);
- // This will be implemented using SolanaPay.createQR()
- // and rendered into a modal.
- showToast('QR code display not implemented yet.', 'error');
- },
-
- async monitorTransaction(signature) {
- console.log(`Monitoring signature: ${signature}`);
- // This will use solanaWeb3.Connection to check transaction status.
- showToast('Transaction monitoring not implemented yet.', 'error');
- }
-};
-
-// Example of how it would be called from the skill rendering logic:
-// <button onclick="PurchaseFlow.initiatePurchase(...)">Buy</button>
-```
-
-<!-- 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/06-solana-pay-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/06-ui-payment-modal.md b/prompts/monetization/06-ui-payment-modal.md
deleted file mode 100644
index ee7c71417..000000000
--- a/prompts/monetization/06-ui-payment-modal.md
+++ /dev/null
@@ -1,59 +0,0 @@
----
-status: not-started
----
-
-# Prompt 6: UI Payment Modal
-
-## Objective
-Design and implement a payment confirmation modal that appears when a user clicks the "Purchase Skill" button.
-
-## Explanation
-A modal is an excellent way to provide a focused and clear payment experience. This modal will display the details of the skill being purchased, the price, and a final confirmation button to initiate the transaction.
-
-## Instructions
-1. **Create the Modal HTML:**
- * In `marketplace.html`, add the HTML structure for a modal. It should be hidden by default.
- * The modal should have a header, body, and footer.
- * The body should contain placeholders for the skill name, price, and other details.
- * The footer should have "Cancel" and "Confirm Purchase" buttons.
-
-2. **Implement JavaScript Logic:**
- * In `src/marketplace.js`, add an event listener for clicks on the "Purchase" buttons.
- * When a button is clicked, populate the modal with the correct skill information and display it.
- * The "Confirm Purchase" button will trigger the blockchain transaction.
-
-## Code Example (HTML - `marketplace.html`)
-
-```html
-<div id="payment-modal" class="modal-overlay hidden">
- <div class="modal">
- <div class="modal-header">
- <h3>Confirm Purchase</h3>
- <button id="close-payment-modal">&times;</button>
- </div>
- <div class="modal-body">
- <p>You are about to purchase the skill:</p>
- <h4 id="modal-skill-name"></h4>
- <p>Price: <strong id="modal-skill-price"></strong></p>
- </div>
- <div class="modal-footer">
- <button id="cancel-purchase" class="btn">Cancel</button>
- <button id="confirm-purchase" class="btn btn-primary">Confirm</button>
- </div>
- </div>
-</div>
-```
-
-<!-- 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/06-ui-payment-modal.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/06-verifying-purchase-and-unlocking-skill.md b/prompts/monetization/06-verifying-purchase-and-unlocking-skill.md
deleted file mode 100644
index 179b8c89f..000000000
--- a/prompts/monetization/06-verifying-purchase-and-unlocking-skill.md
+++ /dev/null
@@ -1,103 +0,0 @@
-# Prompt 6: Verifying Purchase and Unlocking Skill
-
-## Objective
-Create a backend system to verify that a skill purchase transaction was successful on-chain and then formally grant the user access to that skill in the database.
-
-## Explanation
-After the frontend submits the transaction to the Solana network, it gets a transaction signature. The frontend then sends this signature to our backend. The backend's job is to use this signature to query the Solana blockchain, confirm the transaction was successfully processed and finalized, and then update our application's database to reflect that the user now owns the skill. This is a critical step for security and ensuring users get what they paid for.
-
-## Instructions
-1. **Create a Verification Endpoint:**
- * Create a new API endpoint, e.g., `/api/marketplace/skills/verify-purchase`.
- * This endpoint will accept a POST request containing the `transactionSignature`, `agentId`, and `skillName`.
-
-2. **Backend Verification Logic:**
- * The endpoint will use the Solana `@solana/web3.js` library to connect to the cluster.
- * It will call `connection.getTransaction(transactionSignature)` to fetch the transaction details.
- * The backend must parse the transaction to ensure it matches what was expected:
- * Was the transfer from the correct buyer?
- * Was it to the correct creator treasury?
- * Was the amount correct?
- * Was the currency (mint) correct?
- * This verification prevents users from sending fake transaction signatures or signatures for unrelated transactions.
-
-3. **Update the Database:**
- * If the on-chain transaction is fully verified, the backend will add a new record to a `user_purchased_skills` table.
- * This table should link a user ID to the agent ID and skill name they purchased.
-
-## Database Schema (`user_purchased_skills`)
-
-```sql
-CREATE TABLE user_purchased_skills (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- user_id UUID REFERENCES auth.users(id) NOT NULL,
- agent_id UUID REFERENCES agents(id) NOT NULL,
- skill_name TEXT NOT NULL,
- purchased_at TIMESTAMPTZ DEFAULT NOW(),
- transaction_signature TEXT NOT NULL,
- UNIQUE(user_id, agent_id, skill_name)
-);
-```
-
-## Code Example (`api/marketplace/skills/verify-purchase.js`)
-
-```javascript
-import { Connection, clusterApiUrl } from '@solana/web3.js';
-import { supabase } from '../../_lib/supabase';
-import { json, error } from '../../_lib/http';
-
-export default async function handler(req, res) {
- const { transactionSignature, agentId, skillName } = req.body;
- // Assume we get userId from session/token
- const { userId } = await getUserFromRequest(req);
-
- if (!userId) return error(res, 401, 'Unauthorized');
-
- const connection = new Connection(clusterApiUrl('devnet'));
-
- // 1. Confirm the transaction is valid and finalized
- const tx = await connection.getTransaction(transactionSignature, { maxSupportedTransactionVersion: 0 });
-
- if (!tx || !tx.meta || tx.meta.err) {
- return error(res, 400, 'Transaction not found or failed.');
- }
-
- // 2. Perform deep verification (omitted for brevity, but crucial)
- // - Check sender, receiver, amount, mint etc. match expected values
- // - This prevents re-using old signatures or sending malicious ones.
-
- // 3. If verified, record the purchase in the database
- const { error: dbError } = await supabase
- .from('user_purchased_skills')
- .insert({
- user_id: userId,
- agent_id: agentId,
- skill_name: skillName,
- transaction_signature: transactionSignature,
- });
-
- if (dbError) {
- // Handle potential unique constraint violation (user trying to re-verify)
- if (dbError.code === '23505') {
- return json(res, { success: true, message: 'Skill already unlocked.' });
- }
- return error(res, 500, 'Failed to record purchase.');
- }
-
- return json(res, { success: true, message: 'Skill unlocked successfully!' });
-}
-```
-
-<!-- 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/06-verifying-purchase-and-unlocking-skill.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/06_db_schema_for_purchases.md b/prompts/monetization/06_db_schema_for_purchases.md
deleted file mode 100644
index 86f7fc906..000000000
--- a/prompts/monetization/06_db_schema_for_purchases.md
+++ /dev/null
@@ -1,76 +0,0 @@
----
-status: not-started
-last_updated: 2026-05-04
----
-# Prompt 06: Database Schema for Purchased Skills
-
-## Objective
-Create the necessary database table to track which users have purchased which skills.
-
-## Explanation
-To manage access to paid skills, we need to record every successful purchase. A `user_purchased_skills` table will create a permanent record linking a user to a specific agent's skill they have acquired. This table is critical for the access control logic that will be built later.
-
-## Instructions
-1. **Design the Table:**
- * Create a new table named `user_purchased_skills`.
- * The table should have the following columns:
- * `id`: Primary key (UUID or SERIAL).
- * `user_id`: Foreign key referencing the `users` table.
- * `agent_id`: Foreign key referencing the `agent_identities` table.
- * `skill_name`: A text field for the name of the skill.
- * `purchase_tx_signature`: The on-chain transaction signature of the purchase, for auditing purposes.
- * `price_amount`: The amount paid (in lamports or smallest unit).
- * `price_currency_mint`: The currency used for the purchase.
- * `created_at`: Timestamp of purchase.
- * Add a unique constraint on (`user_id`, `agent_id`, `skill_name`) to prevent duplicate purchase records.
-
-2. **Write the SQL Migration:**
- * Create a new SQL migration file.
- * Write the `CREATE TABLE` statement based on the design.
- * Add indexes on `user_id` and `agent_id` to speed up lookups for checking skill ownership.
-
-## SQL Example
-
-Here is the PostgreSQL `CREATE TABLE` statement.
-
-```sql
-CREATE TABLE IF NOT EXISTS user_purchased_skills (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- user_id UUID NOT NULL,
- agent_id UUID NOT NULL,
- skill_name VARCHAR(255) NOT NULL,
- purchase_tx_signature VARCHAR(128) NOT NULL,
- price_amount BIGINT NOT NULL,
- price_currency_mint VARCHAR(255) NOT NULL,
- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
-
- CONSTRAINT fk_user
- FOREIGN KEY(user_id)
- REFERENCES users(id)
- ON DELETE CASCADE,
-
- CONSTRAINT fk_agent
- FOREIGN KEY(agent_id)
- REFERENCES agent_identities(id)
- ON DELETE CASCADE,
-
- UNIQUE (user_id, agent_id, skill_name)
-);
-
-CREATE INDEX idx_user_purchased_skills_user_id ON user_purchased_skills(user_id);
-CREATE INDEX idx_user_purchased_skills_agent_id ON user_purchased_skills(agent_id);
-```
-
-<!-- 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/06_db_schema_for_purchases.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/07-creator-dashboard-monetization-tab.md b/prompts/monetization/07-creator-dashboard-monetization-tab.md
deleted file mode 100644
index 3ab71396c..000000000
--- a/prompts/monetization/07-creator-dashboard-monetization-tab.md
+++ /dev/null
@@ -1,107 +0,0 @@
-# Prompt 7: Creator Dashboard Monetization Tab
-
-## Objective
-Create the basic structure for a new "Monetization" tab within the agent creator's dashboard, where they will manage skill pricing and view earnings.
-
-## Explanation
-To empower creators to sell their skills, they need a dedicated space within the application to manage their monetization settings. This first step involves creating the UI shell for this new section. We will add a new tab to the agent editing interface and create the container where the pricing and earnings components will live.
-
-## Instructions
-1. **Add Tab to Dashboard UI:**
- * Locate the HTML file for the agent editing/dashboard page (e.g., `agent-edit.html`).
- * Add a new tab button for "Monetization" alongside existing tabs like "Profile" or "Skills".
- * Add a corresponding tab panel container that will be shown when the Monetization tab is active.
-
-2. **Implement Tab Switching Logic:**
- * In the corresponding JavaScript file (e.g., `src/agent-edit.js`), update the tab switching logic to handle the new Monetization tab.
- * When the Monetization tab is clicked, its panel should become visible, and others should be hidden.
-
-3. **Create Placeholder Content:**
- * Inside the Monetization tab panel, add placeholder sections for "Skill Pricing" and "Earnings". This sets the stage for future prompts where we will build out these features.
-
-## HTML Example (`agent-edit.html`)
-
-```html
-<!-- In the tab list -->
-<div class="tabs">
- <button class="tab-link" data-tab="profile">Profile</button>
- <button class="tab-link" data-tab="skills">Skills</button>
- <button class="tab-link" data-tab="monetization">Monetization</button>
-</div>
-
-<!-- In the tab content area -->
-<div class="tab-content-wrapper">
- <div id="profile" class="tab-content">...</div>
- <div id="skills" class="tab-content">...</div>
- <div id="monetization" class="tab-content" style="display: none;">
- <h2>Monetization</h2>
- <div class="card">
- <h3>Skill Pricing</h3>
- <p>Set the price for your agent's premium skills.</p>
- <div id="skill-pricing-container">
- <!-- Pricing UI will go here -->
- </div>
- </div>
- <div class="card">
- <h3>Earnings</h3>
- <p>View your sales and manage payouts.</p>
- <div id="earnings-container">
- <!-- Earnings dashboard will go here -->
- </div>
- </div>
- <div class="card">
- <h3>Payout Wallet</h3>
- <p>Set the Solana wallet address where you will receive payments.</p>
- <div id="treasury-wallet-container">
- <label for="treasuryWallet">Your Solana Wallet Address:</label>
- <input type="text" id="treasuryWallet" placeholder="Enter public key...">
- <button id="saveTreasuryWallet">Save</button>
- </div>
- </div>
- </div>
-</div>
-```
-
-## JavaScript Example (`src/agent-edit.js`)
-
-```javascript
-document.addEventListener('DOMContentLoaded', () => {
- const tabs = document.querySelectorAll('.tab-link');
- const contents = document.querySelectorAll('.tab-content');
-
- tabs.forEach(tab => {
- tab.addEventListener('click', () => {
- const target = tab.getAttribute('data-tab');
-
- // Hide all content
- contents.forEach(content => {
- content.style.display = 'none';
- });
-
- // Show target content
- document.getElementById(target).style.display = 'block';
-
- // Update active tab style
- tabs.forEach(t => t.classList.remove('active'));
- tab.classList.add('active');
- });
- });
-
- // Default to the first tab
- tabs[0].click();
-});
-```
-
-<!-- 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/07-creator-dashboard-monetization-tab.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/07-frontend-payment-and-signing.md b/prompts/monetization/07-frontend-payment-and-signing.md
deleted file mode 100644
index 4364e554e..000000000
--- a/prompts/monetization/07-frontend-payment-and-signing.md
+++ /dev/null
@@ -1,97 +0,0 @@
-# Prompt 7: Frontend Payment and Transaction Signing
-
-## Status
-- [ ] Not Started
-
-## Objective
-Implement the frontend logic to receive the serialized transaction from the backend, prompt the user to sign it with their wallet, and send the signed transaction to the network.
-
-## Explanation
-This prompt connects the UI to the backend payment API. When the user confirms a purchase, the frontend will fetch the transaction, use the wallet adapter to sign it, and then broadcast it to the Solana network.
-
-## Instructions
-1. **Update Modal Event Listener:**
- * In the `handlePurchaseClick` logic, add a click event listener to the `modal-confirm-btn`.
- * This listener will trigger the payment process.
-
-2. **Implement the Payment Flow:**
- * When the confirm button is clicked, make a `POST` request to your `/api/payments/prepare-transaction` endpoint.
- * Send the necessary data: `skillName`, `agentId`, and the connected user's public key.
- * The backend will respond with a base64-encoded serialized transaction.
-
-3. **Sign and Send the Transaction:**
- * Deserialize the transaction received from the backend.
- * Use the connected wallet adapter's `signTransaction` method.
- * Once signed, use the `connection.sendRawTransaction` method from `@solana/web3.js` to broadcast it.
- * Wait for the transaction to be confirmed and then notify the user of the result (success or failure).
-
-## Code Example (Frontend Payment Logic)
-```javascript
-// Add this to your marketplace.js or a dedicated payments module
-import { Connection, Transaction } from '@solana/web3.js';
-import { getConnectedWallet, getConnectedWalletAddress } from './wallet.js';
-
-const connection = new Connection(process.env.NEXT_PUBLIC_SOLANA_RPC_URL, 'confirmed');
-
-async function handleConfirmPurchase() {
- const skillData = JSON.parse(document.getElementById('modal-confirm-btn').dataset.skillData);
- const buyerPublicKey = getConnectedWalletAddress();
- const wallet = getConnectedWallet();
-
- if (!buyerPublicKey || !wallet) {
- alert('Please connect your wallet first.');
- return;
- }
-
- // 1. Fetch transaction from backend
- const response = await fetch('/api/payments/prepare-transaction', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- ...skillData,
- buyerPublicKey,
- agentId: currentAgent.id, // Assuming 'currentAgent' is available in scope
- }),
- });
-
- const { transaction: base64Transaction } = await response.json();
- const transactionBuffer = Buffer.from(base64Transaction, 'base64');
- const transaction = Transaction.from(transactionBuffer);
-
- try {
- // 2. Sign the transaction
- const signedTransaction = await wallet.signTransaction(transaction);
-
- // 3. Send and confirm the transaction
- const signature = await connection.sendRawTransaction(signedTransaction.serialize());
- await connection.confirmTransaction(signature, 'confirmed');
-
- alert(`Purchase successful! Transaction signature: ${signature}`);
- // Next step: Update UI to show the user owns the skill.
- } catch (error) {
- console.error('Purchase failed:', error);
- alert('Purchase failed. See console for details.');
- } finally {
- // Hide the modal
- document.getElementById('purchase-confirm-modal').classList.add('modal-hidden');
- }
-}
-
-// Attach this to the confirm button
-document.getElementById('modal-confirm-btn').addEventListener('click', handleConfirmPurchase);
-
-```
-
-<!-- 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/07-frontend-payment-and-signing.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/07-frontend-unlock-skill-button.md b/prompts/monetization/07-frontend-unlock-skill-button.md
deleted file mode 100644
index 19f1ed6e4..000000000
--- a/prompts/monetization/07-frontend-unlock-skill-button.md
+++ /dev/null
@@ -1,114 +0,0 @@
----
-status: not-started
----
-
-# Prompt 7: Frontend - "Unlock Skill" Button
-
-## Objective
-Update the marketplace UI (`marketplace.js` and `marketplace.html`) to show a prominent "Unlock" or "Purchase" button next to paid skills.
-
-## Explanation
-Now that we can display prices, the next logical step for the user is an action to purchase the skill. This task involves changing the static price badge into an interactive button for skills that are not free and have not yet been purchased by the user.
-
-## Instructions
-1. **Fetch User's Unlocked Skills:**
- * You'll need a way to know which skills the currently logged-in user already owns. This requires a new API endpoint, e.g., `GET /api/users/me/unlocked-skills`, which returns an array of skill names or IDs the user has purchased.
- * In `marketplace.js`, when the application loads, fetch this list of unlocked skills and store it.
-
-2. **Modify the `renderDetail` function:**
- * In `src/marketplace.js`, within the `renderDetail` function where you iterate over skills, you now need three pieces of information for each skill:
- 1. The skill's details (name, description).
- 2. The skill's price (from `agent.skill_prices`).
- 3. Whether the current user has unlocked it (from the list fetched in step 1).
-
-3. **Conditional Rendering Logic:**
- * Inside the loop, implement the following logic for each skill:
- * **If `price` does not exist:** The skill is free. Render a "Free" badge.
- * **If `price` exists AND the user has unlocked the skill:** The skill is already owned. Render an "Unlocked" or "Owned" badge.
- * **If `price` exists AND the user has NOT unlocked the skill:** The skill is available for purchase. Render a "Unlock for X USDC" button.
-
-4. **Add Data Attributes:**
- * The "Unlock" button needs to have necessary information attached to it so its event handler knows what to do. Use `data-*` attributes to store the `agentId` and `skillName`.
-
-## Code Example (`src/marketplace.js` inside `renderDetail`)
-
-```javascript
-// Assume `unlockedSkills` is a Set or array of skill names fetched on page load
-const unlockedSkills = new Set(['Jupiter Swapper']); // Example data
-
-// ... inside renderDetail loop ...
-const skillPrices = a.skill_prices || {};
-$('d-skills').innerHTML = skillsArr.map((s) => {
- const name = typeof s === 'string' ? s : (s.name || '');
- const price = skillPrices[name];
-
- let badgeHtml;
- if (!price) {
- badgeHtml = `<span class="price-badge price-free">Free</span>`;
- } else if (unlockedSkills.has(name)) {
- badgeHtml = `<span class="price-badge price-unlocked">✅ Unlocked</span>`;
- } else {
- const amount = (price.amount / 1e6).toFixed(2);
- badgeHtml = `
- <button
- class="btn-unlock-skill"
- data-agent-id="${escapeHtml(a.id)}"
- data-skill-name="${escapeHtml(name)}">
- Unlock for ${amount} USDC
- </button>
- `;
- }
-
- return `<div class="skill-entry">
- <span class="skill-name">${escapeHtml(name)}</span>
- ${badgeHtml}
- </div>`;
-}).join('');
-```
-
-## CSS Example (`/marketplace.css`)
-
-```css
-.skill-entry {
- display: flex;
- justify-content: space-between;
- align-items: center;
- padding: 8px 4px;
- border-bottom: 1px solid #333;
-}
-
-.price-unlocked {
- color: #a7f3d0; /* Same as free, but with a checkmark */
- background-color: rgba(52, 211, 153, 0.1);
-}
-
-.btn-unlock-skill {
- background-color: #4f46e5;
- color: white;
- border: none;
- padding: 4px 10px;
- font-size: 11px;
- font-weight: 600;
- border-radius: 5px;
- cursor: pointer;
- transition: background-color 0.2s;
-}
-
-.btn-unlock-skill:hover {
- background-color: #6366f1;
-}
-```
-
-<!-- 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/07-frontend-unlock-skill-button.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/07-marketplace-paid-indicator.md b/prompts/monetization/07-marketplace-paid-indicator.md
deleted file mode 100644
index 0712877c2..000000000
--- a/prompts/monetization/07-marketplace-paid-indicator.md
+++ /dev/null
@@ -1,101 +0,0 @@
-# Prompt 7: Visual Indicator for Paid Agents in Marketplace
-
-## Objective
-Add a visual badge or indicator to agent cards in the main marketplace grid to quickly show users which agents offer paid skills.
-
-## Explanation
-While filters are useful, users browsing the full list of agents should be able to identify monetized agents at a glance. A simple, clear visual indicator (like a "$" icon or a "Premium" badge) on the agent card will significantly improve scannability.
-
-## Instructions
-1. **Modify Backend API:**
- * The marketplace agent list endpoint (`/api/marketplace/agents`) needs to provide a flag indicating if an agent has any paid skills.
- * When querying the list of agents, perform a `JOIN` or a subquery with `agent_skill_prices`.
- * For each agent in the response, add a boolean field, such as `has_paid_skills: true` or `false`.
- * *Optimization Note:* This is more efficient than the frontend making a separate request for each agent.
-
-2. **Update Frontend UI:**
- * Open `src/marketplace.js`, and find the function that renders the grid of agent cards (e.g., `renderAgentGrid`).
- * Inside the loop that creates each agent card, check for the new `agent.has_paid_skills` flag.
- * If the flag is `true`, add an HTML element for the badge to the card's template.
-
-3. **Add CSS Styling:**
- * Open `/marketplace.css` (or the relevant stylesheet).
- * Add styles for your new badge to make it stand out. Position it in a corner of the agent card, for example.
-
-## Code Example (Backend - SQL Query Idea)
-
-```sql
--- A query to fetch agents and a flag indicating if they have priced skills
-SELECT
- agents.*,
- (CASE WHEN COUNT(agent_skill_prices.skill_name) > 0 THEN TRUE ELSE FALSE END) AS has_paid_skills
-FROM
- agents
-LEFT JOIN
- agent_skill_prices ON agents.id = agent_skill_prices.agent_id
-GROUP BY
- agents.id;
-```
-
-## Code Example (Frontend - `src/marketplace.js`)
-
-```javascript
-// Inside your function that renders the agent grid (e.g., renderAgentGrid)
-
-function renderAgentCard(agent) {
- const card = document.createElement('div');
- card.className = 'agent-card';
-
- const premiumBadge = agent.has_paid_skills
- ? '<div class="premium-badge" title="Offers paid skills">⚡</div>'
- : '';
-
- card.innerHTML = `
- <div class="card-thumbnail" style="background-image: url('${escapeHtml(agent.thumbnail_url)}')">
- ${premiumBadge}
- </div>
- <div class="card-body">
- <h3 class="card-title">${escapeHtml(agent.name)}</h3>
- <p class="card-description">${escapeHtml(agent.description)}</p>
- </div>
- `;
- return card;
-}
-```
-
-## Code Example (CSS - `/marketplace.css`)
-
-```css
-.agent-card .card-thumbnail {
- position: relative;
- /* ... existing styles ... */
-}
-
-.premium-badge {
- position: absolute;
- top: 8px;
- right: 8px;
- background-color: rgba(253, 224, 71, 0.9); /* Same as --paid-bg but more opaque */
- color: #18181b; /* Dark text for contrast */
- padding: 1px 6px;
- font-size: 14px;
- font-weight: 700;
- border-radius: 6px;
- line-height: 1.4;
- box-shadow: 0 1px 3px rgba(0,0,0,0.3);
-}
-```
-
-<!-- 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/07-marketplace-paid-indicator.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/07-purchase-skill-ui.md b/prompts/monetization/07-purchase-skill-ui.md
deleted file mode 100644
index f5b1a05d0..000000000
--- a/prompts/monetization/07-purchase-skill-ui.md
+++ /dev/null
@@ -1,123 +0,0 @@
----
-status: not-started
----
-
-# Prompt 7: Purchase Skill UI
-
-## Objective
-Create the user interface elements for purchasing a skill, including a "Buy" button and a modal to display the payment QR code.
-
-## Explanation
-With the basic Solana Pay integration in place, we now need the UI that users will interact with. This involves replacing the price badge for unowned, paid skills with a "Buy" button and designing a modal window that will contain the payment instructions and QR code.
-
-## Instructions
-1. **Update Skill Rendering Logic:**
- * In the agent detail page's JavaScript, modify the skill rendering function.
- * For a paid skill that the user has *not* yet purchased, instead of just a price badge, render a "Buy" button alongside the price.
- * The button should have an event listener (e.g., `onclick`) that calls the `PurchaseFlow.initiatePurchase(agent, skillName)` function.
- * You will need a (currently mock) function `userHasSkill(skillName)` to check ownership.
-
-2. **Create the Payment Modal HTML:**
- * In `marketplace.html`, add the HTML structure for a modal dialog.
- * It should be hidden by default (e.g., with `display: none`).
- * The modal should include:
- * A title, e.g., "Complete Your Purchase".
- * A container element where the QR code will be rendered.
- * An area to display information like the skill name and price.
- * A "Cancel" or close button.
-
-3. **Style the Modal:**
- * Add CSS to style the modal as an overlay with a centered content box, similar to other modals in the application.
-
-4. **Implement Modal Show/Hide Logic:**
- * Create simple JavaScript functions `showPaymentModal()` and `hidePaymentModal()`.
- * The `PurchaseFlow.displayPaymentQR` function will call `showPaymentModal()` once it's ready to display the QR code.
- * The close button and overlay background should call `hidePaymentModal()`.
-
-## Code Example (Updated Skill Rendering)
-
-```javascript
-// (Assuming a mock function `userHasSkill` for now)
-const userUnlockedSkills = []; // Mock: will be populated with user data
-function userHasSkill(skillName) {
- return userUnlockedSkills.includes(skillName);
-}
-
-// Inside agent detail rendering
-const skillPrices = agent.skill_prices || {};
-skillsElement.innerHTML = agent.skills.map(skill => {
- const name = skill.name || skill;
- const price = skillPrices[name];
-
- let badgeOrButton;
- if (price) {
- if (userHasSkill(name)) {
- badgeOrButton = `<span class="price-badge price-unlocked">✅ Purchased</span>`;
- } else {
- const priceStr = `${(price.amount / 1e6).toFixed(2)} USDC`;
- badgeOrButton = `<span class="price-badge price-paid">${priceStr}</span>
- <button class="buy-button" onclick='PurchaseFlow.initiatePurchase(${JSON.stringify(agent)}, "${escapeJs(name)}")'>Buy</button>`;
- }
- } else {
- badgeOrButton = `<span class="price-badge price-free">Free</span>`;
- }
- return `<span class="skill-entry">${escapeHtml(name)}${badgeOrButton}</span>`;
-}).join('');
-```
-
-## Code Example (HTML for Payment Modal)
-
-```html
-<!-- Add this somewhere in your marketplace.html body -->
-<div id="payment-modal-backdrop" class="modal-backdrop">
- <div class="modal-content">
- <div class="modal-header">
- <h3>Complete Your Purchase</h3>
- <button id="payment-modal-close" class="close-button">&times;</button>
- </div>
- <div class="modal-body">
- <p>Scan the code with a Solana Pay compatible wallet to purchase:</p>
- <strong id="payment-skill-name"></strong> for <strong id="payment-skill-price"></strong>
- <div id="payment-qr-container">
- <!-- QR Code will be rendered here -->
- </div>
- <div class="spinner" id="payment-spinner"></div>
- <p class="status-text" id="payment-status-text">Waiting for payment...</p>
- </div>
- </div>
-</div>
-```
-
-## CSS for Buy Button
-
-```css
-.buy-button {
- background-color: var(--accent);
- color: #000;
- border: none;
- border-radius: 4px;
- padding: 3px 8px;
- font-size: 10px;
- font-weight: 600;
- cursor: pointer;
- margin-left: 8px;
- vertical-align: middle;
-}
-.buy-button:hover {
- background-color: #00ff55;
-}
-```
-
-<!-- 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/07-purchase-skill-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/07-real-time-ui-update.md b/prompts/monetization/07-real-time-ui-update.md
deleted file mode 100644
index 4a89708ed..000000000
--- a/prompts/monetization/07-real-time-ui-update.md
+++ /dev/null
@@ -1,102 +0,0 @@
-# Prompt 7: Real-time UI Update on Purchase
-
-## Objective
-Update the agent detail page UI in real-time to reflect a successful skill purchase without requiring a page refresh.
-
-## Explanation
-A seamless user experience requires immediate feedback. After a user approves the transaction on their phone, the webpage should detect the successful purchase and automatically update the UI. It should change the "Purchase" button to an "Owned" status indicator. We can achieve this by having the frontend poll a confirmation endpoint while the payment modal is open.
-
-## Instructions
-1. **Create a Polling Endpoint (Backend):**
- * Create a new, simple endpoint, e.g., `/api/payments/check-purchase-status`.
- * This endpoint will take a transaction `reference` ID as a query parameter.
- * It will check the `user_skill_ownership` table to see if the record for that purchase exists.
- * It should return a status, e.g., `{ status: 'confirmed' }` or `{ status: 'pending' }`.
-
-2. **Implement Polling (Frontend - `src/marketplace.js`):**
- * When you first make the `POST` request to prepare the transaction, the response should include the unique `reference` ID.
- * Once the QR code is displayed, start a polling mechanism (e.g., using `setInterval`).
- * Every 2-3 seconds, make a `GET` request to `/api/payments/check-purchase-status?reference=<reference_id>`.
- * If the status comes back as `confirmed`:
- * Stop the polling (`clearInterval`).
- * Close the payment modal.
- * Re-render the skills section or dynamically update the specific skill entry in the DOM to show the "Owned" state.
- * Show a success notification (toast).
- * The polling should also have a timeout (e.g., 5 minutes) to prevent it from running forever if something goes wrong.
-
-## Code Example (Frontend - `src/marketplace.js`)
-
-```javascript
-// Inside handlePurchaseClick, after the POST request succeeds
-const { transaction, message, reference } = await response.json(); // Backend must return reference
-
-const url = `solana:${encodeURIComponent(transaction)}`;
-renderPaymentModal(url, message);
-
-// Start polling for confirmation
-const pollInterval = setInterval(async () => {
- try {
- const statusRes = await fetch(`/api/payments/check-purchase-status?reference=${reference}`);
- const { status } = await statusRes.json();
-
- if (status === 'confirmed') {
- clearInterval(pollInterval);
- $('payment-modal').close();
- showToast('Purchase successful!', 'success');
-
- // Find the button and replace it with an 'Owned' span
- const button = document.querySelector(`.purchase-skill-btn[data-skill-name="${skillName}"]`);
- if (button) {
- const ownedSpan = document.createElement('span');
- ownedSpan.className = 'skill-owned';
- ownedSpan.textContent = '✓ Owned';
- button.replaceWith(ownedSpan);
- }
- }
- } catch (err) {
- // Silently ignore polling errors, or stop polling after too many failures
- console.warn('Polling error:', err);
- }
-}, 2500);
-
-// Add a timeout to stop polling after 5 minutes
-setTimeout(() => {
- clearInterval(pollInterval);
-}, 300000);
-```
-
-## Backend Status Endpoint (`api/payments/check-purchase-status.js`)
-
-```javascript
-import { findOwnershipByReference } from '../_lib/db'; // Placeholder DB function
-
-export default async function handler(req, res) {
- if (req.method !== 'GET') return res.status(405).end();
-
- const { reference } = req.query;
- if (!reference) return res.status(400).json({ error: 'Reference required' });
-
- // This DB function needs to link the reference to the ownership record
- const isOwned = await findOwnershipByReference(reference);
-
- if (isOwned) {
- return res.status(200).json({ status: 'confirmed' });
- } else {
- return res.status(200).json({ status: 'pending' });
- }
-}
-```
-
-<!-- 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/07-real-time-ui-update.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/07-solana-payment-integration.md b/prompts/monetization/07-solana-payment-integration.md
deleted file mode 100644
index f95907bd5..000000000
--- a/prompts/monetization/07-solana-payment-integration.md
+++ /dev/null
@@ -1,64 +0,0 @@
----
-status: not-started
----
-
-# Prompt 7: Solana Payment Integration
-
-## Objective
-Integrate the Solana wallet-adapter to process skill purchase transactions on the Solana blockchain.
-
-## Explanation
-To handle payments in a decentralized way, we will use the Solana wallet-adapter to connect to the user's wallet (like Phantom) and request them to sign and send the transaction.
-
-## Instructions
-1. **Add Wallet-Adapter Dependencies:**
- * Include the necessary wallet-adapter scripts in `marketplace.html`.
- * You will need `@solana/wallet-adapter-base`, `@solana/wallet-adapter-wallets`, and `@solana/web3.js`.
-
-2. **Implement Connection Logic:**
- * In `src/marketplace.js`, add a "Connect Wallet" button and the logic to connect to the user's wallet.
- * Store the user's public key when they connect.
-
-3. **Implement the Purchase Transaction:**
- * When the user confirms the purchase in the modal, construct a Solana transaction.
- * The transaction will transfer the required amount of SOL or SPL tokens (like USDC) from the user's wallet to the creator's wallet.
- * Use the wallet-adapter to ask the user to sign and send the transaction.
-
-## Code Example (JavaScript - `src/marketplace.js`)
-
-```javascript
-// Inside the 'confirm-purchase' button's event listener
-
-const provider = getProvider(); // From your wallet-adapter setup
-const connection = new solanaWeb3.Connection(solanaWeb3.clusterApiUrl('devnet'));
-
-const transaction = new solanaWeb3.Transaction().add(
- solanaWeb3.SystemProgram.transfer({
- fromPubkey: user.publicKey,
- toPubkey: new solanaWeb3.PublicKey(creatorWalletAddress),
- lamports: price.amount,
- })
-);
-
-try {
- const signature = await provider.sendTransaction(transaction, connection);
- await connection.confirmTransaction(signature, 'processed');
- // On success, notify the backend to unlock the skill
-} catch (error) {
- console.error("Transaction failed", 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/07-solana-payment-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/07_api_purchase_prep.md b/prompts/monetization/07_api_purchase_prep.md
deleted file mode 100644
index 553ddbd79..000000000
--- a/prompts/monetization/07_api_purchase_prep.md
+++ /dev/null
@@ -1,97 +0,0 @@
----
-status: not-started
-last_updated: 2026-05-04
----
-# Prompt 07: Backend API for Purchase Preparation
-
-## Objective
-Create a backend endpoint that prepares an on-chain transaction for a user to purchase a skill.
-
-## Explanation
-When a user clicks the "Purchase" button, the frontend needs to request a transaction from the backend. This endpoint will not execute the transaction but will prepare it. It will construct a Solana transaction that, when signed by the user, will transfer the correct amount of USDC from the user's wallet to the agent creator's wallet. This is a crucial step for security and a smooth user experience.
-
-## Instructions
-1. **Create the API Endpoint:**
- * Create a new file or handler, e.g., `POST /api/skills/purchase-prep`.
-
-2. **Implement the Logic:**
- * **Authentication:** Ensure the user is authenticated.
- * **Input Validation:** The request body should contain the `agent_id` and `skill_name`. Validate these inputs.
- * **Fetch Data:**
- * Retrieve the skill's price from the `agent_skill_prices` table.
- * Retrieve the agent creator's wallet address from the `agent_identities` table (`meta.onchain.wallet`).
- * Retrieve the buyer's wallet address from their session or a trusted source.
- * **Construct Transaction:**
- * Using the Solana Web3.js library (`@solana/web3.js`), create a new transaction.
- * The transaction should contain one primary instruction: a `spl-token` transfer from the buyer's USDC associated token account (ATA) to the creator's USDC ATA.
- * The amount should be the price fetched from the database.
- * The transaction's `feePayer` should be set to the buyer's public key.
- * **Serialization:**
- * Serialize the transaction without signing it.
- * Return the serialized transaction as a base64-encoded string. This is what the frontend will receive and pass to the user's wallet to be signed.
- * **Record Preparation:**
- * It's good practice to store a temporary record of this preparation step (e.g., in Redis or a `skill_purchase_preparations` table) with an expiration time, to prevent replay attacks and to link it to the confirmation step.
-
-## Code Example (Vercel Serverless Function)
-
-```javascript
-import { Connection, PublicKey, Transaction } from '@solana/web3.js';
-import { getOrCreateAssociatedTokenAccount, createTransferInstruction } from '@solana/spl-token';
-import { sql } from '../../_lib/db.js';
-// ... other imports
-
-export default wrap(async (req, res) => {
- // ... auth and validation
- const { agent_id, skill_name } = req.body;
- const user = await getSessionUser(req);
- const buyerPublicKey = new PublicKey(user.wallet_address);
-
- // 1. Fetch skill price and creator wallet
- const [skillPrice] = await sql`...`;
- const [agent] = await sql`...`;
- const creatorPublicKey = new PublicKey(agent.meta.onchain.wallet);
- const usdcMint = new PublicKey(skillPrice.currency_mint);
-
- // 2. Setup connection and ATAs
- const connection = new Connection(rpcUrl('mainnet-beta'));
- const buyerAta = await getOrCreateAssociatedTokenAccount(connection, buyerPublicKey, usdcMint, buyerPublicKey);
- const creatorAta = await getOrCreateAssociatedTokenAccount(connection, buyerPublicKey, usdcMint, creatorPublicKey);
-
- // 3. Create transaction
- const { blockhash } = await connection.getLatestBlockhash();
- const tx = new Transaction({
- feePayer: buyerPublicKey,
- recentBlockhash: blockhash,
- });
-
- tx.add(
- createTransferInstruction(
- buyerAta.address,
- creatorAta.address,
- buyerPublicKey,
- skillPrice.amount
- )
- );
-
- // 4. Serialize and return
- const serializedTx = tx.serialize({ requireAllSignatures: false }).toString('base64');
-
- // 5. Save prep record (omitted for brevity)
-
- return json(res, 200, { transaction: serializedTx });
-});
-```
-
-<!-- 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/07_api_purchase_prep.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/08-backend-api-process-payment.md b/prompts/monetization/08-backend-api-process-payment.md
deleted file mode 100644
index 855a6af29..000000000
--- a/prompts/monetization/08-backend-api-process-payment.md
+++ /dev/null
@@ -1,65 +0,0 @@
----
-status: not-started
----
-
-# Prompt 8: Backend API to Process Payments
-
-## Objective
-Create a backend endpoint to verify and record a skill purchase transaction after it has been confirmed on the blockchain.
-
-## Explanation
-After a user's transaction is successfully sent to the Solana network, the frontend needs to notify the backend. The backend will then verify the transaction and, if it's valid, record that the user now owns the skill. This prevents users from accessing paid skills without a valid payment.
-
-## Instructions
-1. **Create a New API Endpoint:**
- * Create a new endpoint, for example, `POST /api/marketplace/skills/purchase`.
- * This endpoint will receive the transaction signature and the skill name being purchased.
-
-2. **Verify the Transaction:**
- * In the backend, use the Solana web3 library to fetch the transaction details using the signature.
- * Verify that the transaction is valid:
- * It transferred the correct amount of the correct currency.
- * The funds were sent from the user's wallet to the correct creator's wallet.
- * The transaction has been successfully confirmed.
-
-3. **Record the Purchase:**
- * If the transaction is valid, insert a new record into the `user_skill_purchases` table to grant the user ownership of the skill.
-
-## Code Example (Backend - Node.js with `@solana/web3.js`)
-
-```javascript
-// POST /api/marketplace/skills/purchase
-router.post('/skills/purchase', async (req, res) => {
- const { signature, skillName, agentId } = req.body;
- const userId = req.session.userId;
-
- // 1. Fetch transaction details from the blockchain
- const connection = new solanaWeb3.Connection(solanaWeb3.clusterApiUrl('devnet'));
- const tx = await connection.getTransaction(signature);
-
- // 2. Verify the transaction's details (amount, recipient, etc.)
- const isValid = verifyTransaction(tx, { /* expected details */ });
-
- if (isValid) {
- // 3. Record the purchase in the database
- await db.recordSkillPurchase(userId, skillName, agentId);
- res.status(200).json({ success: true });
- } else {
- res.status(400).json({ error: 'Invalid transaction' });
- }
-});
-```
-
-<!-- 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/08-backend-api-process-payment.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/08-backend-solana-pay-transaction.md b/prompts/monetization/08-backend-solana-pay-transaction.md
deleted file mode 100644
index 83588d44c..000000000
--- a/prompts/monetization/08-backend-solana-pay-transaction.md
+++ /dev/null
@@ -1,119 +0,0 @@
----
-status: not-started
----
-
-# Prompt 8: Backend Solana Pay Transaction Request
-
-## Objective
-Create a backend API endpoint that generates a Solana Pay transaction request for a specific skill purchase.
-
-## Explanation
-When a user clicks "Buy", the frontend needs to ask the backend to prepare a transaction. The backend will define the transaction parameters (recipient, amount, etc.) and encode them into a special URL format that Solana Pay wallets understand. This ensures that the payment details are secure and controlled by the platform.
-
-## Instructions
-1. **Create the API Endpoint:**
- * Create a new GET endpoint, for example, `/api/purchase/transaction`.
- * This endpoint should accept query parameters for `agentId` and `skillName`.
-
-2. **Logic to Fetch Price:**
- * Inside the endpoint, use the `agentId` and `skillName` to look up the price from the `agent_skill_prices` table in your database.
- * If no price is found, return an error.
-
-3. **Define Transaction Parameters:**
- * **Recipient:** This should be the agent owner's public key, which you should have stored alongside the agent's data. For now, you can use a placeholder wallet address.
- * **Amount:** The price of the skill, fetched from the database.
- * **SPL Token:** The currency mint address (e.g., USDC).
- * **Reference:** A unique public key generated on the fly for this specific transaction. This is crucial for tracking the payment later. Use `Keypair.generate().publicKey`.
- * **Label:** The name of your platform or store.
- * **Message:** A descriptive message, e.g., "Purchase of 'SkillName' for 'AgentName'".
- * **Memo:** A short, unique identifier for the purchase, which will be attached to the on-chain transaction. This helps with auditing. E.g., `agent-123:skill-abc`.
-
-4. **Construct Solana Pay URL:**
- * The endpoint needs to return a URL that starts with `solana:`. The rest of the URL is the *URL of the endpoint itself*, which the wallet will then call to get the transaction details.
- * Example: `solana:https://your-api.com/api/purchase/details?agentId=...&skillName=...`
-
-5. **Create the Transaction Details Endpoint:**
- * Create a second endpoint (e.g., `POST /api/purchase/details`) that the wallet will call. This is part of the Solana Pay spec.
- * This endpoint receives the user's public key in the request body (`{ account: "USER_WALLET_ADDRESS" }`).
- * It should return a JSON object containing the full transaction details, including a base64-encoded, serialized transaction.
- * Use the `@solana/web3.js` library to build a `SystemProgram.transfer` or `splToken.createTransferInstruction` transaction.
- * Add the `memo` to the transaction.
- * Serialize the transaction, but **do not sign it**. The user's wallet will sign.
-
-## Code Example (Backend - Express.js style)
-
-```javascript
-// This is the first endpoint the frontend calls
-// GET /api/purchase/transaction?agentId=...&skillName=...
-app.get('/api/purchase/transaction', (req, res) => {
- const { agentId, skillName } = req.query;
- // IMPORTANT: The URL returned here is the *next* endpoint the wallet will call.
- const url = new URL(`${req.protocol}://${req.get('host')}/api/purchase/details`);
- url.searchParams.set('agentId', agentId);
- url.searchParams.set('skillName', skillName);
-
- // This is the URL the QR code will encode
- const solanaPayUrl = `solana:${encodeURIComponent(url.toString())}`;
- res.json({ url: solanaPayUrl });
-});
-
-
-// This is the second endpoint the WALLET calls
-// POST /api/purchase/details
-app.post('/api/purchase/details', async (req, res) => {
- const { account } = req.body; // User's wallet address
- const { agentId, skillName } = req.query;
-
- // 1. Fetch skill price and agent owner's wallet from DB
- const priceInfo = await db.getSkillPrice(agentId, skillName); // { amount, currency_mint, owner_wallet }
- if (!priceInfo) {
- return res.status(404).json({ error: "Skill or price not found" });
- }
-
- // 2. Create a reference keypair for tracking
- const reference = new solanaWeb3.Keypair().publicKey;
-
- // 3. Build the transaction
- const transaction = new solanaWeb3.Transaction();
- // ... logic to get recent blockhash ...
-
- // Add a transfer instruction
- transaction.add(
- splToken.createTransferInstruction(...) // From: `account`, To: `priceInfo.owner_wallet`, Amount: `priceInfo.amount`
- );
-
- // Add the memo
- transaction.add(new solanaWeb3.TransactionInstruction({
- keys: [],
- programId: new solanaWeb3.PublicKey('MemoSq4gqABAXKb96qnH8TysNcVnuizgaCgWvunP'),
- data: Buffer.from(`Purchase: ${skillName} from Agent ${agentId}`),
- }));
-
- transaction.feePayer = new solanaWeb3.PublicKey(account);
- transaction.recentBlockhash = ...;
-
- // 4. Serialize and encode
- const serializedTx = transaction.serialize({ requireAllSignatures: false });
- const base64Tx = serializedTx.toString('base64');
-
- // 5. Return the response in Solana Pay format
- res.json({
- transaction: base64Tx,
- message: `Purchase ${skillName}`,
- });
-});
-```
-
-<!-- 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/08-backend-solana-pay-transaction.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/08-detect-paid-skill-usage.md b/prompts/monetization/08-detect-paid-skill-usage.md
deleted file mode 100644
index 6f88eac24..000000000
--- a/prompts/monetization/08-detect-paid-skill-usage.md
+++ /dev/null
@@ -1,97 +0,0 @@
-# Prompt 8: Detect Paid Skill Usage in Chat
-
-## Objective
-In the chat interface, implement logic to detect when a user attempts to use a skill that requires payment.
-
-## Explanation
-This is the entry point for the payment flow within the chat itself. When the user's prompt is interpreted by the AI and mapped to a specific skill, the system needs to check if that skill has an associated price before attempting to execute it.
-
-## Instructions
-1. **Modify Chat Backend/Orchestrator:**
- * Identify the part of your application that receives the AI model's response, which indicates the intent to use a skill. This could be in `/api/chat.js` or a similar backend orchestrator.
- * Before executing the skill, this orchestrator needs access to the agent's skill pricing information.
- * When fetching the agent's details at the beginning of a chat session, make sure to also fetch its `skill_prices` (as implemented in Prompt 1) and keep them available in the session's context.
-
-2. **Implement the Price Check:**
- * After the AI model decides which skill to use (e.g., `skill_name: "generate-image"`), but *before* executing the skill's logic, perform a check:
- ```javascript
- const skillPrices = agent.skill_prices || {};
- const price = skillPrices[skillToExecute.name];
-
- if (price && price.amount > 0) {
- // This is a paid skill.
- // Halt execution and proceed to the payment flow.
- } else {
- // This is a free skill.
- // Proceed with normal execution.
- }
- ```
-
-3. **Check for Existing Access Grants:**
- * Before flagging a skill as needing payment, you must first check if the user *already has access*. This requires a new database lookup.
- * Query the `skill_access_grants` table (which will be created in a later prompt) for a valid grant for the current `user_id`, `agent_id`, and `skill_name`.
- * A grant is valid if `expires_at` is in the future or `uses_left` is greater than 0.
- * If a valid grant exists, treat the skill as free and proceed with execution. If not, proceed to the payment flow.
-
-4. **Signal to the Frontend:**
- * If payment is required, the backend should not execute the skill. Instead, it must send a specific message back to the chat UI.
- * This can be a special message type in your WebSocket or SSE stream, or a structured JSON response via HTTP.
- * The message must contain the necessary information to render a payment modal: `skill_name`, `amount`, `currency_mint`.
-
-## Code Example (Backend - `/api/chat.js` or similar)
-
-```javascript
-// Inside the main chat processing logic, after receiving the AI's intent to use a skill
-
-async function processUserMessage(message, agent, user) {
- // ... logic to get AI response ...
- const { skillToExecute, parameters } = ai.interpret(message);
-
- if (skillToExecute) {
- const skillPrices = agent.skill_prices || {};
- const price = skillPrices[skillToExecute.name];
-
- if (price && price.amount > 0) {
- // Paid skill detected. First, check if user already has access.
- const hasAccess = await db.checkForValidSkillGrant({
- userId: user.id,
- agentId: agent.id,
- skillName: skillToExecute.name
- });
-
- if (!hasAccess) {
- // No access. Signal to frontend to start payment flow.
- return {
- type: 'payment_required',
- data: {
- skill_name: skillToExecute.name,
- amount: price.amount,
- currency_mint: price.currency_mint
- }
- };
- }
- // User has access, fall through to execution.
- }
-
- // Free skill or user has access, execute it.
- const result = await executeSkill(skillToExecute.name, parameters);
- return { type: 'message', data: { text: result } };
- }
-
- // ... handle regular text response ...
-}
-```
-
-<!-- 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/08-detect-paid-skill-usage.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/08-frontend-payment-flow.md b/prompts/monetization/08-frontend-payment-flow.md
deleted file mode 100644
index a5509d721..000000000
--- a/prompts/monetization/08-frontend-payment-flow.md
+++ /dev/null
@@ -1,109 +0,0 @@
----
-status: not-started
----
-
-# Prompt 8: Frontend - Payment Flow
-
-## Objective
-Implement the client-side logic to handle the entire skill purchase flow: requesting the transaction, getting the user's signature, sending it to the network, and confirming it.
-
-## Explanation
-This prompt connects the "Unlock" button to the backend and the user's wallet. When a user clicks the button, the frontend will orchestrate the process of fetching, signing, and broadcasting the payment transaction on the Solana network. This is a critical user-facing step that needs to be smooth and provide clear feedback.
-
-## Instructions
-1. **Add Event Listener:**
- * In `src/marketplace.js`, add a click event listener to the container of the skills list (or delegate from a higher-level element). When a `.btn-unlock-skill` is clicked, the handler should fire.
-
-2. **Request the Transaction:**
- * Inside the event handler, get the `agentId` and `skillName` from the button's `data-*` attributes.
- * Get the connected user's public key from the `useWallet` hook. If no wallet is connected, prompt the user to connect first.
- * Send a `POST` request to your `/api/payments/create-transaction` endpoint with the `agentId`, `skillName`, and `buyerPublicKey`.
- * Show a loading indicator to the user (e.g., disable the button and show a spinner).
-
-3. **Deserialize and Sign:**
- * The API will respond with a base64-encoded transaction string.
- * Decode the base64 string into a buffer.
- * Use `Transaction.from()` from `@solana/web3.js` to deserialize the buffer back into a `Transaction` object.
- * Use the `signTransaction` function from the `useWallet` hook to prompt the user to sign the transaction with their wallet. This will open a popup in their wallet extension.
-
-4. **Send and Confirm the Transaction:**
- * Once the user signs, the `signTransaction` function will return the signed transaction.
- * Serialize the signed transaction and use `connection.sendRawTransaction` to broadcast it to the Solana network. This will return a transaction signature (ID).
- * Use `connection.confirmTransaction` with the signature to wait for the transaction to be confirmed by the network. This is crucial for ensuring the payment went through before considering the skill unlocked.
-
-5. **Provide Feedback:**
- * While confirming, keep the user informed (e.g., "Confirming transaction...").
- * On successful confirmation, show a success message ("Skill unlocked!").
- * You should then refresh the UI to show the skill as "Unlocked", either by re-fetching user data or just updating the DOM for that specific skill.
- * If any step fails (user rejects signature, transaction fails), show a clear error message.
-
-## Code Example (`src/marketplace.js`)
-
-```javascript
-import { useWallet, useConnection } from '@solana/wallet-adapter-react';
-import { Transaction } from '@solana/web3.js';
-// ... other imports
-
-// Add this listener in your initialization code
-document.getElementById('d-skills').addEventListener('click', async (event) => {
- if (!event.target.matches('.btn-unlock-skill')) return;
-
- const button = event.target;
- const { agentId, skillName } = button.dataset;
- const { publicKey, signTransaction } = useWallet(); // From wallet adapter context
- const { connection } = useConnection(); // From wallet adapter context
-
- if (!publicKey || !signTransaction) {
- showToast('Please connect your wallet first.', 'error');
- return;
- }
-
- try {
- button.disabled = true;
- button.textContent = 'Processing...';
-
- // 1. Fetch transaction from backend
- const response = await fetch('/api/payments/create-transaction', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ agentId, skillName, buyerPublicKey: publicKey.toBase58() })
- });
- if (!response.ok) throw new Error('Failed to create transaction.');
- const { transaction: base64Transaction } = await response.json();
-
- // 2. Deserialize, sign, and send
- const transaction = Transaction.from(Buffer.from(base64Transaction, 'base64'));
- const signedTransaction = await signTransaction(transaction);
- const signature = await connection.sendRawTransaction(signedTransaction.serialize());
-
- // 3. Confirm transaction
- await connection.confirmTransaction(signature, 'confirmed');
-
- showToast('Skill unlocked successfully!', 'success');
-
- // 4. Update UI
- button.outerHTML = `<span class="price-badge price-unlocked">✅ Unlocked</span>`;
- // Optionally, add skillName to a local `unlockedSkills` set.
-
- } catch (error) {
- console.error('Purchase failed:', error);
- showToast(error.message || 'Purchase failed. Please try again.', 'error');
- button.disabled = false;
- button.textContent = 'Unlock for ...'; // Restore original text
- }
-});
-```
-
-<!-- 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/08-frontend-payment-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/08-set-skill-prices-ui.md b/prompts/monetization/08-set-skill-prices-ui.md
deleted file mode 100644
index d013a3440..000000000
--- a/prompts/monetization/08-set-skill-prices-ui.md
+++ /dev/null
@@ -1,116 +0,0 @@
-# Prompt 8: "Set Skill Prices" UI
-
-## Objective
-Create a user interface within the agent creation/editing page (`agent-edit.html`) that allows creators to set prices for their agent's skills.
-
-## Explanation
-To enable monetization, creators need a simple and intuitive way to manage the prices of their skills. This task involves building the UI components (input fields, selectors) where a creator can assign a price and currency to each skill associated with their agent.
-
-## Instructions
-1. **Modify Agent Edit Page (`agent-edit.html`):**
- * Locate the section where skills are listed or added for an agent.
- * For each skill listed, add input fields for `price` and a dropdown for `currency`.
-
-2. **Structure the UI:**
- * The UI should be clear. Next to each skill name, add:
- * An `<input type="number">` for the price. It should have `step="0.01"` and `min="0"` for decimal values.
- * A `<select>` dropdown for the currency. Initially, this can be hardcoded to just "USDC". In the future, it could be populated with other SPL tokens.
- * A "Save Prices" button at the end of the section.
-
-3. **Fetch Existing Prices:**
- * When the agent edit page loads, it fetches the agent's data. This data should now include any previously saved skill prices.
- * The UI should be populated with these existing prices when the page loads.
-
-## HTML Example (Inside `agent-edit.html`)
-
-```html
-<!-- Inside the form for editing an agent -->
-<div id="skills-pricing-section">
- <h3>Monetize Skills</h3>
- <p>Set a price for your skills. Leave the price as 0 for a free skill.</p>
- <div id="skill-price-list">
- <!-- This list will be populated dynamically by JavaScript -->
- </div>
- <button type="button" id="save-skill-prices-btn">Save Prices</button>
-</div>
-```
-
-## JavaScript for Rendering (`src/agent-edit.js`)
-
-```javascript
-// Function to render the skill price inputs
-function renderSkillPricing(agent) {
- const skills = agent.skills || [];
- const prices = agent.skill_prices || {};
- const container = document.getElementById('skill-price-list');
-
- if (!skills.length) {
- container.innerHTML = '<p>Add skills to your agent to set their prices.</p>';
- return;
- }
-
- container.innerHTML = skills.map(skill => {
- const skillName = skill.name || skill;
- const price = prices[skillName] ? (prices[skillName].amount / 1e6) : 0;
- const currency = prices[skillName] ? prices[skillName].currency_mint : 'USDC';
-
- return `
- <div class="skill-price-entry" data-skill-name="${escapeHtml(skillName)}">
- <label for="price-${escapeHtml(skillName)}">${escapeHtml(skillName)}</label>
- <input
- type="number"
- id="price-${escapeHtml(skillName)}"
- class="skill-price-input"
- value="${price}"
- min="0"
- step="0.01"
- placeholder="e.g., 1.99"
- />
- <select class="skill-currency-select">
- <option value="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6d" ${currency === 'USDC' ? 'selected' : ''}>USDC</option>
- <!-- Other currencies can be added later -->
- </select>
- </div>
- `;
- }).join('');
-}
-
-// In your page load logic:
-// const agentData = await fetchAgentData(agentId);
-// renderSkillPricing(agentData);
-```
-
-## CSS for Styling
-
-```css
-.skill-price-entry {
- display: flex;
- align-items: center;
- gap: 12px;
- margin-bottom: 8px;
-}
-.skill-price-entry label {
- flex: 1;
- font-weight: 500;
-}
-.skill-price-input, .skill-currency-select {
- padding: 6px 8px;
- border-radius: 4px;
- border: 1px solid var(--border);
- background: var(--panel);
-}
-```
-
-<!-- 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/08-set-skill-prices-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/08_frontend_signing_logic.md b/prompts/monetization/08_frontend_signing_logic.md
deleted file mode 100644
index 888617676..000000000
--- a/prompts/monetization/08_frontend_signing_logic.md
+++ /dev/null
@@ -1,111 +0,0 @@
----
-status: not-started
-last_updated: 2026-05-04
----
-# Prompt 08: Frontend Logic for Signing and Sending Transaction
-
-## Objective
-Implement the client-side logic that takes the prepared transaction from the backend, asks the user to sign it with their wallet, and sends it to the Solana network.
-
-## Explanation
-This is the core of the on-chain interaction from the user's perspective. The frontend will receive the base64-encoded transaction, deserialize it, prompt the user for a signature via their connected wallet (e.g., Phantom), and then broadcast the signed transaction to the blockchain.
-
-## Instructions
-1. **Integrate with Wallet Adapter:**
- * Ensure a Solana wallet adapter (like `@solana/wallet-adapter-react` or a vanilla equivalent) is integrated into your frontend to manage wallet connections.
-
-2. **Handle the "Purchase" Button Click:**
- * In `src/marketplace.js`, attach an async function to the purchase button's click event.
-
-3. **Implement the Purchase Flow:**
- * **Step 1: Fetch Prepared Transaction:**
- * When the button is clicked, call the `POST /api/skills/purchase-prep` endpoint created in the previous prompt.
- * **Step 2: Deserialize:**
- * Take the base64 `transaction` string from the response and deserialize it into a `Transaction` object using the Solana Web3.js library.
- * **Step 3: Sign Transaction:**
- * Use the connected wallet's `signTransaction` method to ask the user to sign the transaction. This will pop up the wallet interface. Handle potential user rejection of the signature.
- * **Step 4: Send Transaction:**
- * If signing is successful, use the `connection.sendRawTransaction` method to broadcast the signed transaction to the network.
- * **Step 5: Confirm Transaction:**
- * Wait for the transaction to be confirmed by the network using `connection.confirmTransaction`. This gives the user feedback that their purchase was successful.
- * **Step 6: Finalize with Backend:**
- * After on-chain confirmation, call a new backend endpoint (`/api/skills/purchase-confirm`, to be built next) with the transaction signature. This will record the purchase in our database.
-
-## Code Example (`src/marketplace.js`)
-
-```javascript
-import { Connection, Transaction } from '@solana/web3.js';
-// Assume `wallet` is the connected wallet object from a wallet adapter
-// Assume `connection` is an initialized Connection object
-
-async function handlePurchase(agentId, skillName, button) {
- try {
- // 1. Prepare
- button.disabled = true;
- button.textContent = 'Preparing...';
- const prepRes = await fetch('/api/skills/purchase-prep', {
- method: 'POST',
- body: JSON.stringify({ agent_id: agentId, skill_name: skillName }),
- headers: { 'Content-Type': 'application/json' }
- });
- if (!prepRes.ok) throw new Error('Failed to prepare transaction.');
- const { transaction: base64Tx } = await prepRes.json();
-
- // 2. Deserialize
- const tx = Transaction.from(Buffer.from(base64Tx, 'base64'));
-
- // 3. Sign
- button.textContent = 'Please sign...';
- const signedTx = await wallet.signTransaction(tx);
-
- // 4. Send
- button.textContent = 'Sending...';
- const signature = await connection.sendRawTransaction(signedTx.serialize());
-
- // 5. Confirm
- button.textContent = 'Confirming...';
- await connection.confirmTransaction(signature, 'confirmed');
-
- // 6. Finalize with our backend
- const confirmRes = await fetch('/api/skills/purchase-confirm', {
- method: 'POST',
- body: JSON.stringify({ agent_id: agentId, skill_name: skillName, signature }),
- headers: { 'Content-Type': 'application/json' }
- });
- if (!confirmRes.ok) throw new Error('Failed to confirm purchase with server.');
-
- // 7. Update UI
- button.textContent = '✓ Owned';
- button.classList.add('owned');
- // Prevent further clicks
- button.replaceWith(button.cloneNode(true));
-
- } catch (err) {
- console.error('Purchase failed:', err);
- button.disabled = false;
- button.textContent = 'Purchase Failed - Retry';
- }
-}
-
-// Modify the event listener from Prompt 5
-document.getElementById('d-skills').addEventListener('click', (e) => {
- if (e.target.matches('.btn-purchase:not(:disabled)')) {
- const { skillName, agentId } = e.target.dataset;
- handlePurchase(agentId, skillName, e.target);
- }
-});
-```
-
-<!-- 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/08_frontend_signing_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/09-backend-create-skill-ownership-table.md b/prompts/monetization/09-backend-create-skill-ownership-table.md
deleted file mode 100644
index 829895a80..000000000
--- a/prompts/monetization/09-backend-create-skill-ownership-table.md
+++ /dev/null
@@ -1,69 +0,0 @@
----
-status: not-started
----
-
-# Prompt 9: Backend - Create Skill Ownership Table
-
-## Objective
-Create a database table to permanently record which users have successfully purchased which skills.
-
-## Explanation
-After a user pays for a skill, we need to record their ownership so they don't have to pay for it again. A dedicated table, `user_unlocked_skills`, will store the relationship between a user, an agent, and a specific skill. This table will be the source of truth for checking skill access.
-
-## Instructions
-1. **Design the Table Schema:**
- * Name the table `user_unlocked_skills`.
- * It needs a column to link to the user (`user_id`).
- * It needs a column to link to the agent (`agent_id`).
- * It needs a column to identify the skill (`skill_name`).
- * It's highly recommended to store a reference to the purchase transaction (`purchase_tx_signature`) for auditing and customer support purposes.
- * Add a primary key and foreign keys to `users` and `agent_identities`.
- * Create a unique constraint on (`user_id`, `agent_id`, `skill_name`) to ensure a user can't have duplicate entries for the same skill.
-
-2. **Create a SQL Migration File:**
- * Create a new SQL migration file (e.g., `scripts/migrations/003_create_user_unlocked_skills.sql`).
- * Write the `CREATE TABLE` statement.
- * Include a `created_at` timestamp to know when the skill was unlocked.
-
-## Code Example (SQL)
-
-```sql
--- scripts/migrations/003_create_user_unlocked_skills.sql
-
-CREATE TABLE IF NOT EXISTS user_unlocked_skills (
- id SERIAL PRIMARY KEY,
- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- agent_id INTEGER NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,
- skill_name VARCHAR(255) NOT NULL,
-
- -- The Solana transaction signature of the purchase
- purchase_tx_signature VARCHAR(88) NOT NULL,
-
- -- Store price info at time of purchase for historical records
- purchase_amount BIGINT NOT NULL,
- purchase_currency_mint VARCHAR(44) NOT NULL,
-
- unlocked_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
-
- -- A user can only unlock a specific agent's skill once.
- UNIQUE (user_id, agent_id, skill_name)
-);
-
--- Add indexes for common queries
-CREATE INDEX IF NOT EXISTS idx_user_unlocked_skills_user_id ON user_unlocked_skills(user_id);
-CREATE INDEX IF NOT EXISTS idx_user_unlocked_skills_agent_id ON user_unlocked_skills(agent_id);
-```
-
-<!-- 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/09-backend-create-skill-ownership-table.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/09-backend-set-skill-prices.md b/prompts/monetization/09-backend-set-skill-prices.md
deleted file mode 100644
index 666d4b4d7..000000000
--- a/prompts/monetization/09-backend-set-skill-prices.md
+++ /dev/null
@@ -1,128 +0,0 @@
-# Prompt 9: Backend for Setting Skill Prices
-
-## Objective
-Create the backend API endpoint for agent creators to save the prices for their skills.
-
-## Explanation
-The UI for setting skill prices needs a corresponding backend endpoint to persist the data. This endpoint will receive the agent ID, skill name, price, and currency, and it will update the `agent_skill_prices` database table accordingly. This requires proper authentication to ensure only the agent's creator can modify prices.
-
-## Instructions
-1. **Create New API File:**
- * Create a new file, for example, at `api/agents/[id]/pricing.js`. This creates a route like `/api/agents/AGENT_ID/pricing`.
-
-2. **Endpoint Logic (POST/PUT):**
- * The endpoint should handle POST or PUT requests.
- * It needs to authenticate the request to ensure the logged-in user is the creator of the agent specified by the ID in the URL.
- * The request body should contain `skillName`, `amount`, and `currencyMint`.
- * The logic will perform an "upsert" operation on the `agent_skill_prices` table:
- * If a price for that agent and skill already exists, it will be updated.
- * If it doesn't exist, a new record will be created.
-
-3. **Endpoint Logic (GET):**
- * The same endpoint should handle GET requests to fetch all existing prices for a given agent, which is used by the UI in the previous prompt.
-
-## Database Schema (`agent_skill_prices`)
-
-```sql
-CREATE TABLE agent_skill_prices (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- agent_id UUID REFERENCES agents(id) NOT NULL,
- skill_name TEXT NOT NULL,
- amount BIGINT NOT NULL, -- Price in smallest unit (e.g., lamports)
- currency_mint TEXT NOT NULL, -- e.g., PublicKey of the SPL token
- created_at TIMESTAMPTZ DEFAULT NOW(),
- updated_at TIMESTAMPTZ DEFAULT NOW(),
- UNIQUE(agent_id, skill_name)
-);
-
--- Policy: Only agent creator can manage prices
-CREATE POLICY "Creators can manage their agent skill prices"
-ON agent_skill_prices
-FOR ALL
-USING (auth.uid() = (SELECT creator_id FROM agents WHERE id = agent_id));
-```
-
-## Code Example (`api/agents/[id]/pricing.js`)
-
-```javascript
-import { supabase } from '../../_lib/supabase';
-import { json, error } from '../../_lib/http';
-import { getAuthUser } from '../../_lib/auth';
-
-export default async function handler(req, res) {
- const { id: agentId } = req.query;
- const user = await getAuthUser(req);
-
- if (!user) {
- return error(res, 401, 'Unauthorized');
- }
-
- // Verify ownership
- const { data: agent, error: agentError } = await supabase
- .from('agents')
- .select('creator_id')
- .eq('id', agentId)
- .single();
-
- if (agentError || agent.creator_id !== user.id) {
- return error(res, 403, 'You do not own this agent.');
- }
-
- if (req.method === 'POST') {
- const { skillName, amount, currencyMint } = req.body;
-
- if (!skillName || amount == null || !currencyMint) {
- return error(res, 400, 'Missing required pricing information.');
- }
-
- const { data, error: upsertError } = await supabase
- .from('agent_skill_prices')
- .upsert({
- agent_id: agentId,
- skill_name: skillName,
- amount: amount,
- currency_mint: currencyMint,
- }, { onConflict: 'agent_id, skill_name' })
- .select();
-
- if (upsertError) {
- return error(res, 500, 'Failed to save price.');
- }
- return json(res, data[0]);
-
- } else if (req.method === 'GET') {
- const { data, error: fetchError } = await supabase
- .from('agent_skill_prices')
- .select('*')
- .eq('agent_id', agentId);
-
- if (fetchError) {
- return error(res, 500, 'Failed to fetch prices.');
- }
-
- // Reshape into a map for easier frontend use
- const prices = data.reduce((acc, price) => {
- acc[price.skill_name] = { amount: price.amount, currency_mint: price.currency_mint };
- return acc;
- }, {});
-
- return json(res, prices);
- }
-
- return error(res, 405, 'Method Not Allowed');
-}
-```
-
-<!-- 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/09-backend-set-skill-prices.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/09-db-schema-user-purchases.md b/prompts/monetization/09-db-schema-user-purchases.md
deleted file mode 100644
index f26e309e1..000000000
--- a/prompts/monetization/09-db-schema-user-purchases.md
+++ /dev/null
@@ -1,53 +0,0 @@
----
-status: not-started
----
-
-# Prompt 9: Database Schema for User Purchases
-
-## Objective
-Create a database table to track which users have purchased which skills.
-
-## Explanation
-This table is essential for managing skill ownership. It will provide a record of every successful purchase, allowing the application to check if a user has access to a particular paid skill.
-
-## Instructions
-1. **Design the Table:**
- * Create a new table named `user_skill_purchases`.
- * The table should have the following columns:
- * `id`: Primary key.
- * `user_id`: Foreign key referencing the `users` table.
- * `agent_id`: Foreign key referencing the `agents` table.
- * `skill_name`: The name of the skill that was purchased.
- * `transaction_signature`: The Solana transaction signature of the purchase.
- * `created_at`: Timestamp.
-
-2. **Create a Migration:**
- * Use your database migration tool to create and apply a migration for the `user_skill_purchases` table.
-
-## SQL Example
-
-```sql
-CREATE TABLE user_skill_purchases (
- id SERIAL PRIMARY KEY,
- user_id UUID NOT NULL REFERENCES users(id),
- agent_id UUID NOT NULL REFERENCES agents(id),
- skill_name VARCHAR(255) NOT NULL,
- transaction_signature VARCHAR(255) NOT NULL,
- created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
- UNIQUE(user_id, agent_id, skill_name)
-);
-```
-
-<!-- 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/09-db-schema-user-purchases.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/09-frontend-gating-for-skills.md b/prompts/monetization/09-frontend-gating-for-skills.md
deleted file mode 100644
index 15724699d..000000000
--- a/prompts/monetization/09-frontend-gating-for-skills.md
+++ /dev/null
@@ -1,76 +0,0 @@
-# Prompt 9: Frontend Gating for Skills
-
-## Objective
-Implement a check in the frontend UI that calls the backend verification endpoint before allowing a user to use a paid skill.
-
-## Explanation
-This is the user-facing part of the access control system. When a user tries to interact with a paid skill (e.g., clicking a button in the chat interface that triggers the skill), the frontend must first confirm they have the right to do so.
-
-## Instructions
-1. **Identify Skill Triggers:**
- * Go through the chat UI or agent interaction logic and identify all the points where a skill is triggered.
-
-2. **Create a Central Skill Dispatcher:**
- * Instead of triggering skills directly, create a central function, e.g., `tryUseSkill(skillName)`.
- * This function will be responsible for handling the gating logic.
-
-3. **Implement the Check:**
- * Inside `tryUseSkill`, first determine if the skill is free or paid by checking the agent's `skill_prices` data.
- * If the skill is free, execute it immediately.
- * If the skill is paid, call the `/api/skills/verify-ownership` endpoint you created in the previous step.
- * Based on the `has_access` response:
- * If `true`, execute the skill.
- * If `false`, show a message to the user, e.g., "You need to purchase this skill to use it," and provide a link or button to the marketplace page.
-
-4. **Cache Verification Results:**
- * To avoid calling the verification endpoint every single time, cache the results on the frontend for the duration of the user's session. A simple JavaScript object or `sessionStorage` can work for this.
-
-## Code Example (Frontend Skill Dispatcher)
-```javascript
-const skillAccessCache = {};
-
-async function tryUseSkill(skillName) {
- const agent = getCurrentAgentData();
- const isPaid = skillName in agent.skill_prices;
-
- if (!isPaid) {
- executeSkill(skillName);
- return;
- }
-
- // Check cache first
- if (skillAccessCache[skillName]) {
- executeSkill(skillName);
- return;
- }
-
- // If not in cache, verify with backend
- const userWallet = wallet.publicKey.toBase58(); // from wallet adapter
- const response = await fetch(`/api/skills/verify-ownership?user_wallet=${userWallet}&agent_id=${agent.id}&skill_name=${skillName}`);
- const data = await response.json();
-
- if (data.has_access) {
- skillAccessCache[skillName] = true; // Update cache
- executeSkill(skillName);
- } else {
- showPurchasePrompt(skillName); // UI function to tell user to buy the skill
- }
-}
-
-// Example usage:
-// Instead of `runDanceSkill()`, you'd call `tryUseSkill('dance')`.
-```
-
-<!-- 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/09-frontend-gating-for-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/09-frontend-solana-pay-qr.md b/prompts/monetization/09-frontend-solana-pay-qr.md
deleted file mode 100644
index 9296e1d11..000000000
--- a/prompts/monetization/09-frontend-solana-pay-qr.md
+++ /dev/null
@@ -1,127 +0,0 @@
----
-status: not-started
----
-
-# Prompt 9: Frontend Solana Pay QR Code
-
-## Objective
-Implement the frontend logic to display the Solana Pay QR code in the payment modal and handle user interaction.
-
-## Explanation
-Once the frontend receives the Solana Pay URL from the backend, it needs to use the Solana Pay SDK to render it as a scannable QR code. This prompt covers the client-side rendering and the beginning of the payment monitoring loop.
-
-## Instructions
-1. **Update `fetchTransactionRequest`:**
- * In the `PurchaseFlow` module, modify the `fetchTransactionRequest` function.
- * It should now make a real `fetch` call to your new backend endpoint (`/api/purchase/transaction`).
- * It should expect a JSON response like `{ url: "solana:..." }` and return the URL.
-
-2. **Implement `displayPaymentQR`:**
- * This function will take the Solana Pay URL as an argument.
- * Get the QR code container element from the payment modal.
- * Use the `SolanaPay.createQR()` function from the SDK to generate the QR code. This function takes a URL and optional parameters for size and background color.
- * Append the generated QR code (which is an `HTMLDivElement`) to your container.
- * Populate the modal with skill name and price information.
- * Finally, call `showPaymentModal()` to reveal the modal to the user.
-
-3. **Start the Monitoring Loop:**
- * The Solana Pay QR code flow includes a reference keypair that allows you to find the transaction once it's been confirmed.
- * The `createQR` function can help with this. The Solana Pay spec involves the wallet calling your API, and your API finding the transaction.
- * A simple way to start is to begin polling a "check status" endpoint on your backend after displaying the QR code.
- * Modify `initiatePurchase` to start a `setInterval` loop that calls a new function, e.g., `checkPaymentStatus()`.
-
-## Code Example (JavaScript - `PurchaseFlow` module)
-
-```javascript
-const PurchaseFlow = {
- // ... other functions
- currentPurchase: null, // To store state between steps
-
- async initiatePurchase(agent, skillName) {
- // Store context for use in other functions
- this.currentPurchase = { agent, skillName, reference: null };
-
- // Get the Solana Pay URL from our server
- const response = await fetch(`/api/purchase/transaction?agentId=${agent.id}&skillName=${encodeURIComponent(skillName)}`);
- if (!response.ok) {
- showToast('Error creating transaction.', 'error');
- return;
- }
- const { url, reference } = await response.json(); // Assume backend also returns the reference public key
- this.currentPurchase.reference = new solanaWeb3.PublicKey(reference);
-
- this.displayPaymentQR(url, agent, skillName);
-
- // Start checking for the transaction confirmation
- this.startMonitoring();
- },
-
- displayPaymentQR(url, agent, skillName) {
- const qrContainer = document.getElementById('payment-qr-container');
- qrContainer.innerHTML = ''; // Clear previous QR code
-
- // Use the Solana Pay SDK to create the QR code element
- const qr = SolanaPay.createQR(url, 300, 'white', 'black');
- qrContainer.appendChild(qr.canvas);
-
- // Update modal text
- const price = agent.skill_prices[skillName];
- document.getElementById('payment-skill-name').textContent = skillName;
- document.getElementById('payment-skill-price').textContent = `${(price.amount / 1e6).toFixed(2)} USDC`;
-
- // Show the modal
- showPaymentModal();
- },
-
- startMonitoring() {
- this.stopMonitoring(); // Clear any existing interval
- this.monitoringInterval = setInterval(async () => {
- try {
- // This will be a new backend endpoint
- const response = await fetch(`/api/purchase/status?reference=${this.currentPurchase.reference.toBase58()}`);
- const data = await response.json();
-
- if (data.status === 'confirmed') {
- this.stopMonitoring();
- showToast('Payment confirmed!', 'success');
- hidePaymentModal();
- // TODO: Refresh UI to show the skill as "Purchased"
- } else if (data.status === 'expired') {
- this.stopMonitoring();
- showToast('Transaction expired.', 'error');
- hidePaymentModal();
- }
- } catch (e) {
- console.error('Error checking payment status:', e);
- }
- }, 2000); // Poll every 2 seconds
- },
-
- stopMonitoring() {
- if (this.monitoringInterval) {
- clearInterval(this.monitoringInterval);
- this.monitoringInterval = null;
- }
- }
-};
-
-// Ensure monitoring stops when the modal is closed manually
-document.getElementById('payment-modal-close').addEventListener('click', () => {
- PurchaseFlow.stopMonitoring();
- hidePaymentModal();
-});
-```
-
-<!-- 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/09-frontend-solana-pay-qr.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/09-payment-required-modal.md b/prompts/monetization/09-payment-required-modal.md
deleted file mode 100644
index 288c53072..000000000
--- a/prompts/monetization/09-payment-required-modal.md
+++ /dev/null
@@ -1,115 +0,0 @@
-# Prompt 9: "Payment Required" Modal in Chat
-
-## Objective
-Create a modal dialog in the chat UI that appears when a user needs to pay for a skill, clearly presenting the price and prompting for action.
-
-## Explanation
-When the backend signals that a skill requires payment, the frontend must stop the normal message flow and present the user with a clear choice. This modal is the centerpiece of the in-chat purchasing experience.
-
-## Instructions
-1. **File to Edit:**
- * Open the main JavaScript/Svelte/React component file for your chat interface (e.g., `chat/src/App.svelte` or similar).
-
-2. **Create the Modal HTML/Structure:**
- * Add the HTML for a modal dialog. It should be hidden by default.
- * The modal should contain:
- * A title, e.g., "Premium Skill".
- * A descriptive text, e.g., "The skill 'generate-image' requires a one-time payment to use."
- * A display for the price (e.g., "Price: 1.00 USDC").
- * A "Pay and Continue" button.
- * A "Cancel" button or close icon.
-
-3. **Implement Frontend Logic:**
- * Listen for the `payment_required` message from your backend (as designed in Prompt 8).
- * When this message is received:
- * Populate the modal with the `skill_name` and `price` information from the message data. Remember to format the amount from lamports to a user-friendly decimal format.
- * Make the modal visible.
-
-4. **Handle Button Clicks:**
- * **Cancel:** If the user clicks "Cancel" or closes the modal, hide the modal and perhaps send a "payment cancelled" message to the chat history.
- * **Pay and Continue:** If the user clicks the pay button:
- * Keep the modal open but show a loading/spinner state.
- * Trigger the frontend payment flow function (which will be built in the next prompt). This function will orchestrate the API calls and wallet interaction.
-
-## Code Example (Frontend - Svelte Component)
-
-```svelte
-<!-- In your main chat component, e.g., App.svelte -->
-
-{#if paymentRequired}
-<div class="modal-backdrop">
- <div class="modal">
- <h3>Premium Skill</h3>
- <p>
- The skill <strong>{paymentDetails.skill_name}</strong> requires a payment to continue.
- </p>
- <div class="price-display">
- Price: <span>{(paymentDetails.amount / 1e6).toFixed(2)} USDC</span>
- </div>
-
- {#if isLoadingPayment}
- <div class="spinner">Processing...</div>
- {:else}
- <div class="modal-actions">
- <button on:click={cancelPayment}>Cancel</button>
- <button class="primary" on:click={initiatePayment}>Pay and Continue</button>
- </div>
- {/if}
- </div>
-</div>
-{/if}
-
-<script>
- let paymentRequired = false;
- let paymentDetails = {};
- let isLoadingPayment = false;
-
- // Function to be called when backend sends 'payment_required'
- function onPaymentRequired(details) {
- paymentDetails = details;
- paymentRequired = true;
- isLoadingPayment = false;
- }
-
- function cancelPayment() {
- paymentRequired = false;
- // Optionally add a "Cancelled" message to the chat history
- }
-
- async function initiatePayment() {
- isLoadingPayment = true;
- try {
- // This function will be implemented in the next prompt
- const result = await handlePaymentFlow(paymentDetails);
- if (result.success) {
- paymentRequired = false;
- // The backend will now re-run the skill and send the result.
- } else {
- // Handle payment failure, show an error
- isLoadingPayment = false;
- }
- } catch (err) {
- // Handle errors from the payment flow
- isLoadingPayment = false;
- }
- }
-</script>
-
-<style>
- /* Add styles for .modal-backdrop, .modal, .price-display, etc. */
-</style>
-```
-
-<!-- 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/09-payment-required-modal.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/09-save-skill-prices-backend.md b/prompts/monetization/09-save-skill-prices-backend.md
deleted file mode 100644
index 1a6b23d33..000000000
--- a/prompts/monetization/09-save-skill-prices-backend.md
+++ /dev/null
@@ -1,114 +0,0 @@
-# Prompt 9: Save Skill Prices (Backend)
-
-## Objective
-Create a backend API endpoint that allows agent creators to save the prices they have set for their skills.
-
-## Explanation
-After a creator sets up the prices for their skills in the UI (from the previous prompt), we need a secure endpoint to save this information to the database. This endpoint will receive a list of skills and their prices, validate the data, and update the `agent_skill_prices` table.
-
-## Instructions
-1. **Database Schema:**
- * Ensure you have an `agent_skill_prices` table.
- * Columns should include `id`, `agent_id`, `skill_name`, `amount` (as a `bigint` to store lamports), and `currency_mint` (as a string).
- * The combination of `agent_id` and `skill_name` should be unique.
-
-2. **Create the API Endpoint:**
- * Create a new file, e.g., `api/agents/[id]/skill-prices.js`.
- * This endpoint should handle `POST` or `PUT` requests.
- * It must be protected, ensuring only the agent's creator can update the prices.
-
-3. **Implement the Endpoint Logic:**
- * The request body should contain an object or array of skill prices, like: `[{ skillName: 'DataAnalysis', price: 1.99, currency: 'USDC' }, ...]`.
- * The handler should:
- * Authenticate the user and verify they own the agent specified by `:id`.
- * Iterate through the submitted skill prices.
- * For each skill, convert the price (e.g., 1.99 USDC) into its smallest unit (lamports, e.g., 1,990,000).
- * Perform an "upsert" operation on the `agent_skill_prices` table:
- * If a price for that `agent_id` and `skill_name` already exists, `UPDATE` it.
- * If it doesn't exist, `INSERT` a new row.
- * Return a success response.
-
-## SQL for `agent_skill_prices` Table
-
-```sql
-CREATE TABLE agent_skill_prices (
- id SERIAL PRIMARY KEY,
- agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
- skill_name VARCHAR(255) NOT NULL,
- amount BIGINT NOT NULL, -- e.g., 1_990_000 for 1.99 USDC
- currency_mint VARCHAR(255) NOT NULL,
- created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
- updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
- UNIQUE(agent_id, skill_name)
-);
-```
-
-## Code Example (Backend - `api/agents/[id]/skill-prices.js`)
-
-```javascript
-import { db } from '../../_lib/database-client';
-import { verifyAgentOwnership } from '../../_lib/auth';
-
-const USDC_DECIMALS = 6;
-
-export default async function handler(req, res) {
- if (req.method !== 'POST') return res.status(405).end();
-
- try {
- const agentId = req.query.id;
- const userId = req.user.id; // From auth middleware
-
- // 1. Verify ownership
- if (!await verifyAgentOwnership(userId, agentId)) {
- return res.status(403).json({ error: 'You do not own this agent.' });
- }
-
- const { prices } = req.body; // Expects: [{ skillName, price, currencyMint }]
- if (!Array.isArray(prices)) {
- return res.status(400).json({ error: 'Invalid prices format.' });
- }
-
- // 2. Use a transaction to update all prices atomically
- await db.tx(async t => {
- for (const item of prices) {
- const { skillName, price, currencyMint } = item;
-
- // 3. Convert to lamports (smallest unit)
- const amountInLamports = Math.round(parseFloat(price) * (10 ** USDC_DECIMALS));
-
- await t.query(
- `
- INSERT INTO agent_skill_prices (agent_id, skill_name, amount, currency_mint)
- VALUES ($1, $2, $3, $4)
- ON CONFLICT (agent_id, skill_name) DO UPDATE SET
- amount = EXCLUDED.amount,
- currency_mint = EXCLUDED.currency_mint,
- updated_at = CURRENT_TIMESTAMP;
- `,
- [agentId, skillName, amountInLamports, currencyMint]
- );
- }
- });
-
- res.status(200).json({ message: 'Skill prices updated successfully.' });
-
- } catch (error) {
- console.error('Error saving skill prices:', error);
- res.status(500).json({ error: 'Internal Server 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/09-save-skill-prices-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/09-update-ui-for-owned-skills.md b/prompts/monetization/09-update-ui-for-owned-skills.md
deleted file mode 100644
index a93a2f3ba..000000000
--- a/prompts/monetization/09-update-ui-for-owned-skills.md
+++ /dev/null
@@ -1,95 +0,0 @@
-# Prompt 9: Update UI for Owned Skills
-
-## Status
-- [ ] Not Started
-
-## Objective
-Modify the agent detail page to visually reflect the skills a user already owns, disabling the "Purchase" button for those skills.
-
-## Explanation
-To prevent users from re-purchasing skills they already own, the UI needs to be updated based on their ownership status. This requires fetching the user's owned skills and adjusting the rendering logic.
-
-## Instructions
-1. **Backend: Expose Owned Skills:**
- * When fetching the agent details (`/api/marketplace/agents/:id`), if a user is authenticated, also query the `user_owned_skills` table.
- * Include a list of owned skill names for that specific agent in the API response.
-
-2. **Frontend: Update Rendering Logic:**
- * In `src/marketplace.js`, the `renderDetail` function will now receive the list of owned skills.
- * In the skill rendering loop, check if the current skill is in the user's owned list.
- * If the user owns the skill, display an "Owned" badge or indicator instead of the "Purchase" button.
-
-## Code Example (Backend API Response Snippet)
-```json
-{
- "id": "agent-uuid-123",
- "name": "Super Agent",
- "skills": ["super-jump", "laser-eyes"],
- "skill_prices": {
- "laser-eyes": { "amount": 2000000, "currency_mint": "..." }
- },
- "user_owned_skills": ["super-jump"]
-}
-```
-
-## Code Example (Frontend - `src/marketplace.js` Update)
-```javascript
-// Inside renderDetail function
-const skillPrices = a.skill_prices || {};
-const ownedSkills = new Set(a.user_owned_skills || []); // Use a Set for efficient lookups
-
-$('d-skills').innerHTML = skillsArr.map((s) => {
- const name = typeof s === 'string' ? s : (s.name || '');
- const price = skillPrices[name];
- let actionElement;
-
- if (ownedSkills.has(name)) {
- actionElement = `<span class="ownership-badge">Owned</span>`;
- } else if (price) {
- const priceDisplay = `${(price.amount / 1e6).toFixed(2)} USDC`;
- actionElement = `<button class="purchase-skill-btn"
- data-skill-name="${escapeHtml(name)}"
- ... >
- Purchase for ${priceDisplay}
- </button>`;
- } else {
- // This is a free skill that hasn't been "claimed" or "owned" yet.
- // You might have a different state for free skills that are implicitly owned.
- actionElement = `<span class="price-badge price-free">Free</span>`;
- }
-
- return `<div class="skill-entry">
- <span>${escapeHtml(name)}</span>
- ${actionElement}
- </div>`;
-}).join('');
-```
-
-## CSS for "Owned" Badge
-```css
-/* Add to marketplace.css */
-.ownership-badge {
- display: inline-block;
- padding: 4px 10px;
- font-size: 11px;
- font-weight: 700;
- border-radius: 12px;
- background-color: #059669; /* Green */
- color: #d1fae5;
- border: 1px solid #06c78a;
-}
-```
-
-<!-- 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/09-update-ui-for-owned-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/09_api_purchase_confirm.md b/prompts/monetization/09_api_purchase_confirm.md
deleted file mode 100644
index c4469c185..000000000
--- a/prompts/monetization/09_api_purchase_confirm.md
+++ /dev/null
@@ -1,104 +0,0 @@
----
-status: not-started
-last_updated: 2026-05-04
----
-# Prompt 09: Backend API for Purchase Confirmation
-
-## Objective
-Create a backend endpoint to verify a skill purchase transaction on-chain and record it in the database.
-
-## Explanation
-After the frontend successfully broadcasts the transaction, it must notify the backend. This endpoint's job is to act as a final "source of truth." It verifies that the transaction signature provided by the client is valid, that it corresponds to the intended purchase, and that it was successful. Only after this verification does it save the purchase record to the `user_purchased_skills` table.
-
-## Instructions
-1. **Create the API Endpoint:**
- * Create a new file or handler for `POST /api/skills/purchase-confirm`.
-
-2. **Implement the Logic:**
- * **Authentication:** The user must be authenticated.
- * **Input Validation:** The request body should contain `agent_id`, `skill_name`, and `signature`.
- * **Fetch Purchase Details:**
- * Retrieve the skill price and creator's wallet address, just as in the "prep" step. This is to ensure the on-chain transaction matches what we expected.
- * **On-Chain Verification:**
- * Use the Solana `connection.getParsedTransaction` method with the provided `signature`.
- * Inspect the transaction details to confirm:
- * The transaction was successful ( `tx.meta.err` is null).
- * The source account matches the buyer's wallet.
- * The destination account matches the creator's wallet.
- * The transfer amount matches the skill price.
- * The token mint matches the currency (e.g., USDC).
- * This step is critical to prevent users from submitting fraudulent or irrelevant transaction signatures.
- * **Database Operation:**
- * If on-chain verification passes, insert a new record into the `user_purchased_skills` table. Store all relevant details, including the transaction signature, for auditing.
-
-## Code Example (Vercel Serverless Function)
-
-```javascript
-import { Connection } from '@solana/web3.js';
-import { sql } from '../../_lib/db.js';
-// ... other imports
-
-export default wrap(async (req, res) => {
- // ... auth and input validation
- const { agent_id, skill_name, signature } = req.body;
- const user = await getSessionUser(req);
- const buyerWallet = user.wallet_address;
-
- // 1. Fetch expected details for verification
- const [skillPrice] = await sql`SELECT ...`;
- const [agent] = await sql`SELECT ...`;
- const creatorWallet = agent.meta.onchain.wallet;
- const expectedAmount = skillPrice.amount;
- const currencyMint = skillPrice.currency_mint;
-
- // 2. Verify transaction on-chain
- const connection = new Connection(rpcUrl('mainnet-beta'), 'confirmed');
- const tx = await connection.getParsedTransaction(signature, { maxSupportedTransactionVersion: 0 });
-
- if (!tx || tx.meta.err) {
- return error(res, 400, 'tx_failed', 'Transaction failed or not found.');
- }
-
- // Find the token transfer instruction
- const transferInstruction = tx.transaction.message.instructions.find(ix =>
- ix.parsed?.type === 'transfer' &&
- ix.program === 'spl-token'
- );
-
- if (!transferInstruction) {
- return error(res, 400, 'invalid_tx', 'No token transfer found in transaction.');
- }
-
- const { source, destination, amount } = transferInstruction.parsed.info;
- // Note: A robust implementation would resolve ATAs to owner wallets.
- // This is a simplified check.
- if (source !== buyerWalletAta || destination !== creatorWalletAta || amount !== expectedAmount) {
- return error(res, 400, 'tx_mismatch', 'Transaction details do not match expected purchase.');
- }
-
- // 3. Record the purchase in the database
- await sql`
- INSERT INTO user_purchased_skills
- (user_id, agent_id, skill_name, purchase_tx_signature, price_amount, price_currency_mint)
- VALUES
- (${user.id}, ${agent_id}, ${skill_name}, ${signature}, ${expectedAmount}, ${currencyMint})
- ON CONFLICT (user_id, agent_id, skill_name) DO NOTHING;
- `;
-
- return json(res, 201, { success: true, message: 'Purchase confirmed and recorded.' });
-});
-```
-
-<!-- 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/09_api_purchase_confirm.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/10-access-control-for-skills.md b/prompts/monetization/10-access-control-for-skills.md
deleted file mode 100644
index 3f6db9d47..000000000
--- a/prompts/monetization/10-access-control-for-skills.md
+++ /dev/null
@@ -1,36 +0,0 @@
----
-status: not-started
----
-
-# Prompt 10: Access Control for Paid Skills
-
-## Objective
-Implement a system to ensure that only users who have purchased a skill can use it.
-
-## Explanation
-This is a critical part of the monetization feature. The system needs to check for ownership before allowing the execution of a paid skill. This can be done at the API gateway or within the agent's core logic.
-
-## Instructions
-1. **Create a Middleware:**
- * Implement a middleware that sits in front of the skill execution endpoint.
- * The middleware should extract the user's ID, the agent ID, and the skill name from the request.
-
-2. **Check for Ownership:**
- * In the middleware, query the `user_skill_purchases` table to see if a record exists for the user, agent, and skill.
- * Also, check if the skill is free by looking at the `agent_skill_prices` table.
- * If the skill is free or if the user owns it, allow the request to proceed.
- * If the skill is paid and the user does not own it, return a `403 Forbidden` or `402 Payment Required` 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/10-access-control-for-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/10-agent-editor-ui-for-pricing.md b/prompts/monetization/10-agent-editor-ui-for-pricing.md
deleted file mode 100644
index 254a636c9..000000000
--- a/prompts/monetization/10-agent-editor-ui-for-pricing.md
+++ /dev/null
@@ -1,105 +0,0 @@
-# Prompt 10: Create Agent Creation/Editing UI for Pricing
-
-## Status
-- [ ] Not Started
-
-## Objective
-Develop a user interface for agent creators to set and manage prices for their agent's skills.
-
-## Explanation
-For creators to monetize their work, they need a simple way to define which skills are for sale and at what price. This prompt focuses on building the UI for this purpose in the agent creation or editing page.
-
-## Instructions
-1. **Locate the Agent Editor:**
- * Find the HTML and JavaScript files responsible for the agent creation/editing form (e.g., `agent-edit.html` and `src/agent-editor.js`).
-
-2. **Enhance the Skills Section:**
- * In the part of the form where skills are listed or added, add new input fields next to each skill.
- * The new fields should be for:
- * `Price`: A number input for the skill's price.
- * `Currency`: A dropdown/select input to choose the payment currency (e.g., USDC, SOL).
-
-3. **Manage State:**
- * The JavaScript for the editor needs to manage this new pricing data.
- * When the form is loaded for an existing agent, it should be populated with the current skill prices.
- * As the creator changes the prices, the state should be updated.
-
-4. **Handle Form Submission:**
- * When the agent creator saves their changes, the pricing information should be collected and sent to the backend.
- * The data should be structured in a way that's easy for the backend to process, e.g., an object where keys are skill names.
-
-## Code Example (HTML in `agent-edit.html`)
-```html
-<div id="skills-editor">
- <!-- This part will be dynamically populated by JavaScript -->
-</div>
-
-<template id="skill-editor-template">
- <div class="skill-price-row">
- <input type="text" class="skill-name-input" placeholder="Skill Name" readonly>
- <input type="number" class="skill-price-input" placeholder="Price">
- <select class="skill-currency-select">
- <option value="USDC_MINT_ADDRESS">USDC</option>
- <option value="SOL_MINT_ADDRESS">SOL</option>
- <!-- Add other supported currencies -->
- </select>
- </div>
-</template>
-```
-
-## Code Example (JavaScript in `src/agent-editor.js`)
-```javascript
-function renderSkillPricer(skills, currentPrices) {
- const container = document.getElementById('skills-editor');
- const template = document.getElementById('skill-editor-template');
- container.innerHTML = '';
-
- skills.forEach(skillName => {
- const skillRow = template.content.cloneNode(true);
- const price = currentPrices[skillName];
-
- skillRow.querySelector('.skill-name-input').value = skillName;
- if (price) {
- skillRow.querySelector('.skill-price-input').value = price.amount / 1e6; // Display in human-readable format
- skillRow.querySelector('.skill-currency-select').value = price.currency_mint;
- }
-
- container.appendChild(skillRow);
- });
-}
-
-function getSkillPricesFromForm() {
- const prices = {};
- document.querySelectorAll('#skills-editor .skill-price-row').forEach(row => {
- const name = row.querySelector('.skill-name-input').value;
- const amountInput = row.querySelector('.skill-price-input').value;
- const currency = row.querySelector('.skill-currency-select').value;
-
- if (amountInput && parseFloat(amountInput) > 0) {
- prices[name] = {
- amount: parseFloat(amountInput) * 1e6, // Convert to smallest unit
- currency_mint: currency
- };
- }
- });
- return prices;
-}
-
-// On save/submit:
-const updatedPrices = getSkillPricesFromForm();
-// Now, send 'updatedPrices' to the backend.
-```
-
-<!-- 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/10-agent-editor-ui-for-pricing.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/10-backend-prepare-payment.md b/prompts/monetization/10-backend-prepare-payment.md
deleted file mode 100644
index 0bbe95bed..000000000
--- a/prompts/monetization/10-backend-prepare-payment.md
+++ /dev/null
@@ -1,115 +0,0 @@
-# Prompt 10: Backend Endpoint to Prepare Payment
-
-## Objective
-Create a backend endpoint that prepares a Solana transaction for the user to sign to pay for a skill.
-
-## Explanation
-This is a critical security step. The server, not the client, must construct the transaction. This prevents tampering with the payment amount or destination. This endpoint will generate an unsigned transaction that transfers the correct amount from the user to the appropriate account and return it to the client for signing.
-
-## Instructions
-1. **Create API Route:**
- * Set up a new endpoint: `POST /api/payments/prepare-skill-payment`.
- * This endpoint must be authenticated.
-
-2. **Request Body:**
- * The endpoint should accept a JSON body with `agent_id` and `skill_name`.
-
-3. **Backend Logic:**
- * **Fetch Price:** Using `agent_id` and `skill_name`, look up the price (`amount` and `currency_mint`) from the `agent_skill_prices` table. If no price is found, return an error.
- * **Identify Payer and Receiver:**
- * The **payer** is the authenticated user making the request. Get their public key.
- * The **receiver** is the agent's associated treasury or holdings account. This address should be stored with the agent's data.
- * **Construct the Transaction:**
- * Using the Solana Web3.js library (`@solana/web3.js`), create a new `Transaction`.
- * Add a `spl-token` `createTransfer` instruction.
- * **Source:** The user's Associated Token Account (ATA) for the given `currency_mint`.
- * **Destination:** The agent's treasury ATA for the same `currency_mint`.
- * **Amount:** The `amount` from the database.
- * **Owner:** The user's public key.
- * **Set Blockhash and Fee Payer:**
- * Get a recent blockhash from the Solana cluster.
- * Set the `recentBlockhash` and `feePayer` (the user) on the transaction.
- * **Create Payment Record:**
- * Create a record in a new `skill_payments` table with a `pending` status. Include `user_id`, `agent_id`, `skill_name`, `amount`, and the transaction's blockhash for later reference. Store a unique ID for this payment intent.
- * **Serialize and Respond:**
- * Serialize the *unsigned* transaction and encode it (e.g., in Base64).
- * Return the serialized transaction and the unique payment ID to the frontend.
-
-## Code Example (Backend - `/api/payments/prepare-skill-payment.js`)
-
-```javascript
-import { Transaction, SystemProgram, PublicKey } from '@solana/web3.js';
-import { createTransferInstruction } from '@solana/spl-token';
-import { getAssociatedTokenAddress } from '@solana/spl-token';
-
-// --- Inside your API handler ---
-
-const { agent_id, skill_name } = req.body;
-const user = await getAuthenticatedUser(req);
-
-// 1. Fetch skill price and agent details
-const priceInfo = await db.getSkillPrice(agent_id, skill_name);
-const agent = await db.getAgentById(agent_id);
-if (!priceInfo || !agent) {
- return res.status(404).json({ error: 'Skill or agent not found.' });
-}
-
-// 2. Define parties
-const payerPublicKey = new PublicKey(user.solana_pubkey);
-const receiverPublicKey = new PublicKey(agent.treasury_address); // The agent's main treasury wallet
-const currencyMint = new PublicKey(priceInfo.currency_mint);
-
-// 3. Find the ATAs for the token transfer
-const payerAta = await getAssociatedTokenAddress(currencyMint, payerPublicKey);
-const receiverAta = await getAssociatedTokenAddress(currencyMint, receiverPublicKey);
-
-// 4. Create the transfer instruction
-const transferInstruction = createTransferInstruction(
- payerAta, // from
- receiverAta, // to
- payerPublicKey, // from's owner
- priceInfo.amount // amount
-);
-
-// 5. Create the transaction
-const connection = new Connection(process.env.SOLANA_RPC_URL);
-const { blockhash } = await connection.getRecentBlockhash();
-
-const transaction = new Transaction({
- recentBlockhash: blockhash,
- feePayer: payerPublicKey,
-}).add(transferInstruction);
-
-// 6. Create a pending payment record
-const paymentIntent = await db.createPaymentIntent({
- userId: user.id,
- agentId: agent.id,
- skillName: skill_name,
- amount: priceInfo.amount,
- reference: blockhash, // Use blockhash or a new UUID as a reference
-});
-
-// 7. Serialize and respond
-const serializedTransaction = transaction.serialize({
- requireAllSignatures: false,
-}).toString('base64');
-
-res.status(200).json({
- paymentId: paymentIntent.id,
- transaction: serializedTransaction,
-});
-```
-
-<!-- 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/10-backend-prepare-payment.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/10-backend-transaction-verification.md b/prompts/monetization/10-backend-transaction-verification.md
deleted file mode 100644
index 237b3d7f6..000000000
--- a/prompts/monetization/10-backend-transaction-verification.md
+++ /dev/null
@@ -1,118 +0,0 @@
----
-status: not-started
----
-
-# Prompt 10: Backend - Transaction Verification and Fulfillment
-
-## Objective
-Create a backend mechanism to securely verify a Solana transaction and, upon success, record the skill ownership in the database.
-
-## Explanation
-A crucial security step is to verify the payment on the backend *after* the frontend reports it as confirmed. The frontend can be manipulated, so the server must independently fetch the transaction details from the Solana RPC and validate them before granting access to the skill. This is the "fulfillment" step of the purchase.
-
-## Instructions
-1. **Create a Verification API Endpoint:**
- * Create a new API file, e.g., `api/payments/verify-transaction.js`.
- * This endpoint will accept a `POST` request at `/api/payments/verify-transaction`.
- * The frontend will call this endpoint *after* it has successfully confirmed the transaction on its end.
-
-2. **Request Body and Authentication:**
- * The request body should contain:
- * `signature`: The transaction signature returned by `sendRawTransaction`.
- * `agentId`: The agent ID for the skill purchased.
- * `skillName`: The name of the skill purchased.
- * This endpoint must be authenticated to get the `userId` of the purchaser.
-
-3. **Backend Verification Logic:**
- * Inside the API handler:
- 1. **Fetch Transaction:** Use the Solana `connection.getParsedTransaction(signature)` method to get the transaction details from the RPC.
- 2. **Prevent Replay Attacks:** Check if this `signature` has already been used to unlock a skill in your `user_unlocked_skills` table. If it exists, return an error. This is critical.
- 3. **Fetch Skill Price:** Get the expected price (`amount`, `currency_mint`) and the creator's wallet address from your database for the given `agentId` and `skillName`.
- 4. **Validate Details:** Parse the fetched transaction and verify that:
- * It was successful (the `meta.err` field in the response is `null`).
- * It contains a token transfer instruction.
- * The transfer's `source` address belongs to the authenticated user (`userId`).
- * The transfer's `destination` address belongs to the agent's creator.
- * The transfer `amount` matches the expected price from your database.
- * The transfer `mint` matches the expected currency from your database.
- 5. **Handle Failure:** If any of these checks fail, return a `400 Bad Request` or `422 Unprocessable Entity` error with a clear message.
-
-4. **Record Ownership:**
- * If all checks pass, `INSERT` a new row into the `user_unlocked_skills` table with the `userId`, `agentId`, `skillName`, `purchase_tx_signature`, and the price details.
-
-5. **Return Success:**
- * Return a `200 OK` response to the frontend to confirm that the backend has successfully verified and fulfilled the purchase.
-
-## Code Example (`api/payments/verify-transaction.js`)
-
-```javascript
-import { Connection, PublicKey } from '@solana/web3.js';
-import { json, wrap } from '../_lib/http.js';
-import { getAuth } from '../_lib/auth.js';
-import { sql } from '../_lib/db.js';
-
-const connection = new Connection(process.env.SOLANA_RPC_ENDPOINT);
-
-export default wrap(async (req, res) => {
- // ... authentication ...
- const { userId } = await getAuth(req);
- const { signature, agentId, skillName } = req.body;
-
- // 1. Check for replay attacks
- const [existing] = await sql`SELECT id FROM user_unlocked_skills WHERE purchase_tx_signature = ${signature}`;
- if (existing) {
- return json(res, 409, { error: 'Transaction has already been used.' });
- }
-
- // 2. Fetch expected price and creator info from DB
- // ... query to get priceInfo and creatorWallet ...
-
- // 3. Fetch and parse the transaction from Solana RPC
- const tx = await connection.getParsedTransaction(signature, 'confirmed');
- if (!tx || tx.meta.err) {
- return json(res, 400, { error: 'Transaction not found or failed.' });
- }
-
- // 4. Validate the transaction details (this is a simplified example)
- const transfer = tx.transaction.message.instructions.find(
- (ix) => ix.parsed?.type === 'transfer' && ix.program === 'spl-token'
- );
-
- if (!transfer) {
- return json(res, 400, { error: 'No valid SPL token transfer found.' });
- }
-
- const { source, destination, amount } = transfer.parsed.info;
- // You would also need to verify the owner of the source account matches the user.
- // This requires more complex parsing of account data.
-
- const expectedAmount = priceInfo.amount.toString();
- const expectedDestination = creatorTokenAccountAddress; // You need to derive this
-
- if (amount !== expectedAmount || destination !== expectedDestination) {
- return json(res, 400, { error: 'Transaction details do not match expected values.' });
- }
-
- // 5. If all checks pass, record the purchase
- await sql`
- INSERT INTO user_unlocked_skills (user_id, agent_id, skill_name, purchase_tx_signature, purchase_amount, purchase_currency_mint)
- VALUES (${userId}, ${agentId}, ${skillName}, ${signature}, ${priceInfo.amount}, ${priceInfo.currency_mint})
- `;
-
- return json(res, 200, { success: true, message: 'Skill unlocked.' });
-});
-```
-
-<!-- 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/10-backend-transaction-verification.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/10-creator-payout-wallet-management.md b/prompts/monetization/10-creator-payout-wallet-management.md
deleted file mode 100644
index f6e7e6bf6..000000000
--- a/prompts/monetization/10-creator-payout-wallet-management.md
+++ /dev/null
@@ -1,129 +0,0 @@
-# Prompt 10: Creator Payout Wallet Management
-
-## Objective
-Implement the UI and backend logic for an agent creator to specify their Solana treasury wallet, where they will receive payments from skill sales.
-
-## Explanation
-For creators to receive their earnings, they must provide a valid Solana wallet address. This task involves adding an input field in the monetization dashboard for this address and creating a secure backend endpoint to save it. This address will be stored and associated with the agent, to be used later in the payment transaction logic.
-
-## Instructions
-1. **Add UI in Dashboard:**
- * In the "Monetization" tab in `agent-edit.html`, use the placeholder from prompt #7. It should contain an `<input>` for the wallet public key and a "Save" button.
-
-2. **Frontend Logic:**
- * In `src/agent-edit.js`, fetch the agent's current treasury wallet address when the tab loads and populate the input field.
- * Add a click event listener to the "Save" button. This handler will read the value from the input, perform basic validation (e.g., check if it's a valid Solana public key format), and send it to the backend.
-
-3. **Backend Endpoint:**
- * Create a new endpoint, for example `/api/agents/[id]/treasury`, to handle updating the treasury wallet.
- * This endpoint must be secure, verifying that the user making the request is the creator of the agent.
- * It will take the `treasuryWallet` public key from the request body and update the `creator_treasury_wallet` column on the `agents` table for the specified agent.
-
-## Database Schema (Alter `agents` table)
-
-```sql
--- Add a new column to the agents table to store the payout address
-ALTER TABLE agents
-ADD COLUMN creator_treasury_wallet TEXT;
-
--- You might want to add a check constraint for valid base58 format
--- but this can also be handled at the application layer.
-```
-
-## Code Example (`src/agent-edit.js`)
-
-```javascript
-// Add to the monetization tab logic
-const treasuryInput = document.getElementById('treasuryWallet');
-const saveTreasuryBtn = document.getElementById('saveTreasuryWallet');
-
-async function loadTreasuryWallet(agentId) {
- const agent = await getAgentData(agentId); // Assuming this function exists
- if (agent.creator_treasury_wallet) {
- treasuryInput.value = agent.creator_treasury_wallet;
- }
-}
-
-saveTreasuryBtn.addEventListener('click', async () => {
- const agentId = /* get agent id from context */;
- const newWallet = treasuryInput.value.trim();
-
- // Basic validation (more robust validation is recommended)
- if (!newWallet || newWallet.length < 32 || newWallet.length > 44) {
- alert('Please enter a valid Solana public key.');
- return;
- }
-
- try {
- const response = await fetch(`/api/agents/${agentId}/treasury`, {
- method: 'PUT',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ treasuryWallet: newWallet }),
- });
-
- if (!response.ok) throw new Error('Failed to save wallet address.');
-
- alert('Payout wallet updated successfully!');
- } catch (error) {
- alert(`Error: ${error.message}`);
- }
-});
-
-// Call loadTreasuryWallet when the tab is shown
-```
-
-## Code Example (`api/agents/[id]/treasury.js`)
-
-```javascript
-import { supabase } from '../../_lib/supabase';
-import { json, error } from '../../_lib/http';
-import { getAuthUser } from '../../_lib/auth';
-
-export default async function handler(req, res) {
- if (req.method !== 'PUT') return error(res, 405, 'Method Not Allowed');
-
- const { id: agentId } = req.query;
- const user = await getAuthUser(req);
- const { treasuryWallet } = req.body;
-
- if (!user) return error(res, 401, 'Unauthorized');
- if (!treasuryWallet) return error(res, 400, 'Missing treasuryWallet');
-
- // Verify ownership
- const { data: agent, error: agentError } = await supabase
- .from('agents')
- .select('creator_id')
- .eq('id', agentId)
- .single();
-
- if (agentError || agent.creator_id !== user.id) {
- return error(res, 403, 'Forbidden');
- }
-
- // Update the agent's treasury wallet
- const { error: updateError } = await supabase
- .from('agents')
- .update({ creator_treasury_wallet: treasuryWallet })
- .eq('id', agentId);
-
- if (updateError) {
- return error(res, 500, 'Failed to update treasury wallet.');
- }
-
- return json(res, { success: true });
-}
-```
-
-<!-- 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/10-creator-payout-wallet-management.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/public/changelog.json b/public/changelog.json
index 12ee99373..07389cd7d 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-17T07:22:22.805Z",
+ "generated_at": "2026-06-17T08:20:44.960Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -187,11 +187,12 @@
{
"date": "2026-06-17",
"type": "update",
- "title": "IRL world: closed a bulk location-scrape path on placed agents",
- "summary": "The /irl world lets you place 3D agents at real GPS spots and discover the ones near you. The 'discover nearby' feed always hid who placed each agent, but an internal bulk window-load endpoint — used only by the live realtime server to hydrate a neighborhood — was reachable from the open web, which in principle let someone download many placements' exact coordinates in one request. That endpoint is now locked to the realtime server with a shared secret, the public nearby feed is rate-limited so it can't be systematically gridded, and the maximum window size was tightened. Live discovery, your own pins, and the realtime map are unchanged.",
+ "title": "IRL world: placed agents are private by location — discovered only in person",
+ "summary": "We changed how the /irl world reveals where agents are placed, for safety. There is no list, map, or feed of agent locations anywhere: an agent's spot is shared with your device only when you are physically within a short distance of it, so you come across one by walking up and pointing your camera — never by browsing locations from afar. The live realtime server no longer broadcasts a neighborhood's placements to everyone connected; it now carries only presence (how many people are viewing nearby) and ambient reactions, both kept coarse and anonymous. The 'nearby' read is hard-capped to a tight radius and rate-limited so it can't be swept to rebuild a map. Placing agents and the multiplayer presence layer keep working as before.",
"link": "/irl",
"tags": [
- "security"
+ "security",
+ "improvement"
]
},
{
diff --git a/public/changelog.xml b/public/changelog.xml
index 27f754993..96bbbad41 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -143,12 +143,12 @@
<description>The first time you open three.ws/irl, a quick setup card explains why each sensor matters and asks for one at a time: the camera to see your agents in the real world, motion to look around, and location to place agents and discover the ones others left nearby. Every outcome is designed — you see why we’re asking, a green check when access is granted, and if you decline you get the exact steps to switch it back on (the precise iOS Settings path on iPhone) with a Try again button, not a toast that vanishes. Sensors your device doesn’t have are handled honestly, with a note on what still works. Block something later and a one-tap ‘Enable camera’ or ‘Enable location’ chip stays in the top bar so recovery is always within reach — and turning on the camera or pinning an agent re-asks through the same clear cards instead of failing silently. Your choices are remembered, so you’re never nagged twice.</description>
</item>
<item>
- <title>IRL world: closed a bulk location-scrape path on placed agents</title>
+ <title>IRL world: placed agents are private by location — discovered only in person</title>
<link>https://three.ws/irl</link>
- <guid isPermaLink="false">2026-06-17:IRL world: closed a bulk location-scrape path on placed agents</guid>
+ <guid isPermaLink="false">2026-06-17:IRL world: placed agents are private by location — discovered only in person</guid>
<pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>
<category>security</category>
- <description>The /irl world lets you place 3D agents at real GPS spots and discover the ones near you. The 'discover nearby' feed always hid who placed each agent, but an internal bulk window-load endpoint — used only by the live realtime server to hydrate a neighborhood — was reachable from the open web, which in principle let someone download many placements' exact coordinates in one request. That endpoint is now locked to the realtime server with a shared secret, the public nearby feed is rate-limited so it can't be systematically gridded, and the maximum window size was tightened. Live discovery, your own pins, and the realtime map are unchanged.</description>
+ <description>We changed how the /irl world reveals where agents are placed, for safety. There is no list, map, or feed of agent locations anywhere: an agent's spot is shared with your device only when you are physically within a short distance of it, so you come across one by walking up and pointing your camera — never by browsing locations from afar. The live realtime server no longer broadcasts a neighborhood's placements to everyone connected; it now carries only presence (how many people are viewing nearby) and ambient reactions, both kept coarse and anonymous. The 'nearby' read is hard-capped to a tight radius and rate-limited so it can't be swept to rebuild a map. Placing agents and the multiplayer presence layer keep working as before.</description>
</item>
<item>
<title>Jump straight from an agent's profile into IRL or XR</title>
diff --git a/public/features.json b/public/features.json
index 5db00c67b..58bf0d78f 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-17T07:22:22.793Z",
+ "generated_at": "2026-06-17T08:20:44.934Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/scripts/irl-d1-smoke.mjs b/scripts/irl-d1-smoke.mjs
deleted file mode 100644
index 6be9960ce..000000000
--- a/scripts/irl-d1-smoke.mjs
+++ /dev/null
@@ -1,206 +0,0 @@
-// Live round-trip smoke for D1 — IRL realtime pin sync.
-//
-// node scripts/irl-d1-smoke.mjs
-//
-// Where irl-d3-smoke unit-tests the privacy filter, this one proves the actual
-// liveness contract end-to-end: it boots the REAL multiplayer server (the same
-// multiplayer/src/index.js prod runs, with the irl_world room + signed
-// /internal/irl-publish webhook wired exactly as deployed), connects two
-// colyseus.js clients to one geocell room, fires a signed publish, and asserts
-// the change lands on the other client within the ~1 s liveness budget.
-//
-// It mechanises the spec's manual "two phones at the same spot" checklist:
-// 1. A places a pin → it appears on B within ~1 s (schema delta). [add]
-// 2. A removes a pin → it disappears on B live. [remove]
-// 3. A late joiner is handed the full current pin set on join (schema sync). [late join]
-// 4. A forged / tampered / stale publish is rejected (401) and never reaches [auth]
-// the room — the channel can't be poisoned by an unsigned request.
-//
-// The server's pin hydration is pointed at a dead API base so onCreate loads an
-// empty cell deterministically (it degrades gracefully on load failure), and the
-// shared secret is fixed — so the run needs no DB, no env, and no network.
-// Assertions throw on failure; a clean run prints "D1 SMOKE: PASS".
-
-import { spawn } from 'node:child_process';
-import { fileURLToPath } from 'node:url';
-import path from 'node:path';
-
-import { Client, getStateCallbacks } from 'colyseus.js';
-import { IrlState } from '../multiplayer/src/irl-schemas.js';
-import { encodeGeohash } from '../multiplayer/src/geohash.js';
-import { hmacSha256, sha256Base64Url } from '../api/_lib/crypto.js';
-
-const ROOT = path.resolve(fileURLToPath(new URL('.', import.meta.url)), '..');
-const PORT = 2599;
-const HOST = '127.0.0.1';
-const BASE_HTTP = `http://${HOST}:${PORT}`;
-const BASE_WS = `ws://${HOST}:${PORT}`;
-const SECRET = 'd1-smoke-secret';
-const LIVENESS_MS = 1500; // the spec's "~1 s" plus headroom for CI scheduling jitter
-
-// A real coordinate (downtown SF) and the precision-6 cell it lands in — the
-// client's room key and the publish's geocell must agree, so we derive both from
-// the same encoder the app uses.
-const LAT = 37.7749;
-const LNG = -122.4194;
-const GEOCELL = encodeGeohash(LAT, LNG, 6);
-
-let failures = 0;
-function check(name, cond) {
- if (cond) console.log(` ✓ ${name}`);
- else { console.error(` ✗ ${name}`); failures++; }
-}
-
-// ── Boot the real multiplayer server ─────────────────────────────────────────
-function startServer() {
- const child = spawn(process.execPath, ['multiplayer/src/index.js'], {
- cwd: ROOT,
- env: {
- ...process.env,
- PORT: String(PORT),
- HOST,
- NODE_ENV: 'development', // allows origin-less node-client upgrades
- MULTIPLAYER_SHARED_SECRET: SECRET,
- HOLDER_PASS_SECRET: SECRET,
- // Dead API base → onCreate's pin hydration fails fast and the room starts
- // empty, so the test set is exactly what THIS run publishes (deterministic).
- WORLD_API_BASE: 'http://127.0.0.1:9',
- REDIS_URI: '',
- REDIS_URL: '',
- },
- stdio: ['ignore', 'pipe', 'pipe'],
- });
- const ready = new Promise((resolve, reject) => {
- const timer = setTimeout(() => reject(new Error('server did not start within 15s')), 15000);
- child.stdout.on('data', (b) => {
- if (String(b).includes('listening on ws://')) { clearTimeout(timer); resolve(); }
- });
- child.stderr.on('data', (b) => {
- const s = String(b);
- // Surface real boot failures; the dead-API pin-load warning is expected noise.
- if (/FATAL|Error:|failed to start/.test(s) && !/pin load failed/.test(s)) {
- process.stderr.write(`[server] ${s}`);
- }
- });
- child.on('exit', (code) => { if (code) reject(new Error(`server exited early (${code})`)); });
- });
- return { child, ready };
-}
-
-// ── A signed publish, mirroring api/_lib/irl-publish.js byte-for-byte ─────────
-async function publish(type, pin, { secret = SECRET, ts = Math.floor(Date.now() / 1000) } = {}) {
- const pinHash = await sha256Base64Url(JSON.stringify(pin ?? {}));
- const sig = await hmacSha256(secret, `irl:${GEOCELL}:${type}:${ts}:${pinHash}`);
- const res = await fetch(`${BASE_HTTP}/internal/irl-publish`, {
- method: 'POST',
- headers: { 'content-type': 'application/json', 'x-mp-signature': sig, 'x-mp-timestamp': String(ts) },
- body: JSON.stringify({ geocell: GEOCELL, type, pin }),
- });
- const body = await res.json().catch(() => ({}));
- return { status: res.status, body };
-}
-
-// Connect a client and expose the live pins map + a waiter for a specific pin id.
-async function connectClient(label) {
- const client = new Client(BASE_WS);
- const room = await client.joinOrCreate('irl_world', { geocell: GEOCELL, deviceToken: label, lat: LAT, lng: LNG }, IrlState);
- const present = new Set();
- const addWaiters = new Map(); // id → resolve
- const removeWaiters = new Map();
- const $ = getStateCallbacks(room);
- $(room.state).pins.onAdd((pin, id) => {
- present.add(id);
- addWaiters.get(id)?.(pin); addWaiters.delete(id);
- });
- $(room.state).pins.onRemove((pin, id) => {
- present.delete(id);
- removeWaiters.get(id)?.(); removeWaiters.delete(id);
- });
- const waitFor = (map) => (id, ms) => new Promise((resolve, reject) => {
- const t = setTimeout(() => reject(new Error(`${label}: timeout waiting on ${id} (${ms}ms)`)), ms);
- map.set(id, (v) => { clearTimeout(t); resolve(v); });
- });
- return {
- room,
- present,
- has: (id) => present.has(id),
- waitAdd: (id, ms) => (present.has(id) ? Promise.resolve(room.state.pins.get(id)) : waitFor(addWaiters)(id, ms)),
- waitRemove: (id, ms) => (!present.has(id) ? Promise.resolve() : waitFor(removeWaiters)(id, ms)),
- leave: () => room.leave().catch(() => {}),
- };
-}
-
-async function main() {
- const { child, ready } = startServer();
- let A, B, C;
- try {
- await ready;
- console.log(`server up on ${BASE_WS} — cell ${GEOCELL}\n`);
-
- console.log('1) two viewers in one cell — a placed pin lands live on the other');
- A = await connectClient('A');
- B = await connectClient('B');
- check('both clients joined the same room instance', A.room.roomId === B.room.roomId);
-
- const pin = {
- id: 'smoke-pin-1', lat: LAT, lng: LNG, heading: 90,
- avatarUrl: 'https://three.ws/cdn/default.glb', avatarName: 'Greeter',
- caption: 'gm', agentId: 'agent-xyz', placedAt: Date.now(),
- };
- const t0 = Date.now();
- const pub = await publish('pin:add', pin);
- check('publish accepted (signed)', pub.status === 200);
- check('publish dispatched to ≥1 live room', Number(pub.body?.delivered) >= 1);
-
- const landed = await B.waitAdd(pin.id, LIVENESS_MS);
- const elapsed = Date.now() - t0;
- check(`B received the pin within ${LIVENESS_MS}ms (took ${elapsed}ms)`, elapsed <= LIVENESS_MS);
- check('B sees the full pin payload (caption + avatar + heading)',
- landed?.caption === 'gm' && landed?.avatarUrl === pin.avatarUrl && Math.round(landed?.heading) === 90);
-
- console.log('\n2) a late joiner is handed the full current set on join (schema sync)');
- C = await connectClient('C');
- // The pin was placed before C joined; Colyseus hands the full state on join,
- // applied in the room-state message that lands just after joinOrCreate resolves.
- // So we await the sync (resolves instantly if already present) rather than race it.
- await C.waitAdd(pin.id, LIVENESS_MS);
- check('C is handed the pin placed before it joined (join-time state sync)', C.has(pin.id));
- check('C and B/A share the same room instance', C.room.roomId === A.room.roomId);
-
- console.log('\n3) a removal disappears on the other viewers live');
- const tR = Date.now();
- const rem = await publish('pin:remove', { id: pin.id });
- check('remove publish accepted', rem.status === 200);
- await Promise.all([B.waitRemove(pin.id, LIVENESS_MS), C.waitRemove(pin.id, LIVENESS_MS)]);
- check(`B & C saw the removal within ${LIVENESS_MS}ms (took ${Date.now() - tR}ms)`, !B.has(pin.id) && !C.has(pin.id));
-
- console.log('\n4) the channel rejects forged / tampered / stale publishes');
- const unsigned = await fetch(`${BASE_HTTP}/internal/irl-publish`, {
- method: 'POST', headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ geocell: GEOCELL, type: 'pin:add', pin: { id: 'forged' } }),
- });
- check('unsigned publish → 401', unsigned.status === 401);
-
- const wrongSecret = await publish('pin:add', { id: 'forged-2', lat: LAT, lng: LNG }, { secret: 'not-the-secret' });
- check('wrong-secret publish → 401', wrongSecret.status === 401);
-
- const stale = await publish('pin:add', { id: 'forged-3', lat: LAT, lng: LNG }, { ts: Math.floor(Date.now() / 1000) - 600 });
- check('stale-timestamp publish → 401', stale.status === 401);
-
- check('no forged pin reached the room', !B.has('forged') && !B.has('forged-2') && !B.has('forged-3'));
- } finally {
- await Promise.allSettled([A?.leave(), B?.leave(), C?.leave()]);
- child.kill('SIGTERM');
- }
-
- if (failures) {
- console.error(`\nD1 SMOKE: FAIL (${failures} check${failures === 1 ? '' : 's'})`);
- process.exit(1);
- }
- console.log('\nD1 SMOKE: PASS');
-}
-
-main().catch((err) => {
- console.error('\nD1 SMOKE: ERROR —', err?.message || err);
- process.exit(1);
-});
diff --git a/src/animation-manager.js b/src/animation-manager.js
index 4fd3fe178..436bc4e45 100644
--- a/src/animation-manager.js
+++ b/src/animation-manager.js
@@ -1,6 +1,10 @@
import { AnimationClip, AnimationMixer, LoopRepeat, LoopOnce } from 'three';
import { canonicalizeBoneName } from './glb-canonicalize.js';
-import { canonicalNodeMapFromObject, retargetClip } from './animation-retarget.js';
+import {
+ canonicalNodeMapFromObject,
+ canonicalRestMapFromObject,
+ retargetClip,
+} from './animation-retarget.js';
import { log } from './shared/log.js';
// Minimum number of canonical bones a skinned model must expose before the
@@ -71,6 +75,11 @@ export class AnimationManager {
// so the library drives ANY humanoid rig — Mixamo, VRM-via-Mixamo,
// CharacterStudio, Blender — not just an already-canonical Avaturn rig.
this._canonicalToNode = canonicalNodeMapFromObject(model);
+ // Captured here, while the model is still in its authored bind pose, so
+ // the retargeter can re-express each clip in the rig's own rest frame
+ // (a Mixamo rig bakes the up-axis as a −90°X Hips rest the clips would
+ // otherwise overwrite, tipping the avatar onto its back).
+ this._canonicalRest = canonicalRestMapFromObject(model);
this._canonicalClipsSupported = _modelSupportsCanonicalClips(model);
for (const [name, clip] of this.clips) {
@@ -92,7 +101,9 @@ export class AnimationManager {
*/
_retarget(clip) {
if (!this._canonicalToNode || this._canonicalToNode.size === 0) return null;
- const { clip: out } = retargetClip(clip, this._canonicalToNode);
+ const { clip: out } = retargetClip(clip, this._canonicalToNode, {
+ targetRest: this._canonicalRest,
+ });
return out;
}
@@ -105,6 +116,7 @@ export class AnimationManager {
}
this.model = null;
this._canonicalToNode = null;
+ this._canonicalRest = null;
this._canonicalClipsSupported = false;
this.actions.clear();
this.currentAction = null;
diff --git a/src/animation-retarget.js b/src/animation-retarget.js
index b90e03541..4eab97816 100644
--- a/src/animation-retarget.js
+++ b/src/animation-retarget.js
@@ -14,7 +14,7 @@
// Pure module — three + the canonicalizer only — so it runs unchanged in the
// browser (the /pose gallery) and in Node (the apply_animation MCP tool, vitest).
-import { AnimationClip, Vector3 } from 'three';
+import { AnimationClip, Quaternion, Vector3 } from 'three';
import { canonicalizeBoneName } from './glb-canonicalize.js';
// A clip retargets cleanly only when enough of its tracks find a home on the
@@ -22,7 +22,29 @@ import { canonicalizeBoneName } from './glb-canonicalize.js';
// than a performance, so callers surface an actionable "can't retarget" error.
export const MIN_COVERAGE = 0.5;
+// Rest (bind-pose) local rotation of each canonical bone *on the authoring rig*
+// the clips were baked against (canonical Avaturn). The library stores absolute
+// local rotations, so a clip only looks right when the target bone's rest
+// matches the authoring rest — otherwise we must replay the motion in the
+// target's own rest frame (see `bindCorrections`).
+//
+// Only Hips is listed: it's the skeleton root, the one bone that carries the
+// up-axis convention. Mixamo/FBX exports bake a +90°X on the armature node and a
+// −90°X on Hips; copying the clip's (≈identity) Hips rotation verbatim wipes that
+// −90°X out and tips the whole body onto its back. The authoring rig's Hips rest
+// is identity, so a correction of `targetHipsRest · I` re-applies whatever rest
+// the target rig needs. Limb bones aren't listed because their authoring rest is
+// avatar-specific and copying verbatim has always been the (acceptable) status
+// quo for non-Avaturn rigs; adding them would require shipping the full authoring
+// rest pose and would change limb output for every rig.
+const SOURCE_REST = new Map([['Hips', new Quaternion(0, 0, 0, 1)]]);
+
+// A quaternion within this of identity (|w| ≈ 1) is treated as no rotation, so a
+// rig that already matches the authoring convention round-trips bit-for-bit.
+const BIND_EPSILON = 1e-6;
+
const _v = new Vector3();
+const _q = new Quaternion();
/**
* @typedef {Object} RetargetResult
@@ -77,6 +99,96 @@ export function canonicalNodeMapFromRig(rig) {
return map;
}
+/**
+ * Capture each canonical bone's rest (bind-pose) local rotation by walking an
+ * Object3D graph — the companion to {@link canonicalNodeMapFromObject}, read in
+ * the same first-bone-wins order so the rest quaternion belongs to the very node
+ * a track gets renamed onto. Call while the model is in its authored bind pose
+ * (i.e. before any clip has been sampled), which is the case at attach time.
+ *
+ * @param {import('three').Object3D} root
+ * @returns {Map<string,import('three').Quaternion>}
+ */
+export function canonicalRestMapFromObject(root) {
+ const map = new Map();
+ const consider = (node) => {
+ if (!node?.name) return;
+ const canonical = canonicalizeBoneName(node.name);
+ if (canonical && !map.has(canonical)) map.set(canonical, node.quaternion.clone());
+ };
+ const skinned = [];
+ root.traverse((node) => {
+ if (node.isSkinnedMesh) skinned.push(node);
+ if (node.isBone) consider(node);
+ });
+ for (const sm of skinned) {
+ for (const bone of sm.skeleton?.bones || []) consider(bone);
+ }
+ return map;
+}
+
+/**
+ * Rest-rotation map from a GltfRig/MannequinRig, mirroring
+ * {@link canonicalNodeMapFromRig}.
+ *
+ * @param {{ getBones: () => Array<{key:string,node:import('three').Object3D}> }} rig
+ * @returns {Map<string,import('three').Quaternion>}
+ */
+export function canonicalRestMapFromRig(rig) {
+ const map = new Map();
+ for (const { key, node } of rig.getBones?.() || []) {
+ if (node && !map.has(key)) map.set(key, node.quaternion.clone());
+ }
+ return map;
+}
+
+/**
+ * Per-bone bind correction `C = targetRest · sourceRest⁻¹`. Applying `C · q` to a
+ * clip keyframe replays the source bone's deviation-from-rest in the target
+ * bone's own rest frame, so a clip authored for one rest pose drives a rig with a
+ * different one (e.g. a Mixamo rig whose Hips bakes the up-axis as −90°X). Bones
+ * whose correction is identity are omitted, so a matching rig skips the work and
+ * round-trips unchanged.
+ *
+ * @param {Map<string,import('three').Quaternion>|null} targetRest
+ * @returns {Map<string,import('three').Quaternion>}
+ */
+function bindCorrections(targetRest) {
+ const out = new Map();
+ if (!(targetRest instanceof Map)) return out;
+ for (const [canonical, sourceRest] of SOURCE_REST) {
+ const tr = targetRest.get(canonical);
+ if (!tr) continue;
+ const c = new Quaternion().multiplyQuaternions(tr, sourceRest.clone().invert());
+ if (1 - Math.abs(c.w) < BIND_EPSILON) continue; // identity → no correction
+ out.set(canonical, c);
+ }
+ return out;
+}
+
+// Pre-multiply every [x,y,z,w] keyframe of a quaternion track by `c` in place:
+// q ← c · q (deviation replayed in the target bone's rest frame).
+function premultiplyQuaternionTrack(values, c) {
+ for (let i = 0; i < values.length; i += 4) {
+ _q.set(values[i], values[i + 1], values[i + 2], values[i + 3]).premultiply(c);
+ values[i] = _q.x;
+ values[i + 1] = _q.y;
+ values[i + 2] = _q.z;
+ values[i + 3] = _q.w;
+ }
+}
+
+// Rotate every [x,y,z] keyframe of a position track by `c` in place, so root
+// motion stays aligned once the parent armature's axis convention is corrected.
+function rotateVectorTrack(values, c) {
+ for (let i = 0; i < values.length; i += 3) {
+ _v.set(values[i], values[i + 1], values[i + 2]).applyQuaternion(c);
+ values[i] = _v.x;
+ values[i + 1] = _v.y;
+ values[i + 2] = _v.z;
+ }
+}
+
/**
* World-space rest height of the target's hips, used to scale root translation
* onto a differently-sized rig. Returns 0 if it can't be determined (callers
@@ -117,6 +229,7 @@ function clipHipBaselineY(clip) {
export function retargetClip(clip, canonicalToNode, opts = {}) {
const hipScale = Number.isFinite(opts.hipScale) && opts.hipScale > 0 ? opts.hipScale : 1;
const minCoverage = opts.minCoverage ?? MIN_COVERAGE;
+ const corrections = bindCorrections(opts.targetRest);
const total = clip.tracks.length;
const dropped = [];
const tracks = [];
@@ -134,6 +247,14 @@ export function retargetClip(clip, canonicalToNode, opts = {}) {
}
const next = track.clone();
next.name = `${nodeName}.${property}`;
+ // Bind correction: rotate the bone's rest convention onto the target rig
+ // so a clip authored for one rest pose doesn't flip a differently-rigged
+ // avatar (e.g. a Mixamo Hips baked at −90°X reading as "lying down").
+ const correction = corrections.get(canonical);
+ if (correction) {
+ if (property === 'quaternion') premultiplyQuaternionTrack(next.values, correction);
+ else if (property === 'position') rotateVectorTrack(next.values, correction);
+ }
if (hipScale !== 1 && canonical === 'Hips' && property === 'position') {
for (let i = 0; i < next.values.length; i++) next.values[i] *= hipScale;
}
@@ -161,6 +282,7 @@ export function retargetClip(clip, canonicalToNode, opts = {}) {
*/
export function retargetClipToRig(clip, rig, opts = {}) {
const map = canonicalNodeMapFromRig(rig);
+ const targetRest = canonicalRestMapFromRig(rig);
let hipScale = 1;
if (opts.scaleHips !== false) {
const targetY = hipRestHeight(rig);
@@ -171,7 +293,7 @@ export function retargetClipToRig(clip, rig, opts = {}) {
hipScale = Math.min(5, Math.max(0.2, targetY / sourceY));
}
}
- return retargetClip(clip, map, { hipScale, minCoverage: opts.minCoverage });
+ return retargetClip(clip, map, { hipScale, minCoverage: opts.minCoverage, targetRest });
}
/**
@@ -185,7 +307,8 @@ export function retargetClipToRig(clip, rig, opts = {}) {
*/
export function retargetClipToObject(clip, root, opts = {}) {
const map = canonicalNodeMapFromObject(root);
- return retargetClip(clip, map, opts);
+ const targetRest = opts.targetRest || canonicalRestMapFromObject(root);
+ return retargetClip(clip, map, { ...opts, targetRest });
}
/**
diff --git a/tests/animation-retarget.test.js b/tests/animation-retarget.test.js
index 0f01f2acd..ccb95a622 100644
--- a/tests/animation-retarget.test.js
+++ b/tests/animation-retarget.test.js
@@ -21,9 +21,11 @@ import {
VectorKeyframeTrack,
AnimationClip,
Object3D,
+ Quaternion,
} from 'three';
import {
canonicalNodeMapFromObject,
+ canonicalRestMapFromObject,
retargetClip,
retargetClipToObject,
scaleClipSpeed,
@@ -150,6 +152,67 @@ describe('retargetClip', () => {
});
});
+describe('bind-rotation correction', () => {
+ // Mixamo/FBX rigs bake the up-axis as a −90°X rest on Hips (with a +90°X on
+ // the armature parent). A clip authored for an identity-Hips rest would wipe
+ // that out and tip the avatar onto its back; the correction re-applies it.
+ const HIPS_MINUS_90X = new Quaternion().setFromAxisAngle({ x: 1, y: 0, z: 0 }, -Math.PI / 2);
+
+ it('round-trips a clip unchanged when the rig already matches the authoring rest', () => {
+ const clip = makeCanonicalClip();
+ const rig = makeRig(CANONICAL_RIG); // every bone at identity rest
+ const map = canonicalNodeMapFromObject(rig);
+ const targetRest = canonicalRestMapFromObject(rig);
+ const r = retargetClip(clip, map, { hipScale: 1, targetRest });
+ const hipsQ = r.clip.tracks.find((t) => t.name === 'Hips.quaternion');
+ expect(Array.from(hipsQ.values)).toEqual([0, 0, 0, 1, 0, 0, 0, 1]);
+ });
+
+ it('re-applies a −90°X Hips rest the clip would otherwise overwrite', () => {
+ const clip = makeCanonicalClip(); // Hips.quaternion is identity at every key
+ const rig = makeRig(CANONICAL_RIG);
+ rig.getObjectByName('Hips').quaternion.copy(HIPS_MINUS_90X);
+ const map = canonicalNodeMapFromObject(rig);
+ const targetRest = canonicalRestMapFromObject(rig);
+ const r = retargetClip(clip, map, { hipScale: 1, targetRest });
+
+ // C · identity = C = the rig's Hips rest, so the body stands upright.
+ const hipsQ = r.clip.tracks.find((t) => t.name === 'Hips.quaternion');
+ expect(hipsQ.values[0]).toBeCloseTo(HIPS_MINUS_90X.x, 5);
+ expect(hipsQ.values[3]).toBeCloseTo(HIPS_MINUS_90X.w, 5);
+
+ // Root-motion keyframes are rotated by the same correction: (0,1,0) → (0,0,−1).
+ const hipsP = r.clip.tracks.find((t) => t.name === 'Hips.position');
+ expect(hipsP.values[0]).toBeCloseTo(0, 5);
+ expect(hipsP.values[1]).toBeCloseTo(0, 5);
+ expect(hipsP.values[2]).toBeCloseTo(-1, 5);
+ });
+
+ it('leaves limb bones verbatim even when the rig gives them a non-identity rest', () => {
+ const clip = makeCanonicalClip();
+ const rig = makeRig(CANONICAL_RIG);
+ rig.getObjectByName('LeftArm').quaternion.copy(HIPS_MINUS_90X);
+ const map = canonicalNodeMapFromObject(rig);
+ const targetRest = canonicalRestMapFromObject(rig);
+ const r = retargetClip(clip, map, { hipScale: 1, targetRest });
+ const armQ = r.clip.tracks.find((t) => t.name === 'LeftArm.quaternion');
+ // Only Hips carries the up-axis convention; limbs are copied as authored.
+ expect(Array.from(armQ.values)).toEqual([0, 0, 0, 1, 0, 0, 0, 1]);
+ });
+
+ it('hip scaling and rotation compose: position is both rotated and scaled', () => {
+ const clip = makeCanonicalClip();
+ const rig = makeRig(CANONICAL_RIG);
+ rig.getObjectByName('Hips').quaternion.copy(HIPS_MINUS_90X);
+ const map = canonicalNodeMapFromObject(rig);
+ const targetRest = canonicalRestMapFromObject(rig);
+ const r = retargetClip(clip, map, { hipScale: 2, targetRest });
+ const hipsP = r.clip.tracks.find((t) => t.name === 'Hips.position');
+ // (0,1,0) rotated → (0,0,−1), then ×2 → (0,0,−2).
+ expect(hipsP.values[2]).toBeCloseTo(-2, 5);
+ });
+});
+
describe('retargetClipToObject', () => {
it('retargets straight onto an Object3D graph', () => {
const clip = makeCanonicalClip();
diff --git a/tests/api/irl-pins-location-guards.test.js b/tests/api/irl-pins-location-guards.test.js
new file mode 100644
index 000000000..a627ec2fd
--- /dev/null
+++ b/tests/api/irl-pins-location-guards.test.js
@@ -0,0 +1,135 @@
+// GET /api/irl/pins — location-privacy guards.
+//
+// Placed agents are private by location: another agent's coordinates are revealed
+// ONLY through the per-viewer nearby read, and only for the handful physically
+// within a tight radius of the caller. This locks in the guarantees that make
+// that true:
+// 1. There is NO bulk window feed. A `bbox` query is not a special path — it
+// falls through to the nearby branch and 400s without lat/lng, never
+// returning a multi-pin neighbourhood roster.
+// 2. The discovery radius is HARD-CAPPED small server-side, so even a crafted
+// huge radius only ever scans a tight box around the caller.
+// 3. The public nearby feed is IP rate-limited (so it can't be gridded into a
+// scrape) and never projects owner identifiers.
+// DB / auth / limiter are mocked so the suite stays offline.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const PIN = {
+ id: 'pin-1', user_id: 'owner-1', device_token: 'dev-1', agent_id: null,
+ lat: 40.7128, lng: -74.006, heading: 0,
+ avatar_url: null, avatar_name: 'Aria', caption: 'hi', x402_endpoint: null,
+ placed_at: '2026-01-01T00:00:00Z', view_count: 0,
+ anchor_height_m: null, anchor_yaw_deg: null, anchor_quat: null,
+ gps_accuracy_m: null, altitude_m: null, anchor_source: null, avatar_version: 0,
+ room_id: null, rel_east_m: null, rel_north_m: null,
+ origin_lat: null, origin_lng: null, origin_yaw_deg: null,
+};
+
+// The nearby pin SELECT carries `FROM irl_pins` + `lat BETWEEN`; return one
+// in-range pin for it and [] for everything else (ensureTable DDL etc).
+const sqlMock = vi.fn((strings) => {
+ const q = Array.isArray(strings) ? strings.join(' ') : String(strings);
+ if (/FROM\s+irl_pins/i.test(q) && /lat BETWEEN/i.test(q)) return Promise.resolve([PIN]);
+ return Promise.resolve([]);
+});
+vi.mock('../../api/_lib/db.js', () => ({ sql: (...a) => sqlMock(...a) }));
+
+vi.mock('../../api/_lib/auth.js', () => ({ getSessionUser: vi.fn(async () => null) }));
+
+let publicVerdict = { success: true, reset: Date.now() + 60_000 };
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { publicIp: vi.fn(async () => publicVerdict) },
+ clientIp: () => '127.0.0.1',
+}));
+
+const { default: handler } = await import('../../api/irl/pins.js');
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ headersSent: false,
+ writableEnded: false,
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ getHeader(k) { return this._h[k.toLowerCase()]; },
+ end(body) { this.writableEnded = true; this._body = body; },
+ };
+}
+async function get({ query = {}, headers = {} } = {}) {
+ const res = makeRes();
+ await handler({ url: '/api/irl/pins', method: 'GET', headers: { host: 'x', ...headers }, query }, res);
+ let parsed = null;
+ try { parsed = JSON.parse(res._body); } catch {}
+ return { res, body: parsed };
+}
+// The nearby SELECT is interpolated `WHERE lat BETWEEN ${latLo} AND ${latHi} AND
+// lng BETWEEN ${lngLo} AND ${lngHi} …`, so its call args are [strings, latLo,
+// latHi, lngLo, lngHi]. Return that call (or null) so a test can inspect the box.
+function nearbySelectCall() {
+ return sqlMock.mock.calls.find(([s]) => {
+ const q = Array.isArray(s) ? s.join(' ') : String(s);
+ return /FROM\s+irl_pins/i.test(q) && /lat BETWEEN/i.test(q);
+ }) || null;
+}
+function ranPinSelect() {
+ return nearbySelectCall() !== null;
+}
+
+beforeEach(() => {
+ sqlMock.mockClear();
+ publicVerdict = { success: true, reset: Date.now() + 60_000 };
+});
+
+describe('GET /api/irl/pins — no bulk location window', () => {
+ it('treats a bbox param as a normal query: 400s without lat/lng, never reads pins', async () => {
+ const { res } = await get({ query: { bbox: '40.70,-74.02,40.73,-73.99' } });
+ expect(res.statusCode).toBe(400);
+ expect(ranPinSelect()).toBe(false);
+ });
+
+ it('grants no special access for the old internal-hydration header', async () => {
+ // The shared-secret window feed is gone — a bbox + secret header is just a
+ // query missing lat/lng, so it 400s like any other and reads nothing.
+ const { res } = await get({
+ query: { bbox: '40.70,-74.02,40.73,-73.99' },
+ headers: { 'x-mp-internal': 'any-secret-at-all' },
+ });
+ expect(res.statusCode).toBe(400);
+ expect(ranPinSelect()).toBe(false);
+ });
+});
+
+describe('GET /api/irl/pins — tight proximity radius', () => {
+ it('hard-caps the radius so a huge requested radius still scans a tiny box', async () => {
+ const { res } = await get({ query: { lat: '40.7128', lng: '-74.006', radius: '100000' } });
+ expect(res.statusCode).toBe(200);
+ const call = nearbySelectCall();
+ expect(call).not.toBeNull();
+ const [, latLo, latHi] = call;
+ // 60 m cap → half-window 60/110540 ≈ 0.00054°, so the full lat span is ~0.0011°.
+ // Assert it's well under ~150 m (0.0027°) — proves the requested 100 km was clamped.
+ expect(latHi - latLo).toBeLessThan(0.0027);
+ });
+});
+
+describe('GET /api/irl/pins — public nearby feed', () => {
+ it('200s a normal nearby query, consults the limiter, and hides owner identifiers', async () => {
+ const { limits } = await import('../../api/_lib/rate-limit.js');
+ limits.publicIp.mockClear();
+ const { res, body } = await get({ query: { lat: '40.7128', lng: '-74.006', radius: '40' } });
+ expect(res.statusCode).toBe(200);
+ expect(body.pins[0].id).toBe('pin-1');
+ // Owner identifiers are never projected into the public feed.
+ expect(body.pins[0]).not.toHaveProperty('user_id');
+ expect(body.pins[0]).not.toHaveProperty('device_token');
+ expect(limits.publicIp).toHaveBeenCalledTimes(1);
+ });
+
+ it('429s the nearby feed when the public limiter is exhausted, before any DB read', async () => {
+ publicVerdict = { success: false, reset: Date.now() + 30_000 };
+ const { res } = await get({ query: { lat: '40.7128', lng: '-74.006', radius: '40' } });
+ expect(res.statusCode).toBe(429);
+ expect(ranPinSelect()).toBe(false);
+ });
+});