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.

Sweep verified-done task/prompt specs; add prune + curated-docs scripts

nirholase3105b9c2446
diff --git a/prompts/monetization-prompts/13-allow-free-skills.md b/prompts/monetization-prompts/13-allow-free-skills.md
deleted file mode 100644
index 27af94370..000000000
--- a/prompts/monetization-prompts/13-allow-free-skills.md
+++ /dev/null
@@ -1,100 +0,0 @@
-# Prompt 13: Allow Creators to List Skills for Free
-
-**Status:** - [ ] Not Started
-
-## Objective
-Enhance the skill monetization interface to allow creators to explicitly list a skill as "Free" or remove its price, making it available to all users without a purchase.
-
-## Explanation
-Not all skills should require payment. Creators may want to offer some skills for free as a preview or for community-building. The system needs to support toggling a skill between a paid and free state.
-
-## Instructions
-1. **Update the UI for Price Management:**
- * In the "Skill Monetization" section of `agent-edit.html`, for each skill, add a "Make Free" or "Remove Price" button next to the pricing inputs.
- * If a skill currently has a price, this button should be active. If it's already free, the button can be disabled or hidden.
- * The UI should visually indicate that a skill is free (e.g., by displaying "Free" instead of price inputs).
-
-2. **Create a Backend Endpoint for Removing Prices:**
- * Create a new API endpoint, e.g., `api/agents/remove-skill-price.js`.
- * This endpoint must be authenticated and verify that the user is the agent's creator.
- * It should accept `agentId` and `skillName`.
- * The handler will `DELETE` the corresponding record from the `agent_skill_prices` table.
-
-3. **Connect Frontend to Backend:**
- * In the JavaScript for the agent edit page, add an event listener for the "Remove Price" button.
- * When clicked, it should call the new `DELETE` endpoint.
- * On success, update the UI for that skill to show it as free and clear the price input fields.
-
-## Code Example (JavaScript for `agent-edit.html`)
-
-```javascript
-// Inside the event listener for the skill pricing list
-$('skill-pricing-list').addEventListener('click', async (e) => {
- // ... (handle 'set-price-btn' clicks)
-
- if (e.target.classList.contains('remove-price-btn')) {
- const skillName = e.target.dataset.skillName;
-
- // Optional: Ask for confirmation
- if (!confirm(`Are you sure you want to make the skill "${skillName}" free?`)) {
- return;
- }
-
- const response = await fetch('/api/agents/remove-skill-price', {
- method: 'POST', // Or DELETE, depending on your API design
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- agentId: currentAgentId,
- skillName,
- }),
- });
-
- if (response.ok) {
- showToast('Skill is now free!', 'success');
- // Re-render the pricing section to reflect the change
- // Or dynamically update the specific row
- const priceInput = document.querySelector(`input[data-skill-name="${skillName}"]`);
- priceInput.value = '';
- } else {
- showToast('Failed to update skill.', 'error');
- }
- }
-});
-```
-
-## Code Example (Backend - `api/agents/remove-skill-price.js`)
-
-```javascript
-import { getDB } from './_lib/db';
-
-export default async function handler(req, res) {
- // Assume user is authenticated and is the agent owner
- const { agentId, skillName } = req.body;
-
- const db = getDB();
- try {
- await db.query(
- 'DELETE FROM agent_skill_prices WHERE agent_id = $1 AND skill_name = $2',
- [agentId, skillName]
- );
- res.status(200).json({ success: true, message: 'Skill price removed.' });
- } catch (error) {
- console.error('Failed to remove skill price:', error);
- res.status(500).json({ error: 'Failed to update skill.' });
- }
-}
-```
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/monetization-prompts/13-allow-free-skills.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/monetization-prompts/13-frontend-buy-skill-button.md b/prompts/monetization-prompts/13-frontend-buy-skill-button.md
deleted file mode 100644
index 6d1dc6f8a..000000000
--- a/prompts/monetization-prompts/13-frontend-buy-skill-button.md
+++ /dev/null
@@ -1,67 +0,0 @@
-# Prompt 13: "Buy Skill" Button on Agent Detail Page
-
-## Objective
-Add a "Buy" or "Unlock" button next to paid skills on the agent detail page in the marketplace.
-
-## Explanation
-Following Prompt 01 where we displayed the price, we now need to add a call-to-action button. This button will be the entry point for the user to initiate the purchase flow. It should only appear for skills that have a price and that the current user has not yet purchased.
-
-## Instructions
-1. **Fetch User's Purchased Skills:**
- * The backend endpoint for the agent detail page (`/api/marketplace/agents/:id`) needs to know the current user to determine which skills they own.
- * If a user is logged in, fetch their purchase history for the current agent from `user_skill_purchases`.
- * Add a new field to the agent detail response, e.g., `owned_skills: ["skill_name1", "skill_name2"]`.
-
-2. **Update Frontend Skill Rendering:**
- * In `src/marketplace.js`, within the `renderDetail` function's skill-rendering loop:
- * Check if the current skill is in the `owned_skills` array.
- * Check if the skill has a price in the `skill_prices` object.
- * **Conditional Rendering Logic:**
- * If `price` exists AND the skill is NOT in `owned_skills`: Render a "Buy" button.
- * If `price` exists AND the skill IS in `owned_skills`: Render an "Owned" badge or checkmark.
- * If `price` does not exist: Render the "Free" badge.
-
-3. **Add Event Listener:**
- * Attach a click event listener to the "Buy" button.
- * The listener should call the `onBuySkill(agentId, skillId)` function created in Prompt 06, which kicks off the purchase modal and QR code generation.
-
-## Code Example (`src/marketplace.js`)
-
-```javascript
-// Inside renderDetail function
-
-const skillPrices = a.skill_prices || {};
-const ownedSkills = new Set(a.owned_skills || []);
-
-$('d-skills').innerHTML = skillsArr.map((s) => {
- const name = s.name || '';
- const price = skillPrices[name];
- let badge = '';
-
- if (price) {
- if (ownedSkills.has(name)) {
- badge = `<span class="badge owned">✓ Owned</span>`;
- } else {
- const priceStr = `${(price.amount / 1e6).toFixed(2)} USDC`;
- badge = `<button class="btn-buy" data-agent-id="${a.id}" data-skill-id="${name}">Buy for ${priceStr}</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-prompts/13-frontend-buy-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-prompts/13-platform-fee-logic.md b/prompts/monetization-prompts/13-platform-fee-logic.md
deleted file mode 100644
index 6b793faea..000000000
--- a/prompts/monetization-prompts/13-platform-fee-logic.md
+++ /dev/null
@@ -1,84 +0,0 @@
----
-status: not-started
----
-
-# Prompt 13: Platform Fee Logic
-
-## Objective
-Implement the logic to automatically take a platform fee from each skill purchase transaction.
-
-## Explanation
-A platform fee is a common monetization strategy. This involves splitting the payment from the buyer into two parts: one for the creator and one for the platform. This logic should be handled securely on the backend when the transaction is created.
-
-## Instructions
-- [ ] **Configure Platform Wallet:**
- - [ ] Store the platform's fee-collecting wallet address in a secure configuration file or environment variable on your backend. Do not hardcode it in the API logic.
-
-- [ ] **Define Platform Fee Rate:**
- - [ ] Define the platform's fee percentage (e.g., `5%` or `0.05`) in the same configuration.
-
-- [ ] **Update the "Create Transaction" Endpoint:**
- - [ ] In your `POST /api/transactions/create-skill-purchase` endpoint:
- - [ ] After fetching the skill price, calculate the fee amount (e.g., `feeAmount = price * platformFeeRate`).
- - [ ] Calculate the creator's proceeds (`creatorAmount = price - feeAmount`). Ensure you are working with integers to avoid floating-point issues.
- - [ ] Add a **second** SPL Token Transfer instruction to the Solana transaction.
- - [ ] The first instruction will transfer `creatorAmount` from the buyer to the creator.
- - [ ] The second instruction will transfer `feeAmount` from the buyer to the platform's wallet.
- - [ ] The transaction will now contain two separate transfer instructions. The Solana runtime will execute them atomically.
-
-- [ ] **Update the "Verify Transaction" Endpoint:**
- - [ ] Your verification logic at `POST /api/skills/purchase/verify` must also be updated.
- - [ ] It should now look for **two** transfer instructions in the fetched transaction.
- - [ ] It must verify that both transfers are correct: the right amount to the right creator, and the right fee amount to the right platform wallet. Verification fails if either is incorrect.
-
-## Code Example (Create Transaction Endpoint with Fee)
-
-```javascript
-// ... inside /api/transactions/create-skill-purchase
-
-const PLATFORM_FEE_RATE = 0.05; // 5%
-const PLATFORM_WALLET = new PublicKey(process.env.PLATFORM_WALLET_ADDRESS);
-
-const price = priceInfo.amount;
-const feeAmount = Math.round(price * PLATFORM_FEE_RATE);
-const creatorAmount = price - feeAmount;
-
-// ... get buyerUsdcAccount, creatorUsdcAccount, etc.
-const platformUsdcAccount = await getOrCreateAssociatedTokenAccount(connection, buyer, usdcMint, PLATFORM_WALLET);
-
-const transaction = new Transaction()
- .add(
- // Instruction 1: Payment to Creator
- createTransferInstruction(
- buyerUsdcAccount.address,
- creatorUsdcAccount.address,
- buyer,
- creatorAmount
- )
- )
- .add(
- // Instruction 2: Fee to Platform
- createTransferInstruction(
- buyerUsdcAccount.address,
- platformUsdcAccount.address,
- buyer,
- feeAmount
- )
- );
-
-// ... set feePayer, blockhash, and serialize
-```
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/monetization-prompts/13-platform-fee-logic.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/monetization-prompts/14-creator-dashboard-backend.md b/prompts/monetization-prompts/14-creator-dashboard-backend.md
deleted file mode 100644
index 29be72746..000000000
--- a/prompts/monetization-prompts/14-creator-dashboard-backend.md
+++ /dev/null
@@ -1,75 +0,0 @@
----
-status: not-started
----
-
-# Prompt 14: Creator Dashboard - Backend
-
-## Objective
-Create the backend API endpoints required to power a dashboard for creators to track their sales and earnings.
-
-## Explanation
-To empower creators, we need to give them visibility into their performance. This involves creating secure, read-only endpoints that aggregate sales data from the database.
-
-## Instructions
-- [ ] **Design API Endpoints:**
- - [ ] Plan a few key endpoints for the creator dashboard. For example:
- - [ ] `GET /api/creator/dashboard/stats`: Returns key stats like total revenue, total sales, and average sale price.
- - [ ] `GET /api/creator/dashboard/sales-history`: Returns a paginated list of individual sales, including skill name, date, and amount earned.
- - [ ] `GET /api/creator/dashboard/sales-by-skill`: Returns an aggregate of sales grouped by skill name.
-
-- [ ] **Implement `stats` Endpoint:**
- - [ ] This endpoint should be protected by authentication.
- - [ ] It needs to query your transaction or unlocked skills database.
- - [ ] To get total revenue, you'll need to join your `unlocked_skills` table with `agent_skill_prices` and filter by the agents owned by the current user (`req.user.id`).
- - [ ] Sum the prices of all skills sold. Remember to subtract the platform fee from the creator's view of revenue.
- - [ ] Return the aggregated data as a JSON object.
-
-- [ ] **Implement `sales-history` Endpoint:**
- - [ ] This endpoint will also perform a join similar to the stats endpoint.
- - [ ] Instead of aggregating, it will return a list of individual sales records.
- - [ ] Implement pagination using `LIMIT` and `OFFSET` in your SQL query (or the equivalent in your ORM) to handle potentially large numbers of sales.
- - [ ] Return the list and pagination metadata (e.g., `total_pages`, `current_page`).
-
-## Database Query Example (PostgreSQL for Stats)
-
-```sql
--- This query calculates total revenue and sales for a specific creator (user_id = $1)
-SELECT
- -- Sum of prices, adjusted for platform fee (e.g., 5%)
- SUM(prices.amount * (1 - 0.05)) AS total_revenue,
- COUNT(unlocked.id) AS total_sales
-FROM
- unlocked_skills AS unlocked
-JOIN
- agents ON unlocked.agent_id = agents.id
-JOIN
- agent_skill_prices AS prices ON unlocked.agent_id = prices.agent_id AND unlocked.skill_name = prices.skill_name
-WHERE
- -- Filter for sales of agents owned by the logged-in creator
- agents.creator_id = $1;
-```
-
-## API Response Example (`/stats`)
-
-```json
-{
- "totalRevenue": 85500000,
- "totalSales": 92,
- "topSellingSkill": "AdvancedDataAnalysis",
- "currency": "USDC"
-}
-```
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/monetization-prompts/14-creator-dashboard-backend.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/monetization-prompts/14-frontend-ui-update-post-purchase.md b/prompts/monetization-prompts/14-frontend-ui-update-post-purchase.md
deleted file mode 100644
index 471037aff..000000000
--- a/prompts/monetization-prompts/14-frontend-ui-update-post-purchase.md
+++ /dev/null
@@ -1,73 +0,0 @@
-# Prompt 14: UI Update After Successful Purchase
-
-## Objective
-After a skill purchase is successfully confirmed, dynamically update the agent detail UI to reflect the user's new ownership status without requiring a page reload.
-
-## Explanation
-A seamless user experience requires immediate feedback. Once the frontend polling (from Prompt 09) confirms a successful purchase, the UI should change instantly. The "Buy" button for the skill should be replaced with an "Owned" indicator, and any related UI elements should be updated.
-
-## Instructions
-1. **Identify the Skill Element:**
- * Ensure the HTML element for each skill in the list has a unique and predictable ID or class that includes the skill name, e.g., `<span class="skill-entry" id="skill-entry-weather-forecast">...</span>`.
-
-2. **Modify the Polling Success Callback:**
- * In `src/marketplace.js`, locate the success block within the purchase confirmation polling loop (`if (status === 'confirmed')`).
- * When a purchase is confirmed, you will have the `agentId` and `skillId`.
- * **Find the UI Element:** Use the `skillId` to select the specific skill's UI element in the DOM.
- * **Replace the Button:** Find the "Buy" button within that element and replace it with the "Owned" badge HTML.
- * For example: `<span class="badge owned">✓ Owned</span>`.
-
-3. **Show a Success Notification:**
- * Use a toast notification or a simple alert to explicitly tell the user their purchase was successful and they can now use the skill.
-
-## Code Example (`src/marketplace.js`)
-
-```javascript
-// In the polling success callback, you have access to the skillId.
-// Let's assume you stored it from when the "Buy" button was clicked.
-const currentSkillId = 'weather-forecast'; // The skill being purchased
-
-function onPurchaseSuccess(skillId) {
- // 1. Hide the modal and stop polling (already done).
-
- // 2. Find the skill entry in the DOM.
- const skillEntry = document.getElementById(`skill-entry-${skillId}`);
- if (!skillEntry) return;
-
- // 3. Find the buy button within it.
- const buyButton = skillEntry.querySelector('.btn-buy');
-
- // 4. Create and insert the "Owned" badge.
- const ownedBadge = document.createElement('span');
- ownedBadge.className = 'badge owned';
- ownedBadge.innerHTML = '✓ Owned';
-
- if (buyButton) {
- buyButton.replaceWith(ownedBadge);
- }
-
- // 5. Show a success notification.
- showToast('Purchase successful! You can now use the skill.');
-}
-
-// Inside the polling loop:
-if (status === 'confirmed') {
- clearInterval(pollingId);
- $('purchase-modal').hidden = true;
- onPurchaseSuccess(currentSkillId);
-}
-```
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/monetization-prompts/14-frontend-ui-update-post-purchase.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/monetization-prompts/14-skill-gating-logic.md b/prompts/monetization-prompts/14-skill-gating-logic.md
deleted file mode 100644
index aeb759ba2..000000000
--- a/prompts/monetization-prompts/14-skill-gating-logic.md
+++ /dev/null
@@ -1,91 +0,0 @@
-# Prompt 14: Implement Skill Gating Logic
-
-**Status:** - [ ] Not Started
-
-## Objective
-Enforce access control for skills, preventing users from using or executing a paid skill unless they have purchased it.
-
-## Explanation
-Skill gating is the core of the monetization feature. Once a skill is marked as paid, the system must check for ownership before allowing it to be executed. This check should happen both on the backend (for security) and frontend (for a better user experience).
-
-## Instructions
-1. **Backend Gating:**
- * Identify the API endpoint that executes or "performs" a skill (e.g., `/api/agent-actions.js` or a similar handler for `perform-skill`).
- * Before executing a skill, this endpoint must perform a check:
- * Is the skill a paid skill for this agent? (Query `agent_skill_prices`).
- * If it is paid, does the logged-in user own it? (Query `user_agent_skills`).
- * If the user does not own the paid skill, return a `403 Forbidden` error with a clear message like "You must purchase this skill to use it."
-
-2. **Frontend UI Gating:**
- * The UI should visually indicate that a skill is locked if it's paid and not owned.
- * For example, on the agent detail page or in a chat interface where skills can be triggered, the button or control for a locked skill should be disabled or styled differently.
- * When a user tries to interact with a locked skill, the UI should guide them to purchase it (e.g., by showing a tooltip or popping up the purchase modal).
-
-## Code Example (Backend - e.g., in `/api/agent-actions.js`)
-
-```javascript
-// Inside the handler for performing a skill
-export default async function handler(req, res) {
- // Assume user is authenticated
- const userId = req.user.id;
- const { agentId, skillName, args } = req.body;
-
- const db = getDB();
-
- // Check if the skill is priced
- const skillPrice = await db.getSkillPrice(agentId, skillName);
-
- if (skillPrice) {
- // It's a paid skill, so check for ownership
- const hasOwnership = await db.checkSkillOwnership(userId, agentId, skillName);
- if (!hasOwnership) {
- return res.status(403).json({
- error: 'Access Denied',
- message: 'You must purchase this skill to use it.'
- });
- }
- }
-
- // If we get here, the user has access. Proceed with skill execution.
- // ... (rest of the skill execution logic)
-}
-```
-
-## Code Example (Frontend UI - Conceptual)
-
-```javascript
-// When rendering a list of skill buttons for an agent to use
-function renderSkillButtons(agent, purchasedSkills) {
- const container = document.getElementById('agent-skill-buttons');
-
- container.innerHTML = agent.skills.map(skill => {
- const isPaid = !!agent.skill_prices[skill.name];
- const isOwned = purchasedSkills.includes(skill.name);
- const isLocked = isPaid && !isOwned;
-
- if (isLocked) {
- return `<button class="skill-btn locked" title="Purchase this skill to use it.">
- ${escapeHtml(skill.name)} (Locked)
- </button>`;
- } else {
- return `<button class="skill-btn" data-skill-name="${skill.name}">
- ${escapeHtml(skill.name)}
- </button>`;
- }
- }).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-prompts/14-skill-gating-logic.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/monetization-prompts/15-creator-earnings-dashboard.md b/prompts/monetization-prompts/15-creator-earnings-dashboard.md
deleted file mode 100644
index dbde29aa7..000000000
--- a/prompts/monetization-prompts/15-creator-earnings-dashboard.md
+++ /dev/null
@@ -1,98 +0,0 @@
-# Prompt 15: Create a Creator Dashboard for Earnings
-
-**Status:** - [ ] Not Started
-
-## Objective
-Develop a dashboard page for creators to track their sales and earnings from the skills they've monetized.
-
-## Explanation
-To create a healthy ecosystem, creators need visibility into how their paid skills are performing. A dedicated dashboard provides them with key metrics like total revenue, number of sales, and a breakdown of earnings per skill.
-
-## Instructions
-1. **Design the Dashboard UI:**
- * Create a new page, e.g., `creator-dashboard.html`.
- * This page should be accessible to logged-in users.
- * Design sections for:
- * **Key Metrics:** Total revenue, total sales, number of monetized skills.
- * **Earnings Breakdown:** A table or list showing each monetized skill, its price, number of sales, and total revenue generated.
- * **Transaction History:** A list of recent sales, including the skill, date, and amount.
-
-2. **Create Backend Endpoints for Dashboard Data:**
- * Create an endpoint `/api/creators/me/dashboard-stats`.
- * This authenticated endpoint will fetch and aggregate data for the logged-in user:
- * Query the `agent_skill_prices` table for all skills priced by the creator.
- * For each priced skill, query the `user_agent_skills` table to count the number of sales.
- * Calculate total revenue and other key metrics.
- * The endpoint should return a JSON object with all the data needed to populate the dashboard.
- * You might want a separate, paginated endpoint for the detailed transaction history.
-
-3. **Connect Frontend to Backend:**
- * In the JavaScript for `creator-dashboard.html`, make a request to the new dashboard endpoint when the page loads.
- * Use the returned data to populate the different sections of the dashboard.
- * Use a library for charts (e.g., Chart.js) to visualize earnings over time if desired.
-
-## Code Example (Backend - `/api/creators/me/dashboard-stats.js`)
-
-```javascript
-import { getDB } from './_lib/db';
-
-export default async function handler(req, res) {
- // Assume user is authenticated and we have their user_id and wallet address
- const creatorId = req.user.id;
-
- const db = getDB();
- try {
- // Get all agents owned by the creator
- const creatorAgents = await db.query('SELECT id FROM agents WHERE creator_id = $1', [creatorId]);
- const agentIds = creatorAgents.map(a => a.id);
-
- // Get all sales for those agents
- const sales = await db.query(
- `SELECT asp.skill_name, asp.amount, a.name as agent_name
- FROM user_agent_skills uas
- JOIN agent_skill_prices asp ON uas.agent_id = asp.agent_id AND uas.skill_name = asp.skill_name
- JOIN agents a ON uas.agent_id = a.id
- WHERE uas.agent_id = ANY($1::uuid[])`,
- [agentIds]
- );
-
- let totalRevenue = 0;
- let totalSales = sales.length;
- const skillBreakdown = {};
-
- for (const sale of sales) {
- totalRevenue += parseInt(sale.amount, 10);
- const key = `${sale.agent_name} - ${sale.skill_name}`;
- if (!skillBreakdown[key]) {
- skillBreakdown[key] = { sales: 0, revenue: 0 };
- }
- skillBreakdown[key].sales++;
- skillBreakdown[key].revenue += parseInt(sale.amount, 10);
- }
-
- res.status(200).json({
- totalRevenue,
- totalSales,
- skillBreakdown,
- });
-
- } catch (error) {
- console.error('Failed to fetch dashboard stats:', error);
- res.status(500).json({ error: 'Failed to fetch stats.' });
- }
-}
-```
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/monetization-prompts/15-creator-earnings-dashboard.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/monetization-prompts/15-skill-pricing-management-ui.md b/prompts/monetization-prompts/15-skill-pricing-management-ui.md
deleted file mode 100644
index f4e427e0f..000000000
--- a/prompts/monetization-prompts/15-skill-pricing-management-ui.md
+++ /dev/null
@@ -1,88 +0,0 @@
----
-status: not-started
----
-
-# Prompt 15: Skill Pricing Management - UI
-
-## Objective
-Create a user interface on the agent creation/editing page that allows creators to set and update prices for their skills.
-
-## Explanation
-Creators need a simple and intuitive way to manage the prices of their skills. This involves adding new form elements to the page where they configure their agents.
-
-## Instructions
-- [ ] **Design the UI:**
- - [ ] On the page where a creator edits their agent (e.g., `agent-edit.html`), locate the section where skills are listed or added.
- - [ ] For each skill listed, add a price input field and a currency selector (for now, this can be a disabled dropdown showing "USDC").
- - [ ] If a skill is meant to be free, the creator should be able to leave the price field blank or set it to 0.
- - [ ] Add a "Save Prices" or "Update Agent" button to submit the changes.
-
-- [ ] **Implement Frontend Logic:**
- - [ ] When the agent edit page loads, it should fetch the agent's details, including the existing `skill_prices` map.
- - [ ] Use this data to populate the price input fields for each skill.
- - [ ] When the "Save" button is clicked, gather all the skill names and their new prices from the input fields.
- - [ ] Structure this data into a map, e.g., `{ "skill_one": 10.50, "skill_two": 0 }`.
- - [ ] Make a `PUT` request to a new backend API endpoint to save these prices.
-
-## HTML Example (Inside an agent edit form)
-
-```html
-<div id="skill-pricing-section">
- <h3>Manage Skill Prices</h3>
-
- <!-- This would be dynamically generated -->
- <div class="skill-price-entry">
- <label for="price-skill_one">Skill One</label>
- <input type="number" id="price-skill_one" name="skill_prices[skill_one]" placeholder="e.g., 5.00">
- <span>USDC</span>
- </div>
-
- <div class="skill-price-entry">
- <label for="price-skill_two">Skill Two</label>
- <input type="number" id="price-skill_two" name="skill_prices[skill_two]" placeholder="Leave blank for Free">
- <span>USDC</span>
- </div>
-
- <button id="save-prices-btn">Save Prices</button>
-</div>
-```
-
-## JavaScript Example (on Save button click)
-
-```javascript
-document.getElementById('save-prices-btn').addEventListener('click', async () => {
- const prices = {};
- const agentId = /* get agent ID from page */;
-
- document.querySelectorAll('.skill-price-entry').forEach(entry => {
- const input = entry.querySelector('input[type="number"]');
- const skillName = input.name.match(/\[(.*?)\]/)[1]; // Extracts "skill_one"
- const price = parseFloat(input.value) || 0;
-
- // Convert to smallest unit (e.g., 1 USDC = 1,000,000)
- prices[skillName] = price * 1e6;
- });
-
- await fetch(`/api/agents/${agentId}/prices`, {
- method: 'PUT',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ prices })
- });
-
- // Show success 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-prompts/15-skill-pricing-management-ui.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/monetization-prompts/16-skill-pricing-management-api.md b/prompts/monetization-prompts/16-skill-pricing-management-api.md
deleted file mode 100644
index a27d26f95..000000000
--- a/prompts/monetization-prompts/16-skill-pricing-management-api.md
+++ /dev/null
@@ -1,99 +0,0 @@
----
-status: not-started
----
-
-# Prompt 16: Skill Pricing Management - API
-
-## Objective
-Create the backend API endpoint to allow creators to save the prices they set for their skills.
-
-## Explanation
-This endpoint will receive the pricing information from the UI and persist it in the `agent_skill_prices` database table. It needs to be secure and handle updates efficiently.
-
-## Instructions
-- [ ] **Create the Database Table (if not exists):**
- - [ ] You should have a table `agent_skill_prices`. If not, create it.
- - [ ] Columns: `id`, `agent_id`, `skill_name`, `amount` (use a numeric type that can handle large integers, like `BIGINT`), `currency_mint`.
- - [ ] Create a unique constraint on `(agent_id, skill_name)`.
-
-- [ ] **Create the API Endpoint:**
- - [ ] Create a new endpoint, e.g., `PUT /api/agents/:id/prices`.
- - [ ] The `:id` parameter will be the agent's ID.
- - [ ] Protect this endpoint with authentication middleware.
-
-- [ ] **Implement Authorization and Validation:**
- - [ ] Verify that the authenticated user (`req.user.id`) is the actual creator of the agent with the given `:id`. If not, return `403 Forbidden`.
- - [ ] The request body will contain a `prices` object (a map of skill names to amounts).
- - [ ] Validate this object: ensure it's a map, keys are strings, and values are non-negative integers.
-
-- [ ] **Implement Database Logic (Upsert):**
- - [ ] Iterate through the `prices` map from the request body.
- - [ ] For each skill, perform an "upsert" operation in the `agent_skill_prices` table:
- - [ ] If a row already exists for that `agent_id` and `skill_name`, `UPDATE` its `amount`.
- - [ ] If it doesn't exist, `INSERT` a new row.
- - [ ] If a skill's price is set to 0, you can either store it as 0 or `DELETE` the corresponding row, effectively making it a free skill. Deleting is often cleaner.
-
-## SQL Upsert Example (PostgreSQL)
-
-```sql
-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;
-```
-
-## API Logic Example (Node.js)
-
-```javascript
-// PUT /api/agents/:id/prices
-export default async function handler(req, res) {
- // Assume auth middleware has run
- const agentId = parseInt(req.query.id);
- const creatorId = req.user.id;
-
- // 1. Authorization
- const agent = await db.getAgent(agentId);
- if (agent.creator_id !== creatorId) {
- return res.status(403).json({ message: "You are not the creator of this agent." });
- }
-
- const { prices } = req.body; // e.g., { "skill_one": 5000000 }
-
- // 2. Database updates in a transaction
- const dbClient = await db.getClient();
- try {
- await dbClient.query('BEGIN');
- for (const skillName in prices) {
- const amount = prices[skillName];
- if (amount > 0) {
- // Perform UPSERT
- await dbClient.query(upsertSql, [agentId, skillName, amount, 'USDC_MINT_ADDRESS']);
- } else {
- // Perform DELETE for skills set to 0
- await dbClient.query(deleteSql, [agentId, skillName]);
- }
- }
- await dbClient.query('COMMIT');
- res.status(200).json({ message: "Prices updated successfully." });
- } catch (e) {
- await dbClient.query('ROLLBACK');
- res.status(500).json({ message: "Failed to update prices." });
- } finally {
- dbClient.release();
- }
-}
-```
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/monetization-prompts/16-skill-pricing-management-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-prompts/17-affiliate-program.md b/prompts/monetization-prompts/17-affiliate-program.md
deleted file mode 100644
index c3c26f752..000000000
--- a/prompts/monetization-prompts/17-affiliate-program.md
+++ /dev/null
@@ -1,91 +0,0 @@
-# Prompt 17: Affiliate and Referral Program
-
-**Status:** - [ ] Not Started
-
-## Objective
-Design and implement an affiliate program where users can earn a commission for referring new customers who purchase skills.
-
-## Explanation
-A referral program can be a powerful growth engine. By rewarding users for promoting agents and skills, you can incentivize word-of-mouth marketing and expand the platform's reach.
-
-## Instructions
-1. **Database Schema Changes:**
- * Create a `referrals` table to track referral relationships.
- * Columns: `id`, `referrer_user_id`, `referred_user_id`, `created_at`.
- * Add a `referrer_user_id` column to the `user_agent_skills` table to link a purchase to a specific referral. This can be nullable.
-
-2. **Generate Unique Referral Links:**
- * In the user's profile, provide a unique referral link (e.g., `three.ws/marketplace?ref=user_id`).
- * When a new user signs up after visiting a referral link, store the referrer's ID in a cookie.
- * When the new user signs up, read the cookie and create a record in the `referrals` table.
-
-3. **Attribute Purchases to Referrers:**
- * When a user makes a purchase, the backend should check if they were referred.
- * If so, populate the `referrer_user_id` in the `user_agent_skills` record.
-
-4. **Payout Logic for Referrers:**
- * Modify the creator payout cron job (`/api/cron/process-payouts.js`) or smart contract.
- * When processing a sale that has a referrer, the payment needs to be split three ways: creator, platform, and referrer.
- * Define the commission rates (e.g., 5% for the referrer).
-
-5. **Referral Dashboard for Users:**
- * Create a section in the user's dashboard to track their referrals.
- * Display stats like number of sign-ups from their link, number of purchases made by their referrals, and total commission earned.
-
-## Code Example (Conceptual - Purchase Endpoint Modification)
-
-```javascript
-// In /api/marketplace/purchase-skill.js
-export default async function handler(req, res) {
- const userId = req.user.id;
- // ...
-
- // Check for a referrer ID, which might be stored in the user's session
- // or looked up from the 'referrals' table.
- const referrerId = await db.findReferrerForUser(userId);
-
- // ... (Transaction verification logic)
-
- if (verificationSuccess) {
- // Pass referrerId when recording the purchase
- await db.recordSkillPurchase(userId, agentId, skillName, referrerId);
- // ...
- }
-}
-```
-
-## Code Example (Conceptual - Payout Logic Modification)
-
-```javascript
-// In the payout cron job
-for (const purchase of pendingPurchases) {
- const creatorBase = purchase.amount * (1 - PLATFORM_FEE_PERCENT / 100);
- let creatorShare = creatorBase;
-
- if (purchase.referrer_id) {
- const referrerCommission = purchase.amount * (REFERRAL_COMMISSION_PERCENT / 100);
- creatorShare -= referrerCommission;
-
- // Add to referrer's payout
- const referrer = await db.getUser(purchase.referrer_id);
- payouts[referrer.wallet_address] = (payouts[referrer.wallet_address] || 0) + referrerCommission;
- }
-
- // Add to creator's payout
- payouts[purchase.creator_address] = (payouts[purchase.creator_address] || 0) + creatorShare;
-}
-```
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/monetization-prompts/17-affiliate-program.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/monetization-prompts/17-creator-payout-settings-ui.md b/prompts/monetization-prompts/17-creator-payout-settings-ui.md
deleted file mode 100644
index 71d8d8ef3..000000000
--- a/prompts/monetization-prompts/17-creator-payout-settings-ui.md
+++ /dev/null
@@ -1,95 +0,0 @@
----
-status: not-started
----
-
-# Prompt 17: Creator Payout Settings - UI
-
-## Objective
-Create a user interface in the user's settings or profile page for them to manage their payout wallet address.
-
-## Explanation
-To receive payments, creators need a secure and simple way to input and update their Solana wallet address. This UI should provide clear instructions and validation.
-
-## Instructions
-- [ ] **Design the UI:**
- - [ ] Choose a suitable location for this setting, such as a "Payouts" or "Monetization" tab in the user's main profile/settings page.
- - [ ] Add a new section titled "Payout Wallet".
- - [ ] Include an input field for the Solana wallet address.
- - [ ] Add a "Save" button.
- - [ ] Display the currently saved address (if any) and provide clear helper text, e.g., "This is the Solana wallet where you will receive payments for skill purchases."
- - [ ] Add a warning about the importance of using the correct address.
-
-- [ ] **Implement Frontend Logic:**
- - [ ] When the page loads, fetch the user's current settings, including their `payout_wallet_address`, and populate the input field.
- - [ ] When the user clicks "Save":
- - [ ] Get the value from the input field.
- - [ ] Perform client-side validation to check if it looks like a valid Solana address (e.g., check length and characters). A full validation on the backend is still required.
- - [ ] Make a `PUT` request to the backend endpoint (`/api/users/payout-settings`) with the new address.
- - [ ] Display a success or error message to the user based on the API response.
-
-## HTML Example (in a user settings page)
-
-```html
-<div class="settings-section">
- <h3>Payout Wallet</h3>
- <p class="helper-text">Enter the Solana wallet address where you want to receive payments.</p>
-
- <div class="form-group">
- <label for="payout-wallet">Solana Wallet Address</label>
- <input type="text" id="payout-wallet" placeholder="Enter your Solana public key">
- <small>Warning: Ensure this address is correct. Payments sent to a wrong address cannot be recovered.</small>
- </div>
-
- <button id="save-payout-btn">Save Wallet Address</button>
- <div id="payout-status-message"></div>
-</div>
-```
-
-## JavaScript Example (on Save button click)
-
-```javascript
-document.getElementById('save-payout-btn').addEventListener('click', async () => {
- const walletAddress = document.getElementById('payout-wallet').value;
- const statusEl = document.getElementById('payout-status-message');
-
- // Basic client-side check
- if (walletAddress.length < 32 || walletAddress.length > 44) {
- statusEl.textContent = 'Please enter a valid Solana address.';
- statusEl.style.color = 'red';
- return;
- }
-
- try {
- const response = await fetch('/api/users/payout-settings', {
- method: 'PUT',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ payout_wallet_address: walletAddress }),
- });
-
- if (!response.ok) {
- const error = await response.json();
- throw new Error(error.message);
- }
-
- statusEl.textContent = 'Payout address updated successfully!';
- statusEl.style.color = 'green';
- } catch (error) {
- statusEl.textContent = `Error: ${error.message}`;
- statusEl.style.color = 'red';
- }
-});
-```
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/monetization-prompts/17-creator-payout-settings-ui.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/monetization-prompts/18-api-creator-withdrawal.md b/prompts/monetization-prompts/18-api-creator-withdrawal.md
deleted file mode 100644
index 4226687cf..000000000
--- a/prompts/monetization-prompts/18-api-creator-withdrawal.md
+++ /dev/null
@@ -1,83 +0,0 @@
-# Prompt 18: API Endpoint for Creator Withdrawal Request
-
-## Objective
-Create a secure API endpoint that allows a creator to request a withdrawal of their available earnings balance.
-
-## Explanation
-This endpoint is the first step in the payout process. It allows a creator to formally request a withdrawal. The system will validate the request, create a payout record with a 'requested' status, and deduct the amount from their withdrawable balance. A separate background process will handle the actual on-chain transaction.
-
-## Instructions
-1. **Create the API File:**
- * Create a new API endpoint, e.g., `api/dashboard/request-withdrawal.js`.
-
-2. **Implement the `POST` Handler:**
- * **Authentication:** Get the logged-in user.
- * **Input Validation:** Expect an `amount` in the request body.
- * **Fetch Balance:** Get the creator's current balance from the `creator_balances` table.
- * **Validate Request:**
- * Ensure the requested `amount` is greater than zero and not more than their available balance.
- * Ensure the user has a destination wallet address configured in their profile.
- * **Database Transaction:**
- * Start a database transaction to ensure atomicity.
- * **Decrement Balance:** Subtract the `amount` from the `creator_balances` table.
- * **Create Payout Record:** Insert a new row into the `creator_payouts` table with `status = 'requested'`.
- * Commit the transaction.
- * **Return Success:** Respond with a success message.
-
-## Code Example (`api/dashboard/request-withdrawal.js`)
-
-```javascript
-import { sql } from '../_lib/db.js';
-import { getSessionUser } from '../_lib/auth.js';
-import { error, json, wrap } from '../_lib/http.js';
-
-export default wrap(async (req, res) => {
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized');
-
- const { amount } = await req.json();
- // TODO: Fetch user's configured destination wallet
- const destinationAddress = '...';
-
- if (!amount || amount <= 0) return error(res, 400, 'invalid_amount');
-
- try {
- await sql.begin(async sql => {
- const [balance] = await sql`
- SELECT balance, currency_mint FROM creator_balances WHERE user_id = ${user.id} FOR UPDATE
- `;
-
- if (!balance || balance.balance < amount) {
- throw new Error('Insufficient funds');
- }
-
- await sql`
- UPDATE creator_balances SET balance = balance - ${amount} WHERE user_id = ${user.id}
- `;
-
- await sql`
- INSERT INTO creator_payouts (user_id, amount, currency_mint, destination_address, status)
- VALUES (${user.id}, ${amount}, ${balance.currency_mint}, ${destinationAddress}, 'requested')
- `;
- });
- } catch (e) {
- return error(res, 400, 'transaction_failed', e.message);
- }
-
- return json(res, { success: true, message: 'Withdrawal requested.' });
-});
-```
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/monetization-prompts/18-api-creator-withdrawal.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/monetization-prompts/18-creator-dashboard-ui.md b/prompts/monetization-prompts/18-creator-dashboard-ui.md
deleted file mode 100644
index 8f4a69ace..000000000
--- a/prompts/monetization-prompts/18-creator-dashboard-ui.md
+++ /dev/null
@@ -1,111 +0,0 @@
----
-status: not-started
----
-
-# Prompt 18: Creator Dashboard - UI
-
-## Objective
-Build the frontend for the creator dashboard, visualizing the sales and earnings data provided by the backend APIs.
-
-## Explanation
-A visual dashboard is essential for creators to understand their performance at a glance. We will create a new page that consumes the creator dashboard APIs and presents the data using charts and tables.
-
-## Instructions
-- [ ] **Create the Dashboard Page:**
- - [ ] Create a new HTML file, e.g., `creator-dashboard.html`.
- - [ ] Create a corresponding JavaScript file, e.g., `src/creator-dashboard.js`.
-
-- [ ] **Fetch and Display Key Stats:**
- - [ ] On page load, make a request to the `GET /api/creator/dashboard/stats` endpoint.
- - [ ] Display the returned stats (total revenue, total sales) in prominent "stat cards" at the top of the page.
- - [ ] Remember to format the revenue from the smallest unit to a human-readable number.
-
-- [ ] **Display Sales History:**
- - [ ] Make a request to the `GET /api/creator/dashboard/sales-history` endpoint.
- - [ ] Render the returned list of sales in a table. The table should include columns like "Date", "Skill Name", "Agent", "Price", and "Earnings".
-
-- [ ] **Add a Chart (Optional but recommended):**
- - [ ] Include a charting library like Chart.js or D3.
- - [ ] Make a request to an endpoint that provides time-series data (e.g., `GET /api/creator/dashboard/revenue-over-time`). You may need to create this endpoint.
- - [ ] Render a line or bar chart showing daily or weekly earnings.
-
-## HTML Structure Example (`creator-dashboard.html`)
-
-```html
-<body>
- <h1>Creator Dashboard</h1>
-
- <div id="stats-grid">
- <div class="stat-card">
- <h4>Total Revenue</h4>
- <p id="total-revenue-stat">$0.00</p>
- </div>
- <div class="stat-card">
- <h4>Total Sales</h4>
- <p id="total-sales-stat">0</p>
- </div>
- </div>
-
- <div id="sales-chart-container">
- <canvas id="sales-chart"></canvas>
- </div>
-
- <div id="sales-history-container">
- <h3>Recent Sales</h3>
- <table id="sales-history-table">
- <thead>
- <tr>
- <th>Date</th>
- <th>Skill</th>
- <th>Earnings</th>
- </tr>
- </thead>
- <tbody>
- <!-- Rows will be injected by JavaScript -->
- </tbody>
- </table>
- </div>
-</body>
-```
-
-## JavaScript Example (`src/creator-dashboard.js`)
-
-```javascript
-async function initDashboard() {
- // Fetch and display stats
- const statsRes = await fetch('/api/creator/dashboard/stats');
- const stats = await statsRes.json();
- document.getElementById('total-revenue-stat').textContent = `$${(stats.totalRevenue / 1e6).toFixed(2)}`;
- document.getElementById('total-sales-stat').textContent = stats.totalSales;
-
- // Fetch and render sales history table
- const historyRes = await fetch('/api/creator/dashboard/sales-history');
- const history = await historyRes.json();
- const tableBody = document.querySelector('#sales-history-table tbody');
- tableBody.innerHTML = history.sales.map(sale => `
- <tr>
- <td>${new Date(sale.date).toLocaleDateString()}</td>
- <td>${escapeHtml(sale.skillName)}</td>
- <td>$${(sale.earnings / 1e6).toFixed(2)}</td>
- </tr>
- `).join('');
-
- // Logic to initialize chart would go here
-}
-
-initDashboard();
-```
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/monetization-prompts/18-creator-dashboard-ui.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/monetization-prompts/18-subscription-model.md b/prompts/monetization-prompts/18-subscription-model.md
deleted file mode 100644
index 1f486f8e2..000000000
--- a/prompts/monetization-prompts/18-subscription-model.md
+++ /dev/null
@@ -1,70 +0,0 @@
-# Prompt 18: Skill Subscription Model
-
-**Status:** - [ ] Not Started
-
-## Objective
-Implement a subscription model where users can pay a recurring fee for access to a set of skills from a creator, or all skills on the platform.
-
-## Explanation
-Subscriptions provide a predictable revenue stream for creators and the platform. This model can be attractive to power users who want access to a wide range of premium skills without making individual purchases. This could be implemented using a system like Solana Pay or by integrating with a dedicated NFT subscription service.
-
-## Instructions
-1. **Database Schema for Subscriptions:**
- * Create a `subscriptions` table:
- * Columns: `id`, `user_id`, `subscription_tier_id`, `start_date`, `end_date`, `status` (e.g., 'active', 'cancelled').
- * Create a `subscription_tiers` table:
- * Columns: `id`, `creator_id` (nullable, for creator-specific tiers), `name`, `price`, `currency_mint`, `duration_days`.
-
-2. **UI for Subscribing:**
- * Create a new "Subscriptions" page.
- * Display available subscription tiers (e.g., "Pro Tier - All Skills", "Creator X's All-Access Pass").
- * Add a "Subscribe" button for each tier.
-
-3. **Handle Recurring Payments:**
- * This is the most complex part. On-chain recurring payments on Solana are not as straightforward as with traditional payment systems.
- * **Option 1: Solana Pay.** Integrate with Solana Pay to allow users to approve recurring transactions. This still requires user action for each payment period.
- * **Option 2: Subscription-as-an-NFT.** A user mints an NFT that represents their subscription. The NFT has an expiration date. The dApp checks for a valid (non-expired) subscription NFT in the user's wallet. The user has to manually "renew" by purchasing a new subscription NFT.
- * **Option 3: Off-chain with Credit Card.** For a hybrid model, use a service like Stripe for recurring billing and then have the backend airdrop a subscription NFT to the user.
-
-4. **Update Skill Gating Logic:**
- * Modify the skill gating logic from Prompt 14.
- * Before denying access to a paid skill, the system must also check if the user has an active subscription that grants access to that skill.
- * This check involves looking for a valid record in the `subscriptions` table or a valid subscription NFT in the user's wallet.
-
-## Code Example (Conceptual - Skill Gating Update)
-
-```javascript
-// In the backend skill execution endpoint
-// ... (after checking for a price)
-
-if (skillPrice) {
- // Check for direct ownership first
- const hasOwnership = await db.checkSkillOwnership(userId, agentId, skillName);
-
- if (!hasOwnership) {
- // If not owned directly, check for an active subscription
- const hasActiveSub = await db.checkActiveSubscription(userId, agentId, skillName);
-
- if (!hasActiveSub) {
- return res.status(403).json({ error: 'Subscription or purchase required.' });
- }
- }
-}
-
-// Proceed with execution
-// ...
-```
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/monetization-prompts/18-subscription-model.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/monetization-prompts/19-skill-gating-logic.md b/prompts/monetization-prompts/19-skill-gating-logic.md
deleted file mode 100644
index 85d078a53..000000000
--- a/prompts/monetization-prompts/19-skill-gating-logic.md
+++ /dev/null
@@ -1,76 +0,0 @@
----
-status: not-started
----
-
-# Prompt 19: Skill Usage Gating
-
-## Objective
-Implement the core logic that prevents users from using a paid skill unless they have successfully purchased it.
-
-## Explanation
-This is where monetization becomes functional. So far, we can sell skills, but there's nothing stopping a user from trying to use them anyway. This "gating" logic must be enforced on the backend to be secure.
-
-## Instructions
-- [ ] **Locate the Skill Execution Logic:**
- - [ ] Find the part of your backend code that is responsible for executing an agent's skill. This might be in a chat API, a general agent interaction endpoint, or a dedicated skill execution endpoint.
-
-- [ ] **Add a Pre-Execution Check:**
- - [ ] Before the skill's code is run, insert a new checking mechanism.
- - [ ] This check needs to know which user is making the request, which agent is being used, and which skill is being invoked.
-
-- [ ] **Perform Ownership Verification:**
- - [ ] Inside the check, first determine if the skill in question is a paid skill. Query the `agent_skill_prices` table for the agent and skill name.
- - [ ] If the skill is **not** in the prices table, it's free. Allow execution to proceed.
- - [ ] If the skill **is** in the prices table, it's a paid skill. You must now query the `unlocked_skills` table.
- - [ ] Check if a row exists in `unlocked_skills` for the current `user_id`, `agent_id`, and `skill_name`.
- - [ ] **If a row exists**, the user owns the skill. Allow execution to proceed.
- - [ ] **If no row exists**, the user does not own the skill. Block the execution and return an error message to the user, e.g., `402 Payment Required`, with a message like "You must purchase this skill to use it."
-
-## Code Example (Backend Skill Execution Endpoint)
-
-```javascript
-// Example of an endpoint that runs a skill
-export default async function handler(req, res) {
- // Assume auth middleware has run and req.user is available
- const { agentId, skillName, skillInputs } = req.body;
- const userId = req.user.id;
-
- // --- NEW GATING LOGIC ---
- // 1. Check if the skill is priced
- const price = await db.getSkillPrice(agentId, skillName);
-
- if (price) {
- // It's a paid skill, so check for ownership
- const isOwned = await db.checkSkillOwnership(userId, agentId, skillName);
- if (!isOwned) {
- return res.status(402).json({
- message: `This is a paid skill. Please purchase it from the marketplace to use it.`
- });
- }
- }
- // --- END OF GATING LOGIC ---
-
- // If the logic reaches here, the user is allowed to proceed.
- // Original skill execution logic follows:
- try {
- const result = await executeSkill(agentId, skillName, skillInputs);
- res.status(200).json({ result });
- } catch (error) {
- res.status(500).json({ message: "Skill execution failed." });
- }
-}
-```
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/monetization-prompts/19-skill-gating-logic.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/monetization-prompts/19-worker-payout-processing.md b/prompts/monetization-prompts/19-worker-payout-processing.md
deleted file mode 100644
index 468a1895d..000000000
--- a/prompts/monetization-prompts/19-worker-payout-processing.md
+++ /dev/null
@@ -1,54 +0,0 @@
-# Prompt 19: Background Worker for Payout Processing
-
-## Objective
-Create a background worker or cron job that processes pending withdrawal requests, executes the on-chain transaction, and updates the payout record.
-
-## Explanation
-Sending crypto assets requires a secure, asynchronous process. A withdrawal request should not be processed within a user-facing API call. A background worker will periodically scan for 'requested' payouts, use a secure hot wallet to send the funds, and update the database with the transaction signature and final status.
-
-## Instructions
-1. **Create a Worker File:**
- * In the `workers/` directory, create a new file, e.g., `payout-processor.js`.
-
-2. **Implement the Worker Logic:**
- * **Fetch Pending Payouts:** Write a query to select all records from `creator_payouts` where `status` is `'requested'`.
- * **Loop and Process:** Iterate through each requested payout.
- * **Securely Load Hot Wallet:** Load the private key for the platform's treasury/hot wallet from a secure secret manager (e.g., Vercel environment variables). **Never hardcode private keys.**
- * **Execute Transaction:**
- * Use the `@solana/web3.js` and `@solana/spl-token` libraries to build and send the SPL token transfer transaction from the hot wallet to the creator's `destination_address`.
- * Update the payout record's `status` to `'processing'`.
- * **Handle Confirmation:**
- * Await confirmation of the transaction.
- * On success, update the `creator_payouts` record with `status = 'completed'` and the `transaction_id`.
- * On failure, update the status to `'failed'` and *revert the balance deduction* in a compensating transaction or log for manual review.
-
-3. **Schedule the Worker:**
- * Configure this script to run on a schedule. If using Vercel, you can define it as a Cron Job in `vercel.json`.
-
-## Vercel Cron Job Example (`vercel.json`)
-
-```json
-{
- "crons": [
- {
- "path": "/api/cron/process-payouts",
- "schedule": "0 * * * *" // Run every hour
- }
- ]
-}
-```
-*(This requires creating an API endpoint that triggers the worker 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-prompts/19-worker-payout-processing.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/monetization-prompts/20-skill-reviews-and-ratings.md b/prompts/monetization-prompts/20-skill-reviews-and-ratings.md
deleted file mode 100644
index eaa8d3000..000000000
--- a/prompts/monetization-prompts/20-skill-reviews-and-ratings.md
+++ /dev/null
@@ -1,66 +0,0 @@
-# Prompt 20: User Reviews and Ratings for Skills
-
-**Status:** - [ ] Not Started
-
-## Objective
-Implement a system for users to leave reviews and ratings for purchased skills, and display these on the agent detail page.
-
-## Explanation
-Social proof is a powerful driver for purchasing decisions. Allowing users to rate and review skills helps other users make informed decisions and provides valuable feedback to creators.
-
-## Instructions
-1. **Database Schema for Reviews:**
- * Create a `skill_reviews` table:
- * Columns: `id`, `user_id`, `agent_id`, `skill_name`, `rating` (1-5), `review_text`, `created_at`.
-
-2. **UI for Submitting a Review:**
- * On the "My Purchased Skills" page (from Prompt 11), add a "Leave a Review" button next to each skill the user has not yet reviewed.
- * Clicking this button should open a modal or form with a star rating system (1-5) and a textarea for the review text.
-
-3. **Backend for Submitting Reviews:**
- * Create an endpoint `/api/skills/submit-review`.
- * This endpoint must verify that the user owns the skill they are reviewing before accepting the review.
- * It will insert the new review into the `skill_reviews` table.
-
-4. **Display Reviews and Average Rating:**
- * Modify the agent detail endpoint (`/api/marketplace/agents/:id`) to also fetch and aggregate review data for the agent's skills.
- * For each skill, calculate the average rating and the total number of reviews.
- * On the `marketplace.html` detail page, display the average star rating next to each skill.
- * Consider adding a new tab or section on the detail page to display all written reviews for the agent's skills.
-
-## Code Example (UI for displaying rating)
-
-```javascript
-// In the marketplace.js skill rendering loop
-const averageRating = skill.average_rating || 0;
-const reviewCount = skill.review_count || 0;
-
-let ratingDisplay = '';
-if (reviewCount > 0) {
- ratingDisplay = `<span class="skill-rating">
- ${'★'.repeat(Math.round(averageRating))}${'☆'.repeat(5 - Math.round(averageRating))}
- (${reviewCount})
- </span>`;
-}
-
-// Add ratingDisplay to the skill entry HTML
-return `<div class="skill-entry">
- <span class="skill-name">${escapeHtml(name)}</span>
- ${ratingDisplay}
- ${badgeOrButton}
- </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-prompts/20-skill-reviews-and-ratings.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-ownership-verification.md b/prompts/monetization/08-backend-ownership-verification.md
deleted file mode 100644
index 5f2fb4eb0..000000000
--- a/prompts/monetization/08-backend-ownership-verification.md
+++ /dev/null
@@ -1,67 +0,0 @@
-# Prompt 8: Backend Ownership Verification
-
-## Objective
-Create a secure backend endpoint that can verify whether a given user wallet holds the specific NFT required to access a paid skill.
-
-## Explanation
-Gating access to a feature requires a reliable way to check for ownership. This check must be done on the backend to prevent users from simply manipulating frontend code to bypass the restriction. The backend will query the Solana blockchain directly to verify NFT ownership.
-
-## Instructions
-1. **Create Verification Endpoint:**
- * Create a new API endpoint, e.g., `/api/skills/verify-ownership`.
- * It should accept `user_wallet`, `agent_id`, and `skill_name` as query parameters.
-
-2. **Find the Required NFT:**
- * This is the challenging part. A user could own many NFTs. You need to find the *correct* one.
- * The most robust method is to query all token accounts for the `user_wallet`.
- * Then, for each token they own (where `amount > 0`), fetch its metadata.
- * Check the metadata to see if the NFT is part of the agent's verified `collection` (the `collection_mint` address you stored earlier).
- * Also, check if the NFT's name or a trait in its metadata matches the `skill_name`.
-
-3. **Use a Solana RPC Provider or Indexer:**
- * Fetching all this data can be slow using a standard RPC. For performance, use a dedicated NFT indexing service like Helius, Shyft, or SimpleHash. These services provide APIs to quickly fetch all NFTs owned by a wallet and their metadata.
-
-4. **Return Verification Status:**
- * The endpoint should return a simple JSON response, like `{ "has_access": true }` or `{ "has_access": false }`.
-
-## Code Example (Backend using Helius API)
-```javascript
-// This is a conceptual example of using an indexer API
-
-async function verifyOwnership(req, res) {
- const { user_wallet, agent_id, skill_name } = req.query;
- const agent = await getAgentFromDB(agent_id);
- const agentCollectionMint = agent.collection_mint;
-
- // Use an indexer API to get all assets owned by the user
- const response = await fetch(`https://api.helius.xyz/v0/addresses/${user_wallet}/nfts?api-key=YOUR_API_KEY`);
- const data = await response.json();
-
- let has_access = false;
- for (const nft of data.items) {
- if (nft.grouping?.group_key === 'collection' && nft.grouping?.group_value === agentCollectionMint) {
- // This NFT is in the right collection. Now check if it's the right skill.
- if (nft.content?.metadata?.name.includes(skill_name)) {
- has_access = true;
- break;
- }
- }
- }
-
- res.status(200).json({ has_access });
-}
-```
-
-<!-- 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-ownership-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/08-record-skill-ownership.md b/prompts/monetization/08-record-skill-ownership.md
deleted file mode 100644
index db1e23019..000000000
--- a/prompts/monetization/08-record-skill-ownership.md
+++ /dev/null
@@ -1,117 +0,0 @@
-# Prompt 8: Record Skill Ownership in Database
-
-## Status
-- [ ] Not Started
-
-## Objective
-Create a database table to track which users have purchased which skills, and an API endpoint to record a successful purchase.
-
-## Explanation
-After a transaction is successfully confirmed on the blockchain, we need to record the user's ownership of the skill in our own database. This allows us to easily check if a user has access to a skill without needing to query the blockchain every time.
-
-## Instructions
-1. **Design `user_owned_skills` Table:**
- * Create a new table with columns like:
- * `id`: Primary key.
- * `user_id`: Foreign key to the `users` table.
- * `agent_id`: Foreign key to the `agents` table.
- * `skill_name`: The name of the purchased skill.
- * `purchase_transaction_signature`: The Solana transaction signature of the purchase.
- * `created_at`: Timestamp.
- * Add a unique constraint on `(user_id, agent_id, skill_name)`.
-
-2. **Create a "Finalize Purchase" API Endpoint:**
- * Create a new endpoint, e.g., `POST /api/payments/finalize-purchase`.
- * This endpoint will be called by the frontend *after* a transaction has been confirmed.
- * It should accept the `agent_id`, `skill_name`, and `transaction_signature`.
-
-3. **Implement Finalization Logic:**
- * The backend should first verify the transaction signature on the Solana network to ensure it's valid and recent.
- * It should decode the transaction to confirm that the correct amount was transferred to the correct seller.
- * If the transaction is valid, insert a new record into the `user_owned_skills` table.
-
-## SQL Example
-```sql
-CREATE TABLE user_owned_skills (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
- skill_name VARCHAR(255) NOT NULL,
- purchase_transaction_signature VARCHAR(255) NOT NULL,
- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
-);
-
-CREATE UNIQUE INDEX idx_user_owned_skills_on_user_agent_skill
-ON user_owned_skills (user_id, agent_id, skill_name);
-```
-
-## Code Example (Backend - `/api/payments/finalize-purchase.js`)
-```javascript
-import { Connection } from '@solana/web3.js';
-import { recordSkillOwnership } from './_db.js'; // DB function
-
-export default async function handler(req, res) {
- const { agentId, skillName, transactionSignature, userId } = req.body;
-
- // 1. Verify transaction on-chain
- const connection = new Connection(process.env.SOLANA_RPC_URL, 'confirmed');
- const tx = await connection.getTransaction(transactionSignature, { maxSupportedTransactionVersion: 0 });
-
- if (!tx) {
- return res.status(400).json({ error: 'Transaction not found or not confirmed.' });
- }
-
- // 2. (Recommended) Decode the transaction to verify its contents
- // This part can be complex, involving parsing instructions and account keys.
- // For simplicity here, we're trusting the client, but in production, you MUST verify:
- // - The source wallet matches the user.
- // - The destination wallet matches the agent creator.
- // - The transfer amount and mint are correct.
- const isTransactionValid = true; // Placeholder for real validation logic
-
- if (!isTransactionValid) {
- return res.status(400).json({ error: 'Transaction validation failed.' });
- }
-
- // 3. Record ownership in the database
- await recordSkillOwnership(userId, agentId, skillName, transactionSignature);
-
- res.status(200).json({ success: true });
-}
-```
-
-## Frontend Update
-After a successful purchase, the frontend should call this new endpoint.
-```javascript
-// Inside the purchase success block in the frontend
-const signature = await connection.sendRawTransaction(signedTransaction.serialize());
-await connection.confirmTransaction(signature, 'confirmed');
-
-// New part: Finalize with your backend
-await fetch('/api/payments/finalize-purchase', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- agentId: currentAgent.id,
- skillName: skillData.skillName,
- transactionSignature: signature,
- userId: currentUser.id // Assuming you have the user's ID
- }),
-});
-
-alert('Purchase successful 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/08-record-skill-ownership.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/11-backend-creator-wallet-table.md b/prompts/monetization/11-backend-creator-wallet-table.md
deleted file mode 100644
index c5ff1b6a2..000000000
--- a/prompts/monetization/11-backend-creator-wallet-table.md
+++ /dev/null
@@ -1,68 +0,0 @@
----
-status: not-started
----
-
-# Prompt 11: Backend - Creator Wallet Table
-
-## Objective
-Create a database table for agent creators to securely store their Solana payout wallet address.
-
-## Explanation
-To pay creators their share of skill sales, we need to know where to send the funds. A dedicated table, `creator_payout_wallets`, will store a mapping between a `user_id` and their chosen Solana wallet address. This separates the payout wallet from their login credentials or other profile information, providing flexibility and better security.
-
-## Instructions
-1. **Design the Table Schema:**
- * Name the table `creator_payout_wallets`.
- * It needs a column to link to the user (`user_id`), which should be unique. This enforces a one-to-one relationship: one user account has one payout wallet.
- * It needs a column to store the Solana wallet public key (`wallet_address` as `VARCHAR(44)`).
- * Add a primary key on `user_id` for efficient lookups and to enforce the unique constraint.
- * Add a foreign key constraint from `user_id` to the `users(id)` table.
- * Include `created_at` and `updated_at` timestamps.
-
-2. **Create a SQL Migration File:**
- * Create a new SQL migration file (e.g., `scripts/migrations/004_create_creator_payout_wallets.sql`).
- * Write the `CREATE TABLE` statement for `creator_payout_wallets`.
- * Set up the `updated_at` trigger for this new table as you've done for previous tables.
-
-## Code Example (SQL)
-
-```sql
--- scripts/migrations/004_create_creator_payout_wallets.sql
-
-CREATE TABLE IF NOT EXISTS creator_payout_wallets (
- user_id INTEGER PRIMARY KEY,
- -- Solana public key address
- wallet_address VARCHAR(44) NOT NULL,
- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
-
- CONSTRAINT fk_user
- FOREIGN KEY(user_id)
- REFERENCES users(id)
- ON DELETE CASCADE
-);
-
--- Use the existing trigger function for updated_at
-CREATE TRIGGER set_timestamp
-BEFORE UPDATE ON creator_payout_wallets
-FOR EACH ROW
-EXECUTE PROCEDURE set_updated_at_timestamp();
-
-```
-
-## Note on Data Integrity
-By setting `user_id` as the primary key, we ensure that each user can only have one payout wallet entry. When they want to change their wallet, we will perform an `UPDATE` operation on their existing row rather than inserting a new one.
-
-<!-- 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/11-backend-creator-wallet-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/12_creator_payouts_dashboard.md b/prompts/monetization/12_creator_payouts_dashboard.md
deleted file mode 100644
index 008df34af..000000000
--- a/prompts/monetization/12_creator_payouts_dashboard.md
+++ /dev/null
@@ -1,100 +0,0 @@
----
-status: not-started
-last_updated: 2026-05-04
----
-# Prompt 12: Creator Payouts Dashboard
-
-## Objective
-Create a dashboard for creators to view their sales history and total earnings.
-
-## Explanation
-To provide transparency and a good creator experience, we need a dashboard that shows them how much they've earned from their paid skills. This involves aggregating data from the `user_purchased_skills` table and presenting it in a clear, easy-to-understand format.
-
-## Instructions
-1. **Create a New Page:**
- * Create a new HTML file for the dashboard, e.g., `creator-dashboard.html`.
- * This page will be accessible to logged-in users from their profile or a main navigation link.
-
-2. **Backend API for Sales Data:**
- * Create a new endpoint, e.g., `GET /api/creators/sales-data`.
- * **Authentication:** Requires a logged-in user.
- * **Database Query:**
- * The endpoint should query the `user_purchased_skills` table.
- * It needs to find all purchases where the `agent_id` belongs to an agent owned by the current user.
- * It should aggregate the data to calculate:
- * Total revenue (sum of `price_amount`).
- * Number of sales.
- * A list of recent sales transactions with details (skill name, agent name, price, date).
- * The data should be grouped by currency if multiple currencies are supported in the future.
-
-3. **Frontend Implementation:**
- * The `creator-dashboard.html` page's JavaScript will call the new API endpoint.
- * **Display Key Metrics:** Show "Total Revenue" and "Total Sales" in prominent summary cards.
- * **Display Sales History:** Render the list of recent transactions in a table or a list format. Each entry should be clear and provide essential information.
- * **Add Charts (Optional but Recommended):** Use a charting library (like Chart.js) to visualize sales over time (e.g., daily or weekly revenue).
-
-## Code Example (Backend API - `GET /api/creators/sales-data`)
-
-```javascript
-import { sql } from '../../_lib/db.js';
-// ... other imports
-
-export default wrap(async (req, res) => {
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized');
-
- // 1. Get all agents owned by the user
- const userAgents = await sql`
- SELECT id FROM agent_identities WHERE user_id = ${user.id}
- `;
- const agentIds = userAgents.map(a => a.id);
-
- if (agentIds.length === 0) {
- return json(res, 200, { totalRevenue: 0, salesCount: 0, recentSales: [] });
- }
-
- // 2. Aggregate sales data for those agents
- const [salesData] = await sql`
- SELECT
- SUM(price_amount) AS total_revenue,
- COUNT(id) AS sales_count
- FROM user_purchased_skills
- WHERE agent_id = ANY(${agentIds})
- `;
-
- // 3. Get recent sales
- const recentSales = await sql`
- SELECT
- p.skill_name,
- a.name AS agent_name,
- p.price_amount,
- p.price_currency_mint,
- p.created_at
- FROM user_purchased_skills p
- JOIN agent_identities a ON p.agent_id = a.id
- WHERE p.agent_id = ANY(${agentIds})
- ORDER BY p.created_at DESC
- LIMIT 20
- `;
-
- return json(res, 200, {
- totalRevenue: parseInt(salesData.total_revenue) || 0,
- salesCount: parseInt(salesData.sales_count) || 0,
- recentSales: recentSales
- });
-});
-```
-
-<!-- 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/12_creator_payouts_dashboard.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/monetization/13-display-sales-analytics.md b/prompts/monetization/13-display-sales-analytics.md
deleted file mode 100644
index 868230184..000000000
--- a/prompts/monetization/13-display-sales-analytics.md
+++ /dev/null
@@ -1,72 +0,0 @@
-# Prompt 13: Display Sales Analytics in Dashboard
-
-## Objective
-Fetch data from the new `/api/dashboard/analytics` endpoint and use it to populate the creator dashboard UI with dynamic charts and statistics.
-
-## Explanation
-This prompt brings the creator dashboard to life by replacing the static placeholder elements with real, live data from the backend.
-
-## Instructions
-1. **Fetch Data on Page Load:**
- * In the JavaScript file for the dashboard (`dashboard.js`), add a function that runs when the page loads.
- * This function should make a `fetch` request to the `/api/dashboard/analytics` endpoint.
-
-2. **Populate Stat Cards:**
- * Once the data is received, update the content of the summary cards for "Total Revenue" and "Total Sales" with the values from the API response.
- * Format the revenue as a currency string (e.g., using `toLocaleString`).
-
-3. **Render the Chart:**
- * Use a charting library like Chart.js to render the `salesOverTime` data.
- * The X-axis should represent the date, and the Y-axis should represent the number of sales.
- * Configure the chart to be a line chart for a clear visual representation of trends.
-
-## Code Example (JavaScript - `dashboard.js`)
-```javascript
-import Chart from 'chart.js/auto';
-
-async function loadAnalytics() {
- try {
- const response = await fetch('/api/dashboard/analytics');
- if (!response.ok) throw new Error('Failed to fetch analytics');
- const data = await response.json();
-
- // Populate stat cards
- document.getElementById('total-revenue').textContent = (data.totalRevenue / 1e6).toLocaleString('en-US', { style: 'currency', currency: 'USD' });
- document.getElementById('total-sales').textContent = data.totalSales;
-
- // Render chart
- const ctx = document.getElementById('sales-chart').getContext('2d');
- new Chart(ctx, {
- type: 'line',
- data: {
- labels: data.salesOverTime.map(item => new Date(item.date).toLocaleDateString()),
- datasets: [{
- label: 'Sales per Day',
- data: data.salesOverTime.map(item => item.sales),
- borderColor: '#4f46e5',
- tension: 0.1
- }]
- }
- });
- } catch (error) {
- console.error('Error loading analytics:', error);
- // Display an error message in the UI
- }
-}
-
-document.addEventListener('DOMContentLoaded', loadAnalytics);
-```
-
-<!-- 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/13-display-sales-analytics.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/16-subscription-model-database.md b/prompts/monetization/16-subscription-model-database.md
deleted file mode 100644
index 4e65aca74..000000000
--- a/prompts/monetization/16-subscription-model-database.md
+++ /dev/null
@@ -1,73 +0,0 @@
-# Prompt 16: Subscription Model Database Schema
-
-## Objective
-Update the database schema to support recurring subscriptions for agent access, allowing creators to offer monthly or yearly tiers.
-
-## Explanation
-Moving beyond individual skill sales, subscriptions offer a predictable revenue stream for creators and a better value proposition for users who want full access. This foundational step involves designing the necessary database tables to track subscription plans and user statuses.
-
-## Instructions
-1. **Design `subscription_tiers` Table:**
- * Create a new table named `subscription_tiers`.
- * This table will define the plans a creator can offer for an agent.
- * Columns should include:
- * `id`: Primary key.
- * `agent_id`: Foreign key to the `agents` table.
- * `name`: The name of the tier (e.g., "Pro," "All-Access").
- * `price`: The cost of the subscription.
- * `currency_mint`: The currency of the price.
- * `interval`: The billing period (e.g., 'month', 'year').
- * `description`: A brief description of the tier.
-
-2. **Design `user_subscriptions` Table:**
- * Create a new table named `user_subscriptions` to track which users are subscribed to which tiers.
- * Columns should include:
- * `id`: Primary key.
- * `user_id`: Foreign key to the `users` table.
- * `tier_id`: Foreign key to the `subscription_tiers` table.
- * `start_date`: Timestamp when the subscription started.
- * `end_date`: Timestamp when the subscription is due to expire.
- * `status`: The current status (e.g., 'active', 'cancelled', 'past_due').
- * `last_payment_signature`: The transaction signature of the last successful payment.
-
-3. **Apply Migrations:**
- * Create and run a new database migration script to apply these schema changes.
-
-## SQL Schema Example
-```sql
-CREATE TABLE subscription_tiers (
- id SERIAL PRIMARY KEY,
- agent_id INTEGER REFERENCES agents(id) ON DELETE CASCADE,
- name VARCHAR(255) NOT NULL,
- price BIGINT NOT NULL, -- in smallest currency unit, e.g., lamports
- currency_mint VARCHAR(255) NOT NULL,
- interval VARCHAR(50) NOT NULL, -- 'month' or 'year'
- description TEXT,
- created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
-);
-
-CREATE TABLE user_subscriptions (
- id SERIAL PRIMARY KEY,
- user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
- tier_id INTEGER REFERENCES subscription_tiers(id) ON DELETE CASCADE,
- start_date TIMESTAMP WITH TIME ZONE NOT NULL,
- end_date TIMESTAMP WITH TIME ZONE NOT NULL,
- status VARCHAR(50) NOT NULL,
- last_payment_signature VARCHAR(255),
- created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
-);
-```
-
-<!-- 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/16-subscription-model-database.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/monetization/17-creator-dashboard-tab.md b/prompts/monetization/17-creator-dashboard-tab.md
deleted file mode 100644
index d89acad86..000000000
--- a/prompts/monetization/17-creator-dashboard-tab.md
+++ /dev/null
@@ -1,111 +0,0 @@
-# Prompt 17: Creator Dashboard Monetization Tab
-
-## Objective
-Create a new "Earnings" or "Monetization" tab in the agent creator's dashboard to serve as the central hub for managing paid skills and tracking revenue.
-
-## Explanation
-Creators need a dedicated space to view their sales performance, manage their payout settings, and see which of their skills are generating revenue. This prompt establishes the foundation for that space.
-
-## Instructions
-1. **Identify Dashboard File:**
- * Find the main file for the creator dashboard. This might be a file like `dashboard.html` or a route within a frontend framework. The file `agent-edit.html` has tabs, so it's a good candidate for adding a new one.
-
-2. **Add a New Tab:**
- * Add a new "Earnings" tab to the tab list in `agent-edit.html`.
- * Create the corresponding panel `div` that will be shown when the tab is active.
- ```html
- <!-- In the tab list -->
- <button class="edit-tab" data-tab="earnings" role="tab">Earnings</button>
-
- <!-- In the main content area -->
- <section class="edit-panel" id="panel-earnings" role="tabpanel" hidden>
- <!-- Content for the earnings panel will go here -->
- </section>
- ```
-
-3. **Basic Panel Structure:**
- * Inside the `#panel-earnings` div, create the initial layout. This should include:
- * A "Summary" section to display key metrics like "Total Revenue," "Platform Fees," and "Net Earnings."
- * A "Recent Sales" section that will eventually contain a table or list of the latest skill purchases.
- * A "Payouts" section for managing withdrawal settings and viewing payout history.
-
-4. **Backend Data Endpoint:**
- * Create a new backend endpoint, e.g., `GET /api/dashboard/earnings`, that is authenticated for the current user.
- * This endpoint should gather and return all the necessary data for this page:
- * Aggregated earnings stats (total revenue, etc.).
- * A list of the 10 most recent sales transactions.
- * The creator's current payout wallet settings.
-
-5. **Frontend JavaScript:**
- * In the JavaScript for `agent-edit.html`, add logic to handle the new "Earnings" tab.
- * When the tab is clicked for the first time, make a call to the new `/api/dashboard/earnings` endpoint.
- * Use the returned data to populate the sections you created in the HTML. For now, you can just display the raw data or simple placeholders.
-
-## Code Example (Frontend - `agent-edit.html`)
-
-```html
-<!-- Inside the #panel-earnings section -->
-<div class="earnings-summary">
- <div class="summary-card">
- <span class="label">Total Revenue</span>
- <span class="value" id="earnings-total-revenue">$0.00</span>
- </div>
- <div class="summary-card">
- <span class="label">Net Earnings</span>
- <span class="value" id="earnings-net">$0.00</span>
- </div>
- <div class="summary-card">
- <span class="label">Withdrawable</span>
- <span class="value" id="earnings-withdrawable">$0.00</span>
- </div>
-</div>
-
-<h3>Recent Sales</h3>
-<div id="earnings-recent-sales">
- <p>No sales yet.</p>
-</div>
-
-<h3>Payout Settings</h3>
-<div id="earnings-payouts">
- <!-- Payout UI will go here, from a later prompt -->
-</div>
-```
-
-```javascript
-// In the script for agent-edit.html
-
-let earningsDataLoaded = false;
-function initEarningsTab() {
- if (earningsDataLoaded) return;
-
- fetch('/api/dashboard/earnings')
- .then(res => res.json())
- .then(data => {
- document.getElementById('earnings-total-revenue').textContent = formatCurrency(data.summary.total_revenue);
- document.getElementById('earnings-net').textContent = formatCurrency(data.summary.net_earnings);
- document.getElementById('earnings-withdrawable').textContent = formatCurrency(data.summary.withdrawable);
-
- renderRecentSales(data.recent_sales);
- earningsDataLoaded = true;
- })
- .catch(err => {
- document.getElementById('panel-earnings').innerHTML = '<p class="error">Could not load earnings data.</p>';
- });
-}
-
-// In your tab switching logic, call initEarningsTab() when the 'earnings' tab is activated.
-```
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/monetization/17-creator-dashboard-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/17_caching_layer.md b/prompts/monetization/17_caching_layer.md
deleted file mode 100644
index 397899ef4..000000000
--- a/prompts/monetization/17_caching_layer.md
+++ /dev/null
@@ -1,88 +0,0 @@
----
-status: not-started
-last_updated: 2026-05-04
----
-# Prompt 17: Caching Layer for On-Chain Data
-
-## Objective
-Implement a caching layer (e.g., using Redis) to reduce redundant calls to the Solana RPC and other external APIs, improving performance and reliability.
-
-## Explanation
-Our application makes several calls to the Solana network (e.g., `getLatestBlockhash`, `getParsedTransaction`) and potentially other services like CoinGecko. These calls can be slow and are subject to rate limiting. Caching frequently accessed, non-time-sensitive data can significantly speed up our API responses.
-
-## Instructions
-1. **Set Up a Caching Client:**
- * Add a Redis client library (e.g., `ioredis`) to the project.
- * Create a Redis client instance that can be shared across the application, likely in `api/_lib/redis.js`.
-
-2. **Identify Caching Opportunities:**
- * **Skill Prices:** Prices set by creators don't change often. They can be cached for several minutes. The cache should be invalidated whenever a creator updates their prices.
- * **Agent Details:** Marketplace agent data is a prime candidate for caching.
- * **Transaction Details:** A confirmed transaction is immutable. Once we've verified a purchase signature with `getParsedTransaction`, we can cache the result indefinitely. If we check the same signature again, we can serve it from the cache.
- * **SOL/USD Price:** The CoinGecko API has rate limits. We should cache the SOL price for at least 60-120 seconds.
-
-3. **Implement Caching Logic:**
- * Wrap your data-fetching logic in a "cache-aside" pattern:
- * First, try to get the data from the Redis cache using a specific key (e.g., `skill-price:${agentId}:${skillName}`).
- * If the data exists in the cache (a "cache hit"), return it immediately.
- * If not (a "cache miss"), fetch the data from the primary source (database or external API).
- * After fetching, store the data in Redis with a Time-To-Live (TTL) before returning it.
-
-## Code Example (A generic caching function)
-
-```javascript
-// In api/_lib/cache.js
-import { redis } from './redis.js'; // Assume this exports a Redis client
-
-export async function cacheAside(key, ttlSeconds, fetchDataFn) {
- const cachedData = await redis.get(key);
- if (cachedData) {
- return JSON.parse(cachedData);
- }
-
- const liveData = await fetchDataFn();
-
- // Set with TTL and handle cases where liveData might be null
- if (liveData) {
- await redis.set(key, JSON.stringify(liveData), 'EX', ttlSeconds);
- }
-
- return liveData;
-}
-```
-
-## Code Example (Using the cache in a service)
-
-```javascript
-// Inside MonetizationService.js
-import { cacheAside } from '../../_lib/cache.js';
-
-class MonetizationService {
- async getSkillPrice(agentId, skillName) {
- const cacheKey = `skill-price:${agentId}:${skillName}`;
- const ttl = 300; // 5 minutes
-
- return cacheAside(cacheKey, ttl, async () => {
- const [price] = await sql`
- SELECT amount, currency_mint FROM agent_skill_prices
- WHERE agent_id = ${agentId} AND skill_name = ${skillName}
- `;
- return price;
- });
- }
-}
-```
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/monetization/17_caching_layer.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/20-analytics-for-creators.md b/prompts/monetization/20-analytics-for-creators.md
deleted file mode 100644
index c0b57d4c0..000000000
--- a/prompts/monetization/20-analytics-for-creators.md
+++ /dev/null
@@ -1,37 +0,0 @@
----
-status: not-started
----
-
-# Prompt 20: Analytics for Creators
-
-## Objective
-Provide creators with analytics about how their skills are performing in the marketplace.
-
-## Explanation
-Data-driven insights can help creators optimize their offerings and pricing.
-
-## Instructions
-1. **Track Metrics:**
- * Start tracking key metrics, such as skill page views, clicks on the "Purchase" button, and successful purchases.
-
-2. **Create an Analytics Dashboard:**
- * In the creator dashboard, add a new section for analytics.
- * Display charts and graphs for:
- * Sales over time.
- * Conversion rate (views to sales).
- * Top-performing skills.
- * Revenue by skill.
-
-<!-- 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/20-analytics-for-creators.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/20-creator-revenue-api.md b/prompts/monetization/20-creator-revenue-api.md
deleted file mode 100644
index 2de2a7aa6..000000000
--- a/prompts/monetization/20-creator-revenue-api.md
+++ /dev/null
@@ -1,90 +0,0 @@
----
-status: not-started
----
-
-# Prompt 20: Creator Revenue API
-
-## Objective
-Implement the backend API endpoints required to populate the Creator Dashboard with revenue and transaction data.
-
-## Explanation
-The Creator Dashboard UI needs data to be useful. This task involves creating authenticated endpoints that aggregate and return a creator's financial data from the database.
-
-## Instructions
-1. **Create a Summary Stats Endpoint:**
- * Create an endpoint like `GET /api/creators/me/stats`.
- * This endpoint should calculate several key metrics for the logged-in user (creator):
- * **Total Revenue:** Sum the `amount` from all successful purchases (`user_unlocked_skills` joined with prices) and subscription payments (`user_subscriptions` joined with tier prices). This is complex and may require querying transaction logs. A simpler start is to sum from your own records.
- * **30-Day Revenue:** The same calculation, but limited to the last 30 days.
- * **Total Subscribers:** Count the number of `active` subscriptions for all of the creator's agents.
- * **Total Sales:** Count the number of records in `user_unlocked_skills` for the creator's agents.
-
-2. **Create a Transactions Endpoint:**
- * Create an endpoint like `GET /api/creators/me/transactions`.
- * This should return a paginated list of all revenue-generating events for the creator.
- * You will need to `UNION` results from two sources:
- * Skill purchases from `user_unlocked_skills`.
- * Subscription payments (you may need a new `subscription_payments` table for this, or infer it from `user_subscriptions`).
- * Each item in the result should have a consistent shape, e.g., `{ date, type: 'sale' | 'subscription', description, amount, currency, status }`.
-
-3. **Create a Chart Data Endpoint:**
- * Create an endpoint like `GET /api/creators/me/revenue-chart`.
- * This endpoint should return data formatted for a charting library.
- * It should accept a time range parameter (e.g., `?range=30d` or `?range=12m`).
- * The backend should group revenue by day, week, or month and return an array of data points, e.g., `[{ date: 'YYYY-MM-DD', revenue: 15.50 }]`.
-
-4. **Security:**
- * Ensure all endpoints are authenticated and strictly scoped to the data owned by the logged-in user. A creator should never be able to see another creator's revenue.
-
-## Code Example (Backend - Summary Stats Logic)
-
-```javascript
-// GET /api/creators/me/stats
-app.get('/api/creators/me/stats', async (req, res) => {
- const userId = await getUserIdFromRequest(req);
-
- // Query for total sales revenue
- const salesResult = await db.query(`
- SELECT SUM(p.amount)
- FROM user_unlocked_skills u
- JOIN agents a ON u.agent_id = a.id
- JOIN agent_skill_prices p ON u.agent_id = p.agent_id AND u.skill_name = p.skill_name
- WHERE a.owner_id = $1
- `, [userId]);
-
- // Query for active subscribers
- const subsResult = await db.query(`
- SELECT COUNT(*)
- FROM user_subscriptions s
- JOIN agent_subscription_tiers t ON s.tier_id = t.id
- JOIN agents a ON t.agent_id = a.id
- WHERE a.owner_id = $1 AND s.status = 'active'
- `, [userId]);
-
- // ... and so on for other stats.
- // These queries can be complex and should be optimized.
-
- res.json({
- total_revenue: (salesResult.rows[0].sum || 0) / 1e6, // Example
- total_subscribers: parseInt(subsResult.rows[0].count, 10),
- // ... other stats
- });
-});
-```
-
-## Frontend Integration
-The frontend JavaScript for `creator-dashboard.html` will call these new endpoints upon loading and use the returned data to populate the elements created in the previous step.
-
-<!-- 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/20-creator-revenue-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/20-display-earnings-dashboard.md b/prompts/monetization/20-display-earnings-dashboard.md
deleted file mode 100644
index 74cc7135e..000000000
--- a/prompts/monetization/20-display-earnings-dashboard.md
+++ /dev/null
@@ -1,135 +0,0 @@
-# Prompt 20: Display Earnings in Creator Dashboard
-
-## Objective
-Fetch and display the creator's earnings summary and a list of their recent transactions in the "Earnings" tab of their dashboard.
-
-## Explanation
-This prompt brings the creator-facing part of the monetization feature to life. It involves building the backend endpoint to aggregate earnings data and then using that data to populate the UI components created in Prompt 17.
-
-## Instructions
-1. **File to Edit (Backend):**
- * Open the file for the `GET /api/dashboard/earnings` endpoint.
-
-2. **Implement Backend Logic:**
- * **Authentication:** Ensure the user is authenticated.
- * **Summary Metrics:**
- * Write a SQL query to get the `SUM` of `gross_amount`, `platform_fee_amount`, and `net_amount` from the `skill_payment_earnings` table, `WHERE creator_id` matches the current user.
- * Also, calculate the `withdrawable` amount by summing `net_amount` only for earnings where `payout_id` is `NULL`.
- * **Recent Sales:**
- * Write a query to get the 10 most recent records from `skill_payment_earnings` for the current creator, ordered by `created_at DESC`.
- * Join with the `skill_payments` table to get additional details like the `skill_name`.
- * **Response:** Return a JSON object containing `summary` and `recent_sales`.
-
-3. **File to Edit (Frontend):**
- * Open the JavaScript for `agent-edit.html`.
-
-4. **Implement Frontend Rendering:**
- * In the `initEarningsTab` function (from Prompt 17), use the data returned from the API to populate the UI.
- * **Summary:** Update the text content of the summary cards (`#earnings-total-revenue`, etc.) with the formatted currency values.
- * **Recent Sales:**
- * Create a function `renderRecentSales(sales)`.
- * If the `sales` array is empty, show a "No sales yet" message.
- * If it has data, dynamically create a table or a list of `div`s to display each sale.
- * Include columns for `Date`, `Skill Name`, `Gross Revenue`, and `Net Earnings`.
- * Format dates and currency values to be human-readable.
-
-## Code Example (Backend - `/api/dashboard/earnings.js`)
-
-```javascript
-// Inside the API handler
-
-const user = await getAuthenticatedUser(req);
-
-// Query for summary metrics
-const summaryResult = await db('skill_payment_earnings')
- .where({ creator_id: user.id })
- .sum({
- total_revenue: 'gross_amount',
- net_earnings: 'net_amount'
- })
- .first();
-
-const withdrawableResult = await db('skill_payment_earnings')
- .where({ creator_id: user.id, payout_id: null })
- .sum({ amount: 'net_amount' })
- .first();
-
-const summary = {
- total_revenue: summaryResult.total_revenue || 0,
- net_earnings: summaryResult.net_earnings || 0,
- withdrawable: withdrawableResult.amount || 0,
-};
-
-// Query for recent sales
-const recent_sales = await db('skill_payment_earnings as earn')
- .join('skill_payments as pay', 'earn.payment_id', 'pay.id')
- .where('earn.creator_id', user.id)
- .orderBy('earn.created_at', 'desc')
- .limit(10)
- .select(
- 'earn.created_at',
- 'pay.skill_name',
- 'earn.gross_amount',
- 'earn.net_amount',
- 'earn.currency_mint'
- );
-
-res.status(200).json({ summary, recent_sales });
-```
-
-## Code Example (Frontend - `agent-edit.html` script)
-
-```javascript
-function renderRecentSales(sales) {
- const container = document.getElementById('earnings-recent-sales');
- if (!sales || sales.length === 0) {
- container.innerHTML = '<p>No sales yet.</p>';
- return;
- }
-
- const table = document.createElement('table');
- table.className = 'earnings-table';
- table.innerHTML = `
- <thead>
- <tr>
- <th>Date</th>
- <th>Skill</th>
- <th>Gross</th>
- <th>Net</th>
- </tr>
- </thead>
- <tbody>
- ${sales.map(sale => `
- <tr>
- <td>${new Date(sale.created_at).toLocaleDateString()}</td>
- <td>${escapeHtml(sale.skill_name)}</td>
- <td>${formatCurrency(sale.gross_amount, sale.currency_mint)}</td>
- <td>${formatCurrency(sale.net_amount, sale.currency_mint)}</td>
- </tr>
- `).join('')}
- </tbody>
- `;
- container.innerHTML = '';
- container.appendChild(table);
-}
-
-function formatCurrency(amount, mint) {
- // Basic formatting, assuming 6 decimals for USDC
- const value = (amount / 1e6).toFixed(2);
- return `$${value} USDC`;
-}
-```
-
-<!-- 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/20-display-earnings-dashboard.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/monetization/22-backend-for-payouts.md b/prompts/monetization/22-backend-for-payouts.md
deleted file mode 100644
index 67d3ae67d..000000000
--- a/prompts/monetization/22-backend-for-payouts.md
+++ /dev/null
@@ -1,114 +0,0 @@
-# Prompt 22: Backend for Payouts
-
-## Objective
-Create the backend infrastructure to process creator payout requests, batch earnings, and prepare the on-chain transaction.
-
-## Explanation
-This is the core of the payout system. The backend will be responsible for securely gathering all of a creator's unpaid earnings, marking them as "in-progress," and constructing a single Solana transaction to transfer the total amount to the creator's designated wallet.
-
-## Instructions
-1. **Create API Route for Payout Request:**
- * Set up the endpoint `POST /api/dashboard/request-payout`.
- * This endpoint must be authenticated.
-
-2. **Implement Payout Logic:**
- * **a. Get User and Settings:** Get the authenticated `user` and fetch their saved `payout_address` from the database. If no address is set, return a `400 Bad Request` error.
- * **b. Lock Earnings and Calculate Total:**
- * Start a database transaction.
- * Find all records in `skill_payment_earnings` for this `creator_id` where `payout_id` is `NULL`.
- * If there are no such earnings, return an error.
- * Calculate the `total_net_amount` to be paid out. For simplicity, we'll assume a single currency (USDC) for now.
- * **c. Create Payout Record:**
- * Create a new record in the `payouts` table with a `pending` status, the `creator_id`, the `total_net_amount`, and the `destination_address`. Store the `payoutId`.
- * **d. Associate Earnings with Payout:**
- * Update all the earnings records you found in the previous step, setting their `payout_id` to the new `payoutId`. This "locks" them and prevents them from being included in future payouts.
- * **e. Commit Transaction:** Commit the database transaction.
- * **f. Process the Payout (Asynchronously):**
- * The actual on-chain transaction should be handled by a separate, asynchronous process or queue. For this prompt, we can simulate it in a `setTimeout`.
- * This background job will:
- 1. Construct the `spl-token` transfer transaction from a platform-owned treasury/hot wallet to the creator's `payout_address`.
- 2. Sign the transaction with the treasury wallet's key (this key must be securely stored on the server).
- 3. Send and confirm the transaction.
- 4. Update the `payouts` record with the `completed` status and the `tx_signature`.
- * **g. Respond to Client:** Immediately after committing the DB transaction (step e), respond to the client with a success message. Do *not* wait for the on-chain part to finish.
-
-## Code Example (Backend - `/api/dashboard/request-payout.js`)
-
-```javascript
-// --- Inside your API handler ---
-
-const user = await getAuthenticatedUser(req);
-
-// a. Get user and settings
-const payoutSettings = await db.getPayoutSettings(user.id);
-if (!payoutSettings?.payout_address) {
- return res.status(400).json({ error: 'Payout address not configured.' });
-}
-
-let payoutId;
-try {
- // b., c., d. Transactional logic
- await db.transaction(async (trx) => {
- const earningsToPay = await trx('skill_payment_earnings')
- .where({ creator_id: user.id, payout_id: null })
- .select('id', 'net_amount');
-
- if (earningsToPay.length === 0) {
- throw new Error('No withdrawable balance.');
- }
-
- const totalNetAmount = earningsToPay.reduce((sum, e) => sum + e.net_amount, 0);
- const currencyMint = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'; // Assume USDC
-
- // c. Create Payout Record
- const [newPayout] = await trx('payouts')
- .insert({
- creator_id: user.id,
- amount: totalNetAmount,
- currency_mint: currencyMint,
- destination_address: payoutSettings.payout_address,
- status: 'pending',
- })
- .returning('id');
- payoutId = newPayout.id;
-
- // d. Associate Earnings
- const earningIds = earningsToPay.map(e => e.id);
- await trx('skill_payment_earnings')
- .whereIn('id', earningIds)
- .update({ payout_id: payoutId });
- });
-
-} catch (error) {
- return res.status(400).json({ error: error.message });
-}
-
-// f. Trigger async payout processing
-// DO NOT await this. This should be handled by a background worker queue (e.g., BullMQ, Celery).
-// We simulate with a timeout for this example.
-processPayout(payoutId);
-
-// g. Respond to client immediately
-res.status(202).json({ message: 'Payout initiated.', payoutId });
-
-
-// --- In a separate background worker file ---
-async function processPayout(payoutId) {
- // Fetch payout details, create/sign/send transaction, update status to 'completed'.
- // This part is complex and involves secure key management for the treasury wallet.
-}
-```
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/monetization/22-backend-for-payouts.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/23-ui-payout-wallet-config.md b/prompts/monetization/23-ui-payout-wallet-config.md
deleted file mode 100644
index 859eddab2..000000000
--- a/prompts/monetization/23-ui-payout-wallet-config.md
+++ /dev/null
@@ -1,118 +0,0 @@
-# Prompt 23: UI for Payout Wallet Configuration
-
-## Objective
-Implement the UI and the corresponding backend endpoint for creators to securely save and update their Solana payout wallet address.
-
-## Explanation
-Before creators can receive payouts, they must specify where the funds should be sent. This prompt covers creating a simple form for this purpose and the API to persist this setting.
-
-## Instructions
-1. **Database Schema:**
- * Ensure your `users` table (or a related `user_settings` table) has a column to store the payout address, e.g., `payout_sol_address` (nullable `VARCHAR`).
-
-2. **File to Edit (Frontend):**
- * Open `agent-edit.html` and its associated JavaScript. Focus on the "Payout Settings" section of the "Earnings" tab.
-
-3. **Implement Frontend Logic:**
- * **Display Current Address:** When the earnings tab loads, the data from `/api/dashboard/earnings` should include the user's currently saved `payout_address`. Display this in or below the input field.
- * **Save Button Event Listener:**
- * Attach a `click` event listener to the "Save Address" button (`#save-wallet-btn`).
- * When clicked, get the value from the input field (`#payout-wallet-input`).
- * **Validation:** Perform basic client-side validation. A simple check is to ensure the address is between 32 and 44 characters and contains only Base58 characters. For a more robust check, you could use a library.
- * If valid, make a `POST` request to a new `/api/dashboard/payout-settings` endpoint.
- * Display status messages (e.g., "Saving...", "Saved!", "Invalid address.") in the status element (`#payout-wallet-status`).
-
-4. **Create Backend Endpoint (Backend):**
- * Create the new endpoint: `POST /api/dashboard/payout-settings`.
- * **Authentication:** Ensure the user is authenticated.
- * **Validation:**
- * The request body should contain the `address`.
- * Perform robust server-side validation to ensure it's a valid Solana public key. You can do this by trying to construct a `new PublicKey(address)` from `@solana/web3.js` inside a try-catch block.
- * **Database Update:** Update the `payout_sol_address` column for the authenticated user in your `users` (or `user_settings`) table.
- * Return a success message.
-
-## Code Example (Frontend - `agent-edit.html` script)
-
-```javascript
-// In the script for agent-edit.html
-
-const saveWalletBtn = document.getElementById('save-wallet-btn');
-const walletInput = document.getElementById('payout-wallet-input');
-const walletStatus = document.getElementById('payout-wallet-status');
-
-saveWalletBtn.addEventListener('click', async () => {
- const address = walletInput.value.trim();
-
- // Basic client-side validation
- if (address.length < 32 || address.length > 44) {
- walletStatus.textContent = 'Invalid address length.';
- return;
- }
-
- walletStatus.textContent = 'Saving...';
- saveWalletBtn.disabled = true;
-
- try {
- const res = await fetch('/api/dashboard/payout-settings', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ address: address })
- });
-
- if (!res.ok) {
- const { error } = await res.json();
- throw new Error(error || 'Failed to save.');
- }
-
- walletStatus.textContent = 'Saved!';
- } catch (err) {
- walletStatus.textContent = `Error: ${err.message}`;
- } finally {
- saveWalletBtn.disabled = false;
- }
-});
-```
-
-## Code Example (Backend - `/api/dashboard/payout-settings.js`)
-
-```javascript
-import { PublicKey } from '@solana/web3.js';
-
-// --- Inside your API handler ---
-
-const { address } = req.body;
-const user = await getAuthenticatedUser(req);
-
-// Server-side validation
-try {
- // This will throw an error if the address is not a valid base58 string
- new PublicKey(address);
-} catch (error) {
- return res.status(400).json({ error: 'Invalid Solana address format.' });
-}
-
-try {
- // Update the user's record in the database
- await db('users')
- .where({ id: user.id })
- .update({ payout_sol_address: address });
-
- res.status(200).json({ message: 'Payout address updated.' });
-} catch (dbError) {
- res.status(500).json({ error: 'Database 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/23-ui-payout-wallet-config.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/onchain-demo/02-register-genesis-rank1-pda.md b/prompts/onchain-demo/02-register-genesis-rank1-pda.md
deleted file mode 100644
index 949fd94da..000000000
--- a/prompts/onchain-demo/02-register-genesis-rank1-pda.md
+++ /dev/null
@@ -1,179 +0,0 @@
-# Task: Register missing Agent Identity PDA for Genesis Rank #1
-
-## What this does
-330 of 331 genesis agents have Metaplex Agent Identity PDAs registered on-chain. Genesis Rank #1 is the only one missing its PDA. This task registers it.
-
-## Context
-- **agentId:** `6652c67a-8fdf-4b5e-9d3a-51a0d2481bc5`
-- **Asset (Core NFT):** `8RjngnmKqm3n8TzAyzXDNEk6VSXVLS393RsmZtkvzo4`
-- **Collection:** `3HTu8NUoZRCgy38q9m499EjNpmJeVJpXwg9bZhYJ4Wbj`
-- **Missing field:** `identityPda` is absent from `scripts/genesis-results.json` for this agent
-- **Authority wallet:** `3WSwnvVMtBtEtLrUjdWQm3EcPygvUhNcv6sDou64Rgcz` (key at `.keys/authority-3WS.json`)
-- **Registry program:** `1DREGFgysWYxLnRnKQnwrxnJQeSMk2HmGaC6whw2B2p`
-- The registration URI should match all other genesis agents: a `data:application/json;base64,...` inline JSON with name/description/image/model
-
-## Prerequisites
-- Authority wallet must have SOL (registering a PDA costs ~0.002 SOL in rent)
-- Check balance first:
-```bash
-curl -s -X POST https://api.mainnet-beta.solana.com \
- -H "Content-Type: application/json" \
- -d '{"jsonrpc":"2.0","id":1,"method":"getBalance","params":["3WSwnvVMtBtEtLrUjdWQm3EcPygvUhNcv6sDou64Rgcz"]}' \
- | python3 -c "import sys,json; r=json.load(sys.stdin); print('SOL:', r['result']['value']/1e9)"
-```
-If 0, fund the wallet first (task 01 covers this).
-
-## Steps
-
-### 1. Check whether the PDA actually exists on-chain (might be a ledger gap)
-```bash
-node -e "
-const { createUmi } = require('@metaplex-foundation/umi-bundle-defaults');
-const { publicKey, keypairIdentity, createSignerFromKeypair } = require('@metaplex-foundation/umi');
-const { mplCore } = require('@metaplex-foundation/mpl-core');
-const { mplAgentIdentity, safeFetchAgentIdentityV1FromSeeds, findAgentIdentityV1Pda } = require('@metaplex-foundation/mpl-agent-registry');
-const { readFileSync } = require('fs');
-
-(async () => {
- const rpc = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
- const umi = createUmi(rpc).use(mplCore()).use(mplAgentIdentity());
- const ASSET = '8RjngnmKqm3n8TzAyzXDNEk6VSXVLS393RsmZtkvzo4';
- const pda = findAgentIdentityV1Pda(umi, { asset: publicKey(ASSET) })[0];
- console.log('Expected PDA:', pda.toString());
- const identity = await safeFetchAgentIdentityV1FromSeeds(umi, { asset: publicKey(ASSET) });
- console.log('Exists on-chain:', identity !== null);
- if (identity) console.log('agentRegistrationUri:', identity.agentRegistrationUri?.slice(0, 80));
-})();
-"
-```
-
-If it exists on-chain, skip to step 4 (just update the ledger). If not, proceed to step 2.
-
-### 2. Write a registration script for this one agent
-Create `scripts/register-genesis-rank1-pda.mjs`:
-
-```js
-#!/usr/bin/env node
-import { readFileSync, writeFileSync } from 'node:fs';
-import { Keypair } from '@solana/web3.js';
-import bs58 from 'bs58';
-import { createUmi } from '@metaplex-foundation/umi-bundle-defaults';
-import { publicKey as umiPk, keypairIdentity, createSignerFromKeypair } from '@metaplex-foundation/umi';
-import { mplCore } from '@metaplex-foundation/mpl-core';
-import {
- mplAgentIdentity,
- registerIdentityV1,
- findAgentIdentityV1Pda,
- safeFetchAgentIdentityV1FromSeeds,
-} from '@metaplex-foundation/mpl-agent-registry';
-
-const ASSET = '8RjngnmKqm3n8TzAyzXDNEk6VSXVLS393RsmZtkvzo4';
-const COLLECTION = '3HTu8NUoZRCgy38q9m499EjNpmJeVJpXwg9bZhYJ4Wbj';
-const AGENT_ID = '6652c67a-8fdf-4b5e-9d3a-51a0d2481bc5';
-const RANK = 1;
-
-// Build the same registration URI format as all other genesis agents
-const reg = {
- type: 'https://eips.ethereum.org/EIPS/eip-8004#registration-v1',
- name: `Genesis #${RANK}`,
- description: `three.ws Genesis #${RANK}`,
- active: true,
- x402Support: true,
- registrations: [{ agentId: AGENT_ID, agentRegistry: 'https://three.ws' }],
- supportedTrust: ['reputation'],
-};
-const registrationUri = 'data:application/json;base64,' + Buffer.from(JSON.stringify(reg)).toString('base64');
-
-const rpc = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
-const umi = createUmi(rpc).use(mplCore()).use(mplAgentIdentity());
-
-// Load authority key
-const rawKey = JSON.parse(readFileSync('.keys/authority-3WS.json', 'utf8'));
-const solKp = Keypair.fromSecretKey(Uint8Array.from(rawKey));
-const umiKp = umi.eddsa.createKeypairFromSecretKey(solKp.secretKey);
-const signer = createSignerFromKeypair(umi, umiKp);
-umi.use(keypairIdentity(signer));
-
-const assetPk = umiPk(ASSET);
-const collectionPk = umiPk(COLLECTION);
-
-// Idempotency check
-const existing = await safeFetchAgentIdentityV1FromSeeds(umi, { asset: assetPk });
-if (existing) {
- const pda = findAgentIdentityV1Pda(umi, { asset: assetPk })[0].toString();
- console.log('Already registered. PDA:', pda);
- updateLedger(pda);
- process.exit(0);
-}
-
-console.log('Registering Agent Identity PDA for genesis rank 1...');
-await registerIdentityV1(umi, {
- asset: assetPk,
- collection: collectionPk,
- payer: signer,
- authority: signer,
- agentRegistrationUri: registrationUri,
-}).sendAndConfirm(umi, { confirm: { commitment: 'confirmed' } });
-
-const pda = findAgentIdentityV1Pda(umi, { asset: assetPk })[0].toString();
-console.log('✓ Registered. PDA:', pda);
-updateLedger(pda);
-
-function updateLedger(pda) {
- const results = JSON.parse(readFileSync('scripts/genesis-results.json', 'utf8'));
- results[AGENT_ID].identityPda = pda;
- results[AGENT_ID].registered = true;
- writeFileSync('scripts/genesis-results.json', JSON.stringify(results, null, 2));
- console.log('✓ Updated scripts/genesis-results.json');
-}
-```
-
-### 3. Run it
-```bash
-SOLANA_RPC_URL="https://mainnet.helius-rpc.com/?api-key=$(grep HELIUS_API_KEY .env | cut -d= -f2)" \
- node scripts/register-genesis-rank1-pda.mjs
-```
-
-### 4. Verify
-```bash
-# Should print the PDA address
-node -e "
-const { createUmi } = require('@metaplex-foundation/umi-bundle-defaults');
-const { publicKey } = require('@metaplex-foundation/umi');
-const { mplCore } = require('@metaplex-foundation/mpl-core');
-const { mplAgentIdentity, safeFetchAgentIdentityV1FromSeeds } = require('@metaplex-foundation/mpl-agent-registry');
-(async () => {
- const umi = createUmi('https://api.mainnet-beta.solana.com').use(mplCore()).use(mplAgentIdentity());
- const id = await safeFetchAgentIdentityV1FromSeeds(umi, { asset: publicKey('8RjngnmKqm3n8TzAyzXDNEk6VSXVLS393RsmZtkvzo4') });
- console.log('registered:', id !== null);
-})();
-"
-```
-
-### 5. Commit
-```bash
-git add scripts/genesis-results.json scripts/register-genesis-rank1-pda.mjs
-git commit -m "Register missing Agent Identity PDA for genesis rank 1"
-git push threews main && git push threeD main
-```
-
-### 6. Clean up script (it's a one-off)
-```bash
-rm scripts/register-genesis-rank1-pda.mjs
-git add -A && git commit -m "Remove one-off PDA registration script"
-git push threews main && git push threeD main
-```
-
-<!-- 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/onchain-demo/02-register-genesis-rank1-pda.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/onchain-demo/03-verify-metaplex-agents-page.md b/prompts/onchain-demo/03-verify-metaplex-agents-page.md
deleted file mode 100644
index cee790cbc..000000000
--- a/prompts/onchain-demo/03-verify-metaplex-agents-page.md
+++ /dev/null
@@ -1,117 +0,0 @@
-# Task: Verify Metaplex agents page renders three.ws agents correctly
-
-## What this does
-Checks whether `metaplex.com/agents/<asset>` renders our genesis agents and the three.ws platform agent. If the `data:` URI registration format used by genesis agents doesn't render on Metaplex's page, this task creates an HTTPS card endpoint alias that Metaplex can fetch instead, and documents the gap.
-
-## Context
-- Genesis agents (331 total) used `data:application/json;base64,...` inline URIs for `agentRegistrationUri` — chosen because the Solana 1232-byte tx limit required compactness. These URIs cannot be updated on-chain (mpl-agent-registry has no `updateIdentityV1` instruction).
-- The three.ws platform's own agent (registered in task 01) uses `https://three.ws/.well-known/agent-registration.json` — this WILL render on Metaplex.
-- `/api/agents/solana-card?asset=<pubkey>` already serves rich HTTPS card JSON for any registered agent.
-- The Metaplex agents page URL structure: `https://www.metaplex.com/agents/<asset_pubkey>`
-
-## Sample asset addresses to test
-```
-# three.ws platform agent (registered in task 01 — get address from data/three-ws-agent-onchain.json)
-# Genesis rank 1: 8RjngnmKqm3n8TzAyzXDNEk6VSXVLS393RsmZtkvzo4
-# Genesis rank 2: HHmAfvW6KycvYDW4KfjRtDtk1carPjHWTpcTHrLuSS4X
-# Genesis rank 5: 9pG27qeHvCftjHPJLTeKvb9h8ifpnyFGPM6DGCgb6mUc
-```
-
-## Steps
-
-### 1. Check what the on-chain identity PDA stores
-```bash
-node -e "
-const { createUmi } = require('@metaplex-foundation/umi-bundle-defaults');
-const { publicKey } = require('@metaplex-foundation/umi');
-const { mplCore } = require('@metaplex-foundation/mpl-core');
-const { mplAgentIdentity, safeFetchAgentIdentityV1FromSeeds } = require('@metaplex-foundation/mpl-agent-registry');
-(async () => {
- const umi = createUmi('https://api.mainnet-beta.solana.com').use(mplCore()).use(mplAgentIdentity());
- const assets = [
- '8RjngnmKqm3n8TzAyzXDNEk6VSXVLS393RsmZtkvzo4',
- 'HHmAfvW6KycvYDW4KfjRtDtk1carPjHWTpcTHrLuSS4X',
- ];
- for (const a of assets) {
- const id = await safeFetchAgentIdentityV1FromSeeds(umi, { asset: publicKey(a) });
- if (!id) { console.log(a, '→ NO PDA'); continue; }
- const uri = id.agentRegistrationUri || '';
- const isData = uri.startsWith('data:');
- console.log(a.slice(0,8) + '... → uri type:', isData ? 'data: (inline)' : 'https:', uri.slice(0, 60));
- }
-})();
-"
-```
-
-### 2. Open Metaplex agents page in browser
-Open these URLs and note what renders:
-- `https://www.metaplex.com/agents/HHmAfvW6KycvYDW4KfjRtDtk1carPjHWTpcTHrLuSS4X` (genesis rank 2, has PDA)
-- `https://www.metaplex.com/agents/<THREE_WS_ASSET>` (from data/three-ws-agent-onchain.json, uses HTTPS URI)
-
-Record what you see:
-- [ ] Asset name visible
-- [ ] Description visible
-- [ ] Registration card data visible (from agentRegistrationUri)
-- [ ] Blank / "not found" / other
-
-### 3. Check our own agent passport for the same assets
-Open `https://three.ws/agent-passport.html?asset=8RjngnmKqm3n8TzAyzXDNEk6VSXVLS393RsmZtkvzo4&network=mainnet` and confirm the passport renders with on-chain data.
-
-Also test the CAIP endpoint:
-```bash
-curl -s "https://three.ws/api/v1/agents/solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp/$(node -e "console.log(require('./scripts/genesis-results.json')['e02c765c-7e33-401c-8117-1fa81f9443d4'].asset)")" | python3 -m json.tool | head -30
-```
-
-### 4. If Metaplex page is blank for genesis agents (data: URI not parsed)
-
-**Option A — Document the limitation (no code change needed)**
-
-The `data:` URI is readable directly from the on-chain account by any client that reads the PDA; Metaplex's page may not decode it server-side. Our agent passport at `three.ws/agent-passport.html` reads the PDA correctly and is the canonical display surface for genesis agents. Use this URL for demo instead of metaplex.com.
-
-**Option B — Add a Metaplex redirect surface (if time allows)**
-
-If Metaplex supports a `?uri=` or redirected resolution: create a public endpoint that serves the decoded card as HTTPS JSON:
-
-`GET /api/agents/solana-registration-card?asset=<pubkey>`
-
-This endpoint:
-1. Reads the identity PDA from on-chain via `safeFetchAgentIdentityV1FromSeeds`
-2. If `agentRegistrationUri` starts with `data:`, decodes the base64 payload and returns it as `application/json`
-3. If it's already HTTPS, 302-redirects to it
-
-Add a vercel.json route:
-```json
-{ "src": "/api/agents/solana-registration-card", "dest": "/api/agents/solana/[action]?action=registration-card" }
-```
-
-This makes `https://three.ws/api/agents/solana-registration-card?asset=<pubkey>` resolvable by any HTTP client, even if metaplex.com can't decode data: URIs.
-
-### 5. What to show in the demo
-
-**Best demo path:**
-1. `https://three.ws/agent-passport.html?asset=<ASSET>&network=mainnet` — our canonical surface, fully wired, shows on-chain identity + attestations + reputation
-2. `https://www.metaplex.com/agents/<THREE_WS_ASSET>` — three.ws platform agent, uses HTTPS URI, should render on Metaplex
-3. Solana Explorer: `https://explorer.solana.com/address/<ASSET>` — raw on-chain proof the asset exists
-
-**Do NOT try to demo genesis agents on metaplex.com unless you confirm in step 2 that it renders.**
-
-### 6. Commit any new endpoint created
-```bash
-git add api/agents/solana/_handlers.js vercel.json
-git commit -m "Add solana-registration-card endpoint to decode on-chain data: URIs over HTTPS"
-git push threews main && git push threeD main
-```
-
-<!-- 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/onchain-demo/03-verify-metaplex-agents-page.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/prompt-2-lobby-performance.md b/prompts/prompt-2-lobby-performance.md
deleted file mode 100644
index 2be0056b9..000000000
--- a/prompts/prompt-2-lobby-performance.md
+++ /dev/null
@@ -1,193 +0,0 @@
-# Task: Marketplace Lobby 3D Performance
-
-## Project overview
-
-This is a Three.js / Vite app at `/workspaces/3D-Agent`. It renders an AI agent marketplace with a 3D lobby scene showing 3–5 featured avatars on circular podiums with mouse-parallax and click-to-select. The frontend is vanilla JS modules + Vite (`npm run dev` on port 3000).
-
-## File to modify
-
-**`src/marketplace-lobby.js`** — the entire lobby is self-contained in this one file (275 lines). Read it fully before making changes.
-
-## Current problems
-
-1. **No decoder support**: The lobby uses a bare `new GLTFLoader()` with no Draco, KTX2, or meshopt decoders. After asset compression (a separate task), the avatar GLBs will use EXT_meshopt_compression. Without the decoder wired in, compressed GLBs will fail to load silently.
-
-2. **Naive raycasting**: The `onClick` handler calls `raycaster.intersectObjects(slotsRoot.children, true)` which walks every triangle of every avatar mesh on every click. On complex skinned meshes (2–5 avatars, each 5k–20k triangles), this is expensive.
-
-3. **No `powerPreference`**: The WebGLRenderer is constructed without `powerPreference: 'high-performance'` — on laptops with discrete GPUs this defaults to the integrated GPU.
-
-4. **PMREMGenerator not disposed after setup**: `pmrem.fromScene(...)` is called once for the environment, but `pmrem` is only disposed inside `dispose()`. This is correct but `pmremGenerator.dispose()` should also be called right after the environment texture is generated (the PMREMGenerator is not needed after that point — keeping it alive wastes GPU memory).
-
-5. **No animation loop visibility guard**: The RAF loop runs even when the canvas is off-screen (e.g. user scrolls down on the marketplace page). This wastes CPU/GPU on invisible frames.
-
-## Existing decoder infrastructure to reuse
-
-The project has a shared `getDecoders()` function in `src/viewer/internal.js` that lazily initialises DRACOLoader + KTX2Loader + MeshoptDecoder (all memoised — calling it multiple times returns the same Promise). Import and use this instead of setting up decoders from scratch.
-
-```js
-// src/viewer/internal.js exports:
-export function getDecoders() {
- // Returns Promise<{ dracoLoader, ktx2Loader, meshoptDecoder }>
-}
-```
-
-## What to implement
-
-### 1. Install three-mesh-bvh
-
-```bash
-npm install three-mesh-bvh
-```
-
-### 2. Wire decoders into the lobby's GLTFLoader
-
-Replace the current loader setup in `mountLobby`:
-
-**Before** (line 106–107):
-```js
-const loader = new GLTFLoader();
-slots.forEach((avatar, i) => {
-```
-
-**After**: call `getDecoders()` before starting the avatar load loop, then create the loader with all three decoders. The load loop must not start until the decoders are ready:
-
-```js
-import { getDecoders } from './viewer/internal.js';
-
-// Inside mountLobby, after the podium/slot setup:
-const { dracoLoader, ktx2Loader, meshoptDecoder } = await getDecoders();
-const loader = new GLTFLoader()
- .setDRACOLoader(dracoLoader)
- .setKTX2Loader(ktx2Loader.detectSupport(renderer))
- .setMeshoptDecoder(meshoptDecoder);
-
-slots.forEach((avatar, i) => {
- // ... load loop unchanged ...
-});
-```
-
-`mountLobby` is already `async` so the `await` is fine.
-
-### 3. Add BVH-accelerated raycasting
-
-Install and use `three-mesh-bvh` to accelerate the click raycaster.
-
-When each avatar GLB finishes loading, compute a BVH for every mesh geometry in it:
-
-```js
-import { computeBoundsTree, disposeBoundsTree, acceleratedRaycast } from 'three-mesh-bvh';
-import { Mesh } from 'three';
-
-// Patch Three.js Mesh prototype once (at module top level, outside mountLobby):
-Mesh.prototype.raycast = acceleratedRaycast;
-
-// Inside the GLTFLoader onLoad callback, after fitToHeight():
-root.traverse((node) => {
- if (node.isMesh && node.geometry) {
- node.geometry.computeBoundsTree();
- }
-});
-```
-
-Update the `dispose()` function to also clean up BVH data:
-
-```js
-scene.traverse((obj) => {
- if (obj.geometry) {
- obj.geometry.disposeBoundsTree?.();
- obj.geometry.dispose?.();
- }
- // ... existing material dispose ...
-});
-```
-
-### 4. Fix PMREMGenerator disposal
-
-Right after generating the environment texture, dispose the PMREMGenerator immediately:
-
-```js
-scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
-pmrem.dispose(); // done — GPU memory freed
-```
-
-Remove `pmrem.dispose()` from the `dispose()` function at the bottom (it will already be disposed).
-
-### 5. Add `powerPreference` to the renderer
-
-```js
-const renderer = new WebGLRenderer({
- canvas,
- antialias: true,
- alpha: true,
- powerPreference: 'high-performance',
-});
-```
-
-### 6. Add IntersectionObserver visibility guard
-
-Pause the render loop when the canvas is not visible in the viewport (saves GPU on scroll):
-
-```js
-let visible = true;
-const io = new IntersectionObserver(
- ([entry]) => { visible = entry.isIntersecting; },
- { threshold: 0.01 }
-);
-io.observe(canvas);
-
-function tick() {
- if (!alive) return;
- rafId = requestAnimationFrame(tick);
- if (!visible) return; // skip render, keep RAF alive for when it returns
- // ... rest of tick ...
-}
-```
-
-In `dispose()`, add `io.disconnect()`.
-
-### 7. Antialias decision based on DPR
-
-On high-DPR displays (≥ 2×), MSAA antialias is nearly free because the display already downsamples. On low-DPR displays it's expensive. The lobby already caps DPR at 2, which is correct. No change needed — just verify the existing cap is kept.
-
-## Import additions required at top of file
-
-```js
-import { getDecoders } from './viewer/internal.js';
-import { computeBoundsTree, disposeBoundsTree, acceleratedRaycast } from 'three-mesh-bvh';
-import { Mesh } from 'three'; // Mesh is already imported — just add to existing import
-```
-
-`Mesh` is already in the import block — add `acceleratedRaycast` patch at module top level.
-
-## Constraints
-
-- Do not break the existing `onSelect` callback contract — click-to-select must still fire `onSelect(avatar, index)`.
-- Do not change the visual appearance of the scene (lighting, fog, podium geometry, camera angles).
-- The `dispose()` function must remain complete — no GPU resource leaks. All new resources (BVH data, IntersectionObserver) must be cleaned up there.
-- `mountLobby` signature stays identical: `async function mountLobby(canvas, avatars, options = {})`.
-- Do not add any loading spinner or placeholder UI — the podiums already render before GLBs resolve.
-- All imports must resolve correctly with the Vite bundler (no CommonJS `require`).
-
-## Definition of done
-
-- `npm install` runs without errors (three-mesh-bvh added to package.json).
-- `npm run dev` starts on port 3000 with no console errors.
-- Navigate to the marketplace page — the 3D lobby loads, avatars appear on podiums.
-- Clicking an avatar still fires `onSelect`.
-- Network tab shows: if compressed GLBs are present, they load successfully (meshopt decoder wired). If uncompressed, they load as before.
-- `git diff src/marketplace-lobby.js` shows only the changes described above — no unrelated modifications.
-- No TypeErrors or import errors in the browser console.
-
-<!-- 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/prompt-2-lobby-performance.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/prompt-3-bvh-main-viewer.md b/prompts/prompt-3-bvh-main-viewer.md
deleted file mode 100644
index 6c99dee9c..000000000
--- a/prompts/prompt-3-bvh-main-viewer.md
+++ /dev/null
@@ -1,130 +0,0 @@
-# Task: BVH-Accelerated Raycasting in Main Viewer
-
-## Project overview
-
-This is a Three.js / Vite app at `/workspaces/3D-Agent`. The frontend is vanilla JS modules + Vite (`npm run dev` on port 3000). The main 3D viewer is `src/viewer.js` (~1,720 lines). It loads GLB/GLTF avatars and 3D models, handles OrbitControls, animation playback, morph targets, and environment setup.
-
-## Problem
-
-All raycasting in the viewer (hit-testing for click interactions, AR placement, annotation picking) uses Three.js's default brute-force triangle intersection — it checks every triangle of every mesh in the scene on every raycast. On a complex avatar (5k–20k triangles, skinned mesh) this is slow, especially when:
-
-- The user clicks to inspect model annotations
-- The avatar page does hover hit-testing for interactive zones
-- The validator page raycast-samples mesh surface for quality checks
-
-`three-mesh-bvh` wraps Three.js's raycasting system with a Bounding Volume Hierarchy, cutting raycast time from O(n triangles) to O(log n). The integration is a drop-in patch — no call sites change.
-
-## Current raycasting call sites in `src/viewer.js`
-
-Search for `Raycaster` and `intersectObject` in the file to confirm locations. The viewer uses `THREE.Raycaster` through OrbitControls (which calls it internally) and potentially through `_onDblClick`. The BVH patch operates at the `Mesh.prototype.raycast` level so it accelerates **all** raycasting site-wide without touching individual call sites.
-
-## What to implement
-
-### 1. Install three-mesh-bvh
-
-```bash
-npm install three-mesh-bvh
-```
-
-(If it was already installed by a prior task, `npm install` is a no-op — check `package.json` first.)
-
-### 2. Patch Mesh.prototype.raycast at module top level in `src/viewer.js`
-
-At the top of `src/viewer.js`, after the existing Three.js imports, add:
-
-```js
-import { computeBoundsTree, disposeBoundsTree, acceleratedRaycast } from 'three-mesh-bvh';
-import { Mesh } from 'three';
-
-// Accelerate all Three.js raycasting site-wide — must run before any Mesh is created.
-Mesh.prototype.raycast = acceleratedRaycast;
-```
-
-This is the recommended integration pattern from the three-mesh-bvh README. It patches the prototype once; every `Mesh` in the scene automatically uses BVH raycasting after this.
-
-### 3. Compute BVH after model content is set
-
-In `src/viewer.js`, find the `setContent(object, clips)` method. After the content is added to the scene and before the method returns, traverse the object and compute BVH for every geometry:
-
-```js
-// After scene.add(object) and before the final state updates in setContent():
-object.traverse((node) => {
- if (node.isMesh && node.geometry) {
- // computeBoundsTree mutates geometry in place; safe to call every load
- node.geometry.computeBoundsTree();
- }
-});
-```
-
-The exact location: find the line where `this.content` is assigned and the object is added to the scene (around line 750–800 in `setContent`). Place the traversal immediately after `this.scene.add(object)` (or wherever the content is attached).
-
-### 4. Dispose BVH data when content is cleared
-
-In `src/viewer.js`, find the `clear()` method (or wherever `this.content` is removed from the scene and disposed). Add BVH disposal:
-
-```js
-// Inside the content disposal block — wherever geometry.dispose() is called:
-this.content?.traverse((node) => {
- if (node.isMesh && node.geometry) {
- node.geometry.disposeBoundsTree?.();
- }
-});
-```
-
-This must run **before** `geometry.dispose()` is called, because `disposeBoundsTree` references the geometry's internal arrays.
-
-### 5. Handle skinned meshes correctly
-
-Skinned meshes (avatars with bone animation) use `SkinnedMesh`, which extends `Mesh`. BVH works on the **rest-pose geometry** — it does not account for bone deformation. This is acceptable for click/hover hit-testing on avatars because:
-- The bounding volume of the rest pose is a conservative approximation of the animated pose
-- False negatives are rare (slightly missing a click near the edge of an animated limb)
-- The alternative (brute-force) is much slower
-
-No special handling required — the patch applies equally to `Mesh` and `SkinnedMesh`.
-
-### 6. Handle non-indexed geometries
-
-`computeBoundsTree()` works on both indexed and non-indexed geometries. If a geometry has no index, three-mesh-bvh handles it correctly. No special casing needed.
-
-## Files to modify
-
-- `src/viewer.js` — three changes: import patch at top, `computeBoundsTree` call in `setContent`, `disposeBoundsTree` call in content clear.
-
-## Files to read before editing
-
-Read `src/viewer.js` fully before making changes, particularly:
-- The import block at the top (to insert the new import correctly)
-- The `setContent(object, clips)` method — find where `this.content` is assigned and `this.scene.add(object)` happens
-- The content disposal / `clear()` logic — find where `geometry.dispose()` is called for old content
-
-## Constraints
-
-- Do not modify any call sites — the prototype patch handles everything globally.
-- Do not add BVH to the skybox, environment meshes, or helper meshes (AxesHelper, GridHelper, SkeletonHelper). These are not raycasted by user interaction. To avoid wasting memory, only compute BVH for `node.isMesh && node.geometry && !node.isHelper`.
- - Check: `AxesHelper`, `GridHelper`, `SkeletonHelper` set `isHelper = true` on their child objects — use that flag.
- - Simplest safe check: only process nodes where `node.geometry.attributes.position` exists and `node.geometry.attributes.position.count > 0`.
-- Do not change OrbitControls, camera, lighting, animation, or any other viewer behaviour.
-- The patch must not break the existing morph-target system (`src/agent-avatar.js` drives morph targets every frame — BVH does not touch morph target influences, so there is no conflict).
-
-## Definition of done
-
-- `npm install` completes without errors (three-mesh-bvh in package.json).
-- `npm run dev` starts on port 3000.
-- Load an avatar in the viewer — no console errors, avatar renders and animates.
-- Click the avatar — the interaction fires (if there is one). No raycasting errors.
-- `git diff src/viewer.js` shows only the three changes described: import, computeBoundsTree traversal, disposeBoundsTree traversal.
-- No other files modified.
-
-<!-- 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/prompt-3-bvh-main-viewer.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/prompt-4-postprocessing.md b/prompts/prompt-4-postprocessing.md
deleted file mode 100644
index 3764eef91..000000000
--- a/prompts/prompt-4-postprocessing.md
+++ /dev/null
@@ -1,233 +0,0 @@
-# Task: Replace Three.js Post-Processing with pmndrs/postprocessing
-
-## Project overview
-
-This is a Three.js / Vite app at `/workspaces/3D-Agent`. The frontend is vanilla JS modules + Vite (`npm run dev` on port 3000). The main viewer is `src/viewer.js` (~1,720 lines). The marketplace lobby is `src/marketplace-lobby.js` (275 lines).
-
-## What this task does
-
-**@pmndrs/postprocessing** is a post-processing library built specifically for Three.js. Compared to Three.js's built-in `EffectComposer` (from `three/addons/postprocessing/`), it:
-
-1. **Merges shader passes** — multiple effects (bloom, vignette, depth-of-field) compile into a single fullscreen shader program instead of N separate render passes. This is a significant performance win.
-2. **Correct alpha compositing** — the library handles alpha output correctly, which matters for the avatar viewer where the canvas background is transparent.
-3. **Selective bloom via layers** — objects can be assigned to a bloom layer (Three.js Layer system) so only specific objects (e.g. podium rings, avatar outline glow) bloom, not the whole scene.
-
-The current codebase does **not** use any post-processing. This task adds it to both the main viewer and the marketplace lobby, enabling selective bloom on avatar podium rings and a subtle vignette on the main viewer.
-
-## Part A: Main Viewer (`src/viewer.js`)
-
-### Install
-
-```bash
-npm install postprocessing
-```
-
-The package name is `postprocessing` (npm) — the import is also `import { ... } from 'postprocessing'`.
-
-### Add to `src/viewer.js`
-
-#### Step 1 — Import at top of file
-
-```js
-import {
- EffectComposer,
- RenderPass,
- BloomEffect,
- VignetteEffect,
- EffectPass,
- SelectiveBloomEffect,
-} from 'postprocessing';
-```
-
-Do not import `EffectComposer` from `three/addons` — the `postprocessing` package provides its own.
-
-#### Step 2 — Create composer after renderer setup
-
-In the `Viewer` constructor, after `this.renderer` is set up and `this.scene` / `this.defaultCamera` exist, add:
-
-```js
-this._composer = new EffectComposer(this.renderer);
-this._renderPass = new RenderPass(this.scene, this.defaultCamera);
-this._composer.addPass(this._renderPass);
-
-// Subtle vignette — darkens edges, focuses attention on avatar center
-const vignetteEffect = new VignetteEffect({ eskil: false, offset: 0.35, darkness: 0.4 });
-
-// Bloom — low intensity, wide radius, for specular highlights on metallic avatars
-const bloomEffect = new BloomEffect({
- intensity: 0.6,
- luminanceThreshold: 0.8, // only pixels brighter than 80% luminance bloom
- luminanceSmoothing: 0.05,
- mipmapBlur: true, // faster than the default multi-pass blur
-});
-
-this._effectPass = new EffectPass(this.defaultCamera, bloomEffect, vignetteEffect);
-this._effectPass.renderToScreen = true;
-this._composer.addPass(this._effectPass);
-```
-
-#### Step 3 — Replace `renderer.render()` calls with `composer.render()`
-
-Search `src/viewer.js` for every call to `this.renderer.render(`. Replace each one with `this._composer.render()`. The composer internally calls `renderer.render(scene, camera)` for you via the `RenderPass`.
-
-**Exception**: The screenshot / capture methods (`takeScreenshot`, `captureScreenshot` in `src/viewer/screenshot.js`) should keep using `this.renderer.render(...)` directly — they write to a separate canvas and compositing there would add noise. Leave those untouched.
-
-**Exception**: The axes renderer (a secondary `WebGLRenderer` for the mini axes display) — this is a separate renderer, leave it alone.
-
-#### Step 4 — Update camera when active camera changes
-
-The `RenderPass` and `EffectPass` reference the camera. When `this.activeCamera` is updated (search for `this.activeCamera =` in the file), also update the passes:
-
-```js
-// Wherever this.activeCamera is reassigned:
-this.activeCamera = newCamera;
-this._renderPass.mainCamera = newCamera;
-this._effectPass.mainCamera = newCamera;
-```
-
-#### Step 5 — Handle resize
-
-In the resize handler (wherever `this.renderer.setSize` is called), also resize the composer:
-
-```js
-this.renderer.setSize(width, height);
-this._composer.setSize(width, height);
-```
-
-#### Step 6 — Dispose in viewer cleanup
-
-In the `dispose()` or `destroy()` method of the viewer, add:
-
-```js
-this._composer?.dispose();
-```
-
-## Part B: Marketplace Lobby (`src/marketplace-lobby.js`)
-
-The lobby already renders a custom Three.js scene with the glowing podium ring material. Add selective bloom to make the ring's emissive glow actually appear to bloom without blooming the avatars.
-
-### Three.js Layer system for selective bloom
-
-Three.js has a built-in layer system (`Object3D.layers`). By default every object is on layer 0. Put objects that should bloom on layer 1.
-
-#### Step 1 — Import from postprocessing
-
-Add to imports at top of `marketplace-lobby.js`:
-
-```js
-import {
- EffectComposer,
- RenderPass,
- SelectiveBloomEffect,
- EffectPass,
-} from 'postprocessing';
-```
-
-#### Step 2 — Create composer in `mountLobby`
-
-After the renderer is set up:
-
-```js
-const composer = new EffectComposer(renderer);
-const renderPass = new RenderPass(scene, camera);
-composer.addPass(renderPass);
-
-// Selective bloom — only objects on layer 1 bloom
-const bloomEffect = new SelectiveBloomEffect(scene, camera, {
- intensity: 1.8,
- luminanceThreshold: 0.05,
- luminanceSmoothing: 0.3,
- mipmapBlur: true,
- selection: [], // will be populated when podiums are created
-});
-
-const effectPass = new EffectPass(camera, bloomEffect);
-effectPass.renderToScreen = true;
-composer.addPass(effectPass);
-```
-
-#### Step 3 — Assign bloom layer to podium rings
-
-In `makePodium()`, after creating the `ring` mesh, assign it to layer 1 and add it to the bloom selection:
-
-```js
-ring.layers.enable(1);
-```
-
-Return the ring mesh from `makePodium()` so `mountLobby` can add it to `bloomEffect.selection`. Change `makePodium()` signature to return `{ group, ring }` and collect all rings:
-
-```js
-const bloomSelection = [];
-
-const slotMeta = slots.map((_, i) => {
- const x = startX + i * SLOT_SPACING;
- const { group: podium, ring } = makePodium();
- podium.position.set(x, 0, 0);
- podiumGroup.add(podium);
- bloomSelection.push(ring);
- // ...
-});
-
-bloomEffect.selection.set(bloomSelection);
-```
-
-#### Step 4 — Replace `renderer.render()` in the tick loop
-
-```js
-// Before:
-renderer.render(scene, camera);
-
-// After:
-composer.render();
-```
-
-#### Step 5 — Handle resize
-
-```js
-function resize() {
- // ... existing ...
- renderer.setSize(width, height, false);
- composer.setSize(width, height);
- // ...
-}
-```
-
-#### Step 6 — Dispose in `dispose()`
-
-```js
-composer.dispose();
-```
-
-## Constraints
-
-- **Do not change the visual feel** of the scene beyond adding bloom glow to emissive surfaces. Bloom intensity should be conservative — this is a professional avatar marketplace, not a game. If bloom makes the scene look garish, reduce `intensity`.
-- **Do not add depth-of-field** — it causes motion sickness on interactive 3D and does not apply here.
-- **Screenshot capture** paths in the viewer must continue to work — they use `renderer.render()` directly and must not be changed.
-- **The lobby's `dispose()` function** must clean up all new resources (composer, effect pass). No GPU leaks.
-- **The `makePodium` function signature change** must not break anything — it is only called within `mountLobby`.
-- All imports must work with Vite's ESM bundler. `postprocessing` ships ES modules — no special Vite config should be needed.
-- Do not change any existing lighting, geometry, camera, or control logic.
-
-## Definition of done
-
-- `npm install` runs without errors (`postprocessing` in package.json).
-- `npm run dev` starts on port 3000.
-- Main viewer: load an avatar — it renders with a subtle vignette darkening the edges. No bloom on the avatar body (luminance threshold is set above normal surface brightness). Specular highlights on metallic parts may show mild bloom.
-- Marketplace lobby: podium rings show a soft cyan glow/bloom around them. Avatar meshes do not bloom.
-- No console errors in either scene.
-- Screenshot / capture functionality in the main viewer still produces a clean image.
-- `git diff` shows only `src/viewer.js`, `src/marketplace-lobby.js`, `package.json`, `package-lock.json`.
-
-<!-- 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/prompt-4-postprocessing.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/prompts/monetization/02-purchase-skill-button.md b/prompts/prompts/monetization/02-purchase-skill-button.md
deleted file mode 100644
index bbaa583b1..000000000
--- a/prompts/prompts/monetization/02-purchase-skill-button.md
+++ /dev/null
@@ -1,88 +0,0 @@
----
-status: not-started
----
-# Prompt 2: Add Purchase Button for Priced Skills
-
-## Objective
-In the agent detail page, replace the price badge for unowned, paid skills with a "Purchase" button to initiate the buying process.
-
-## Explanation
-Displaying the price is the first step. Now, we need to give users a clear call-to-action to buy the skill. This prompt focuses on changing the UI to be interactive. The actual payment flow will be handled in subsequent prompts.
-
-## Instructions
-1. **Check Ownership:**
- * The frontend needs to know which skills the current user already owns. Create a new API endpoint (e.g., `/api/users/me/purchased-skills`) that returns a list of skill IDs owned by the authenticated user.
- * In `src/marketplace.js`, fetch the list of purchased skills when the component mounts.
-
-2. **Conditionally Render Button:**
- * Inside the `renderDetail` function, modify the skill rendering loop.
- * For each skill, determine its state: free, paid and owned, or paid and unowned.
- * - If free, show the "Free" badge.
- * - If paid and owned, show an "Owned" badge.
- * - If paid and unowned, show a "Purchase" button with the price.
-
-3. **Button Styling:**
- * Style the "Purchase" button to be a prominent call-to-action.
- * Style the "Owned" badge to give the user clear feedback.
-
-## Code Example (Frontend - `src/marketplace.js`)
-```javascript
-// Inside renderDetail function, assuming `ownedSkills` is a Set of skill names
-
-const skillPrices = a.skill_prices || {};
-$('d-skills').innerHTML = skillsArr.map(s => {
- const name = typeof s === 'string' ? s : (s.name || '');
- const price = skillPrices[name];
- const isOwned = ownedSkills.has(name);
- let badge = '';
-
- if (price && !isOwned) {
- badge = `<button class="purchase-btn" data-skill-name="${escapeHtml(name)}">${(price.amount / 1e6).toFixed(2)} USDC</button>`;
- } else if (price && isOwned) {
- badge = `<span class="price-badge price-owned">Owned</span>`;
- } else {
- badge = `<span class="price-badge price-free">Free</span>`;
- }
- return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;
-}).join(' ');
-```
-
-## CSS Example (`/marketplace.css`)
-```css
-.purchase-btn {
- background-color: #5a67d8;
- color: white;
- border: none;
- padding: 4px 10px;
- font-size: 11px;
- font-weight: 600;
- border-radius: 4px;
- cursor: pointer;
- margin-left: 8px;
- vertical-align: middle;
- transition: background-color 0.2s;
-}
-
-.purchase-btn:hover {
- background-color: #434190;
-}
-
-.price-owned {
- color: #9ae6b4;
- background-color: rgba(72, 187, 120, 0.1);
-}
-```
-
-<!-- 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/prompts/monetization/02-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/prompts/monetization/03-solana-pay-integration.md b/prompts/prompts/monetization/03-solana-pay-integration.md
deleted file mode 100644
index 06ee25f68..000000000
--- a/prompts/prompts/monetization/03-solana-pay-integration.md
+++ /dev/null
@@ -1,79 +0,0 @@
----
-status: not-started
----
-# Prompt 3: Solana Pay Integration for Skill Purchases
-
-## Objective
-Integrate Solana Pay to allow users to purchase skills using a QR code or wallet deeplink.
-
-## Explanation
-We need a robust payment mechanism. Solana Pay is a standard for on-chain payments that provides a great user experience on both desktop and mobile. When a user clicks "Purchase," we will generate a Solana Pay QR code that encodes the transaction details (recipient, amount, currency).
-
-## Instructions
-1. **Add Solana Pay Library:**
- * Add the `@solana/pay` library to your frontend dependencies using npm: `npm install @solana/pay`.
-
-2. **Create a Payment Request API:**
- * Create a new backend endpoint, e.g., `/api/payments/request`.
- * This endpoint should take `agentId` and `skillName` as input.
- * It should look up the skill's price and the creator's payout address from the database.
- * Generate a unique reference key (a new Solana public key) for the transaction and store it in a `skill_purchases` table with a `pending` status. This reference will be used for verification later.
- * The endpoint should return a JSON object containing the `recipient` address, `amount`, `splToken` (mint address for USDC), and the `reference` key as a string.
-
-3. **Generate QR Code on Frontend:**
- * In `src/marketplace.js`, add a click handler to the "Purchase" buttons.
- * When a button is clicked, call the `/api/payments/request` endpoint.
- * Use the response data and the `@solana/pay` library to generate a Solana Pay URL.
- * Display a modal with a QR code generated from this URL. The library provides utilities for this.
- * The modal should also include a "Pay with Wallet" button for mobile users, which creates a `solana:PAY_URL` deeplink.
-
-## Code Example (Frontend - `src/marketplace.js`)
-```javascript
-import { createQR, encodeURL } from '@solana/pay';
-import { PublicKey } from '@solana/web3.js';
-import BigNumber from 'bignumber.js';
-
-// ... inside the purchase button click handler ...
-
-const skillName = button.dataset.skillName;
-const agentId = currentAgent.id;
-
-try {
- const { recipient, amount, splToken, reference } = await post('/api/payments/request', { agentId, skillName });
-
- const url = encodeURL({
- recipient: new PublicKey(recipient),
- amount: new BigNumber(amount).dividedBy(1e6), // Convert from lamports to token units
- splToken: new PublicKey(splToken),
- reference: new PublicKey(reference),
- label: `3D-Agent Skill Purchase`,
- message: `Skill: ${skillName} for Agent: ${agentId}`,
- });
-
- // --- Render Modal with QR Code ---
- const qr = createQR(url);
- const modal = document.getElementById('payment-modal');
- const qrContainer = modal.querySelector('.qr-code-container');
- qrContainer.innerHTML = '';
- qr.append(qrContainer);
- modal.style.display = 'block';
-
-} catch (error) {
- console.error('Payment request 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/prompts/monetization/03-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/prompts/monetization/04-backend-payment-verification.md b/prompts/prompts/monetization/04-backend-payment-verification.md
deleted file mode 100644
index caa2b1536..000000000
--- a/prompts/prompts/monetization/04-backend-payment-verification.md
+++ /dev/null
@@ -1,85 +0,0 @@
----
-status: not-started
----
-# Prompt 4: Backend Payment Verification
-
-## Objective
-Create a backend endpoint to verify the Solana Pay transaction and confirm that the skill purchase was successful.
-
-## Explanation
-After the user completes the payment, the frontend needs to confirm with the backend that the transaction was valid. The backend will find the transaction on the Solana blockchain using the unique `reference` key we generated earlier, validate it, and update the purchase status in the database.
-
-## Instructions
-1. **Create Verification Endpoint:**
- * Create a new backend endpoint, e.g., `GET /api/payments/verify`.
- * It should accept the `reference` public key as a query parameter.
-
-2. **Find and Validate Transaction:**
- * Inside the endpoint, use the Solana Web3 JS library (`@solana/web3.js`) to connect to the blockchain.
- * Use the `findReference` method to find the transaction signature associated with our `reference` public key.
- * Once you have the signature, fetch the full transaction details.
- * Verify that the transaction details (recipient, amount, SPL token mint) match the details stored in your `skill_purchases` table for the given reference. This is crucial for security.
-
-3. **Update Database:**
- * If the transaction is valid, update the corresponding record in the `skill_purchases` table. Set its status from `pending` to `completed` and associate it with the user ID.
- * The endpoint should return a success message.
-
-4. **Frontend Polling:**
- * In the frontend payment modal, after displaying the QR code, start polling the `/api/payments/verify` endpoint every few seconds, sending the `reference` key.
- * When the endpoint returns a success status, close the modal, show a "Purchase Successful" confirmation message, and refresh the agent detail view to show the skill as "Owned".
-
-## Code Example (Backend - `/api/payments/verify.js`)
-```javascript
-import { Connection, PublicKey } from '@solana/web3.js';
-import { findReference, validateTransfer } from '@solana/pay';
-import BigNumber from 'bignumber.js';
-
-// ... inside the endpoint handler ...
-
-const { reference } = req.query;
-if (!reference) {
- return res.status(400).json({ error: 'Reference key is required' });
-}
-
-// 1. Get purchase details from DB
-const purchase = await db.getPendingPurchaseByReference(reference);
-if (!purchase) {
- return res.status(404).json({ error: 'Pending purchase not found' });
-}
-
-// 2. Find transaction on-chain
-const connection = new Connection(process.env.SOLANA_RPC_HOST);
-const signatureInfo = await findReference(connection, new PublicKey(reference), { finality: 'confirmed' });
-
-// 3. Validate transaction
-await validateTransfer(
- connection,
- signatureInfo.signature,
- {
- recipient: new PublicKey(purchase.recipient),
- amount: new BigNumber(purchase.amount).dividedBy(1e6), // Convert to token units
- splToken: new PublicKey(purchase.spl_token_mint),
- reference: new PublicKey(reference),
- },
- { commitment: 'confirmed' }
-);
-
-// 4. If validation passes, update DB
-await db.markPurchaseCompleted(reference, userId);
-
-res.status(200).json({ status: 'verified' });
-```
-
-<!-- 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/prompts/monetization/04-backend-payment-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/prompts/monetization/05-unlock-skill-after-purchase.md b/prompts/prompts/monetization/05-unlock-skill-after-purchase.md
deleted file mode 100644
index 83a5bc849..000000000
--- a/prompts/prompts/monetization/05-unlock-skill-after-purchase.md
+++ /dev/null
@@ -1,71 +0,0 @@
----
-status: not-started
----
-# Prompt 5: Unlock Skill After Purchase
-
-## Objective
-Ensure that once a skill is purchased and verified, the user gains immediate access to use it with the agent.
-
-## Explanation
-The final step of the core purchase flow is to "unlock" the skill. This involves updating the application's state to reflect the new ownership and making sure that the agent's runtime can now execute this skill for the user.
-
-## Instructions
-1. **Modify Skill Execution Logic:**
- * Locate the core logic where an agent's skill is invoked by a user. This might be in the `Runtime` class or a similar agent-brain module.
- * Before executing a skill, add a check:
- * Is the skill priced?
- * If so, does the current user own it?
-
-2. **Create an Ownership Check API:**
- * Create a reusable backend function or endpoint, e.g., `hasSkillAccess(userId, agentId, skillName)`.
- * This function should query your database (`skill_purchases` table) to see if a `completed` purchase record exists for that user and skill.
- * The skill execution logic will call this function. If the user doesn't have access, the skill execution should fail with an informative error message like "You must purchase this skill to use it."
-
-3. **Real-time UI Updates:**
- * Ensure that when the payment verification poll succeeds (from Prompt 4), the frontend state is updated immediately.
- * The `ownedSkills` set from Prompt 2 should be updated with the newly purchased skill name.
- * The UI should automatically re-render, changing the "Purchase" button to an "Owned" badge without requiring a page reload.
-
-## Code Example (Backend - Agent Runtime)
-```javascript
-// Inside the skill execution logic of the agent's brain
-
-async function executeSkill(userId, agentId, skillName, args) {
- const skill = getSkillDefinition(skillName);
- if (!skill) {
- throw new Error('Skill not found.');
- }
-
- // Check if the skill is priced
- const priceInfo = await db.getSkillPrice(agentId, skillName);
-
- if (priceInfo) {
- // If it's a paid skill, verify ownership
- const hasAccess = await db.hasSkillAccess(userId, agentId, skillName);
- if (!hasAccess) {
- // Return a message to the user instead of throwing an error
- return {
- output: `You have not purchased the "${skillName}" skill. Please purchase it from the marketplace to use it.`,
- isError: true,
- };
- }
- }
-
- // --- If checks pass, proceed with skill execution ---
- return skill.execute(args);
-}
-```
-
-<!-- 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/prompts/monetization/05-unlock-skill-after-purchase.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/prompts/monetization/06-user-purchased-skills-api.md b/prompts/prompts/monetization/06-user-purchased-skills-api.md
deleted file mode 100644
index 8d4ca7b96..000000000
--- a/prompts/prompts/monetization/06-user-purchased-skills-api.md
+++ /dev/null
@@ -1,73 +0,0 @@
----
-status: not-started
----
-# Prompt 6: User's Purchased Skills API and UI
-
-## Objective
-Create a dedicated API endpoint and a new UI section in the user's dashboard to display all the skills they have purchased across all agents.
-
-## Explanation
-Users need a central place to see all their purchased assets. This enhances the user experience by providing a clear record of their purchases and reinforces the value of their account on the platform.
-
-## Instructions
-1. **Create Backend API Endpoint:**
- * Create a new endpoint, e.g., `GET /api/users/me/skills`.
- * This endpoint should be authenticated and retrieve the current user's ID.
- * Query the `skill_purchases` table for all `completed` purchases made by the user.
- * Join the data with the `agents` and `skills` tables to return rich information for each purchase, such as the skill name, the agent it belongs to, the agent's avatar, and the purchase date.
-
-2. **Create Dashboard Page:**
- * Create a new HTML file for the dashboard page, e.g., `dashboard.html`, if it doesn't exist.
- * Add a new section or tab to this page titled "My Purchased Skills".
-
-3. **Fetch and Render Skills:**
- * In the corresponding JavaScript file for the dashboard (`dashboard.js`), fetch the data from the `/api/users/me/skills` endpoint when the page loads.
- * Render the purchased skills in a user-friendly list or grid format.
- * Each item should display the skill name, the agent's name, and an avatar, and link back to that agent's detail page in the marketplace.
-
-## Code Example (Frontend - `dashboard.js`)
-```javascript
-async function renderPurchasedSkills() {
- const container = document.getElementById('purchased-skills-container');
- container.innerHTML = 'Loading...';
-
- try {
- const skills = await get('/api/users/me/skills'); // Your API helper
-
- if (!skills || skills.length === 0) {
- container.innerHTML = '<p>You have not purchased any skills yet.</p>';
- return;
- }
-
- container.innerHTML = skills.map(skill => `
- <div class="purchased-skill-card">
- <img src="${skill.agent_avatar_url}" alt="${skill.agent_name}" class="purchased-skill-avatar" />
- <div class="purchased-skill-info">
- <h4 class="purchased-skill-name">${escapeHtml(skill.name)}</h4>
- <p class="purchased-skill-agent">for <a href="/marketplace/agent/${skill.agent_id}">${escapeHtml(skill.agent_name)}</a></p>
- </div>
- <div class="purchased-skill-date">
- Purchased on ${new Date(skill.purchase_date).toLocaleDateString()}
- </div>
- </div>
- `).join('');
- } catch (error) {
- container.innerHTML = '<p>Failed to load your purchased skills.</p>';
- console.error(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/prompts/monetization/06-user-purchased-skills-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/prompts/monetization/07-skill-pricing-dashboard.md b/prompts/prompts/monetization/07-skill-pricing-dashboard.md
deleted file mode 100644
index 4e4d39f88..000000000
--- a/prompts/prompts/monetization/07-skill-pricing-dashboard.md
+++ /dev/null
@@ -1,73 +0,0 @@
----
-status: not-started
----
-# Prompt 7: Skill Pricing Dashboard for Creators
-
-## Objective
-Create a dashboard for agent creators to view their skills and set or update prices for them.
-
-## Explanation
-To create a functioning marketplace, we need to empower creators. This prompt focuses on building the user interface where a creator can manage the monetization of their agent's skills.
-
-## Instructions
-1. **Create Creator Dashboard Page:**
- * In the user dashboard area, create a new section or page accessible to users who have created agents, titled "My Agents & Skills".
- * This page should list all the agents created by the current user.
-
-2. **Agent Skill Management UI:**
- * For each agent listed, provide a "Manage Skills" button.
- * Clicking this button should lead to a view that lists all skills associated with that agent.
- * Next to each skill, display its current price (or "Not for sale") and an "Edit Price" button.
-
-3. **Price Editing Modal:**
- * Clicking "Edit Price" should open a modal.
- * The modal should contain a form with an input for the price and a dropdown for the currency (initially, only USDC on Solana).
- * The form should handle both setting a price for a new skill and updating an existing one.
- * Include a "Remove from sale" button to make a skill free again.
-
-4. **Backend API for Pricing:**
- * Create a secure backend endpoint, e.g., `POST /api/agents/:agentId/skills/price`.
- * The endpoint must verify that the authenticated user is the owner of the agent.
- * It should accept `skillName`, `amount`, and `currencyMint` as input.
- * This endpoint will `INSERT` or `UPDATE` a record in the `agent_skill_prices` table. If the amount is set to 0 or null, the existing price record should be deleted.
-
-## Code Example (Frontend - Price Edit Modal)
-```html
-<div id="price-edit-modal" class="modal">
- <div class="modal-content">
- <span class="close-button">&times;</span>
- <h3>Set Price for <span id="modal-skill-name"></span></h3>
- <form id="price-form">
- <input type="hidden" id="modal-agent-id">
- <div class="form-group">
- <label for="price-amount">Price</label>
- <input type="number" id="price-amount" step="0.01" min="0" required>
- </div>
- <div class="form-group">
- <label for="price-currency">Currency</label>
- <select id="price-currency" disabled>
- <option value="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7uVv">USDC (Solana)</option>
- </select>
- </div>
- <div class="form-actions">
- <button type="submit" class="btn-primary">Save Price</button>
- <button type="button" id="remove-price-btn" class="btn-danger">Remove from Sale</button>
- </div>
- </form>
- </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/prompts/monetization/07-skill-pricing-dashboard.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/siwx/01-db-schema.md b/prompts/siwx/01-db-schema.md
deleted file mode 100644
index d3fbe0dbe..000000000
--- a/prompts/siwx/01-db-schema.md
+++ /dev/null
@@ -1,177 +0,0 @@
-# SIWX prompt 01 — Postgres schema for payment-history + nonce store
-
-## Context
-
-You are working in the **three.ws** workspace at `/workspaces/three.ws`. This
-project sells access to x402 paid endpoints (3D assets, agent skills, dance
-performances) and is adding **Sign-In-With-X (SIWX, CAIP-122)** so a wallet
-that has already paid for a resource can re-access it by signing a message
-instead of re-paying.
-
-Architecture overview lives in [prompts/siwx/PLAN.md](PLAN.md). Read it first.
-
-You are implementing **step 1 of 7**: the Postgres tables that back the SIWX
-storage adapter. Everything else in the plan depends on these tables existing.
-
-## Rails (CLAUDE.md, non-negotiable)
-
-- No mocks, no fake data, no placeholders, no TODOs, no stubs, no
- `throw new Error('not implemented')`, no commented-out code.
-- Real Neon Postgres — same `sql` tag from
- [api/_lib/db.js](../../api/_lib/db.js) every other migration uses.
-- Errors at boundaries only.
-- Done = migration written, applied locally against the Neon database
- pointed at by `$DATABASE_URL`, both tables visible via `\dt` (or
- equivalent SELECT against `information_schema`), `git diff` reviewed.
-
-## What to build
-
-### File 1 — `api/_lib/migrations/2026-05-21-siwx.sql`
-
-Match the style of existing migrations in
-[api/_lib/migrations/](../../api/_lib/migrations/) (look at
-`2026-05-14-x402-skus.sql` and `2026-05-10-skill-purchases.sql` for tone).
-Idempotent (`IF NOT EXISTS` on every CREATE) and self-contained.
-
-Two tables:
-
-```sql
-CREATE TABLE IF NOT EXISTS siwx_payments (
- resource text NOT NULL,
- address text NOT NULL,
- network text NOT NULL, -- CAIP-2, e.g. 'eip155:8453'
- paid_at timestamptz NOT NULL DEFAULT now(),
- expires_at timestamptz, -- NULL = permanent grant
- last_used_at timestamptz, -- updated on each siwx auth
- use_count integer NOT NULL DEFAULT 0,
- PRIMARY KEY (resource, address)
-);
-
-CREATE INDEX IF NOT EXISTS siwx_payments_expires_idx
- ON siwx_payments (expires_at)
- WHERE expires_at IS NOT NULL;
-
-CREATE TABLE IF NOT EXISTS siwx_nonces (
- nonce text PRIMARY KEY,
- resource text NOT NULL,
- address text NOT NULL,
- used_at timestamptz NOT NULL DEFAULT now()
-);
-
-CREATE INDEX IF NOT EXISTS siwx_nonces_used_at_idx
- ON siwx_nonces (used_at);
-```
-
-Notes that must be true in the file:
-
-- `address` is stored exactly as the CAIP-122 payload carries it — for EVM
- that means **lowercase hex** (NOT checksummed), for Solana that means the
- Base58 public key. The storage adapter (prompt 02) is responsible for
- normalizing before SELECT/INSERT. Document this in a 2-line comment above
- the `siwx_payments` table — the adapter relies on the storage layer's
- normalization, not a CHECK constraint.
-- Composite PK (`resource`, `address`) gives us O(1) `hasPaid` lookups and
- natural upserts via `ON CONFLICT (resource, address) DO UPDATE`.
-- `siwx_nonces` is intentionally separate from `siwx_payments` because nonces
- are write-heavy + garbage-collected hourly (prompt 06), while payments are
- read-mostly + long-lived.
-- No FK to any other table — SIWX storage is decoupled from `users`,
- `agent_identities`, `skill_purchases`. A wallet might be SIWX-paid for a
- resource without ever creating an account.
-
-### File 2 — `scripts/apply-siwx-migration.mjs`
-
-A one-shot script that reads the migration file and applies it via the same
-Neon HTTP client. Pattern to match:
-
-```js
-#!/usr/bin/env node
-// Apply the SIWX migration against $DATABASE_URL.
-// Usage: DATABASE_URL=... node scripts/apply-siwx-migration.mjs
-import { readFile } from 'node:fs/promises';
-import { neon } from '@neondatabase/serverless';
-
-const url = process.env.DATABASE_URL;
-if (!url) {
- console.error('DATABASE_URL not set');
- process.exit(1);
-}
-const sql = neon(url);
-const text = await readFile(
- new URL('../api/_lib/migrations/2026-05-21-siwx.sql', import.meta.url),
- 'utf8',
-);
-// Neon's HTTP API runs one statement per call. Split on semicolons that
-// terminate top-level statements (no quoted/escaped ; in this migration).
-const statements = text
- .split(/;\s*$/m)
- .map((s) => s.trim())
- .filter((s) => s && !s.startsWith('--'));
-for (const s of statements) {
- await sql.query(s);
- console.log('OK:', s.slice(0, 80).replace(/\s+/g, ' '));
-}
-console.log('siwx tables ready');
-```
-
-Verify by running it once against the dev database. If a similar `scripts/*`
-helper already exists for another migration (e.g. `scripts/apply-*.mjs`),
-match its style. If not, create the file fresh.
-
-### File 3 — wire it into the codebase
-
-If the project has a migration registry (look for `api/_lib/migrations.js`,
-`scripts/migrate.mjs`, or similar — do NOT create one if none exists), add
-the new migration there in the right place. If migrations are tracked only
-by file name on disk (the current pattern, per `ls api/_lib/migrations/`),
-nothing else to do.
-
-## Verification you must perform
-
-```bash
-# 1. The migration applies cleanly.
-DATABASE_URL=$DATABASE_URL node scripts/apply-siwx-migration.mjs
-
-# 2. Both tables exist with the expected columns.
-DATABASE_URL=$DATABASE_URL node -e "
-import('@neondatabase/serverless').then(async ({ neon }) => {
- const sql = neon(process.env.DATABASE_URL);
- const cols = await sql\`
- select table_name, column_name, data_type
- from information_schema.columns
- where table_name in ('siwx_payments','siwx_nonces')
- order by table_name, ordinal_position\`;
- console.table(cols);
-});
-"
-
-# 3. Re-running the migration is a no-op (no errors).
-DATABASE_URL=$DATABASE_URL node scripts/apply-siwx-migration.mjs
-```
-
-All three must succeed before you call this done. Paste the column listing
-into the final status update so the next prompt can confirm the shape.
-
-## Done means
-
-- `api/_lib/migrations/2026-05-21-siwx.sql` exists and matches the spec above.
-- `scripts/apply-siwx-migration.mjs` exists and runs idempotently.
-- Both tables exist in the Neon database.
-- `git diff` reviewed: nothing committed-out, nothing TODO, no stubs.
-
-Do **not** commit or push. Surface the diff to the user; they'll call the
-push when they're ready.
-
-<!-- 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/siwx/01-db-schema.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/siwx/02-storage-adapter.md b/prompts/siwx/02-storage-adapter.md
deleted file mode 100644
index adf758485..000000000
--- a/prompts/siwx/02-storage-adapter.md
+++ /dev/null
@@ -1,217 +0,0 @@
-# SIWX prompt 02 — Postgres-backed `SIWxStorage` adapter
-
-## Context
-
-three.ws workspace at `/workspaces/three.ws`. Architecture in
-[prompts/siwx/PLAN.md](PLAN.md). Prompt 01 created the `siwx_payments` and
-`siwx_nonces` tables in Neon Postgres.
-
-You are implementing **step 2 of 7**: a Postgres adapter that implements the
-`SIWxStorage` interface from `@x402/extensions/sign-in-with-x` so the
-`paidEndpoint()` integration (prompt 03) has something concrete to write to.
-
-The interface (from
-`node_modules/@x402/extensions/dist/esm/sign-in-with-x/index.d.mts`):
-
-```ts
-interface SIWxStorage {
- hasPaid(resource: string, address: string): boolean | Promise<boolean>;
- recordPayment(resource: string, address: string): void | Promise<void>;
- hasUsedNonce?(nonce: string): boolean | Promise<boolean>;
- recordNonce?(nonce: string): void | Promise<void>;
-}
-```
-
-Per upstream docs: `hasUsedNonce` and `recordNonce` MUST both be implemented
-or both be omitted; implementing only one throws at startup.
-
-## Rails (CLAUDE.md, non-negotiable)
-
-- No mocks, no fake data, no placeholders, no TODOs, no stubs, no
- commented-out code.
-- Real Neon queries via `sql` from [api/_lib/db.js](../../api/_lib/db.js).
-- Errors at boundaries only — internal calls trust each other.
-- `npm test` green when you're done.
-
-## What to build
-
-### File 1 — `api/_lib/siwx-storage.js`
-
-ESM module exporting one factory and one helper. No class hierarchy — keep
-it flat. Match the file-header style of
-[api/_lib/skill-access.js](../../api/_lib/skill-access.js) (purpose comment +
-inline usage example).
-
-```js
-// api/_lib/siwx-storage.js
-//
-// Postgres-backed SIWxStorage for the Sign-In-With-X extension.
-//
-// Wired into api/_lib/x402-paid-endpoint.js (prompt 03). Every paid endpoint
-// that opts into SIWX shares one instance — this module's `siwxStorage`
-// singleton — so the underlying connection pool stays warm across handlers.
-//
-// Address normalization rule: EVM addresses are stored LOWERCASED, Solana
-// addresses are stored AS-IS (Base58, case-sensitive). The normalizer below
-// is the only place that decides — every caller goes through it.
-
-import { sql } from './db.js';
-
-// Normalize an address before SELECT/INSERT. Network is the CAIP-2 string
-// from the verified SIWX payload (e.g. "eip155:8453" or
-// "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp").
-export function normalizeAddress(network, address) {
- if (!network || !address) throw new Error('siwx-storage: network+address required');
- if (network.startsWith('eip155:')) return String(address).toLowerCase();
- if (network.startsWith('solana:')) return String(address);
- throw new Error(`siwx-storage: unsupported CAIP-2 namespace "${network}"`);
-}
-```
-
-#### `siwxStorage` singleton
-
-Export `siwxStorage` as a plain object implementing the four `SIWxStorage`
-methods. Method bodies:
-
-- `hasPaid(resource, address)`
- - Looks up `siwx_payments` by `(resource, normalizedAddress)`.
- - Returns `false` when no row.
- - Returns `false` when `expires_at IS NOT NULL AND expires_at <= now()`.
- - Otherwise returns `true` AND fires-and-forgets an
- `UPDATE ... SET last_used_at = now(), use_count = use_count + 1`
- (await it; the savings of fire-and-forget aren't worth the dropped
- audit trail).
- - **Important:** the upstream contract passes `address` already-recovered
- from the verified signature. EVM verifiers return the checksummed form,
- so we must lowercase before hitting `siwx_payments` regardless of how
- callers stored it. Apply `normalizeAddress` using the network we
- persisted at `recordPayment` time. Since the call site only gives us
- `(resource, address)`, store the network on the row and look it up
- when the call comes in: the `SELECT` matches case-insensitively for
- EVM by lowercasing the input; Solana stays exact. Implement the
- SELECT as:
-
- ```sql
- SELECT 1
- FROM siwx_payments
- WHERE resource = ${resource}
- AND (
- (network LIKE 'eip155:%' AND address = ${String(address).toLowerCase()})
- OR
- (network LIKE 'solana:%' AND address = ${String(address)})
- )
- AND (expires_at IS NULL OR expires_at > now())
- LIMIT 1
- ```
-
-- `recordPayment(resource, address, opts = {})`
- - `opts = { network, ttlSeconds? }`. `network` is required (so we know
- which normalization to apply). `ttlSeconds` defaults to `null` →
- permanent grant.
- - `INSERT ... ON CONFLICT (resource, address) DO UPDATE` so re-purchases
- refresh `paid_at` and extend `expires_at`.
- - Implementation:
-
- ```sql
- INSERT INTO siwx_payments
- (resource, address, network, expires_at)
- VALUES
- (${resource}, ${normalizeAddress(network, address)}, ${network},
- ${ttlSeconds ? sql`now() + (${ttlSeconds} || ' seconds')::interval` : null})
- ON CONFLICT (resource, address) DO UPDATE
- SET network = EXCLUDED.network,
- paid_at = now(),
- expires_at = EXCLUDED.expires_at
- ```
-
-- `hasUsedNonce(nonce)`
- - `SELECT 1 FROM siwx_nonces WHERE nonce = ${nonce} LIMIT 1`.
- - Returns boolean.
-
-- `recordNonce(nonce, opts = {})`
- - `opts = { resource, address }` (so the GC job and audit have context).
- - `INSERT ... ON CONFLICT (nonce) DO NOTHING` — safe to call twice.
-
-#### Helpers exported for tests + cron
-
-- `pruneExpiredPayments(graceSeconds = 7 * 24 * 3600)`
- - `DELETE FROM siwx_payments WHERE expires_at IS NOT NULL AND expires_at < now() - (${graceSeconds} || ' seconds')::interval`.
- - Returns deleted row count.
-- `pruneOldNonces(maxAgeSeconds = 600)`
- - `DELETE FROM siwx_nonces WHERE used_at < now() - (${maxAgeSeconds} || ' seconds')::interval`.
- - Returns deleted row count.
-
-### File 2 — `api/_lib/siwx-storage.test.js`
-
-Vitest test (this project uses Vitest — confirm via `grep '"test"' package.json`
-or the existing `api/_lib/*.test.js` files). The test hits the real `$DATABASE_URL`
-when set, and `it.skipIf(!process.env.DATABASE_URL)` when it isn't, so CI can run
-without leaking secrets and a local dev can run it after `01-db-schema.md`.
-
-Cover:
-
-1. `hasPaid` returns false for an unknown wallet.
-2. `recordPayment` + `hasPaid` round-trips for EVM (mixed-case → lowercase
- match) on `eip155:8453`.
-3. `recordPayment` + `hasPaid` round-trips for Solana (Base58 case-sensitive).
-4. `recordPayment` with `ttlSeconds: 1` then `hasPaid` returns true; after
- `await new Promise(r => setTimeout(r, 1500))` it returns false.
-5. `recordNonce` + `hasUsedNonce` round-trips and is idempotent.
-6. `pruneOldNonces(0)` clears all nonces inserted by the test.
-
-Each test uses a per-run resource string like
-`test-resource-${crypto.randomUUID()}` so concurrent test runs don't collide.
-Tear down explicitly at the end with `DELETE FROM siwx_payments WHERE resource LIKE 'test-resource-%'`
-plus the equivalent for `siwx_nonces`.
-
-### File 3 — register the singleton
-
-Nothing global; prompt 03 imports `siwxStorage` directly from this module.
-Just make sure the export is named and stable.
-
-## Verification you must perform
-
-```bash
-# 1. Lint clean
-npx eslint api/_lib/siwx-storage.js api/_lib/siwx-storage.test.js
-
-# 2. Tests pass against the real DB
-DATABASE_URL=$DATABASE_URL npx vitest run api/_lib/siwx-storage.test.js
-
-# 3. No leftover test rows
-DATABASE_URL=$DATABASE_URL node -e "
-import('@neondatabase/serverless').then(async ({ neon }) => {
- const sql = neon(process.env.DATABASE_URL);
- const a = await sql\`select count(*)::int as n from siwx_payments where resource like 'test-resource-%'\`;
- const b = await sql\`select count(*)::int as n from siwx_nonces where resource like 'test-resource-%'\`;
- console.log('residual payments:', a[0].n, 'nonces:', b[0].n);
-});
-"
-# Both must print 0.
-```
-
-## Done means
-
-- `api/_lib/siwx-storage.js` implements the four `SIWxStorage` methods
- exactly as specified, plus the two `prune*` helpers.
-- `api/_lib/siwx-storage.test.js` exercises every method with real Postgres,
- passes locally with `$DATABASE_URL` set, and cleans up after itself.
-- No mocks, no in-memory fallbacks, no `process.env` defaults that silently
- bypass the DB.
-- `git diff` reviewed.
-
-Do not commit or push.
-
-<!-- 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/siwx/02-storage-adapter.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/siwx/03-paid-endpoint-integration.md b/prompts/siwx/03-paid-endpoint-integration.md
deleted file mode 100644
index 3863e58b5..000000000
--- a/prompts/siwx/03-paid-endpoint-integration.md
+++ /dev/null
@@ -1,351 +0,0 @@
-# SIWX prompt 03 — wire SIWX into the `paidEndpoint()` helper
-
-## Context
-
-three.ws workspace at `/workspaces/three.ws`. Architecture in
-[prompts/siwx/PLAN.md](PLAN.md). Prompts 01 + 02 created
-`siwx_payments` / `siwx_nonces` and a Postgres adapter at
-[api/_lib/siwx-storage.js](../../api/_lib/siwx-storage.js).
-
-This prompt is **step 3 of 7** — the core integration. Every x402 paid
-endpoint in `api/x402/*.js` is built on top of
-[api/_lib/x402-paid-endpoint.js](../../api/_lib/x402-paid-endpoint.js)'s
-`paidEndpoint(spec)` factory. We extend that one helper so any endpoint can
-opt into SIWX by adding a single `siwx:` block to its spec — and existing
-endpoints that don't opt in are unchanged.
-
-Read [api/_lib/x402-paid-endpoint.js](../../api/_lib/x402-paid-endpoint.js)
-in full before you start. The 7-step dance (CORS → method-check → 402 →
-verify → handler → settle → response) is the spine you're extending.
-
-## Rails (CLAUDE.md, non-negotiable)
-
-- No mocks, no fake data, no placeholders, no TODOs, no stubs.
-- No commented-out code in the diff.
-- Real Postgres writes via `siwxStorage`. Real signature verification via
- `@x402/extensions/sign-in-with-x` — not your own crypto.
-- Errors at boundaries only.
-- `npm test` green.
-- Existing endpoints that don't pass a `siwx:` block must continue to
- behave **bit-identically** to today (same 402 body, same headers, same
- response shape). Snapshot-style test in prompt 07 will catch regressions.
-
-## Files to edit / create
-
-### File 1 — `api/_lib/siwx-server.js` (new)
-
-Thin wrapper around the upstream SIWX primitives so `paidEndpoint()` stays
-readable. Match the file-header style of
-[api/_lib/x402-spec.js](../../api/_lib/x402-spec.js).
-
-Exports:
-
-```js
-// api/_lib/siwx-server.js
-//
-// Server-side glue between @x402/extensions/sign-in-with-x and our paidEndpoint()
-// wrapper. Keeps the verification path, extension declaration, and EVM smart-
-// wallet verifier in one place so each new endpoint doesn't have to repeat them.
-
-import {
- declareSIWxExtension,
- parseSIWxHeader,
- validateSIWxMessage,
- verifySIWxSignature,
- SIGN_IN_WITH_X,
-} from '@x402/extensions/sign-in-with-x';
-import { createPublicClient, http } from 'viem';
-import { base } from 'viem/chains';
-
-import { env } from './env.js';
-import { siwxStorage, normalizeAddress } from './siwx-storage.js';
-
-export { SIGN_IN_WITH_X };
-
-// Lazily build a viem PublicClient so verifySIWxSignature can verify
-// smart-contract wallets (EIP-1271) and counterfactual wallets (EIP-6492).
-// Uses our private RPC (env.BASE_RPC_URL) to avoid leaking buyer addresses
-// to a public node. Returns undefined when BASE_RPC_URL isn't configured —
-// the upstream verifier then falls back to EOA-only verification.
-let _baseClient;
-function getEvmVerifier() {
- if (!env.BASE_RPC_URL) return undefined;
- if (!_baseClient) {
- _baseClient = createPublicClient({
- chain: base,
- transport: http(env.BASE_RPC_URL),
- });
- }
- return _baseClient.verifyMessage;
-}
-
-// Build the extensions block that goes into the 402 body when SIWX is
-// enabled for an endpoint. The upstream helper auto-derives `domain`,
-// `resourceUri`, and refreshes `nonce`/`issuedAt` — we just pass network +
-// the human-readable statement.
-//
-// `networks` is the same CAIP-2 array the rest of paidEndpoint() uses
-// (e.g. ['eip155:8453', 'solana:5eykt...']). Multi-chain support is the
-// whole reason CAIP-122 exists — emit all of them, the client picks one.
-export function declareSiwxExtensionFor({ networks, statement, expirationSeconds = 300 }) {
- return declareSIWxExtension({
- network: networks.length === 1 ? networks[0] : networks,
- statement,
- expirationSeconds,
- });
-}
-
-// Given an incoming Vercel request, attempt to authenticate via SIGN-IN-WITH-X.
-// Returns { ok: true, address, network } when the signature is valid AND the
-// (resource, address) pair is on record. Returns { ok: false, status, error }
-// on validation/verification failure (caller emits 401/402 accordingly).
-// Returns null when the header is absent — caller continues with the normal
-// X-PAYMENT flow.
-export async function authenticateSiwx({ req, resourceUrl }) {
- const header =
- req.headers['sign-in-with-x'] ||
- req.headers['SIGN-IN-WITH-X'] ||
- req.headers['Sign-In-With-X'];
- if (!header) return null;
-
- let payload;
- try {
- payload = parseSIWxHeader(String(header));
- } catch (err) {
- return { ok: false, status: 400, code: 'siwx_parse_failed', error: err.message };
- }
-
- const validation = await validateSIWxMessage(payload, resourceUrl, {
- // Tighten the default 5-min window slightly so we don't accept stale
- // signatures across deploys / cold starts.
- maxAge: 5 * 60 * 1000,
- checkNonce: async (n) => !(await siwxStorage.hasUsedNonce(n)),
- });
- if (!validation.valid) {
- return { ok: false, status: 401, code: 'siwx_message_invalid', error: validation.error };
- }
-
- const verification = await verifySIWxSignature(payload, { evmVerifier: getEvmVerifier() });
- if (!verification.valid || !verification.address) {
- return { ok: false, status: 401, code: 'siwx_signature_invalid', error: verification.error };
- }
-
- const normalizedAddress = normalizeAddress(payload.chainId, verification.address);
- if (!(await siwxStorage.hasPaid(resourceUrl, normalizedAddress))) {
- return { ok: false, status: 402, code: 'siwx_not_paid', error: 'wallet has not paid for this resource' };
- }
-
- await siwxStorage.recordNonce(payload.nonce, {
- resource: resourceUrl,
- address: normalizedAddress,
- });
-
- return { ok: true, address: normalizedAddress, network: payload.chainId };
-}
-
-// Record a fresh payment so the wallet can re-enter via SIWX next time.
-// Called from paidEndpoint() after a successful facilitator settle.
-export async function recordSiwxPayment({ resourceUrl, payer, network, ttlSeconds = null }) {
- if (!payer) return; // direct-scheme settlements without a payer (BSC fallback) skip recording.
- await siwxStorage.recordPayment(resourceUrl, payer, { network, ttlSeconds });
-}
-```
-
-Add `BASE_RPC_URL` to [api/_lib/env.js](../../api/_lib/env.js) if it isn't
-already listed (look first — `env.BASE_RPC_URL` may already exist for the
-Permit2 / BSC flow). If you add it, keep the existing alphabetical/grouping
-convention of that file.
-
-### File 2 — extend `api/_lib/x402-paid-endpoint.js`
-
-Three changes, **and nothing else**:
-
-#### 2a. New optional `siwx` field on the `spec` argument
-
-```js
-const {
- route,
- method = 'GET',
- priceAtomics = env.X402_MAX_AMOUNT_REQUIRED,
- networks = ['base', 'solana'],
- description,
- mimeType = 'application/json',
- bazaar,
- handler,
- // NEW: when present, this endpoint advertises and accepts SIWX auth.
- // { statement: string; ttlSeconds?: number | null; expirationSeconds?: number }
- // - statement: human-readable purpose shown to the wallet on signing
- // - ttlSeconds: how long the payment grant lasts (null = permanent)
- // - expirationSeconds: SIWX message validity window (default 300s)
- siwx,
-} = spec;
-```
-
-#### 2b. Declare the SIWX extension on the 402 challenge
-
-Inside the `paidHandler` async function, after building `requirements` but
-before constructing the `challenge` object, build the extensions block when
-SIWX is enabled and pass it through `send402` (which already supports an
-`extensions` option via `build402Body`):
-
-```js
-const siwxExtensions = siwx
- ? declareSiwxExtensionFor({
- networks: requirements.map((r) => r.network),
- statement: siwx.statement,
- expirationSeconds: siwx.expirationSeconds,
- })
- : null;
-
-const challenge = {
- resourceUrl,
- accepts: requirements,
- description,
- mimeType,
- bazaar,
- ...(siwxExtensions ? { extensions: siwxExtensions } : {}),
-};
-```
-
-`build402Body` in [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js)
-already merges arbitrary extensions — confirm by re-reading lines around
-`extraExtensions`. No change needed there.
-
-#### 2c. SIWX auth path: before falling through to the 402 flow
-
-Right after `const paymentHeader = req.headers['x-payment'] || req.headers['payment-signature'];`,
-add the SIWX short-circuit:
-
-```js
-if (siwx && !paymentHeader) {
- const auth = await authenticateSiwx({ req, resourceUrl });
- if (auth?.ok) {
- let result;
- try {
- result = await handler({
- req,
- res,
- requirement: null, // no payment requirement was used
- payer: auth.address, // recovered SIWX wallet
- siwx: { address: auth.address, network: auth.network },
- });
- } catch (err) {
- if (err instanceof X402Error && err.status === 402) {
- return send402(res, { ...challenge, error: err.message });
- }
- return error(res, err.status || 500, err.code || 'internal_error', err.message);
- }
- if (res.writableEnded) return;
- res.setHeader('cache-control', 'no-store');
- res.setHeader('content-type', `${mimeType}; charset=utf-8`);
- res.end(typeof result === 'string' ? result : JSON.stringify(result));
- return;
- }
- if (auth && !auth.ok) {
- // Validation/verification failed — return a 401 so callers don't keep
- // retrying with the same broken signature. They can drop the header and
- // re-attempt the normal pay-with-USDC flow.
- return error(res, auth.status, auth.code, auth.error);
- }
- // auth === null → header absent → fall through to standard 402 dance.
-}
-```
-
-Import `X402Error` (already imported), `authenticateSiwx`, and
-`declareSiwxExtensionFor` from `./siwx-server.js`. The `siwx` extra arg to
-`handler` is opt-in — existing handlers ignore it; new handlers can branch on
-"served via signature" vs. "served via payment" if they care (most won't).
-
-#### 2d. Record the payment after settlement
-
-In the same handler, after the existing `settlePayment(...)` call succeeds
-and before `res.setHeader('x-payment-response', ...)`, record the grant:
-
-```js
-if (siwx) {
- await recordSiwxPayment({
- resourceUrl,
- payer: verified.payer,
- network: verified.requirement.network,
- ttlSeconds: siwx.ttlSeconds ?? null,
- });
-}
-```
-
-Import `recordSiwxPayment` from `./siwx-server.js`. Don't try/catch this:
-if Postgres is down, the payment already settled on-chain; logging the
-error and surfacing a 500 is fine — we don't want to silently lose a
-grant on a Neon hiccup. Let it throw; the outer `error(res, ...)` already
-catches handler errors and returns a clean response.
-
-Actually — wait. The settle path doesn't currently wrap further work in a
-try/catch (it goes straight to writing headers). Wrap the `recordSiwxPayment`
-call in a `try/catch` that returns a `502 siwx_record_failed` so the buyer
-sees a clear error instead of a hung connection. They can retry; the upsert
-on `siwx_payments` is idempotent and the on-chain transaction is final.
-
-### File 3 — JSDoc + tests
-
-Update the JSDoc / file-top comment of
-[api/_lib/x402-paid-endpoint.js](../../api/_lib/x402-paid-endpoint.js) so the
-8-step dance is correctly described (was 7). Add one paragraph explaining
-the SIWX opt-in.
-
-New test file `api/_lib/x402-paid-endpoint.siwx.test.js` (Vitest) covering:
-
-1. Endpoint without `siwx:` — 402 body has no `extensions['sign-in-with-x']`
- (current behavior preserved).
-2. Endpoint with `siwx:` — 402 body has `extensions['sign-in-with-x']` with
- `supportedChains` matching `requirements[].network`.
-3. With a real Solana keypair (`@solana/web3.js` is already a dep — see
- `package.json`), generate a SIWX message, sign it, send the encoded
- header → endpoint returns 402 with `siwx_not_paid` because no grant
- exists.
-4. After calling `siwxStorage.recordPayment(resourceUrl, address, { network })`
- directly, the same SIWX request now returns 200 with the handler's
- response body.
-
-Use `$DATABASE_URL` like prompt 02's tests; `it.skipIf(!process.env.DATABASE_URL)`.
-
-## Verification you must perform
-
-```bash
-# 1. Lint
-npx eslint api/_lib/siwx-server.js api/_lib/x402-paid-endpoint.js api/_lib/x402-paid-endpoint.siwx.test.js
-
-# 2. Existing tests still pass
-npm test
-
-# 3. New SIWX tests pass against real DB
-DATABASE_URL=$DATABASE_URL npx vitest run api/_lib/x402-paid-endpoint.siwx.test.js
-
-# 4. A no-siwx endpoint's 402 is bit-identical (snapshot the body before and
-# after your diff to confirm).
-```
-
-## Done means
-
-- `api/_lib/siwx-server.js` exists and is the only place that touches the
- `@x402/extensions/sign-in-with-x` API surface.
-- `api/_lib/x402-paid-endpoint.js` accepts an optional `siwx:` spec and
- handles the three new responsibilities (declare, authenticate, record).
-- Tests above all green.
-- Existing endpoints (skill-marketplace, dance-tip, others in `api/x402/*.js`)
- are **untouched** by this prompt. Wiring them is prompt 04.
-- `git diff` reviewed.
-
-Do not commit or push.
-
-<!-- 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/siwx/03-paid-endpoint-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/siwx/04-wire-endpoints.md b/prompts/siwx/04-wire-endpoints.md
deleted file mode 100644
index 166248c9f..000000000
--- a/prompts/siwx/04-wire-endpoints.md
+++ /dev/null
@@ -1,341 +0,0 @@
-# SIWX prompt 04 — opt in existing endpoints + add the canonical asset-download endpoint
-
-## Context
-
-three.ws workspace at `/workspaces/three.ws`. Architecture in
-[prompts/siwx/PLAN.md](PLAN.md). Prompt 03 added an optional `siwx:` field
-to `paidEndpoint(spec)` in
-[api/_lib/x402-paid-endpoint.js](../../api/_lib/x402-paid-endpoint.js).
-
-This prompt is **step 4 of 7** — turning on SIWX for real endpoints. We do
-three things:
-
-1. Opt in `skill-marketplace` and `dance-tip` (existing endpoints).
-2. Ship a brand-new `asset-download` endpoint that is the textbook "buy
- once, re-download forever" use case — a creator uploads a GLB / avatar /
- accessory, prices it, buyers pay once via x402, and afterwards any
- wallet on the grant list can re-download by signing.
-3. Surface SIWX status on the `/api/x402-status` page so we can debug.
-
-## Rails (CLAUDE.md, non-negotiable)
-
-- No mocks. No fake data. No placeholders. No TODOs. No stubs. No commented-
- out code. No `setTimeout` fake-loading. No fallback sample arrays.
-- Real R2 (or whatever object store this repo already uses — check
- [api/_lib/r2.js](../../api/_lib/r2.js)) for the asset bytes.
-- Real Neon for listing rows.
-- Real signed URLs / streams from R2 — don't proxy bytes through Vercel
- unless you've checked the file is small (<5MB) and the route stays
- under Vercel's response size limits.
-- Done = endpoint works end-to-end in `npm run dev`, browser console clean,
- network tab shows the SIWX retry returning 200, payments table has the
- expected row, `git diff` reviewed.
-
-## Files to edit / create
-
-### A. Opt in `api/x402/skill-marketplace.js`
-
-The marketplace catalog is polled by agent shoppers — paying $0.001 per
-poll is fine the first time, but a returning agent should be able to
-re-fetch for free by signing. Add to the existing `paidEndpoint({...})`
-spec:
-
-```js
-siwx: {
- statement: 'Sign in to refresh the three.ws skill marketplace without re-paying.',
- ttlSeconds: 24 * 3600, // grants expire after 24h so prices stay paid-fresh
- expirationSeconds: 300,
-},
-```
-
-Nothing else changes — the handler doesn't care whether it served via
-payment or signature. Verify by re-reading the file after your edit; the
-diff should be exactly the new `siwx:` block.
-
-### B. Opt in `api/x402/dance-tip.js`
-
-A tipper who paid to make Dancer 1 perform Rumba should be able to retrigger
-the same performance later from the same wallet without re-paying. But each
-new `(dancer, dance)` combination is a fresh purchase. The grant key is the
-endpoint URL, not the query params — so we add `siwx:` but keep grants
-permanent (one wallet = one free repeat of any previously-paid combo).
-
-The handler currently issues a fresh `ticketId` per call. Keep that — the
-ticket is per-performance, not per-grant. The signing flow just lets the
-buyer skip the payment step before the ticket is issued.
-
-```js
-siwx: {
- statement: 'Sign in to retrigger a dance you already tipped for.',
- ttlSeconds: null, // permanent grant
- expirationSeconds: 300,
-},
-```
-
-### C. New endpoint — `api/x402/asset-download.js`
-
-This is the marquee SIWX example. Creators monetize 3D assets; buyers pay
-once and re-download as many times as they want from the same wallet.
-
-Schema (already exists or add via migration if not — check
-[api/_lib/migrations/](../../api/_lib/migrations/) first):
-
-```sql
--- in api/_lib/migrations/2026-05-21-paid-assets.sql, IF not already present
-CREATE TABLE IF NOT EXISTS paid_assets (
- id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
- slug text NOT NULL UNIQUE, -- 'rumba-dancer-glb', 'cz-avatar', ...
- title text NOT NULL,
- description text NOT NULL,
- mime_type text NOT NULL, -- 'model/gltf-binary', 'image/png', ...
- size_bytes bigint NOT NULL,
- r2_key text NOT NULL, -- e.g. 'assets/rumba-dancer.glb'
- price_atomics text NOT NULL, -- USDC atomics, '5000' = $0.005
- creator_payto_base text, -- optional override; defaults to env.X402_PAY_TO_BASE
- creator_payto_solana text, -- optional override; defaults to env.X402_PAY_TO_SOLANA
- created_at timestamptz NOT NULL DEFAULT now()
-);
-
-CREATE INDEX IF NOT EXISTS paid_assets_slug_idx ON paid_assets (slug);
-```
-
-Apply the same way prompt 01's migration was applied (one-shot
-`scripts/apply-paid-assets-migration.mjs` modeled on
-`scripts/apply-siwx-migration.mjs`).
-
-#### Endpoint behavior
-
-`GET /api/x402/asset-download?slug=<slug>` →
-
-- 402 if no payment + no SIWX. Challenge includes the asset's price (per-asset
- override of `priceAtomics`) and the SIWX extension.
-- 200 + binary body (correct `Content-Type`, `Content-Length`, and `Content-
- Disposition: attachment; filename="<slug>.<ext>"`) on success.
-
-Implementation outline (write the full file, no shortcuts):
-
-```js
-// api/x402/asset-download.js
-import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
-import { buildBazaarSchema, X402Error } from '../_lib/x402-spec.js';
-import { sql } from '../_lib/db.js';
-import { getAssetStream, getAssetBytes } from '../_lib/r2.js'; // use existing R2 client
-
-const ROUTE = '/api/x402/asset-download';
-
-const DESCRIPTION =
- 'three.ws Asset Bazaar — pay once in USDC to unlock a 3D asset (GLB, ' +
- 'avatar, accessory). Wallets that have already paid can re-download for ' +
- 'free by signing in with SIWX (CAIP-122). Each asset has its own price ' +
- 'and creator payout address.';
-
-const INPUT_EXAMPLE = { slug: 'rumba-dancer-glb' };
-
-const INPUT_SCHEMA = { /* slug: string required */ };
-
-const OUTPUT_EXAMPLE = {
- ok: true,
- slug: 'rumba-dancer-glb',
- title: 'Rumba Dancer GLB',
- mimeType: 'model/gltf-binary',
- sizeBytes: 1843201,
- downloadUrl: 'https://...presigned R2 URL...', // when stream-via-presigned
-};
-
-// NOTE on shape: prefer responding with a short-lived presigned R2 URL
-// when the asset is > 1MB. Proxying through Vercel works for small assets
-// (avatars, accessories) but blows past Vercel's body-size limits for
-// full-size GLBs.
-
-export default async function handler(req, res) {
- const slug = req.query?.slug ? String(req.query.slug).trim() : null;
- if (!slug) {
- res.statusCode = 400;
- res.setHeader('content-type', 'application/json');
- res.end(JSON.stringify({ error: 'slug required' }));
- return;
- }
-
- const [asset] = await sql`
- SELECT id, slug, title, description, mime_type, size_bytes, r2_key,
- price_atomics, creator_payto_base, creator_payto_solana
- FROM paid_assets
- WHERE slug = ${slug}
- LIMIT 1
- `;
- if (!asset) {
- res.statusCode = 404;
- res.setHeader('content-type', 'application/json');
- res.end(JSON.stringify({ error: 'asset not found' }));
- return;
- }
-
- // Build a per-asset paidEndpoint on the fly: price + per-creator payout
- // come from the row, everything else is shared.
- const inner = paidEndpoint({
- route: ROUTE,
- method: 'GET',
- priceAtomics: asset.price_atomics,
- networks: ['base', 'solana'],
- description: `${DESCRIPTION} — currently delivering: ${asset.title}.`,
- mimeType: asset.mime_type,
- bazaar: {
- discoverable: true,
- info: {
- input: { type: 'http', method: 'GET', queryParams: INPUT_EXAMPLE },
- output: { type: 'json', example: OUTPUT_EXAMPLE },
- },
- schema: buildBazaarSchema({
- method: 'GET',
- queryParamsSchema: INPUT_SCHEMA,
- outputSchema: { /* full schema */ },
- }),
- },
- siwx: {
- statement: `Sign in to re-download "${asset.title}" without re-paying.`,
- ttlSeconds: null, // permanent grant per (asset, wallet)
- expirationSeconds: 300,
- },
- async handler({ req, res }) {
- // Stream the file (presigned URL preferred — see comment above).
- const presigned = await getAssetStream(asset.r2_key, { expiresSec: 60 });
- return {
- ok: true,
- slug: asset.slug,
- title: asset.title,
- mimeType: asset.mime_type,
- sizeBytes: Number(asset.size_bytes),
- downloadUrl: presigned.url,
- };
- },
- });
-
- return inner(req, res);
-}
-```
-
-**Important — per-creator payouts.** If `asset.creator_payto_base` or
-`asset.creator_payto_solana` is set, the `paidEndpoint` you build inline
-needs to use those instead of the shared `env.X402_PAY_TO_*`. The current
-`buildAccept()` in `api/_lib/x402-paid-endpoint.js` reads directly from
-`env`. Extend `paidEndpoint(spec)` (in this prompt OR push back to prompt
-03 and update both) to accept an optional `payTo: { base?, solana?, bsc? }`
-override map, and have `buildAccept()` fall back to env when a key is
-missing. Document this change in the helper's file-top comment.
-
-#### Seed two real assets
-
-In a new file `scripts/seed-paid-assets.mjs`, upload two real GLBs that
-already live in this repo (e.g. `public/avatars/<name>.glb` — `ls
-public/avatars/*.glb`) to R2 under `assets/<slug>.glb` and insert the rows.
-**No placeholders** — actually push the bytes and write the row with the
-real `size_bytes` from `fs.statSync(file).size`. The script is idempotent
-(slug is UNIQUE; use `ON CONFLICT (slug) DO NOTHING`).
-
-Pick two slugs that map to assets the team will recognize:
-
-- `pole-dancer-rumba` — points at the same GLB the /club page uses for Rumba.
-- One avatar GLB from `public/avatars/`.
-
-Price both at `5000` atomics ($0.005).
-
-#### Register the route in `vercel.json`
-
-Check the existing `vercel.json` rewrites/functions block. The current
-catch-all `api/x402/*.js` rewrite (collapsed in recent commits — see
-`36dfec9a fix(vercel): collapse functions block to a single wildcard`) most
-likely already routes `/api/x402/asset-download` automatically. Confirm via
-`grep -n asset-download vercel.json` plus a `curl -sI http://localhost:3000/api/x402/asset-download?slug=...`
-after `npm run dev`.
-
-### D. Surface SIWX status on `/api/x402-status`
-
-Read [api/x402-status.js](../../api/x402-status.js) and append a new section
-to the JSON it returns:
-
-```js
-siwx: {
- configured: true,
- paymentsRowCount: <int from `select count(*) from siwx_payments`>,
- noncesRowCount: <int from `select count(*) from siwx_nonces`>,
- evmVerifierConfigured: Boolean(env.BASE_RPC_URL),
-}
-```
-
-Wrap the count queries in a try/catch — `siwx_payments` may not exist on a
-brand-new database — and return `{ configured: false, error: err.message }`
-when the SELECT throws. Don't fail the whole status endpoint.
-
-### E. Documentation
-
-Add one section to [docs/api-reference.md](../../docs/api-reference.md) (or
-the closest existing reference page — check `ls docs/`) describing:
-
-- The SIWX flow on three.ws.
-- The `sign-in-with-x` extension declared in 402 bodies.
-- The `SIGN-IN-WITH-X` header clients send to skip payment.
-- That `paid_assets` is the canonical example, and that any new
- `paidEndpoint()` can opt in by adding `siwx: { statement, ttlSeconds }`.
-
-Keep it to ~60 lines. No marketing copy.
-
-## Verification you must perform
-
-```bash
-# 1. Migrations applied
-DATABASE_URL=$DATABASE_URL node scripts/apply-siwx-migration.mjs
-DATABASE_URL=$DATABASE_URL node scripts/apply-paid-assets-migration.mjs
-
-# 2. Seed runs (uploads to R2, inserts rows)
-R2_*=... DATABASE_URL=$DATABASE_URL node scripts/seed-paid-assets.mjs
-
-# 3. Dev server up
-npm run dev
-# In a second terminal:
-
-# 4a. First request: 402 with SIWX extension declared
-curl -sS http://localhost:3000/api/x402/asset-download?slug=pole-dancer-rumba | jq .
-curl -sSI http://localhost:3000/api/x402/asset-download?slug=pole-dancer-rumba | grep -i payment-required
-# Confirm the PAYMENT-REQUIRED header decodes to a body containing
-# extensions['sign-in-with-x'].
-
-# 4b. /api/x402-status reports siwx { configured: true, ... }
-curl -sS http://localhost:3000/api/x402-status | jq .siwx
-
-# 4c. Existing endpoints still work
-curl -sS http://localhost:3000/api/x402/skill-marketplace | jq .
-curl -sS 'http://localhost:3000/api/x402/dance-tip?dancer=1&dance=rumba' | jq .
-```
-
-You don't need to drive the SIWX retry from `curl` here — that's the
-verify dance in prompt 07. For this prompt the goal is: the extension is
-advertised, the seed assets exist, the status endpoint sees the tables.
-
-## Done means
-
-- `api/x402/skill-marketplace.js` and `api/x402/dance-tip.js` each have one
- new `siwx:` block in their `paidEndpoint(...)` call; no other diff.
-- `api/x402/asset-download.js` exists, is end-to-end wired, returns
- presigned R2 URLs, and respects per-asset payout overrides.
-- `paid_assets` table exists and is seeded with two real GLBs from `public/`.
-- `api/x402-status.js` reports SIWX configuration + table counts.
-- `docs/api-reference.md` (or equivalent) explains the flow.
-- Browser test on http://localhost:3000 shows clean network tab + no
- console errors when hitting the three endpoints.
-- `git diff` reviewed.
-
-Do not commit or push.
-
-<!-- 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/siwx/04-wire-endpoints.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/siwx/05-browser-modal.md b/prompts/siwx/05-browser-modal.md
deleted file mode 100644
index fc4cb709b..000000000
--- a/prompts/siwx/05-browser-modal.md
+++ /dev/null
@@ -1,295 +0,0 @@
-# SIWX prompt 05 — browser modal: detect SIWX, sign with wallet, retry
-
-## Context
-
-three.ws workspace at `/workspaces/three.ws`. Architecture in
-[prompts/siwx/PLAN.md](PLAN.md). Prompts 03 + 04 mean every paid endpoint
-that opts into SIWX now advertises the extension in its 402 body and
-accepts a `SIGN-IN-WITH-X` header instead of payment for previously-paid
-wallets.
-
-This prompt is **step 5 of 7** — the browser side. The drop-in modal lives
-at [public/x402.js](../../public/x402.js) (~910 lines). It currently drives
-the **payment** flow for EVM (Base USDC via EIP-3009 + `window.ethereum`)
-and Solana (Phantom + SPL transfer). You're extending it to also drive the
-**sign-in** flow, so a returning buyer's first click is one signature
-instead of one payment.
-
-## UX target
-
-When the user clicks an `[data-x402-endpoint]` element:
-
-1. Modal POPs as today, with merchant + action labels.
-2. Modal hits the endpoint, gets 402, decodes body.
-3. **If body contains `extensions['sign-in-with-x']`:**
- - Modal shows **two** primary buttons: "Sign in with wallet" (top,
- primary) and "Pay $X.XXX USDC" (below, secondary).
- - User clicks "Sign in with wallet" → wallet picker (same EVM/Solana
- branch as the payment flow) → sign the CAIP-122 message → retry the
- endpoint with `SIGN-IN-WITH-X` header.
- - If retry returns 200 → success path identical to a paid call.
- - If retry returns 401/402 with `code: siwx_not_paid` → modal swaps to
- "You haven't paid for this yet — pay now" and proceeds via the payment
- flow (same as if SIWX hadn't been offered).
-4. If body does NOT contain the SIWX extension → behavior unchanged.
-
-No new merchant-side API: same `<button data-x402-endpoint>` works. Same
-`window.X402.pay({...})` programmatic call works. The modal just gains a
-new code path internally.
-
-## Rails (CLAUDE.md, non-negotiable)
-
-- No mocks. No fake data. No placeholders. No TODOs. No stubs. No commented-
- out code in the shipped file.
-- No `setTimeout` fake-loading. No fallback sample arrays.
-- Real wallet APIs: `window.ethereum` (viem under the hood is OK but the
- modal currently uses raw `eth_signTypedData_v4` — staying consistent with
- that is fine), `window.solana` / Phantom adapter.
-- Real signature verification happens server-side via prompt 03; the
- browser just constructs + signs + posts the header.
-- Done = `npm run dev` up, exercised on the `/club` page and any
- `data-x402-endpoint` button, signing flow succeeds, retry returns 200,
- no console errors, no network errors except deliberate 402/401.
-
-## Files to edit / create
-
-### File 1 — `public/x402.js` (edit)
-
-Add SIWX support without breaking the existing payment flow. Suggested
-structure:
-
-1. **Constants** at top of file:
-
- ```js
- const SIWX_HEADER = 'SIGN-IN-WITH-X';
- const SIWX_EXTENSION_KEY = 'sign-in-with-x';
- ```
-
-2. **Helper: detect SIWX in 402 body.**
-
- ```js
- function extractSiwxExtension(body) {
- const ext = body?.extensions?.[SIWX_EXTENSION_KEY];
- if (!ext || !ext.info || !Array.isArray(ext.supportedChains)) return null;
- return ext;
- }
- ```
-
-3. **Helper: match the user's wallet against `supportedChains`.**
-
- ```js
- // Returns { chain, kind: 'evm' | 'solana' } or null.
- function pickSiwxChain(ext, walletKind) {
- for (const chain of ext.supportedChains) {
- if (walletKind === 'evm' && chain.type === 'eip191') return { chain, kind: 'evm' };
- if (walletKind === 'solana' && chain.type === 'ed25519') return { chain, kind: 'solana' };
- }
- return null;
- }
- ```
-
-4. **Helper: build the CAIP-122 message string locally.**
-
- The upstream `formatSIWEMessage` / `formatSIWSMessage` are not exported
- to the browser bundle without a build step. The CAIP-122 message format
- is small enough to reconstruct here — match the spec exactly:
-
- ```
- <domain> wants you to sign in with your <Ethereum|Solana> account:
- <address>
-
- <statement>
-
- URI: <uri>
- Version: 1
- Chain ID: <chainRef> ← numeric for EVM (extract from "eip155:<n>"), genesis-hash for Solana
- Nonce: <nonce>
- Issued At: <issuedAt>
- ```
-
- Optional fields (`Expiration Time`, `Not Before`, `Request ID`,
- `Resources`) follow on subsequent lines per CAIP-122. Build them
- conditionally; an empty list means omit the line entirely.
-
- For exact line-by-line correctness re-read
- `node_modules/@x402/extensions/dist/esm/sign-in-with-x/index.d.mts`
- for the field list. Anything you emit must be parseable by
- `parseSIWxHeader` on the server.
-
-5. **Helper: build the encoded `SIGN-IN-WITH-X` header value.**
-
- ```js
- function encodeSiwxHeader(payload) {
- // base64-encoded JSON per x402 v2 spec.
- const json = JSON.stringify(payload);
- // btoa is fine for ASCII JSON (no non-Latin-1 chars in CAIP-122 fields).
- return btoa(unescape(encodeURIComponent(json)));
- }
- ```
-
-6. **EVM signing.** Reuse the existing wallet-connection path. Once you
- have an address, call:
-
- ```js
- const signature = await ethereum.request({
- method: 'personal_sign',
- params: [message, address],
- });
- ```
-
- Build the payload:
-
- ```js
- const payload = {
- domain: ext.info.domain,
- address,
- statement: ext.info.statement,
- uri: ext.info.uri,
- version: ext.info.version || '1',
- chainId: chain.chainId, // CAIP-2 string
- type: 'eip191',
- nonce: ext.info.nonce,
- issuedAt: ext.info.issuedAt,
- ...(ext.info.expirationTime ? { expirationTime: ext.info.expirationTime } : {}),
- ...(ext.info.notBefore ? { notBefore: ext.info.notBefore } : {}),
- ...(ext.info.requestId ? { requestId: ext.info.requestId } : {}),
- ...(ext.info.resources ? { resources: ext.info.resources } : {}),
- signatureScheme: 'eip191',
- signature,
- };
- ```
-
-7. **Solana signing.** Use the existing Phantom path (`window.solana ||
- window.phantom?.solana`). Once connected:
-
- ```js
- const encoded = new TextEncoder().encode(message);
- const { signature } = await provider.signMessage(encoded, 'utf8');
- // signature is Uint8Array; base58-encode for transport.
- const sigB58 = bs58encode(signature);
- ```
-
- You need a base58 encoder in the browser. `bs58` ships in `node_modules`
- (used by `api/_lib/siws.js`); pull a minimal browser-safe base58 helper
- inline rather than adding a bundle dependency. Solana's alphabet is the
- Bitcoin alphabet; the helper is <30 lines. Reference impl: the existing
- `api/_lib/siws.js` uses `bs58` from npm — for the browser side, write
- the encoder inline (a vanilla loop over the byte array). No bundler
- needed; the existing `x402.js` already follows the "no build step"
- constraint.
-
- Payload:
-
- ```js
- const payload = {
- domain: ext.info.domain,
- address: publicKey.toBase58(),
- statement: ext.info.statement,
- uri: ext.info.uri,
- version: '1',
- chainId: chain.chainId,
- type: 'ed25519',
- nonce: ext.info.nonce,
- issuedAt: ext.info.issuedAt,
- ...(ext.info.expirationTime ? { expirationTime: ext.info.expirationTime } : {}),
- signatureScheme: 'siws',
- signature: sigB58,
- };
- ```
-
-8. **Retry with the header.**
-
- ```js
- const headerValue = encodeSiwxHeader(payload);
- const res = await fetch(endpoint, {
- method: requestMethod,
- headers: { ...requestHeaders, [SIWX_HEADER]: headerValue },
- body: requestBody,
- });
- if (res.status === 200) return await res.json();
- if (res.status === 401 || res.status === 402) {
- // Likely siwx_not_paid — fall through to the payment flow.
- return null;
- }
- throw new Error(`SIWX retry failed: ${res.status}`);
- ```
-
-9. **Modal layout** (CSS lives inline in `x402.js`). Add a second action
- button above the existing pay button when SIWX is offered. Style:
- primary = sign-in (the bet is: most clicks become signs as the userbase
- matures), secondary = pay-with-USDC. When the user clicks pay, hide
- the sign-in button so the existing flow runs unchanged.
-
-10. **CustomEvents.** Today the modal dispatches `x402:result` /
- `x402:error`. Add `x402:siwx-signed` (detail: `{ address, network }`)
- fired right after a successful SIWX retry, so merchants can wire
- analytics. Existing events stay.
-
-### File 2 — `public/x402.js` smoke test page
-
-There's an existing test surface — look for `public/x402-test.html` or
-add `public/siwx-test.html`. The page should:
-
-- Have one button bound to `/api/x402/asset-download?slug=pole-dancer-rumba`.
-- Have one button bound to `/api/x402/dance-tip?dancer=1&dance=rumba`.
-- Show the raw `x402:result` and `x402:siwx-signed` event details in a
- `<pre>` block so you can eyeball the flow.
-
-Keep it visually minimal — this is for verification, not marketing.
-
-### File 3 — public docs
-
-Update [public/docs-widgets.html](../../public/docs-widgets.html) (or the
-equivalent "drop-in modal" docs page) to describe the new "Sign in with
-wallet" option. One paragraph + a screenshot or ASCII mockup is enough.
-
-## Verification you must perform
-
-```bash
-# 1. Dev server
-npm run dev
-
-# 2. Manual browser test (MetaMask or Phantom installed):
-# a. Open http://localhost:3000/siwx-test.html
-# b. Click "Buy GLB" — pay flow runs, asset downloads.
-# c. Reload page. Click "Buy GLB" again.
-# d. Modal now shows "Sign in with wallet" first. Click it.
-# e. Wallet prompts to sign a CAIP-122 message. Approve.
-# f. Network tab shows GET /api/x402/asset-download → 401 → GET with
-# SIGN-IN-WITH-X header → 200.
-# g. <pre> block shows x402:siwx-signed then x402:result.
-# h. No console errors.
-
-# 3. Repeat for /api/x402/dance-tip in the second button.
-
-# 4. Sanity: clear browser localStorage, repeat step b without SIWX
-# sign-in — the pay flow must still work bit-identically.
-```
-
-## Done means
-
-- `public/x402.js` has the SIWX detection + sign + retry path, no
- `// TODO`, no commented blocks.
-- The modal renders two buttons when SIWX is offered; one when it isn't.
-- A real wallet (MetaMask + Phantom both tested) can sign and re-enter
- the asset-download endpoint without re-paying.
-- `public/siwx-test.html` exists and reproduces the dance reliably.
-- Docs page mentions the new flow.
-- No regressions in the original payment flow.
-- `git diff` reviewed.
-
-Do not commit or push.
-
-<!-- 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/siwx/05-browser-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/siwx/06-nonce-gc-cron.md b/prompts/siwx/06-nonce-gc-cron.md
deleted file mode 100644
index efab1a3f3..000000000
--- a/prompts/siwx/06-nonce-gc-cron.md
+++ /dev/null
@@ -1,169 +0,0 @@
-# SIWX prompt 06 — daily cron to prune nonces + expired grants
-
-## Context
-
-three.ws workspace at `/workspaces/three.ws`. Architecture in
-[prompts/siwx/PLAN.md](PLAN.md). Prompts 01 + 02 set up
-`siwx_nonces` (write-heavy, replay protection) and `siwx_payments`
-(time-bound grants).
-
-This prompt is **step 6 of 7** — a Vercel cron that runs hourly to keep
-both tables bounded.
-
-## Why this matters
-
-- `siwx_nonces` grows by **one row per successful SIWX auth**. Without
- pruning, the table balloons and `hasUsedNonce` lookups slow down.
-- `siwx_payments` rows with `expires_at` in the past stop granting access
- on read (the `SELECT` filters them), but they linger forever and pollute
- reporting on `/api/x402-status`.
-
-The storage adapter from prompt 02 already exposes the two helpers
-(`pruneOldNonces`, `pruneExpiredPayments`). All this prompt does is wire
-them into the cron dispatcher and the Vercel schedule.
-
-## Rails (CLAUDE.md, non-negotiable)
-
-- No mocks, no fake data, no stubs.
-- Real `sql` calls. Cron is auth-gated like the others.
-- Done = `curl -H 'authorization: Bearer $CRON_SECRET' http://localhost:3000/api/cron/siwx-gc`
- returns a clean summary, both tables shrink as expected, `git diff` reviewed.
-
-## Files to edit
-
-### 1. `api/cron/[name].js` — add a new handler branch
-
-Existing pattern: every cron lives as a handler in the dispatcher at
-[api/cron/[name].js](../../api/cron/[name].js). Add to the `HANDLERS`
-map and define the function. Match the existing style (`handle<X>` async,
-returns `json(res, ...)` from `_lib/http.js`, reads its auth gate from
-`env.CRON_SECRET` exactly like the other handlers do — re-read
-`handleCleanupCsrfTokens` for the closest analogue).
-
-```js
-// Add to HANDLERS map:
-'siwx-gc': handleSiwxGc,
-
-// New handler:
-async function handleSiwxGc(req, res) {
- // Reuse whatever auth gate the surrounding handlers use. Look at
- // handleCleanupCsrfTokens — it likely calls a shared `assertCron(req)`
- // or checks `req.headers.authorization === \`Bearer ${env.CRON_SECRET}\``.
- // Match that exactly; do not invent a new gate.
-
- const { pruneOldNonces, pruneExpiredPayments } = await import('../_lib/siwx-storage.js');
-
- // 10-minute nonce window — well over the 5-minute SIWX message maxAge.
- const noncesDeleted = await pruneOldNonces(10 * 60);
-
- // 7-day grace on expired payments so a slow client doesn't lose access
- // mid-session right at the boundary.
- const paymentsDeleted = await pruneExpiredPayments(7 * 24 * 3600);
-
- return json(res, 200, {
- ok: true,
- noncesDeleted,
- paymentsDeleted,
- ranAt: new Date().toISOString(),
- });
-}
-```
-
-If `json` / `error` / `wrap` aren't already imported in the dispatcher, they
-are — every other handler uses them. Reuse.
-
-### 2. `vercel.json` — schedule the cron
-
-Add to the existing `crons` array (don't reorder the others):
-
-```json
-{
- "path": "/api/cron/siwx-gc",
- "schedule": "23 * * * *"
-}
-```
-
-Hourly at :23 to avoid clustering with the existing :17 csrf cleanup.
-Vercel's free tier limits cron count — verify you're not at the cap with
-`jq '.crons | length' vercel.json` before/after.
-
-### 3. Tiny addition to `/api/x402-status` (optional but easy)
-
-Re-open [api/x402-status.js](../../api/x402-status.js) and surface the most
-recent GC run from the response headers / a `siwx.lastGc` field. If you'd
-need a new table to track that, **skip it** — the cron already returns the
-run timestamp, and operators can see it in Vercel cron logs. Don't build a
-log table just for this.
-
-## Verification you must perform
-
-```bash
-# 1. Local dispatch works.
-CRON_SECRET=$CRON_SECRET npm run dev
-curl -sS -H "authorization: Bearer $CRON_SECRET" \
- http://localhost:3000/api/cron/siwx-gc | jq .
-
-# Expected:
-# {
-# "ok": true,
-# "noncesDeleted": <int>,
-# "paymentsDeleted": <int>,
-# "ranAt": "2026-05-21T..."
-# }
-
-# 2. Auth gate works.
-curl -sS -i http://localhost:3000/api/cron/siwx-gc | head -1
-# Expected: 401 (or 403, matching the other crons exactly).
-
-# 3. Insert two test rows then verify pruning.
-DATABASE_URL=$DATABASE_URL node -e "
-import('@neondatabase/serverless').then(async ({ neon }) => {
- const sql = neon(process.env.DATABASE_URL);
- await sql\`insert into siwx_nonces (nonce, resource, address, used_at) values
- ('gc-test-fresh', '/x', 'a', now()),
- ('gc-test-old', '/x', 'a', now() - interval '20 minutes')\`;
- const before = await sql\`select count(*)::int as n from siwx_nonces where nonce like 'gc-test-%'\`;
- console.log('before:', before[0].n);
-});
-"
-curl -sS -H "authorization: Bearer $CRON_SECRET" \
- http://localhost:3000/api/cron/siwx-gc | jq .
-DATABASE_URL=$DATABASE_URL node -e "
-import('@neondatabase/serverless').then(async ({ neon }) => {
- const sql = neon(process.env.DATABASE_URL);
- const after = await sql\`select nonce from siwx_nonces where nonce like 'gc-test-%'\`;
- console.log('after:', after);
- await sql\`delete from siwx_nonces where nonce like 'gc-test-%'\`;
-});
-"
-# Expected: 'gc-test-fresh' remains, 'gc-test-old' gone.
-
-# 4. vercel.json validates.
-jq '.crons' vercel.json
-node -e "JSON.parse(require('fs').readFileSync('vercel.json','utf8'))"
-```
-
-## Done means
-
-- `api/cron/[name].js` has a `handleSiwxGc` handler registered in `HANDLERS`.
-- `vercel.json` declares the hourly cron at `/api/cron/siwx-gc`.
-- Local curl with `$CRON_SECRET` returns the summary JSON; without the
- secret returns the same error code the other crons return.
-- Test rows are pruned correctly.
-- `git diff` reviewed.
-
-Do not commit or push.
-
-<!-- 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/siwx/06-nonce-gc-cron.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/tripo-gap/01-text-to-animation.md b/prompts/tripo-gap/01-text-to-animation.md
deleted file mode 100644
index 72b947554..000000000
--- a/prompts/tripo-gap/01-text-to-animation.md
+++ /dev/null
@@ -1,191 +0,0 @@
-# Task: Text-to-animation — generate motion from a prompt, retarget onto the user's avatar
-
-## Why this exists
-
-Tripo AI cannot generate animation from a text description. Their animation is
-limited to applying preset clips and Mixamo/Tripo retargeting. We already own
-every downstream piece — a rigged humanoid skeleton on every avatar, a runtime
-retargeting engine, a pose studio with animated-GLB export, and an animation
-library. The only missing link is a **motion-diffusion model** that turns a text
-prompt ("waving confidently", "a slow tai-chi sweep", "celebratory jump") into a
-motion clip we can retarget onto the user's avatar and preview live.
-
-This is our single most defensible feature versus Tripo. Build it completely.
-
-## Rails (CLAUDE.md — non-negotiable; read the full file first)
-
-- **No mocks, no fake data, no placeholders, no fallback sample arrays.** Use a
- real motion-diffusion model running in a real worker. If a credential or model
- weight is missing, find it in `.env` / `vercel env` / the worker's deploy
- config or ask once, then proceed.
-- **No TODOs, no stubs, no commented-out code, no `throw new Error("not implemented")`.**
- If you write it, finish it and wire it 100% — worker → API → UI → export.
-- **The only coin is `$three`** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).
- Never reference any other coin anywhere.
-- **Every state designed** (loading/empty/error/populated); every control has
- hover/active/focus; responsive; accessible; real async indicators.
-- **Done = reachable in the browser, exercised end-to-end, `npm test` green,
- `git diff` self-reviewed.** Run the **completionist** subagent before stopping.
-- **Push only when the user says so**, then to BOTH remotes (`threeD`, `threews`).
-
-## Explore first (spawn these before writing code)
-
-### Subagent A (Explore) — the worker pattern
-> In `/workspaces/three.ws/workers/`, read `model-trellis/`, `model-hunyuan3d/`,
-> and `model-triposr/` and document the exact worker contract they share: HTTP
-> framework, the `POST /infer` request/response shape, the queued-job model
-> (`GET /tasks/:id` polling), how they fetch inputs and upload outputs (GCS/R2),
-> how Firestore/job state is tracked, the Dockerfile/deploy layout, and the
-> GPU/runtime assumptions. Quote `requirements.txt` / `Dockerfile` / the main
-> entry file for one of them verbatim. I am adding a new sibling worker that must
-> match this contract exactly.
-
-### Subagent B (Explore) — the retarget + animation surface
-> In `/workspaces/three.ws`, read and quote the public API of:
-> 1. `src/animation-retarget.js` — the retargeting engine. What skeleton/bone
-> naming does it expect as the *source*? How does it map onto our Wolf3D
-> 25-joint humanoid? What is the minimum-coverage rule?
-> 2. `src/animation-library.js` — how clips are stored, listed, and applied.
-> 3. `src/pose-studio.js` — how it loads a rigged GLB, plays an animation, and
-> exports an animated GLB (the glTF animation-track baking path).
-> 4. `api/_mcp/tools/animations.js` — the existing `apply_animation`,
-> `list_animations`, `create_animation_clip` tools.
-> 5. The existing `prompts/animation-studio/` prompt set — what was already built
-> vs. planned. Quote `00-README.md`.
-> Also report where `/public/animations/` clips live and their format (GLB/FBX),
-> and the exact bone names of our target rig (from `workers/unirig/rig_glb.py`).
-
-Wait for both before starting.
-
-## What to build
-
-### Step 1 — the motion-diffusion worker
-
-Create `workers/model-text2motion/` matching the `model-*` worker contract
-Subagent A documented (same framework, same `POST /infer` → `GET /tasks/:id`
-queued-job shape, same output-upload path).
-
-Model selection — pick a **commercially-licensed** text-to-motion model and state
-the license in the worker README. Evaluate, in order of preference:
-- **MDM (Motion Diffusion Model)** — MIT, HumanML3D skeleton, well-supported.
-- **MoMask** / **T2M-GPT** — higher quality; verify the license is
- commercial-safe before adopting. If the license is non-commercial, do **not**
- use it — fall back to MDM.
-
-Contract:
-- `POST /infer { prompt, length_seconds?=4, fps?=30, job_id? }` → `202 { task_id }`
-- `GET /tasks/:id` → `{ status, clip_url }` where `clip_url` is a GLB (or BVH)
- carrying the generated motion on the model's native skeleton
- (HumanML3D/SMPL 22-joint).
-- Output upload to the same bucket the other workers use.
-- Real GPU inference. No canned/sample motion. Sanitize NaN/Inf the way
- `rig_glb.py` does.
-
-Convert the model's native motion output into a clip on a **standard skeleton**
-(HumanML3D/SMPL joint names) so the existing retarget engine can map it — do the
-SMPL→named-skeleton conversion in the worker, not in the browser.
-
-### Step 2 — the API endpoint
-
-Add a backend endpoint that ties prompt → worker → retarget → user's avatar.
-Reuse `api/forge.js`'s job conventions (`?job=<id>` polling, the queued-status
-shape) and the existing R2/DB helpers (`api/_lib/r2.js`, `api/_lib/db.js`).
-Prefer extending `api/_mcp/tools/animations.js`'s `create_animation_clip` to
-accept a `prompt`, plus a thin public route (e.g. `api/animate.js` or a
-`path: "text"` branch on the animation API) that:
-
-1. Submits the prompt to the text2motion worker, returns a `job_id`.
-2. On completion, retargets the generated clip onto the requesting avatar's rig
- using the engine from `src/animation-retarget.js` (run it server-side in Node
- — Subagent B confirmed it runs in Node as well as the browser).
-3. Stores the retargeted animated GLB in R2 under the avatar's namespace and
- records the clip in the animation library so it shows up in the user's list.
-4. Returns the clip URL + metadata.
-
-Handle errors at the boundary: bad prompt, worker timeout, a rig the retargeter
-can't cover (<50% bone coverage) → a real, actionable error, never a fake clip.
-
-### Step 3 — wire the UI
-
-In the pose/animation studio (`src/pose-studio.js` + its page, and/or the
-`prompts/animation-studio/` surface), add a **"Generate from text"** control:
-
-- A prompt input with a length slider and a Generate button.
-- Loading state: a real progress indicator tied to the job poll (skeleton/au
- progress, not a fake timer).
-- On success: the clip auto-loads onto the avatar in the viewport and plays,
- with the existing scrub/speed/loop controls.
-- Save to library (reuses `animation-library.js`) and **Export animated GLB**
- (reuses the pose-studio baking path).
-- Empty state explains what to type; error state explains failure + recovery.
-- Hover/active/focus on every control; keyboard-operable; responsive at 320 /
- 768 / 1440.
-
-### Step 4 — MCP + monetization hooks
-
-- Expose `text_to_animation(avatar_id, prompt, length?)` as an MCP tool
- alongside the existing animation tools in `api/_mcp/tools/animations.js`.
-- Respect the existing usage/plan gating pattern (see how
- `api/avatar/video-generate` meters free vs. paid in `usage_events`). Free tier
- gets a small quota; paid is unlimited. No new coin references — billing is in
- the platform's existing units / `$three` only where a token is surfaced.
-
-### Step 5 — deploy config
-
-- Add the worker to whatever deploy manifest the other `model-*` workers use
- (`workers/deploy/` or each worker's own deploy file — match the pattern).
-- If the retarget step runs in a Vercel function, confirm its `maxDuration` in
- `vercel.json` is sufficient (retarget is fast; the wait is the worker job,
- which is polled, not held).
-
-### Step 6 — tests
-
-- Unit-test the SMPL→named-skeleton conversion with a tiny synthetic motion
- array (assert joint count, no NaN, monotonic time track).
-- Unit-test the retarget call on a fixture rig (reuse any rig fixture the repo
- already has; otherwise build a minimal rigged GLB the way
- `tests/render-glb.test.js` builds its triangle GLB).
-- Gate the real-worker GPU path behind an env flag (e.g.
- `RUN_GPU_TESTS=1`) and document the skip, mirroring the headful-render test
- convention in `tests/render-glb.test.js`.
-- Endpoint test: stub the worker call at the module boundary, assert the
- endpoint submits the job, retargets, writes R2, records the library row.
-
-### Step 7 — docs
-
-- `workers/model-text2motion/README.md`: model, license, contract, deploy.
-- Add a PROGRESS.md item describing what shipped.
-- If `prompts/animation-studio/` lists text-to-animation as future work, mark it
- done there.
-
-## Definition of done
-
-- A user types a prompt in the studio and a real, model-generated motion plays on
- their own avatar within the job's normal latency — no canned clips.
-- The clip saves to their library and exports as an animated GLB.
-- `text_to_animation` works as an MCP tool with plan gating.
-- `npm test` green (GPU path skipped in CI, documented).
-- The new worker matches the existing `model-*` contract exactly.
-- `git diff` self-reviewed; completionist subagent run and its findings fixed.
-
-## Constraints
-
-- Use a real, commercially-licensed motion model. State the license. If unsure,
- use MDM (MIT). Never ship a non-commercial model in production.
-- Do the SMPL→skeleton conversion in the worker, not the browser.
-- Reuse `src/animation-retarget.js` — do not write a second retargeter.
-- No fake/sample motion anywhere, including tests' "happy path."
-
-<!-- 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/tripo-gap/01-text-to-animation.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/tripo-gap/03-blender-comfyui-plugins.md b/prompts/tripo-gap/03-blender-comfyui-plugins.md
deleted file mode 100644
index 3b0987cd4..000000000
--- a/prompts/tripo-gap/03-blender-comfyui-plugins.md
+++ /dev/null
@@ -1,157 +0,0 @@
-# Task: Blender add-on + ComfyUI node for three.ws generation
-
-## Why this exists
-
-Tripo's biggest distribution advantage is its plugin ecosystem — Blender, Unity,
-Unreal, ComfyUI, Godot, Cocos. We have **zero** plugin coverage. Game and film
-artists never have to leave their tool to use Tripo; they have to leave their
-tool entirely to use us. This task ships the two highest-leverage plugins — a
-**Blender add-on** and a **ComfyUI custom node** — both driving our existing
-`api/forge.js` generation pipeline, so an artist can generate a three.ws model
-without leaving their DCC.
-
-## Rails (CLAUDE.md — non-negotiable; read the full file first)
-
-- **No mocks, no fake data, no placeholders.** The plugins call the real forge
- API and import the real returned GLB. No bundled sample models, no fake
- progress. If an API key flow is needed, build the real one.
-- **No TODOs, no stubs, no commented-out code, no `raise NotImplementedError`.**
- Wire 100%: auth → submit → poll → import.
-- **The only coin is `$three`** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).
- Never reference any other coin anywhere.
-- **Repo hygiene:** plugins live in a dedicated top-level dir (`integrations/`),
- not the repo root. No scratch files committed.
-- **Done = installable and exercised** against a running API, README with install
- steps, `npm test` still green (no regressions to the web app). Run the
- **completionist** subagent before stopping.
-- **Push only when the user says so**, then to BOTH remotes (`threeD`, `threews`).
-
-## Explore first (spawn before writing code)
-
-### Subagent A (Explore) — the forge API surface
-> In `/workspaces/three.ws`, quote the complete external contract of
-> `api/forge.js`: the `POST /api/forge` request body (`prompt`, `image_urls`,
-> `path`, `tier`, `backend`, `aspect_ratio`), the `?job=<id>` poll response
-> (`status`, `glb_url`, `image_url`, `preview_image_url`, `error`, `backend`),
-> and `?catalog`. Then document the authentication model for external callers:
-> how does an API key / token get issued and verified? Look for an API-keys
-> system (the git status referenced `tests/api/api-keys.test.js`) — quote how a
-> key is created and how an endpoint authenticates one. The plugins must use the
-> real auth path, not an unauthenticated backdoor.
-
-### Subagent B (Explore) — existing SDK / packaging conventions
-> In `/workspaces/three.ws`, check `sdk/`, `solana-agent-sdk/`,
-> `agent-payments-sdk/`, and any existing `integrations/` or `plugins/` dir for
-> packaging conventions (how a distributable artifact is structured, versioned,
-> and documented). Also confirm the public base URL of the deployed API (check
-> `vercel.json` rewrites, `api/_lib/env.js` for APP_ORIGIN, and any docs). The
-> plugins need a correct default endpoint.
-
-Wait for both before starting.
-
-## What to build
-
-### Step 1 — Blender add-on
-
-Create `integrations/blender/three_ws/` — a proper Blender add-on package:
-
-- `__init__.py` with `bl_info` (name "three.ws", category "Import-Export",
- Blender ≥ 4.0).
-- A preferences panel for the **API base URL** and **API key** (using the real
- key system Subagent A documented).
-- An N-panel UI in the 3D viewport sidebar with:
- - A prompt field + Generate (text → 3D).
- - An image picker + Generate (image → 3D).
- - Tier / backend dropdowns populated from `GET /api/forge?catalog`.
- - A real progress readout driven by polling `?job=<id>` on a modal/timer
- operator (Blender's `modal()` pattern — never block the UI thread).
-- On completion: download the `glb_url` and import it into the current scene via
- Blender's glTF importer, selected and framed.
-- Real error surfacing in the Blender report system (auth failure, generation
- failure, network) — actionable, never swallowed.
-- `README.md` with install steps (zip the folder → Edit ▸ Preferences ▸ Add-ons ▸
- Install) and a key-setup walkthrough.
-
-### Step 2 — ComfyUI custom node
-
-Create `integrations/comfyui/three_ws_nodes/`:
-
-- `__init__.py` exporting `NODE_CLASS_MAPPINGS` / `NODE_DISPLAY_NAME_MAPPINGS`.
-- A **"three.ws Text→3D"** node: inputs `prompt`, `tier`, `backend`, `api_key`,
- `api_url`; output the path to the downloaded GLB (a `STRING`/path output other
- nodes can consume) plus the preview image as an `IMAGE` output.
-- A **"three.ws Image→3D"** node: `IMAGE` input → GLB path output.
-- Both submit to forge, poll to completion inside the node's execution, and
- download the result to ComfyUI's output dir. Honor ComfyUI's caching so a
- re-run with identical inputs doesn't re-generate.
-- Real error raising with clear messages on failure.
-- `requirements.txt` (just `requests` if that's all that's needed) and a
- `README.md` with install steps (clone into `ComfyUI/custom_nodes/`).
-
-### Step 3 — shared client (avoid duplication)
-
-Factor the submit-and-poll logic into one small Python module reused by both
-plugins (e.g. `integrations/_pyclient/three_ws_client.py`) so the forge contract
-lives in one place. Keep it dependency-light (stdlib `urllib` or `requests`).
-
-### Step 4 — make the API external-ready (only if needed)
-
-If Subagent A finds the forge API is currently locked to same-origin /
-session-cookie auth and has no API-key path for external callers, add **real**
-API-key authentication to `api/forge.js` using the existing key system — issue,
-store (hashed), and verify a key, with a scope for generation. Do not open an
-unauthenticated route. (If prompt `04-monetized-3d-api-mcp.md` has already
-shipped, target that public surface instead and skip this step.)
-
-### Step 5 — tests + verification
-
-- Python: a unit test for the shared client against a stubbed HTTP server
- (assert it submits the right body and polls to completion). No live network in
- CI.
-- If you touched `api/forge.js` auth, add/extend a JS test (see
- `tests/api/api-keys.test.js`) asserting a valid key authenticates and an
- invalid one is rejected. `npm test` must stay green.
-- Manually verify the Blender add-on installs and generates against a running
- API; verify the ComfyUI node loads and outputs a GLB path. Document the manual
- steps you ran.
-
-### Step 6 — docs
-
-- `integrations/README.md` indexing both plugins.
-- A PROGRESS.md item.
-
-## Definition of done
-
-- `integrations/blender/three_ws/` installs as a Blender add-on, authenticates
- with a real key, generates from text and image, and imports the GLB into the
- scene with live progress.
-- `integrations/comfyui/three_ws_nodes/` loads in ComfyUI and outputs a real GLB
- from Text→3D and Image→3D nodes.
-- Shared Python client; no duplicated forge logic.
-- API-key auth is real (existing system or new, hashed, scoped) — no
- unauthenticated generation route.
-- `npm test` green; Python client test green.
-- `git diff` self-reviewed; completionist subagent run and findings fixed.
-
-## Constraints
-
-- Plugins live under `integrations/` — never the repo root.
-- No bundled sample/placeholder models or fake progress in either plugin.
-- Blender polling must use the modal/timer pattern — never block Blender's UI.
-- Respect ComfyUI caching semantics.
-- If you add external auth, use the existing key system; never ship an open
- generation endpoint.
-
-<!-- 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/tripo-gap/03-blender-comfyui-plugins.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/tripo-gap/04-monetized-3d-api-mcp.md b/prompts/tripo-gap/04-monetized-3d-api-mcp.md
deleted file mode 100644
index cc6ae67b1..000000000
--- a/prompts/tripo-gap/04-monetized-3d-api-mcp.md
+++ /dev/null
@@ -1,156 +0,0 @@
-# Task: Monetized public 3D-generation API + MCP tools (x402-gated)
-
-## Why this exists
-
-Tripo's commercial moat is a documented, credit-metered public API plus official
-MCP generation tools (`text_to_3d`, `image_to_3d`). We have the generation
-pipeline (`api/forge.js`) but it isn't packaged as a public, paid, documented
-product, and our MCP server is pump-focused rather than exposing 3D generation.
-
-Our structural advantage is **x402 + agent-payments**: an API that AI agents can
-discover and pay for **autonomously**, in USDC, without a human signing up for a
-credit plan. Tripo cannot copy this without rebuilding their billing around
-agent payments. This task turns forge into that product: an x402-gated public
-generation API and matching MCP tools.
-
-## Rails (CLAUDE.md — non-negotiable; read the full file first)
-
-- **No mocks, no fake data, no placeholders.** Real forge pipeline, real x402
- payment verification, real USDC settlement via the existing payment stack. No
- fake "payment accepted" path.
-- **No TODOs, no stubs, no commented-out code, no `throw new Error("not implemented")`.**
- Wire 100%: x402 challenge → payment → generation → result.
-- **The only coin is `$three`** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).
- Never reference, hardcode, or surface any other coin or token. Payments settle
- in USDC via the existing x402 plumbing where USDC is the protocol unit — that
- is generic payment rails, not a coin reference. Never display another token.
-- **Done = a third-party caller (and an MCP client) can pay and generate
- end-to-end**, with docs, `npm test` green, `git diff` self-reviewed. Run the
- **completionist** subagent before stopping.
-- **Push only when the user says so**, then to BOTH remotes (`threeD`, `threews`).
-
-## Explore first (spawn before writing code)
-
-### Subagent A (Explore) — the x402 / payment surface
-> In `/workspaces/three.ws`, quote how an existing x402-gated endpoint works
-> end-to-end. Read `api/x402/pump-launch.js` and `api/x402/vanity.js` (and any
-> `api/x402/_lib`): the 402 challenge/response shape, how a payment proof is
-> verified, what settles the USDC, and how price is declared. Also quote the
-> `agent-payments-sdk/` public API and how `api/_lib` exposes payment helpers.
-> I am adding a new x402-gated generation endpoint that must reuse this exactly.
-
-### Subagent B (Explore) — forge internals + MCP server
-> In `/workspaces/three.ws`, quote:
-> 1. `api/forge.js` — the full submit/poll contract and `?catalog`, plus
-> `api/_lib/forge-tiers.js` cost/ETA fields.
-> 2. The MCP server: where tools are defined (`api/_mcp/tools/` and the
-> `@three-ws/mcp-server` package — find its source), how a tool is registered,
-> its input schema, and how it authenticates/meters. Quote one existing tool
-> (e.g. `api/_mcp/tools/animations.js`) verbatim as the template.
-> 3. How usage/billing is currently metered (`usage_events`, plan gating — see
-> `api/avatar/video-generate`).
-
-Wait for both before starting.
-
-## What to build
-
-### Step 1 — the x402-gated generation endpoint
-
-Create `api/x402/forge.js` (or `api/x402/generate.js`) reusing the exact x402
-pattern from Subagent A:
-
-- Unpaid request → `402` with a price challenge derived from
- `api/_lib/forge-tiers.js` (draft/standard/high each priced; image vs text vs
- geometry path priced per the catalog).
-- Valid payment proof → submit to the forge pipeline, return `202 { job_id }`.
-- `GET` poll returns the forge status shape (`status`, `glb_url`,
- `preview_image_url`, `error`, `backend`).
-- Price must be declared in the response and in `?catalog` so callers (human or
- agent) know the cost before paying.
-- Real settlement via the existing payment stack — no bypass, no "free if header
- X" backdoor.
-
-### Step 2 — MCP generation tools
-
-Add to the MCP server (matching the `api/_mcp/tools/` registration pattern and
-the `@three-ws/mcp-server` package):
-
-- `text_to_3d(prompt, tier?, backend?, aspect_ratio?)` → returns a job handle /
- result URL.
-- `image_to_3d(image_url|image_urls, tier?, backend?)` → same.
-- Each tool declares its price and pays via the agent-payments path so an agent
- using the MCP server settles autonomously. Reuse the metering/plan logic for
- any platform-account callers.
-- Keep input schemas tight and validated; real errors on failure.
-
-### Step 3 — OpenAPI + docs
-
-- Publish an OpenAPI schema for the public generation API (submit, poll,
- catalog, pricing). Put it where the repo keeps API docs (check existing docs
- layout; otherwise `docs/api/forge-openapi.json` + a short `docs/api/forge.md`).
-- The docs must include: auth/payment flow, pricing table (sourced from
- `forge-tiers.js`), request/response examples, and a worked x402 example using
- the agent-payments path. No other-coin references; USDC only where the protocol
- unit appears.
-
-### Step 4 — rate / abuse guards
-
-- Reuse the existing rate-limit + SSRF patterns already used by the public
- renderers (`api/render/glb.js` has a real SSRF guard + per-IP limit — match
- it). Image URLs supplied by callers must pass the SSRF guard before the worker
- fetches them.
-- Set a sane `maxDuration` in `vercel.json` for the new endpoint consistent with
- other forge routes (generation is polled, not held — the function returns a
- job id quickly).
-
-### Step 5 — tests
-
-- Endpoint test: unpaid request → 402 with correct price; valid stubbed payment
- proof → job submitted; poll returns the forge shape. Stub the payment verifier
- and the forge submit at module boundaries.
-- MCP tool test: `text_to_3d` / `image_to_3d` validate input, declare price,
- and route to the generation path (forge submit stubbed).
-- Pricing test: catalog prices match `forge-tiers.js` (single source of truth —
- do not hardcode prices in two places).
-- `npm test` green.
-
-### Step 6 — docs / progress
-
-- PROGRESS.md item.
-- If this supersedes the API-key step in `03-blender-comfyui-plugins.md`, note
- that the plugins should target this public surface.
-
-## Definition of done
-
-- A third-party `curl` (or agent) hits the endpoint, receives a 402 with a real
- price, pays via x402/USDC, and gets a generated GLB — fully real, no bypass.
-- `text_to_3d` and `image_to_3d` work as MCP tools with autonomous payment.
-- OpenAPI schema + docs published; prices sourced solely from `forge-tiers.js`.
-- SSRF guard + rate limit on caller-supplied inputs.
-- `npm test` green; `git diff` self-reviewed; completionist run and findings fixed.
-
-## Constraints
-
-- Reuse the existing x402 + agent-payments stack — do not invent a parallel
- payment flow.
-- Single source of truth for pricing (`forge-tiers.js`). No duplicated price
- constants.
-- USDC is the only token surfaced, and only as the x402 protocol unit. Never
- reference any coin other than `$three`.
-- No unpaid/backdoor generation route. No fake payment-accepted path, including
- in tests' happy path (stub at the verifier boundary, not by faking success
- inside the endpoint).
-
-<!-- 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/tripo-gap/04-monetized-3d-api-mcp.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/scripts/combine-docs-ai-crypto.mjs b/scripts/combine-docs-ai-crypto.mjs
new file mode 100644
index 000000000..a9c3f5bc2
--- /dev/null
+++ b/scripts/combine-docs-ai-crypto.mjs
@@ -0,0 +1,236 @@
+#!/usr/bin/env node
+// Combine ONLY the AI + crypto/blockchain product docs into a single curated file
+// (docs/AI-CRYPTO.md) for use as a NotebookLM (or any RAG) source.
+//
+// node scripts/combine-docs-ai-crypto.mjs
+//
+// Why this exists, vs. scripts/combine-docs.mjs (which flattens ALL of docs/):
+// - Scope: keeps the AI-agent and crypto/blockchain *concepts* only. 3D-world,
+// metaverse, avatar/appearance, viewer/editor, embedding, UI/design, and
+// internal engineering-process docs (briefs, roadmaps, status logs, build
+// prompts) are intentionally left out so a notebook trained on this file talks
+// about what three.ws *is*, not how it gets built.
+// - The allowlist below is the single source of truth. To add/remove a topic,
+// edit a CATEGORIES entry — nothing here is inferred from the filesystem.
+//
+// Originals under docs/ are never modified. Re-run manually to refresh the snapshot.
+import { readFileSync, writeFileSync, existsSync } from 'node:fs';
+
+const ROOT = process.cwd();
+const OUT = 'docs/AI-CRYPTO.md';
+
+// Curated, thematically-grouped allowlist. Order here = order in the output.
+// Every path is relative to the repo root. Only product/concept docs belong here.
+const CATEGORIES = [
+ {
+ title: 'Platform Overview — agents with a wallet and an on-chain identity',
+ files: [
+ 'docs/introduction.md',
+ 'docs/how-it-works.md',
+ 'docs/architecture.md',
+ 'docs/three-ws-feature-article.md',
+ 'docs/coinmarketcap-article.md',
+ ],
+ },
+ {
+ title: 'AI Agents — system, manifest & behavior',
+ files: [
+ 'docs/agent-system.md',
+ 'docs/agent-manifest.md',
+ 'docs/agents-vs-avatars.md',
+ 'docs/make-your-agent.md',
+ 'docs/multi-agent.md',
+ 'docs/persona-hub.md',
+ 'docs/memory.md',
+ 'docs/skills.md',
+ 'docs/x-spaces.md',
+ ],
+ },
+ {
+ title: 'AI Brains, MCP & agent tooling',
+ files: [
+ 'docs/mcp.md',
+ 'docs/mcp-agent.md',
+ 'docs/mcp-x402-bazaar.md',
+ 'docs/ibm.md',
+ 'docs/ibm-x402-mcp.md',
+ 'docs/aws-builder-center-mcp-agents.md',
+ 'docs/pump-fun-mcp-edge.md',
+ ],
+ },
+ {
+ title: 'Agent security & trust (zauth)',
+ files: [
+ 'docs/zauth/index.md',
+ 'docs/zauth/provider-hub.md',
+ 'docs/zauth/reposcan.md',
+ 'docs/zauth/vector.md',
+ 'docs/zauth/database.md',
+ 'docs/authentication.md',
+ 'docs/permissions.md',
+ 'docs/security.md',
+ ],
+ },
+ {
+ title: 'On-chain identity & reputation',
+ files: [
+ 'docs/onchain-agents.md',
+ 'docs/erc8004.md',
+ 'docs/erc8004/validation-attestation.md',
+ 'docs/smart-contracts.md',
+ 'docs/reputation.md',
+ 'docs/mint-mark.md',
+ ],
+ },
+ {
+ title: 'x402 — agents paying agents',
+ files: [
+ 'docs/x402.md',
+ 'docs/pay-skills-listing.md',
+ 'docs/api/forge-x402.md',
+ 'docs/aws-builder-center-marketplace-x402.md',
+ 'docs/do-i-need-crypto.md',
+ ],
+ },
+ {
+ title: 'Solana & pump.fun',
+ files: [
+ 'docs/solana.md',
+ 'docs/solana-pumpfun.md',
+ 'docs/pump-platform-fee.md',
+ ],
+ },
+ {
+ title: 'pump.fun program reference (protocol)',
+ files: [
+ 'docs/pumpfun-program/README.md',
+ 'docs/pumpfun-program/UPSTREAM-buy-sell-v2-announcement.md',
+ 'docs/pumpfun-program/docs/PUMP_PROGRAM_README.md',
+ 'docs/pumpfun-program/docs/PUMP_SWAP_README.md',
+ 'docs/pumpfun-program/docs/PUMP_SWAP_SDK_README.md',
+ 'docs/pumpfun-program/docs/CPI_README.md',
+ 'docs/pumpfun-program/docs/FAQ.md',
+ 'docs/pumpfun-program/docs/FEE_PROGRAM_README.md',
+ 'docs/pumpfun-program/docs/FEE_RECIPIENTS.md',
+ 'docs/pumpfun-program/docs/BREAKING_FEE_RECIPIENT.md',
+ 'docs/pumpfun-program/docs/PUMP_CASHBACK_README.md',
+ 'docs/pumpfun-program/docs/PUMP_CREATOR_FEE_README.md',
+ 'docs/pumpfun-program/docs/PUMP_SWAP_CREATOR_FEE_README.md',
+ 'docs/pumpfun-program/docs/instructions/BUY.md',
+ 'docs/pumpfun-program/docs/instructions/SELL.md',
+ 'docs/pumpfun-program/docs/instructions/COIN_CREATION.md',
+ 'docs/pumpfun-program/docs/instructions/COLLECT_CREATOR_FEE.md',
+ 'docs/pumpfun-program/docs/instructions/CREATOR_FEE_SHARING.md',
+ 'docs/pumpfun-program/docs/instructions/CLAIM_CASHBACK.md',
+ ],
+ },
+ {
+ title: 'Use cases — AI + crypto',
+ files: [
+ 'docs/content/use-cases/ai-agent-developer.md',
+ 'docs/content/use-cases/crypto-community.md',
+ ],
+ },
+ {
+ title: 'Hands-on tutorials — AI brains, skills & on-chain',
+ files: [
+ 'docs/tutorials/connect-ai-brain.md',
+ 'docs/tutorials/agent-personality.md',
+ 'docs/tutorials/greeting-and-first-speech.md',
+ 'docs/tutorials/custom-skill.md',
+ 'docs/tutorials/skill-with-database-auth.md',
+ 'docs/tutorials/multi-agent-coordination.md',
+ 'docs/tutorials/mcp-server-for-your-agent.md',
+ 'docs/tutorials/mint-pumpfun-token.md',
+ 'docs/tutorials/paid-x402-endpoint.md',
+ 'docs/tutorials/register-onchain.md',
+ ],
+ },
+];
+
+// Unambiguous operating-rule / internal-process markers. These describe how we
+// build, not what we build, and must never reach the notebook. We refuse to emit
+// a file that contains one rather than silently leaking it into the source.
+const FORBIDDEN = [
+ /no mocks/i,
+ /no fake data/i,
+ /prime directive/i,
+ /definition of done/i,
+ /self-review protocol/i,
+ /interview the user/i,
+];
+
+const missing = [];
+const tainted = [];
+
+const sections = [];
+let seq = 0;
+for (const cat of CATEGORIES) {
+ for (const path of cat.files) {
+ if (!existsSync(path)) {
+ missing.push(path);
+ continue;
+ }
+ const raw = readFileSync(path, 'utf8');
+ const hit = FORBIDDEN.find((re) => re.test(raw));
+ if (hit) {
+ tainted.push(`${path} (matched ${hit})`);
+ continue;
+ }
+ seq += 1;
+ sections.push({
+ path,
+ category: cat.title,
+ anchor: `sec-${String(seq).padStart(3, '0')}`,
+ body: raw.replace(/\s+$/, ''),
+ });
+ }
+}
+
+if (missing.length) {
+ console.error('Allowlisted docs not found — fix the path in CATEGORIES:');
+ for (const m of missing) console.error(` - ${m}`);
+ process.exit(1);
+}
+if (tainted.length) {
+ console.error('Allowlisted docs contain operating-rule language (excluded — move the rule out of the doc, or drop the doc):');
+ for (const t of tainted) console.error(` - ${t}`);
+ process.exit(1);
+}
+
+// Thematic table of contents.
+const tocLines = [];
+for (const cat of CATEGORIES) {
+ const inCat = sections.filter((s) => s.category === cat.title);
+ if (!inCat.length) continue;
+ tocLines.push(`\n### ${cat.title}\n`);
+ for (const s of inCat) tocLines.push(`- [${s.path.replace(/^docs\//, '')}](#${s.anchor})`);
+}
+
+const totalBytes = sections.reduce((n, s) => n + Buffer.byteLength(s.body), 0);
+const stamp = new Date().toISOString().slice(0, 10);
+
+const header = `<!-- GENERATED by scripts/combine-docs-ai-crypto.mjs — do not edit by hand. Edit the source files under docs/ and re-run. -->
+# three.ws — AI & On-Chain Knowledge Base
+
+> A curated single-file source covering only the **AI-agent** and **crypto / blockchain** concepts behind three.ws — built for use as a NotebookLM (or other RAG) source. Generated ${stamp} from **${sections.length} documents** (~${Math.round(totalBytes / 1024)} KB).
+>
+> **Scope, on purpose.** This file is about *what three.ws is and what it lets agents do*: autonomous AI agents, LLM brains, MCP tooling, skills, memory, on-chain identity (ERC-8004 / Metaplex Core), reputation, x402 agent-to-agent payments, Solana, and the pump.fun protocol. The platform's 3D-world / metaverse / avatar / viewer / embedding surfaces and all internal engineering-process material (build briefs, roadmaps, status logs, deploy runbooks, operating rules) are **intentionally excluded** so a notebook built on this source discusses the product, not how it is built.
+>
+> The individual source files under \`docs/\` remain the canonical, editable copies — this is a read-only aggregate.
+
+## Table of contents
+${tocLines.join('\n')}
+
+---
+`;
+
+const bodyOut = sections
+ .map(
+ (s) =>
+ `<a id="${s.anchor}"></a>\n\n> **Topic:** ${s.category} · **Source:** \`${s.path}\` · [↑ table of contents](#table-of-contents)\n\n${s.body}`,
+ )
+ .join('\n\n---\n\n');
+
+writeFileSync(`${ROOT}/${OUT}`, `${header}\n${bodyOut}\n`);
+console.log(`Wrote ${OUT}: ${sections.length} docs, ${Math.round(totalBytes / 1024)} KB combined.`);
diff --git a/scripts/finalize-prune.mjs b/scripts/finalize-prune.mjs
new file mode 100644
index 000000000..7e6d62804
--- /dev/null
+++ b/scripts/finalize-prune.mjs
@@ -0,0 +1,46 @@
+#!/usr/bin/env node
+// Parse the verify-and-prune workflow result, persist verdicts, and sweep-delete
+// every file verified `done` that still exists. Keeps partial/pending.
+import { readFileSync, writeFileSync, existsSync, rmSync } from 'node:fs';
+
+const OUT = process.argv[2];
+const wrapper = JSON.parse(readFileSync(OUT, 'utf8'));
+const data = wrapper.result || wrapper;
+const results = data.results || [];
+if (!results.length) { console.error('no results in output'); process.exit(1); }
+
+const byVerdict = v => results.filter(r => r.verdict === v);
+const done = byVerdict('done'), partial = byVerdict('partial'), pending = byVerdict('pending');
+
+// persist full verdicts
+writeFileSync('reports/task-completion-verified.json', JSON.stringify(results, null, 2));
+
+// SWEEP: delete every done file still on disk
+let deletedNow = 0, alreadyGone = 0;
+const deletedManifest = [];
+for (const r of done) {
+ if (existsSync(r.file)) { rmSync(r.file); deletedNow++; deletedManifest.push(r.file); }
+ else { alreadyGone++; }
+}
+writeFileSync('reports/deleted-done-manifest.txt',
+ '# Files deleted because verified DONE (this run + sweep)\n' + done.map(r => r.file).sort().join('\n') + '\n');
+writeFileSync('reports/kept-partial.txt',
+ partial.map(r => `${r.file}\t${r.confidence}\t${(r.missing||'').replace(/\s+/g,' ').slice(0,200)}`).join('\n') + '\n');
+writeFileSync('reports/kept-pending.txt',
+ pending.map(r => `${r.file}\t${r.confidence}\t${(r.missing||'').replace(/\s+/g,' ').slice(0,200)}`).join('\n') + '\n');
+
+// group breakdown
+const groups = {};
+for (const r of results) {
+ const g = r.file.split('/').slice(0, 2).join('/');
+ groups[g] ||= { done: 0, partial: 0, pending: 0 };
+ groups[g][r.verdict]++;
+}
+
+console.log(`VERIFIED: done=${done.length} partial=${partial.length} pending=${pending.length} total=${results.length}`);
+console.log(`SWEEP: deleted now=${deletedNow}, already gone (deleted earlier/by fleet)=${alreadyGone}`);
+console.log(`\nTop groups still needing work (partial+pending):`);
+Object.entries(groups)
+ .map(([g, c]) => [g, c.partial + c.pending, c])
+ .filter(x => x[1] > 0).sort((a, b) => b[1] - a[1]).slice(0, 18)
+ .forEach(([g, n, c]) => console.log(` ${String(n).padStart(3)} open (${c.partial}p/${c.pending}P, ${c.done}done) ${g}`));
diff --git a/tasks/monetization-feature/03-backend-seed-skill-pricing-data.md b/tasks/monetization-feature/03-backend-seed-skill-pricing-data.md
deleted file mode 100644
index 037c8c95e..000000000
--- a/tasks/monetization-feature/03-backend-seed-skill-pricing-data.md
+++ /dev/null
@@ -1,95 +0,0 @@
----
-status: completed
----
-
-# Prompt 3: Backend - Seed Skill Pricing Data
-
-## Objective
-Populate the database with sample data for free and paid skills to enable frontend development and testing.
-
-## Explanation
-With the `agent_skill_prices` table created, we now need some data to work with. A seed script will allow us to consistently create a set of test skills with and without prices. This is crucial for developers working on the UI to be able to see and test all variations of the design.
-
-## Instructions
-1. **Create a Seed Script:**
- * Create a new script in your `scripts/` directory (e.g., `seed-skills.mjs`).
- * The script should connect to your database.
- * It should first create a sample creator user and a few sample skills.
- * Then, for some of those skills, it should insert corresponding entries into the `agent_skill_prices` table.
- * Include at least one free skill (no entry in the prices table) and two paid skills with different prices.
-
-2. **Run the Script:**
- * Execute the script to populate your local database.
- * Make sure to document how to run the script in your project's `README.md`.
-
-## Code Example (Node.js Seeding Script)
-
-```javascript
-// In scripts/seed-skills.mjs
-import { db } from '../api/_lib/db.js'; // Adjust path to your db connection
-
-async function main() {
- console.log('Seeding database...');
-
- // 1. Create a sample creator
- const { rows: [creator] } = await db.query(
- `INSERT INTO users (username, email) VALUES ($1, $2)
- ON CONFLICT (email) DO UPDATE SET username = $1 RETURNING id`,
- ['skill_creator_1', '[email protected]']
- );
- console.log(`Created/found creator user: ${creator.id}`);
-
- // 2. Create some skills
- const { rows: [skill1] } = await db.query(
- `INSERT INTO skills (name, description, creator_id) VALUES ($1, $2, $3) RETURNING id`,
- ['Advanced Market Analysis', 'Provides deep insights into token velocity.', creator.id]
- );
- const { rows: [skill2] } = await db.query(
- `INSERT INTO skills (name, description, creator_id) VALUES ($1, $2, $3) RETURNING id`,
- ['Rug-Pull Detection', 'Flags high-risk tokens using on-chain data.', creator.id]
- );
- const { rows: [skill3] } = await db.query(
- `INSERT INTO skills (name, description, creator_id) VALUES ($1, $2, $3) RETURNING id`,
- ['Wave', 'A simple social emote.', creator.id] // This one will be free
- );
- console.log('Created sample skills.');
-
- // 3. Set prices for paid skills (USDC mint on Solana Mainnet)
- const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6a';
-
- await db.query(
- `INSERT INTO agent_skill_prices (skill_id, creator_id, amount, currency_mint)
- VALUES ($1, $2, $3, $4) ON CONFLICT (skill_id, creator_id) DO NOTHING`,
- [skill1.id, creator.id, 2_000_000, USDC_MINT] // 2 USDC
- );
-
- await db.query(
- `INSERT INTO agent_skill_prices (skill_id, creator_id, amount, currency_mint)
- VALUES ($1, $2, $3, $4) ON CONFLICT (skill_id, creator_id) DO NOTHING`,
- [skill2.id, creator.id, 5_000_000, USDC_MINT] // 5 USDC
- );
- console.log('Set prices for paid skills.');
-
- console.log('Seeding complete.');
- await db.end();
-}
-
-main().catch(err => {
- console.error('Seeding failed:', err);
- process.exit(1);
-});
-```
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "tasks/monetization-feature/03-backend-seed-skill-pricing-data.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/tasks/monetization-feature/08-backend-gate-skill-usage.md b/tasks/monetization-feature/08-backend-gate-skill-usage.md
deleted file mode 100644
index 5d298d18f..000000000
--- a/tasks/monetization-feature/08-backend-gate-skill-usage.md
+++ /dev/null
@@ -1,68 +0,0 @@
----
-status: not-started
----
-
-# Prompt 8: Gate Skill Usage on Backend
-
-**Status:** Not Started
-
-## Objective
-Modify the agent action/chat endpoint to verify that a user owns a paid skill before allowing its execution.
-
-## Explanation
-This is the core enforcement mechanism. When a user tries to use a skill (e.g., via a chat command), the backend must check two things: 1) if the skill is a paid skill, and 2) if the user has purchased it. If it's a paid skill and the user hasn't bought it, the request should be denied with an appropriate message.
-
-## Instructions
-- [ ] **Locate the main agent action endpoint** (e.g., `/api/chat.js` or `/api/agent-actions.js`).
-- [ ] **Modify the Logic:**
- - [ ] When a request to execute a skill comes in, get the `agentId`, `skillName`, and the authenticated `userId`.
- - [ ] First, query `agent_skill_prices` to see if the requested `(agentId, skillName)` has a price.
- - [ ] If it does not have a price, it's a free skill, so proceed with execution as normal.
- - [ ] If it *does* have a price, you must then query the `skill_purchases` table to see if a record exists for `(userId, agentId, skillName)`.
- - [ ] If a purchase record exists, proceed with execution.
- - [ ] If no purchase record exists, return an error response (e.g., HTTP 402 Payment Required).
-- [ ] **Optimize the query:** You can combine these checks into a single, more efficient SQL query.
-
-## Code Example (Conceptual Node.js in `/api/chat.js`)
-
-```javascript
-// ... inside the chat handler, before executing the skill ...
-
-const { agentId, skillName, ... } = req.body;
-const user = await getSessionUser(req);
-
-// Check if the skill is priced
-const [priceInfo] = await sql`SELECT amount FROM agent_skill_prices WHERE agent_id = ${agentId} AND skill_name = ${skillName}`;
-
-if (priceInfo) {
- // It's a paid skill, now check for ownership
- if (!user) {
- return res.status(402).json({ error: 'This is a premium skill. Please sign in to purchase.' });
- }
-
- const [purchase] = await sql`
- SELECT id FROM skill_purchases
- WHERE user_id = ${user.id} AND agent_id = ${agentId} AND skill_name = ${skillName}`;
-
- if (!purchase) {
- return res.status(402).json({ error: `You must purchase the '${skillName}' skill to use it.` });
- }
-}
-
-// If we reach here, the user is authorized to use the skill.
-// ... proceed to execute the skill ...
-```
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "tasks/monetization-feature/08-backend-gate-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/tasks/monetization-feature/09-construct-solana-transaction.md b/tasks/monetization-feature/09-construct-solana-transaction.md
deleted file mode 100644
index de491b31e..000000000
--- a/tasks/monetization-feature/09-construct-solana-transaction.md
+++ /dev/null
@@ -1,111 +0,0 @@
-# Prompt 9: Construct Solana Transaction
-
-## Objective
-On the frontend, write a function that constructs a Solana transaction to transfer the required amount of USDC from the user's wallet to the agent creator's wallet.
-
-## Explanation
-A Solana transaction is a set of instructions that the user must sign. For a simple SPL-token payment (like USDC), the main instruction is a `Token.createTransferInstruction`. This instruction needs several pieces of information:
-- The user's (source) USDC token account address.
-- The creator's (destination) USDC token account address.
-- The user's main wallet address (the owner of the source account).
-- The amount to transfer.
-- The SPL Token Program ID.
-
-Our task is to gather this information and build the transaction object, which we'll then pass to the wallet for signing in the next step. A key challenge is finding the user's and creator's *USDC-specific token accounts*, not just their main wallet addresses.
-
-## Instructions
-1. **Create a Transaction Builder Function:**
- * In `src/marketplace.js`, create a new `async` function called `buildUsdcTransferTransaction`.
- * It should accept the `intent` object (which contains the recipient's main wallet address, amount, and currency mint) and the `payerPublicKey` (the connected user's wallet public key).
-
-2. **Find Associated Token Accounts (ATAs):**
- * The standard way to hold tokens on Solana is in "Associated Token Accounts." We can derive the address of these accounts if we have the main wallet address and the token mint address.
- * Use the `solanaWeb3.PublicKey.findProgramAddress` or a helper from `@solana/spl-token` to find the payer's and recipient's USDC ATAs. The `spl-token` library provides `getAssociatedTokenAddress`.
-
-3. **Handle Missing Recipient ATA:**
- * The recipient might not have a USDC account yet. A robust solution creates the account for them within the same transaction. The `spl-token` library has an instruction for this: `createAssociatedTokenAccountInstruction`. Check if the recipient's ATA exists, and if not, add this instruction to the transaction.
-
-4. **Create the Transfer Instruction:**
- * Use the `spl-token` library's `createTransferInstruction` to build the core payment instruction.
- * You'll need the source ATA, destination ATA, payer's public key (as the owner), and the amount from the intent.
-
-5. **Assemble the Transaction:**
- * Create a new `solanaWeb3.Transaction`.
- * Add the `createAssociatedTokenAccountInstruction` if it was needed.
- * Add the `createTransferInstruction`.
- * Set the `feePayer` to the `payerPublicKey`.
- * Fetch a recent blockhash from the `solanaConnection` and assign it to the transaction's `recentBlockhash`.
- * Return the fully constructed transaction object.
-
-## Code Example (Frontend - `src/marketplace.js`)
-
-**Note:** This is complex and requires the SPL Token library. Assume you have it available via a script tag.
-`<script src="https://unpkg.com/@solana/[email protected]/lib/index.iife.js"></script>`
-
-```javascript
-// Add this helper function to marketplace.js
-const { TOKEN_PROGRAM_ID } = splToken;
-
-async function buildUsdcTransferTransaction(intent, payerPublicKey) {
- const { recipient_address, amount, currency_mint } = intent;
-
- const transaction = new solanaWeb3.Transaction();
-
- const mintPublicKey = new solanaWeb3.PublicKey(currency_mint);
- const recipientPublicKey = new solanaWeb3.PublicKey(recipient_address);
-
- // 1. Get or create the recipient's associated token account
- const recipientAta = await splToken.getAssociatedTokenAddress(
- mintPublicKey,
- recipientPublicKey
- );
- const recipientAtaInfo = await solanaConnection.getAccountInfo(recipientAta);
- if (!recipientAtaInfo) {
- transaction.add(
- splToken.createAssociatedTokenAccountInstruction(
- payerPublicKey,
- recipientAta,
- recipientPublicKey,
- mintPublicKey
- )
- );
- }
-
- // 2. Get the payer's associated token account
- const payerAta = await splToken.getAssociatedTokenAddress(
- mintPublicKey,
- payerPublicKey
- );
-
- // 3. Create the transfer instruction
- transaction.add(
- splToken.createTransferInstruction(
- payerAta,
- recipientAta,
- payerPublicKey,
- parseInt(amount)
- )
- );
-
- // 4. Set the fee payer and recent blockhash
- transaction.feePayer = payerPublicKey;
- const { blockhash } = await solanaConnection.getRecentBlockhash();
- transaction.recentBlockhash = blockhash;
-
- return 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 "tasks/monetization-feature/09-construct-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/tasks/monetization-feature/17-invoicing-and-receipts.md b/tasks/monetization-feature/17-invoicing-and-receipts.md
deleted file mode 100644
index ec92053ad..000000000
--- a/tasks/monetization-feature/17-invoicing-and-receipts.md
+++ /dev/null
@@ -1,42 +0,0 @@
----
-status: not-started
----
-
-# Prompt 17: Invoicing and Receipts
-
-**Status:** Not Started
-
-## Objective
-Generate a simple invoice or receipt for each purchase and make it accessible to the user.
-
-## Explanation
-For accounting and record-keeping, users should be able to get a receipt for their purchases.
-
-## Instructions
-- [ ] **After a successful purchase, generate a receipt.** This can be done in the backend.
-- [ ] **The receipt should contain:**
- - A unique invoice number.
- - Date of purchase.
- - Buyer and seller (creator) details.
- - A description of the item (e.g., "Skill: text-to-speech for Agent X").
- - The price paid.
- - The transaction signature.
-- [ ] **Store the receipt.** You can store it as a JSON object in a new `receipts` table or as a PDF in cloud storage.
-- [ ] **Modify the User Purchase History page.**
- - Add a "View Receipt" link or button to each entry in the history table.
-- [ ] **Create an API endpoint to fetch a single receipt** (e.g., `GET /api/receipts/:id`).
-- [ ] **When a user clicks "View Receipt", display the receipt details** in a clean, printable format.
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "tasks/monetization-feature/17-invoicing-and-receipts.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/tasks/monetization-feature/18-revenue-stats-ui.md b/tasks/monetization-feature/18-revenue-stats-ui.md
deleted file mode 100644
index 4e50ecb6c..000000000
--- a/tasks/monetization-feature/18-revenue-stats-ui.md
+++ /dev/null
@@ -1,127 +0,0 @@
-# Prompt 18: Revenue Stats API and UI
-
-## Objective
-Create a backend API endpoint to calculate and return key revenue statistics for a user, and then display these stats in the new Revenue Dashboard.
-
-## Explanation
-A high-level overview is the most important part of a dashboard. We need to provide creators with key metrics like their current balance, total lifetime revenue, and recent earnings. This requires a backend endpoint that can efficiently query the `agent_revenue_events` table and aggregate the data.
-
-## Instructions
-1. **Create the Backend API Endpoint:**
- * Create a new file: `/api/billing/revenue-stats.js`.
- * This `GET` endpoint must be authenticated.
- * It should query the `agent_revenue_events` table, joined with `agent_identities` to filter by the current `user_id`.
- * Use SQL aggregate functions (`SUM`, `COUNT`) to calculate:
- * `total_revenue_gross`: The sum of `gross_amount` for all time.
- * `total_revenue_net`: The sum of `net_amount` for all time.
- * `earnings_last_30_days`: The sum of `net_amount` where `created_at` is within the last 30 days.
- * `current_balance`: The sum of `net_amount` minus the sum of all withdrawals for this user (from `agent_withdrawals` table).
- * Return these values in a JSON object.
-
-2. **Update the Frontend Dashboard:**
- * In `public/dashboard/dashboard.js`, modify the `renderRevenue` function.
- * After rendering the initial HTML shell, make a `fetch` call to your new `/api/billing/revenue-stats` endpoint.
- * Create a new function, e.g., `renderStats(stats)`, that takes the API response and generates the HTML for a grid of stat cards.
- * Each card should display a label (e.g., "Net Lifetime Revenue") and the formatted value. Make sure to convert amounts from the smallest unit to a human-readable currency format (e.g., divide by 1,000,000 for USDC and format with a dollar sign).
- * Handle loading and error states gracefully.
-
-## Code Example (Backend - `/api/billing/revenue-stats.js`)
-
-```javascript
-import { sql } from '../_lib/db.js';
-import { getSessionUser } from '../_lib/auth.js';
-import { json, wrap, error } from '../_lib/http.js';
-
-export default wrap(async (req, res) => {
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized');
-
- // This query is complex and joins multiple tables.
- // For simplicity, we'll do separate queries. A single, more optimized query is better in production.
-
- const [revenue] = await sql`
- SELECT
- SUM(rev.net_amount) AS total_net,
- SUM(CASE WHEN rev.created_at >= NOW() - INTERVAL '30 days' THEN rev.net_amount ELSE 0 END) AS last_30_days
- FROM agent_revenue_events rev
- JOIN agent_identities ai ON rev.agent_id = ai.id
- WHERE ai.user_id = ${user.id}
- `;
-
- const [withdrawals] = await sql`
- SELECT SUM(amount) AS total_withdrawn
- FROM agent_withdrawals
- WHERE user_id = ${user.id} AND status = 'completed'
- `;
-
- const total_net = BigInt(revenue.total_net || 0);
- const total_withdrawn = BigInt(withdrawals.total_withdrawn || 0);
- const current_balance = total_net - total_withdrawn;
-
- return json(res, 200, {
- total_revenue_net: String(total_net),
- earnings_last_30_days: String(revenue.last_30_days || 0),
- current_balance: String(current_balance),
- });
-});
-```
-
-## Code Example (Frontend - `public/dashboard/dashboard.js`)
-
-```javascript
-async function renderRevenue(root) {
- root.innerHTML = `
- <div class="page-header">
- <h1>Revenue</h1>
- <p class="sub">Track your earnings from paid agent skills.</p>
- </div>
- <div class="stats-grid" id="revenue-stats-grid">
- <div class="stat-card">Loading...</div>
- </div>
- <div id="revenue-events-table-container"></div>
- `;
-
- try {
- const stats = await api.getRevenueStats(); // Assumes an api helper exists
- renderRevenueStats(stats);
- } catch (e) {
- document.getElementById('revenue-stats-grid').innerHTML = `<div class="err">Failed to load stats: ${e.message}</div>`;
- }
-}
-
-function renderRevenueStats(stats) {
- const grid = document.getElementById('revenue-stats-grid');
-
- const formatUSDC = (amount) => `$${(Number(amount) / 1e6).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
-
- grid.innerHTML = `
- <div class="stat-card">
- <div class="label">Current Balance</div>
- <div class="value green">${formatUSDC(stats.current_balance)}</div>
- </div>
- <div class="stat-card">
- <div class="label">Net Earnings (30 Days)</div>
- <div class="value">${formatUSDC(stats.earnings_last_30_days)}</div>
- </div>
- <div class="stat-card">
- <div class="label">Lifetime Net Revenue</div>
- <div class="value">${formatUSDC(stats.total_revenue_net)}</div>
- </div>
- `;
-}
-```
-You would also need to add a helper for `/api/billing/revenue-stats` to your `api` object in `dashboard.js`.
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "tasks/monetization-feature/18-revenue-stats-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/tasks/monetization-feature/23-localization-currency.md b/tasks/monetization-feature/23-localization-currency.md
deleted file mode 100644
index fbad2acab..000000000
--- a/tasks/monetization-feature/23-localization-currency.md
+++ /dev/null
@@ -1,50 +0,0 @@
----
-status: not-started
----
-# Prompt 23: Price Localization
-
-**Status:** Not Started
-
-## Objective
-Display skill prices in the user's local currency (e.g., USD) in addition to the cryptocurrency (e.g., USDC).
-
-## Explanation
-Showing prices in a familiar fiat currency makes them easier for users to understand and can increase the likelihood of a purchase. This requires integrating a third-party API to fetch real-time conversion rates.
-
-## Instructions
-1. **Choose a currency conversion API** (e.g., CoinGecko, an exchange API).
-2. **Backend: Create a new microservice or a cached API endpoint (`/api/prices/conversion-rates`)** that fetches the current price of SOL, USDC, etc., in USD.
- - Cache the results for 5-10 minutes to avoid hitting API rate limits.
-3. **Frontend: In the marketplace, fetch the conversion rates from this new endpoint.**
-4. **When rendering a price, calculate and display the USD equivalent.**
- - Store the conversion rates globally so you don't have to re-fetch on every render.
-5. **Update the UI to show both prices, or allow the user to toggle.**
-
-## Code Example (Frontend - displaying converted price)
-```javascript
-// Assume 'rates' is { "USDC": 1.00, "SOL": 150.25 }
-// Assume 'price' is { amount: 1500000, currency_mint: "EPj..." (USDC) }
-
-const cryptoAmount = price.amount / 1e6; // 1.5
-const rate = rates['USDC']; // 1.00
-const usdAmount = cryptoAmount * rate;
-
-const priceDisplay = `${cryptoAmount.toFixed(2)} USDC (~$${usdAmount.toFixed(2)} USD)`;
-
-// Render priceDisplay in the UI
-```
-This small change can significantly improve the user experience for a global audience.
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "tasks/monetization-feature/23-localization-currency.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/tasks/site-overhaul/D-new-features/D04-shareable-og-cards.md b/tasks/site-overhaul/D-new-features/D04-shareable-og-cards.md
deleted file mode 100644
index 2380ab4b2..000000000
--- a/tasks/site-overhaul/D-new-features/D04-shareable-og-cards.md
+++ /dev/null
@@ -1,42 +0,0 @@
-# D04 — Shareable agent/coin OG cards + share sheet
-
-**Track:** New Features · **Size:** M · **Priority:** P2
-
-## Goal
-Every agent, avatar, and coin page gets a beautiful auto-generated social share image (OG card)
-and a one-tap share sheet — so anything on the platform is screenshot-and-share ready.
-
-## Why it matters
-`CLAUDE.md` quality bar: "What would make someone screenshot this and share it?" Great OG cards
-are free distribution; right now links shared to X/Discord likely render plain.
-
-## Context
-- Dynamic OG images can be generated by a Vercel function (e.g. `@vercel/og` / satori) per agent/coin, pulling real data (name, avatar render, on-chain badge, key stats).
-- On-chain badge is a shared module (memory: `src/shared/onchain-badge.js`) — reflect it on the card.
-- Honest data only.
-
-## Scope
-- An OG-image endpoint (`api/og/[type].js`) rendering a branded card for agents/avatars/coins from real data; wire `<meta og:image>`/Twitter tags on the respective pages.
-- A share sheet component (copy link, X, Discord, download image) on those pages.
-- Designed fallback when an entity has no avatar/image yet.
-- three.ws branding consistent with Track B; `$THREE` only.
-
-## Definition of done
-- Pasting an agent/coin URL into X/Discord/Slack shows a rich, on-brand card with real data; the on-page share sheet works.
-
-## Verify
-- Use a social-card validator (or the platform's link preview) on 3 real entity URLs; confirm correct, branded images and working share actions.
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "tasks/site-overhaul/D-new-features/D04-shareable-og-cards.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/tasks/site-overhaul/E-improve-features/E01-create-flow-whats-next.md b/tasks/site-overhaul/E-improve-features/E01-create-flow-whats-next.md
deleted file mode 100644
index d720dcc84..000000000
--- a/tasks/site-overhaul/E-improve-features/E01-create-flow-whats-next.md
+++ /dev/null
@@ -1,42 +0,0 @@
-# E01 — `/create` → a connected "what's next" path
-
-**Track:** Improve Features · **Size:** M · **Priority:** P1
-
-## Goal
-After a user creates an avatar, guide them into the next valuable step (give it a brain → embed →
-optional: own/monetize) instead of dead-ending at "you made a model."
-
-## Why it matters
-The audit: the create flow is clear (8/10) but "doesn't explain what happens after creation, no
-sense of progression to 'agent'." The drop-off between "made an avatar" and "has a useful agent"
-is where users are lost.
-
-## Context
-- Entry: [pages/create.html](pages/create.html) and the sub-flows (`/create/selfie`, `/scan`, `/forge`, `/avatar-studio`).
-- Memory: selfie handoff to `/create/selfie` via sessionStorage `threews:selfie-handoff` — preserve it.
-- Pairs with C03 (getting started) and D07 (embed wizard).
-
-## Scope
-- A post-creation "next steps" surface presenting the progression: name + brain → embed → optional own/monetize. Each step is a real, working link with a one-line plain benefit.
-- Show the user their just-created avatar in context (carry the real artifact, not a placeholder).
-- Make "give it an AI brain" and "embed it" the primary next actions; crypto steps marked optional.
-
-## Definition of done
-- Finishing any create sub-flow lands the user on a guided next-steps screen wired to real follow-on actions, with their actual new avatar shown.
-
-## Verify
-- Complete `/scan` and `/forge`; confirm the next-steps screen shows the real result and its CTAs work.
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "tasks/site-overhaul/E-improve-features/E01-create-flow-whats-next.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/tasks/walk/06-chrome-extension-content-script.md b/tasks/walk/06-chrome-extension-content-script.md
deleted file mode 100644
index c5b8b81c4..000000000
--- a/tasks/walk/06-chrome-extension-content-script.md
+++ /dev/null
@@ -1,41 +0,0 @@
-# Task 06 — Chrome Extension: Content Script Avatar Injection
-
-## Priority: URGENT
-
-## Objective
-Implement the content script that injects the walking avatar iframe into any website the user is browsing, with the avatar appearing as a persistent floating character in the corner of the page.
-
-## Scope
-- File: `extensions/walk-avatar/content.js`
-- On activation (message from background): create a fixed-position `<iframe>` pointing to `https://three.ws/walk-embed?avatar=<id>&controls=joystick&bg=transparent`
-- iframe must be sandboxed appropriately: `allow="autoplay; scripts; same-origin"`
-- Avatar container: fixed position, bottom-right, 180×260px, z-index 2147483647 (max, above everything)
-- Container is draggable by the user (mousedown/touchstart on a drag handle at top of container)
-- On deactivation (toggle off): remove the iframe cleanly, no DOM residue
-- Handle SPA navigation: listen for `popstate` and `pushState` mutations — do not lose the avatar on client-side route changes
-- On `walk:position` postMessage from iframe: optionally tilt the avatar container slightly based on walk direction (subtle, ±2deg transform)
-- Avatar container has a minimal close × button in the top-right corner
-
-## Definition of Done
-- Avatar appears floating on `google.com`, `github.com`, and any other arbitrary site
-- Drag works on both mouse and touch
-- Close button removes avatar
-- Avatar survives client-side navigation on SPAs (test on twitter.com)
-- No style leakage onto host page
-
-## Rules
-Complete 100%. No stubs. No fake data. Wire every step end-to-end and verify in a real browser with the dev server running.
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "tasks/walk/06-chrome-extension-content-script.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/tasks/walk/13-walk-camera-modes.md b/tasks/walk/13-walk-camera-modes.md
deleted file mode 100644
index 9926d99ce..000000000
--- a/tasks/walk/13-walk-camera-modes.md
+++ /dev/null
@@ -1,43 +0,0 @@
-# Task 13 — Walk Page: Camera Modes (Third / First / Orbit / Cinematic)
-
-## Priority: HIGH
-
-## Objective
-Add four switchable camera modes so users can choose the perspective that fits how they want to experience the walking avatar.
-
-## Scope
-- File: `src/walk.js` + new `src/walk-cameras.js` module
-- Modes:
- 1. **Third-person** (default): camera 4m behind, 1.6m up, looks at avatar head; smoothly follows movement and rotation with critically-damped spring
- 2. **First-person**: camera at avatar's eye position, follows head rotation; avatar mesh culled from view OR rendered with `renderOrder` so own arms/legs visible
- 3. **Orbit**: free orbit around the avatar (existing OrbitControls), no follow
- 4. **Cinematic**: scripted dolly — slowly arcs around avatar at fixed radius; auto-cuts every 5s to a new angle (for screenshot/showcase mode)
-- UI: small camera-mode toggle in top-right HUD, four icons; current mode highlighted; keyboard shortcut `C` cycles modes
-- Mode change is smooth: 600ms lerp from old camera transform to new — no snap
-- Per-mode FOV: third 50°, first 75°, orbit 45°, cinematic 35° (cinematic feel)
-- Each mode persists in `localStorage` as `walk:camera-mode`
-- First-person mode: hide avatar's head mesh (lookup by node name like `Head`, `Wolf3D_Head`) to avoid clipping
-
-## Definition of Done
-- All four modes work and switch smoothly with `C` or HUD button
-- First-person camera does not clip into the head/body
-- Cinematic mode auto-cuts and looks good for at least 60s without breaking
-- Camera mode persists across page reloads
-- No console errors
-
-## Rules
-Complete 100%. No stubs. No fake data. Wire to the existing Three.js scene — do not duplicate scene setup. Verify in a real browser.
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "tasks/walk/13-walk-camera-modes.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/tasks/wow-sprint/04-console-errors-cleanup.md b/tasks/wow-sprint/04-console-errors-cleanup.md
deleted file mode 100644
index 03616591a..000000000
--- a/tasks/wow-sprint/04-console-errors-cleanup.md
+++ /dev/null
@@ -1,46 +0,0 @@
-# Task: Zero console errors & warnings across key pages
-
-Ship-quality apps have a clean console. Drive the real app and eliminate every
-error and warning that originates from our code.
-
-## Scope
-Run `npm run dev` (port 3000) and exercise these routes in a real browser:
-`/`, `/marketplace`, `/agent-home`, `/dashboard`, `/pump-dashboard`,
-`/pricing`, `/skills`, `/walk`, `/club`.
-
-## Method
-1. Open each route, watch the console and network tab through a normal interaction (load, scroll, click primary CTAs).
-2. Catalogue every error and warning. For each, find the source `file:line`.
-3. Fix the root cause, not the symptom:
- - Failed `fetch` → handle the boundary, fix the endpoint path, or add the missing param. Real API only.
- - Undefined variable / null deref → guard correctly or fix the data flow.
- - Three.js warnings (deprecated APIs, missing textures, NaN geometry) → update to current API, fix the asset path.
- - 404s on assets → fix the path or add the asset under `public/`.
- - Hydration/duplicate-id/invalid-nesting HTML warnings → fix the markup.
-4. Ignore warnings that provably originate from third-party libs you can't change — but list them.
-
-## Constraints
-- Do not silence errors by wrapping in empty `try/catch`. Fix the cause.
-- Do not remove features to remove warnings.
-
-## Definition of done
-- Each audited route loads and runs with zero console errors and zero warnings from our code.
-- Network tab: real API calls succeed (or show a designed error state on failure).
-- Run the **completionist** subagent on changed files.
-- Report: before/after console inventory per route.
-
-> Note: this task edits `home.html` / hero code. If running task 07 or 12 in parallel, run this one AFTER them.
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "tasks/wow-sprint/04-console-errors-cleanup.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.