Skip to content

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

feat: redesign /create picker with 'start from yours' lane; prune 145 verified-shipped task specs

nirholas7f51946e2b98
diff --git a/pages/create.html b/pages/create.html
index 441a1ea01..5396aefa7 100644
--- a/pages/create.html
+++ b/pages/create.html
@@ -848,290 +848,202 @@
<script type="module" src="/crypto-optional.js"></script>
<main class="stage" id="main-content">
- <div class="picker-heading">
- <h1>Create new avatar</h1>
- </div>
- <p class="picker-sub">Choose how you want to create your 3D avatar.</p>
- <div class="picker-reassure" data-crypto-optional="compact"></div>
+ <section class="create-hero">
+ <h1 class="create-title">Create your 3D avatar</h1>
+ <p class="create-sub">
+ Pick a starting point. Customize everything in the browser — most
+ paths are free and take about a minute.
+ </p>
+ <div class="picker-reassure" data-crypto-optional="compact"></div>
+ </section>
- <div class="card-grid" role="group" aria-label="Choose avatar creation method">
- <!-- Card 1: Default editor (recommended) -->
- <div
- class="create-card is-recommended"
- id="card-default-editor"
- role="button"
- tabindex="0"
- aria-label="Open avatar web editor (recommended)"
- >
- <span class="recommended-badge" aria-hidden="true">Recommended</span>
- <div class="card-preview">
- <model-viewer
- src="/avatars/default.glb"
- alt="Default 3D avatar preview"
- auto-rotate
- auto-rotate-delay="0"
- rotation-per-second="18deg"
- interaction-prompt="none"
- disable-zoom
- disable-pan
- disable-tap
- shadow-intensity="0.4"
- shadow-softness="0.8"
- exposure="0.95"
- environment-image="neutral"
- camera-orbit="15deg 80deg auto"
- loading="eager"
- ></model-viewer>
- </div>
- <div class="card-icon-row">
- <div class="card-icon" aria-hidden="true">
- <svg
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- stroke-width="1.7"
- stroke-linecap="round"
- stroke-linejoin="round"
- >
- <circle cx="12" cy="8" r="3.5" />
- <path d="M5 20c0-3.87 3.13-7 7-7s7 3.13 7 7" />
- <path d="M18 3l3 3-9 9-4 1 1-4 9-9z" />
- </svg>
- </div>
- <h2 class="card-title">Start with a template</h2>
+ <div class="create-layout">
+ <!-- Returning users: remix one you already made -->
+ <section class="your-avatars" id="your-avatars" hidden aria-label="Your avatars">
+ <div class="your-avatars-head">
+ <h2 class="your-avatars-title">Start from one of yours</h2>
+ <a class="your-avatars-manage" href="/dashboard">Manage all →</a>
</div>
- <p class="card-subtitle">
- Pick a ready-made character and customize it in our web editor. No
- download required.
- </p>
- <span class="card-cta">
- Open editor
- <svg
- width="13"
- height="13"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- stroke-width="2.2"
- stroke-linecap="round"
- stroke-linejoin="round"
- aria-hidden="true"
- >
- <line x1="5" y1="12" x2="19" y2="12" />
- <polyline points="12 5 19 12 12 19" />
- </svg>
- </span>
- </div>
+ <div class="your-avatars-row" id="your-avatars-row"></div>
+ </section>
- <!-- Card 2: three.ws Selfie — photo-to-avatar pipeline -->
- <div
- class="create-card"
- id="card-selfie"
- role="button"
- tabindex="0"
- aria-label="Scan yourself into a 3D avatar with three.ws"
- >
- <div class="card-preview">
- <model-viewer
- src="/avatars/default.glb"
- alt="Selfie-to-avatar preview"
- auto-rotate
- auto-rotate-delay="0"
- rotation-per-second="22deg"
- interaction-prompt="none"
- disable-zoom
- disable-pan
- disable-tap
- shadow-intensity="0.4"
- shadow-softness="0.8"
- exposure="0.95"
- environment-image="neutral"
- camera-orbit="-15deg 80deg auto"
- loading="lazy"
- ></model-viewer>
- </div>
- <div class="card-icon-row">
- <div class="card-icon" aria-hidden="true">
- <svg
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- stroke-width="1.7"
- stroke-linecap="round"
- stroke-linejoin="round"
- >
- <rect x="3" y="5" width="18" height="14" rx="2" />
- <circle cx="12" cy="11" r="3" />
- <path d="M7 19c0-2 2.5-3 5-3s5 1 5 3" />
- </svg>
+ <!-- Recommended: template editor (hero) -->
+ <div
+ class="create-card hero-card is-recommended"
+ id="card-default-editor"
+ role="button"
+ tabindex="0"
+ aria-label="Open avatar web editor (recommended)"
+ >
+ <span class="recommended-badge" aria-hidden="true">Recommended</span>
+ <div class="hero-card-body">
+ <div class="hero-card-text">
+ <div class="card-icon-row">
+ <div class="card-icon" aria-hidden="true">
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
+ <circle cx="12" cy="8" r="3.5" />
+ <path d="M5 20c0-3.87 3.13-7 7-7s7 3.13 7 7" />
+ <path d="M18 3l3 3-9 9-4 1 1-4 9-9z" />
+ </svg>
+ </div>
+ <h2 class="card-title">Start with a template</h2>
+ </div>
+ <p class="card-subtitle">
+ Pick a ready-made character and customize it in our web editor —
+ faces, outfits, colors. No download, nothing to install.
+ </p>
+ <div class="card-meta" aria-hidden="true">
+ <span class="chip">Free</span>
+ <span class="chip">~30 sec</span>
+ <span class="chip chip-ok">No sign-in to try</span>
+ </div>
+ <span class="card-cta">
+ Open editor
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <line x1="5" y1="12" x2="19" y2="12" />
+ <polyline points="12 5 19 12 12 19" />
+ </svg>
+ </span>
+ </div>
+ <div class="hero-card-preview">
+ <model-viewer
+ src="/avatars/default.glb"
+ alt="Default 3D avatar preview"
+ auto-rotate
+ auto-rotate-delay="0"
+ rotation-per-second="18deg"
+ interaction-prompt="none"
+ disable-zoom
+ disable-pan
+ disable-tap
+ shadow-intensity="0.4"
+ shadow-softness="0.8"
+ exposure="0.95"
+ environment-image="neutral"
+ camera-orbit="15deg 80deg auto"
+ loading="eager"
+ ></model-viewer>
+ </div>
</div>
- <h2 class="card-title">Scan yourself to 3D</h2>
</div>
- <p class="card-subtitle">
- Point your camera, hold still. About a minute later: a rigged 3D model you can download, share, and use anywhere.
- </p>
- <span class="card-cta">
- Open the scanner
- <svg
- width="13"
- height="13"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- stroke-width="2.2"
- stroke-linecap="round"
- stroke-linejoin="round"
- aria-hidden="true"
- >
- <line x1="5" y1="12" x2="19" y2="12" />
- <polyline points="12 5 19 12 12 19" />
- </svg>
- </span>
- </div>
- <!-- Card 3: Talking video avatar (paid/approved) -->
- <div
- class="create-card"
- id="card-video-avatar"
- role="button"
- tabindex="0"
- aria-label="Generate a talking avatar video"
- >
- <div class="card-preview card-preview--icon" aria-hidden="true">
- <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round">
- <path d="M15 10l4.553-2.277A1 1 0 0 1 21 8.626v6.748a1 1 0 0 1-1.447.894L15 14" />
- <rect x="3" y="7" width="12" height="10" rx="2" />
- </svg>
- </div>
- <div class="card-icon-row">
- <div class="card-icon" aria-hidden="true">
- <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
- <path d="M15 10l4.553-2.277A1 1 0 0 1 21 8.626v6.748a1 1 0 0 1-1.447.894L15 14" />
- <rect x="3" y="7" width="12" height="10" rx="2" />
- </svg>
+ <div class="secondary-grid" role="group" aria-label="More ways to create">
+ <div class="create-card tile" id="card-selfie" role="button" tabindex="0" aria-label="Scan yourself into a 3D avatar">
+ <div class="card-icon-row">
+ <div class="card-icon" aria-hidden="true">
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
+ <rect x="3" y="5" width="18" height="14" rx="2" />
+ <circle cx="12" cy="11" r="3" />
+ <path d="M7 19c0-2 2.5-3 5-3s5 1 5 3" />
+ </svg>
+ </div>
+ <h2 class="card-title">Scan yourself to 3D</h2>
+ </div>
+ <p class="card-subtitle">
+ Point your camera and hold still. About a minute later: a rigged
+ model you can download and use anywhere.
+ </p>
+ <div class="card-meta" aria-hidden="true">
+ <span class="chip">~1 min</span>
+ <span class="chip chip-auth">Sign-in</span>
+ <span class="chip">Rigged GLB</span>
+ </div>
+ <span class="card-cta card-cta--ghost">
+ Open the scanner
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <line x1="5" y1="12" x2="19" y2="12" />
+ <polyline points="12 5 19 12 12 19" />
+ </svg>
+ </span>
</div>
- <h2 class="card-title">Talking avatar video</h2>
- </div>
- <p class="card-subtitle">
- Upload audio and your avatar lip-syncs to it. Generates a video you can share anywhere.
- </p>
- <span class="card-cta">
- Generate video
- <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
- <line x1="5" y1="12" x2="19" y2="12" />
- <polyline points="12 5 19 12 12 19" />
- </svg>
- </span>
- </div>
-
- <!-- Card 4: Upload GLB -->
- <div
- class="create-card"
- id="card-upload-glb"
- role="button"
- tabindex="0"
- aria-label="Upload a GLB file"
- >
- <div class="card-preview card-preview--icon" aria-hidden="true">
- <svg
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- stroke-width="1.2"
- stroke-linecap="round"
- stroke-linejoin="round"
- aria-hidden="true"
- >
- <polyline points="16 16 12 12 8 16" />
- <line x1="12" y1="12" x2="12" y2="21" />
- <path d="M20.39 18.39A5 5 0 0 0 18 9h-1.26A8 8 0 1 0 3 16.3" />
- </svg>
- </div>
- <div class="card-icon-row">
- <div class="card-icon" aria-hidden="true">
- <svg
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- stroke-width="1.7"
- stroke-linecap="round"
- stroke-linejoin="round"
- >
- <polyline points="16 16 12 12 8 16" />
- <line x1="12" y1="12" x2="12" y2="21" />
- <path d="M20.39 18.39A5 5 0 0 0 18 9h-1.26A8 8 0 1 0 3 16.3" />
- </svg>
+ <div class="create-card tile" id="card-video-avatar" role="button" tabindex="0" aria-label="Generate a talking avatar video">
+ <div class="card-icon-row">
+ <div class="card-icon" aria-hidden="true">
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
+ <path d="M15 10l4.553-2.277A1 1 0 0 1 21 8.626v6.748a1 1 0 0 1-1.447.894L15 14" />
+ <rect x="3" y="7" width="12" height="10" rx="2" />
+ </svg>
+ </div>
+ <h2 class="card-title">Talking avatar video</h2>
+ </div>
+ <p class="card-subtitle">
+ Upload audio and your avatar lip-syncs to it. Generates a video
+ you can share anywhere.
+ </p>
+ <div class="card-meta" aria-hidden="true">
+ <span class="chip chip-auth">Sign-in</span>
+ <span class="chip">Lip-sync</span>
+ </div>
+ <span class="card-cta card-cta--ghost">
+ Generate video
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <line x1="5" y1="12" x2="19" y2="12" />
+ <polyline points="12 5 19 12 12 19" />
+ </svg>
+ </span>
</div>
- <h2 class="card-title">Upload your own GLB</h2>
- </div>
- <p class="card-subtitle">
- Drop a <code>.glb</code> file. Works with any glTF 2.0 model.
- </p>
- <span class="card-cta">
- Choose file
- <svg
- width="13"
- height="13"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- stroke-width="2.2"
- stroke-linecap="round"
- stroke-linejoin="round"
- aria-hidden="true"
- >
- <line x1="5" y1="12" x2="19" y2="12" />
- <polyline points="12 5 19 12 12 19" />
- </svg>
- </span>
- <p class="card-tooltip">
- Need a model? Build one in
- <a href="/studio">three.ws Studio</a>.
- Bringing an avatar from another platform?
- <a href="/import/rpm">Import your existing avatar</a>.
- </p>
- </div>
-
- <!-- Card 5: Agent Avatar Studio (experimental) -->
- <div
- class="create-card"
- id="card-agent-studio"
- role="button"
- tabindex="0"
- aria-label="Try the new Agent Avatar Studio (experimental)"
- >
- <div class="card-preview card-preview--icon" aria-hidden="true">
- <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round">
- <circle cx="12" cy="8" r="3.5" />
- <path d="M5 20c0-3.87 3.13-7 7-7s7 3.13 7 7" />
- <path d="M17 3l2 2-2 2" />
- <path d="M21 5h-4" />
- </svg>
- </div>
- <div class="card-icon-row">
- <div class="card-icon" aria-hidden="true">
- <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
- <circle cx="12" cy="8" r="3.5" />
- <path d="M5 20c0-3.87 3.13-7 7-7s7 3.13 7 7" />
- <path d="M17 3l2 2-2 2" />
- <path d="M21 5h-4" />
- </svg>
+ <div class="create-card tile" id="card-upload-glb" role="button" tabindex="0" aria-label="Upload a GLB file">
+ <div class="card-icon-row">
+ <div class="card-icon" aria-hidden="true">
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
+ <polyline points="16 16 12 12 8 16" />
+ <line x1="12" y1="12" x2="12" y2="21" />
+ <path d="M20.39 18.39A5 5 0 0 0 18 9h-1.26A8 8 0 1 0 3 16.3" />
+ </svg>
+ </div>
+ <h2 class="card-title">Upload your own GLB</h2>
+ </div>
+ <p class="card-subtitle">
+ Already have a model? Drop a <code>.glb</code> file. Works with
+ any glTF 2.0 avatar.
+ </p>
+ <div class="card-meta" aria-hidden="true">
+ <span class="chip">glTF 2.0</span>
+ <span class="chip chip-ok">No sign-in</span>
+ </div>
+ <span class="card-cta card-cta--ghost">
+ Choose file
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <line x1="5" y1="12" x2="19" y2="12" />
+ <polyline points="12 5 19 12 12 19" />
+ </svg>
+ </span>
+ </div>
+ <div class="create-card tile" id="card-agent-studio" role="button" tabindex="0" aria-label="Try the Avatar Studio (beta)">
+ <div class="card-icon-row">
+ <div class="card-icon" aria-hidden="true">
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
+ <circle cx="12" cy="8" r="3.5" />
+ <path d="M5 20c0-3.87 3.13-7 7-7s7 3.13 7 7" />
+ <path d="M17 3l2 2-2 2" />
+ <path d="M21 5h-4" />
+ </svg>
+ </div>
+ <h2 class="card-title">Avatar Studio <span style="font-size:0.7em;opacity:0.5;font-weight:400;">beta</span></h2>
+ </div>
+ <p class="card-subtitle">
+ Build from scratch. Sculpt face and body, pick outfits, add
+ accessories — all in your browser.
+ </p>
+ <div class="card-meta" aria-hidden="true">
+ <span class="chip">Sculpt & dress</span>
+ <span class="chip chip-ok">No sign-in</span>
+ </div>
+ <span class="card-cta card-cta--ghost">
+ Try studio
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <line x1="5" y1="12" x2="19" y2="12" />
+ <polyline points="12 5 19 12 12 19" />
+ </svg>
+ </span>
</div>
- <h2 class="card-title">Avatar Studio <span style="font-size:0.7em;opacity:0.5;font-weight:400;">beta</span></h2>
</div>
- <p class="card-subtitle">
- Build a custom avatar from scratch. Sculpt face and body, pick
- outfits, add accessories — all in your browser.
+
+ <p class="create-footnote">
+ Need a model to upload? Build one in <a href="/studio">three.ws Studio</a>.
+ Bringing an avatar from another platform? <a href="/import/rpm">import it here</a>.
</p>
- <span class="card-cta">
- Try studio
- <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
- <line x1="5" y1="12" x2="19" y2="12" />
- <polyline points="12 5 19 12 12 19" />
- </svg>
- </span>
</div>
- </div>
</main>
<footer class="h-footer-horizon">
diff --git a/src/create.js b/src/create.js
index 1f225e8b6..1c0595fb8 100644
--- a/src/create.js
+++ b/src/create.js
@@ -174,6 +174,65 @@ async function boot() {
e.target.value = '';
await handleGlbFile(file);
});
+
+ loadYourAvatars();
+}
+
+// Returning users with at least one saved avatar get a "Start from one of
+// yours" strip above the cards — each thumbnail remixes that avatar through the
+// same fork path the ?fork= query param uses. Anonymous users (401) and users
+// with no avatars simply never see the strip; it stays hidden.
+async function loadYourAvatars() {
+ const section = document.getElementById('your-avatars');
+ const row = document.getElementById('your-avatars-row');
+ if (!section || !row) return;
+
+ let avatars = [];
+ try {
+ // allowAnonymous: anonymous visitors 401 here by design — apiFetch would
+ // otherwise redirect them to /login, breaking the anonymous create flow.
+ const res = await apiFetch('/api/avatars', { allowAnonymous: true });
+ if (!res.ok) return;
+ avatars = (await res.json()) ?? [];
+ } catch {
+ return; // network/auth issue — leave the strip hidden
+ }
+ if (!Array.isArray(avatars) || avatars.length === 0) return;
+
+ const placeholder =
+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="8" r="4"/><path d="M4 20c0-4 3.58-7 8-7s8 3 8 7"/></svg>';
+
+ const frag = document.createDocumentFragment();
+ for (const av of avatars.slice(0, 8)) {
+ const name = av.display_name || av.name || 'Avatar';
+ const thumb = av.thumbnail_url;
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'ya-thumb';
+ btn.setAttribute('aria-label', `Remix ${name}`);
+
+ const imgWrap = document.createElement('span');
+ imgWrap.className = 'ya-thumb-img';
+ if (thumb) {
+ const img = document.createElement('img');
+ img.src = thumb;
+ img.alt = '';
+ img.loading = 'lazy';
+ imgWrap.appendChild(img);
+ } else {
+ imgWrap.innerHTML = placeholder;
+ }
+
+ const label = document.createElement('span');
+ label.className = 'ya-thumb-label';
+ label.textContent = name;
+
+ btn.append(imgWrap, label);
+ btn.addEventListener('click', () => handleFork(av.id));
+ frag.appendChild(btn);
+ }
+ row.appendChild(frag);
+ section.hidden = false;
}
// Cards are divs with role="button", so we need to wire both click and
diff --git a/tasks/CLEANUP-MANIFEST.md b/tasks/CLEANUP-MANIFEST.md
new file mode 100644
index 000000000..4df4e08bc
--- /dev/null
+++ b/tasks/CLEANUP-MANIFEST.md
@@ -0,0 +1,83 @@
+# Task cleanup — audit manifest
+
+Generated by 17 parallel verification agents (strict bar: DELETE only when every
+Definition-of-done item is verifiably present in current code). 145 specs deleted,
+~200 kept. Deletions are staged (`git rm`), not committed.
+
+## DELETE — 145 specs (feature verified shipped)
+
+### monetization-feature (83) — paid-skills system is fully built
+The marketplace paid-skills flow shipped end-to-end (DB tables `agent_skill_prices`/
+`skill_purchases`, set-price + purchase + access-check APIs, Solana Pay modal,
+on-chain confirm, "✓ Owned" badges). Deleted the 83 sub-task specs whose exact DoD
+is met. Near-duplicate filenames (the swarm wrote many specs per feature) judged
+individually. Representative evidence:
+- 02/03 pricing tables → `api/_lib/schema.sql:1226 agent_skill_prices`, `:1250 skill_purchases`
+- set-price APIs → `api/marketplace/set-skill-price.js`, `api/agents/[id]/skill-prices.js`
+- purchase/confirm → `api/payments/purchase-skill.js`, `api/_lib/purchase-confirm.js`, `api/webhooks/solana-pay.js`
+- access gate → `api/_lib/skill-access.js:hasSkillAccess`
+- UI → `src/marketplace.js:renderDetail`, `src/payment-modal.js`, `pages/marketplace.html #payment-modal-overlay`, `src/components/PriceBadge.js`
+- creator UI → `src/agent-edit.js:renderMonetization`
+- trials/notifications → `api/marketplace/start-trial.js`, `api/_lib/notify.js`, `api/billing/withdrawals/index.js`, `src/dashboard-next/pages/monetize.js`
+
+### agent-monetization (12) — x402 revenue rails shipped
+`01-db-schema, 02-pricing-api, 04-revenue-attribution, 05-payout-wallet-api,
+06-revenue-dashboard-api, 07-withdrawal-api, 09-caller-payment-gate,
+10-revenue-dashboard-ui, 11-withdrawal-ui, 13-agent-marketplace-pricing-display,
+14-sdk-payment-support, 18-e2e-tests`. Evidence: `api/_lib/migrations/2026-04-30-agent-monetization.sql`,
+`api/agents/_id/pricing/*`, `api/billing/{revenue,payout-wallets,withdrawals}/*`,
+`src/skills/index.js:checkPaymentGate`, `sdk/src/agent-client.js`, `tests/agent-monetization.test.js` (25 live tests).
+
+### skills-marketplace (7, whole group) — shipped
+`01-db-schema..07-installed-skills-toolbar`. Evidence: `api/_lib/schema.sql:955 marketplace_skills`,
+`api/skills/*`, `chat/src/SkillsMarketplaceModal.svelte`, seed migration with all 15 slugs,
+`App.svelte` Skills button + installed-skills chip strip.
+
+### wallet-transactions (7, whole group) — shipped
+`01..07`. Evidence: `chat/src/stores.js:walletProvider`, `chat/src/TxApprovalModal.svelte`,
+`chat/src/Toolcall.svelte` tx-result branch, `api/tx/solana/[action].js`,
+`chat/src/tools.js` solana/evm transfer+swap + `walletToolSchema` curated pack.
+
+### pump-dashboard-real-apis (11 of 13) — real-data reskin shipped
+`01..11`. Evidence: `api/agents/featured.js`, `api/wallet/balances.js`,
+`api/pump/price-history.js` (Birdeye), `api/pump/trending.js`, `src/solana/vanity/grinder.js`
+(real WASM keypair), `api/healthz.js`, `api/billing/revenue.js`, `api/api-keys*`,
+config connection probes, `/api/tts/eleven`. (KEEP: 12 — server-side whale/fees/launch alert matching not built.)
+
+### site-overhaul C+D (10) + A06 + B02 (12 total)
+C01 home plain-language, C02 what-is page, C04 glossary+tooltips, C05 features core/optional,
+C07 wallet primer wizard, C08 crypto-optional banner, D01 ⌘K command palette,
+D02 notifications center, D03 template gallery, D08 fiat onramp — all shipped
+(`pages/home.html`, `pages/what-is.html`, `public/glossary.js`, `public/search.js`,
+`public/notifications.js`, `src/templates.js`, `src/shared/add-funds.js`, `src/shared/onchain-primer.js`).
+A06 home-variant reconciliation (canonical `pages/home.html` + redirects) and
+B02 dead-token-system removal (no `--mk-/--pd-/…` tokens remain) both verified.
+
+### walk (4) — shipped slices
+`01-walk-avatar-url-param, 03-walk-embed-iframe, 04-walk-embed-sdk, 21-embed-page-walking-avatar`.
+Evidence: `src/walk.js` avatar URL param, `pages/walk-embed.html`+`src/walk-embed.js`,
+`public/walk-embed-sdk.js`, `src/editor/embed-editor.js` walking mode.
+
+### tasks/ root (8) — test + integration tasks shipped
+`task-01..05` (test suites all exist: `tests/src/runtime.test.js`, `tests/api/mcp.test.js`,
+auth-helpers/siwe/oauth tests, agent-memory tests, agent-skills tests), `task-07`
+(`api/erc8004/register-confirm.js`), `task-08` (`src/runtime/voice-client.js`),
+`task-10` (`api/agent-delegate.js` + MCP `call_agent`).
+
+### wow-sprint (1)
+`01-bug-and-lazy-code-audit` — diagnosis-only task; deliverable `REPORT-01-audit.md` complete.
+
+## KEEP — ~200 specs (a named DoD item is absent or unverifiable)
+Notable genuine gaps surfaced by the audit (still pending work):
+- **NFT skill ownership** (monetization 06/07 nft-collection/minting): `api/agents/[id]/skill-collection.js` is an empty stub; no Metaplex mint.
+- **Creator earnings dashboard** as specced (`earnings.html`/`src/earnings.js`/`creator-dashboard.js`) — built elsewhere under different paths.
+- **Chat endpoint paywall** (monetization 08): `api/chat.js` has no `hasSkillAccess` gate; enforcement lives in client runtime + `api/x402/skill-call.js`.
+- **Subscriptions / Stripe billing** (13–15, 24): no Stripe; subscription schema columns absent.
+- **Multi-currency / fiat conversion** (19/21/23): USDC-only; no SPL dropdown or fiat rates.
+- **Referral first-purchase gate, affiliate share links, fraud/IP checks** (10–12, 18–20).
+- **Most of walk 02, 05–20, 22–50**: named modules (`walk-cameras.js`, `walk-npcs.js`, AR/WebXR, PWA, leaderboard/analytics, docs) not built.
+- **Most of site-overhaul A/B/E/F/G**: open-ended sweeps (console/a11y/perf), `--mk` token deletes incomplete, positioning/partner-kit/docs pages absent.
+- **wow-sprint 02–20**: whole-app passes whose done-state needs a running browser (not code-verifiable), several with real flagged gaps (broken trades-stream, missing shared `three-token-data.js` hook).
+- **task-06** (mcp.js ≤60 lines: actual 90), **task-09** (no `PUT /api/agent-memory`).
+- **agent-monetization 03/08/12/15/16/17/19**: x402 404-vs-409 mismatch, payout-wallet UI section, platform-fee display, cron `SKIP LOCKED`, per-payer rate limit, per-type notif opt-out, security-review artifact.
+- **pump-dashboard 12**: server-side whale/fees/launch alert matching.
diff --git a/tasks/agent-monetization/01-db-schema.md b/tasks/agent-monetization/01-db-schema.md
deleted file mode 100644
index 16a9667df..000000000
--- a/tasks/agent-monetization/01-db-schema.md
+++ /dev/null
@@ -1,104 +0,0 @@
-# Task 01 — Database Schema: Agent Monetization Tables
-
-## Goal
-Add the database tables needed to store per-skill pricing, payment revenue records, and owner payout wallet config. All migrations must be additive (no destructive changes).
-
-## Success Criteria
-- `npm run db:migrate` runs without error
-- All new tables exist with correct columns and constraints
-- Foreign keys reference existing `agent_identities` and `users` tables correctly
-
-## Tables to Create
-
-### `agent_skill_prices`
-Stores the price an agent owner sets for each monetized skill.
-
-```sql
-CREATE TABLE agent_skill_prices (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- agent_id UUID NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,
- skill TEXT NOT NULL, -- skill name, e.g. "answer-question"
- currency_mint TEXT NOT NULL, -- SPL mint or EVM token address
- chain TEXT NOT NULL DEFAULT 'solana', -- "solana" | "base" | "evm"
- amount BIGINT NOT NULL, -- smallest unit (lamports or wei)
- is_active BOOLEAN NOT NULL DEFAULT true,
- created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
- updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
- UNIQUE (agent_id, skill)
-);
-```
-
-### `agent_revenue_events`
-Immutable record written each time a payment intent is consumed. This is the source of truth for earnings.
-
-```sql
-CREATE TABLE agent_revenue_events (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- agent_id UUID NOT NULL REFERENCES agent_identities(id),
- intent_id UUID NOT NULL REFERENCES agent_payment_intents(id),
- skill TEXT NOT NULL,
- gross_amount BIGINT NOT NULL, -- full amount paid by caller (smallest unit)
- fee_amount BIGINT NOT NULL, -- platform fee deducted
- net_amount BIGINT NOT NULL, -- gross_amount - fee_amount
- currency_mint TEXT NOT NULL,
- chain TEXT NOT NULL,
- payer_address TEXT, -- caller wallet (nullable if anonymous)
- created_at TIMESTAMPTZ NOT NULL DEFAULT now()
-);
-```
-
-### `agent_payout_wallets`
-The wallet address where an agent owner wants to receive revenue.
-
-```sql
-CREATE TABLE agent_payout_wallets (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- agent_id UUID REFERENCES agent_identities(id) ON DELETE SET NULL, -- NULL = default for all agents
- address TEXT NOT NULL,
- chain TEXT NOT NULL DEFAULT 'solana',
- is_default BOOLEAN NOT NULL DEFAULT false,
- created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
- UNIQUE (user_id, agent_id, chain)
-);
-```
-
-### `agent_withdrawals`
-Tracks payout requests from agent owners.
-
-```sql
-CREATE TABLE agent_withdrawals (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- user_id UUID NOT NULL REFERENCES users(id),
- agent_id UUID REFERENCES agent_identities(id),
- amount BIGINT NOT NULL,
- currency_mint TEXT NOT NULL,
- chain TEXT NOT NULL,
- to_address TEXT NOT NULL,
- status TEXT NOT NULL DEFAULT 'pending', -- pending | processing | completed | failed
- tx_signature TEXT, -- on-chain tx hash when completed
- created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
- updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
-);
-```
-
-## Migration File
-Create `/api/_lib/migrations/013_agent_monetization.sql` with all four `CREATE TABLE` statements above plus index creation:
-
-```sql
-CREATE INDEX ON agent_skill_prices (agent_id);
-CREATE INDEX ON agent_revenue_events (agent_id, created_at DESC);
-CREATE INDEX ON agent_revenue_events (intent_id);
-CREATE INDEX ON agent_payout_wallets (user_id);
-CREATE INDEX ON agent_withdrawals (user_id, status);
-```
-
-## Files to Touch
-- `/api/_lib/migrations/013_agent_monetization.sql` — new file
-- `/api/_lib/db.js` — verify migration runner picks up new file (check glob pattern)
-
-## Verify
-```bash
-npm run db:migrate
-psql $DATABASE_URL -c "\dt agent_skill_prices agent_revenue_events agent_payout_wallets agent_withdrawals"
-```
diff --git a/tasks/agent-monetization/02-pricing-api.md b/tasks/agent-monetization/02-pricing-api.md
deleted file mode 100644
index dabaa7a90..000000000
--- a/tasks/agent-monetization/02-pricing-api.md
+++ /dev/null
@@ -1,86 +0,0 @@
-# Task 02 — API: Skill Pricing CRUD
-
-## Goal
-REST endpoints so agent owners can read, set, and remove per-skill prices for their agents.
-
-## Success Criteria
-- Owner can GET, PUT, and DELETE skill prices
-- Non-owner gets 403
-- Unauthenticated gets 401
-- PUT validates amount > 0, known chain, non-empty skill name
-- Changes are immediately reflected in x402 manifest (Task 03 depends on this)
-
-## Endpoints
-
-### `GET /api/agents/:id/pricing`
-Returns all active skill prices for the agent.
-
-```json
-{
- "prices": [
- {
- "id": "uuid",
- "skill": "answer-question",
- "currency_mint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
- "chain": "solana",
- "amount": 1000000,
- "is_active": true
- }
- ]
-}
-```
-
-Auth: session or Bearer token. Public agents: prices are readable by anyone. Private agents: owner only.
-
-### `PUT /api/agents/:id/pricing/:skill`
-Create or update the price for a specific skill.
-
-Request body:
-```json
-{
- "currency_mint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
- "chain": "solana",
- "amount": 1000000,
- "is_active": true
-}
-```
-
-Requires: authenticated, `user_id` must match agent owner.
-
-Validation:
-- `amount` must be integer > 0
-- `chain` must be one of: `solana`, `base`, `evm`
-- `currency_mint` must be non-empty string
-- `skill` must be a valid identifier (alphanumeric + hyphens, max 64 chars)
-
-Uses `INSERT ... ON CONFLICT (agent_id, skill) DO UPDATE`.
-
-Response: `201` on create, `200` on update.
-
-### `DELETE /api/agents/:id/pricing/:skill`
-Soft-delete (sets `is_active = false`). Hard-delete on explicit `?hard=true` for owners who want to fully remove.
-
-## File to Create
-`/api/agents/[id]/pricing/index.js` — handles GET
-`/api/agents/[id]/pricing/[skill].js` — handles PUT, DELETE
-
-## Shared Helpers to Use
-- `requireAuth(req)` from `/api/_lib/auth.js`
-- `db` from `/api/_lib/db.js`
-- `json(res, status, body)` and `error(res, status, code, msg)` from `/api/_lib/http.js`
-- `validate(schema, data)` from `/api/_lib/validate.js`
-
-## Verify
-```bash
-# Set price
-curl -X PUT /api/agents/:id/pricing/answer-question \
- -H "Cookie: __Host-sid=..." \
- -d '{"currency_mint":"EPjF...","chain":"solana","amount":1000000}'
-
-# Read back
-curl /api/agents/:id/pricing
-
-# Non-owner should 403
-curl -X PUT /api/agents/:id/pricing/answer-question \
- -H "Cookie: __Host-sid=<other-user-session>" ...
-```
diff --git a/tasks/agent-monetization/04-revenue-attribution.md b/tasks/agent-monetization/04-revenue-attribution.md
deleted file mode 100644
index f6096cee1..000000000
--- a/tasks/agent-monetization/04-revenue-attribution.md
+++ /dev/null
@@ -1,69 +0,0 @@
-# Task 04 — Revenue Attribution: Write Revenue Events on Intent Consumption
-
-## Goal
-When a caller pays for a skill and the intent is consumed, write an immutable `agent_revenue_events` row. This is the financial record that powers the revenue dashboard and withdrawal system.
-
-## Success Criteria
-- Every consumed intent creates exactly one `agent_revenue_events` row
-- Platform fee (configurable, default 2.5%) is calculated and stored
-- `net_amount = gross_amount - fee_amount` is always correct
-- Double-consumption is prevented (the existing intent status check still holds)
-
-## Where to Hook In
-
-Find where intents transition from `paid` → `consumed`. This is likely in:
-- `/api/agents/x402/[...slug].js` (the skill access verification endpoint)
-- Or wherever `UPDATE agent_payment_intents SET status = 'consumed'` happens
-
-After the intent is marked consumed (inside the same transaction if possible), insert into `agent_revenue_events`.
-
-## Platform Fee
-
-Add env var: `PLATFORM_FEE_BPS` (basis points, default `250` = 2.5%).
-
-```js
-// api/_lib/fee.js
-const FEE_BPS = parseInt(process.env.PLATFORM_FEE_BPS ?? '250', 10);
-
-export function calculateFee(grossAmount) {
- const fee = Math.floor((grossAmount * FEE_BPS) / 10_000);
- return { fee, net: grossAmount - fee };
-}
-```
-
-## Revenue Event Insert
-
-```js
-import { calculateFee } from '../_lib/fee.js';
-
-// Inside intent consumption handler, after status update:
-const { fee, net } = calculateFee(intent.amount);
-await db.query(
- `INSERT INTO agent_revenue_events
- (agent_id, intent_id, skill, gross_amount, fee_amount, net_amount,
- currency_mint, chain, payer_address)
- VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)`,
- [intent.agent_id, intent.id, intent.skill, intent.amount,
- fee, net, intent.currency_mint, intent.chain, payerAddress]
-);
-```
-
-`payerAddress` should come from the payment proof in the x402 request headers (the `X-Payment` header contains the signed payment with sender address).
-
-## Files to Touch
-- Find and edit the intent consumption endpoint in `/api/agents/`
-- Add `/api/_lib/fee.js` (new helper)
-
-## Do NOT Change
-- Intent status machine logic
-- x402 header parsing
-- Skill response format
-
-## Verify
-```bash
-# Complete a full payment flow for a priced skill.
-# Then query:
-psql $DATABASE_URL -c "SELECT * FROM agent_revenue_events ORDER BY created_at DESC LIMIT 5;"
-# Verify fee_amount = floor(gross_amount * 0.025)
-# Verify net_amount = gross_amount - fee_amount
-```
diff --git a/tasks/agent-monetization/05-payout-wallet-api.md b/tasks/agent-monetization/05-payout-wallet-api.md
deleted file mode 100644
index 9fee20f7d..000000000
--- a/tasks/agent-monetization/05-payout-wallet-api.md
+++ /dev/null
@@ -1,83 +0,0 @@
-# Task 05 — API: Payout Wallet Configuration
-
-## Goal
-Endpoints for agent owners to register the wallet address that receives their revenue. Supports per-agent and per-user-default wallets, multiple chains.
-
-## Success Criteria
-- Owner can add, list, and remove payout wallets
-- Can mark one wallet as default per chain
-- Wallet address format is validated per chain type
-- `resolvePayoutAddress()` from Task 03 returns correct address
-
-## Endpoints
-
-### `GET /api/billing/payout-wallets`
-Returns all payout wallets for the authenticated user.
-
-```json
-{
- "wallets": [
- {
- "id": "uuid",
- "agent_id": null,
- "address": "7xK...",
- "chain": "solana",
- "is_default": true
- }
- ]
-}
-```
-
-### `POST /api/billing/payout-wallets`
-Register a new payout wallet.
-
-```json
-{
- "address": "7xK...",
- "chain": "solana",
- "agent_id": null,
- "is_default": true
-}
-```
-
-If `is_default: true`, set all other wallets for the same `(user_id, chain)` to `is_default = false` first (in a transaction).
-
-Validation:
-- Solana: base58, 32–44 chars
-- EVM/Base: starts with `0x`, 42 chars, valid checksum preferred
-
-### `DELETE /api/billing/payout-wallets/:id`
-Remove a payout wallet. If it was default, clear the default (caller must set a new one).
-
-## Files to Create
-- `/api/billing/payout-wallets/index.js` — GET, POST
-- `/api/billing/payout-wallets/[id].js` — DELETE
-
-## Address Validation Helper
-
-Add to `/api/_lib/validate.js`:
-
-```js
-export function isValidSolanaAddress(addr) {
- return /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(addr);
-}
-
-export function isValidEvmAddress(addr) {
- return /^0x[0-9a-fA-F]{40}$/.test(addr);
-}
-```
-
-## Verify
-```bash
-# Add a Solana payout wallet
-curl -X POST /api/billing/payout-wallets \
- -H "Cookie: __Host-sid=..." \
- -d '{"address":"7xK...","chain":"solana","is_default":true}'
-
-# List wallets
-curl /api/billing/payout-wallets -H "Cookie: __Host-sid=..."
-
-# Invalid address should 400
-curl -X POST /api/billing/payout-wallets \
- -d '{"address":"not-valid","chain":"solana"}'
-```
diff --git a/tasks/agent-monetization/06-revenue-dashboard-api.md b/tasks/agent-monetization/06-revenue-dashboard-api.md
deleted file mode 100644
index 5d878c620..000000000
--- a/tasks/agent-monetization/06-revenue-dashboard-api.md
+++ /dev/null
@@ -1,88 +0,0 @@
-# Task 06 — API: Revenue Dashboard Data
-
-## Goal
-An endpoint that gives agent owners aggregated earnings data to display in the dashboard UI (Task 12).
-
-## Success Criteria
-- Returns total earnings, per-skill breakdown, and time-series data
-- Scoped to the authenticated user's agents only
-- Optional filter by `agent_id` query param
-- Optional filter by date range (`from` / `to` ISO-8601 params)
-- Returns zero-values gracefully (no earnings yet = valid response, not 404)
-
-## Endpoint
-
-### `GET /api/billing/revenue`
-
-Query params:
-- `agent_id` (optional UUID) — filter to a single agent
-- `from` (optional ISO date) — defaults to 30 days ago
-- `to` (optional ISO date) — defaults to now
-- `granularity` — `day` | `week` | `month` (default: `day`)
-
-Response:
-```json
-{
- "summary": {
- "gross_total": 15000000,
- "fee_total": 375000,
- "net_total": 14625000,
- "currency_mint": "EPjF...",
- "chain": "solana",
- "payment_count": 42
- },
- "by_skill": [
- { "skill": "answer-question", "net_total": 10000000, "count": 30 },
- { "skill": "generate-image", "net_total": 4625000, "count": 12 }
- ],
- "timeseries": [
- { "period": "2026-04-01", "net_total": 500000, "count": 3 },
- { "period": "2026-04-02", "net_total": 1000000, "count": 7 }
- ]
-}
-```
-
-## SQL Queries
-
-### Summary
-```sql
-SELECT
- SUM(gross_amount) AS gross_total,
- SUM(fee_amount) AS fee_total,
- SUM(net_amount) AS net_total,
- COUNT(*) AS payment_count,
- currency_mint, chain
-FROM agent_revenue_events re
-JOIN agent_identities ai ON ai.id = re.agent_id
-WHERE ai.user_id = $1
- AND re.created_at BETWEEN $2 AND $3
- AND ($4::uuid IS NULL OR re.agent_id = $4)
-GROUP BY currency_mint, chain
-```
-
-### Time-series (daily example)
-```sql
-SELECT
- date_trunc('day', created_at) AS period,
- SUM(net_amount) AS net_total,
- COUNT(*) AS count
-FROM agent_revenue_events re
-JOIN agent_identities ai ON ai.id = re.agent_id
-WHERE ai.user_id = $1
- AND re.created_at BETWEEN $2 AND $3
-GROUP BY period
-ORDER BY period
-```
-
-## File to Create
-`/api/billing/revenue.js`
-
-## Verify
-```bash
-curl "/api/billing/revenue?from=2026-01-01&to=2026-04-30" \
- -H "Cookie: __Host-sid=..."
-# Returns { summary, by_skill, timeseries }
-
-# Without any revenue yet:
-# Returns { summary: { gross_total: 0, ... }, by_skill: [], timeseries: [] }
-```
diff --git a/tasks/agent-monetization/07-withdrawal-api.md b/tasks/agent-monetization/07-withdrawal-api.md
deleted file mode 100644
index 1c023b15f..000000000
--- a/tasks/agent-monetization/07-withdrawal-api.md
+++ /dev/null
@@ -1,89 +0,0 @@
-# Task 07 — API: Withdrawal (Payout) Flow
-
-## Goal
-Allow agent owners to request a payout of their earned revenue. The flow is: owner requests withdrawal → backend validates sufficient balance → creates `agent_withdrawals` row in `pending` state → (cron or webhook) processes the on-chain transfer → marks `completed`.
-
-## Success Criteria
-- Owner can request a withdrawal for a specific amount and currency
-- System validates available (unconsumed) net balance before creating the request
-- Double-withdrawal is prevented (pending + processing withdrawals reduce available balance)
-- Status transitions: `pending` → `processing` → `completed` | `failed`
-- Only the owner can initiate; only an admin or cron can advance status to `processing`/`completed`
-
-## Endpoints
-
-### `POST /api/billing/withdrawals`
-Initiate a withdrawal request.
-
-```json
-{
- "amount": 10000000,
- "currency_mint": "EPjF...",
- "chain": "solana",
- "to_address": "7xK...",
- "agent_id": "uuid-or-null"
-}
-```
-
-**Available balance check:**
-```sql
-SELECT
- COALESCE(SUM(net_amount), 0) AS earned,
- (
- SELECT COALESCE(SUM(amount), 0)
- FROM agent_withdrawals w2
- WHERE w2.user_id = $1
- AND w2.status IN ('pending','processing')
- AND w2.currency_mint = $2
- ) AS pending_amount
-FROM agent_revenue_events re
-JOIN agent_identities ai ON ai.id = re.agent_id
-WHERE ai.user_id = $1
- AND re.currency_mint = $2
-```
-
-`available = earned - pending_amount`. If `requested_amount > available` → 422 `{ error: "insufficient_balance" }`.
-
-On success: insert into `agent_withdrawals` with `status = 'pending'`, return `{ id, status, amount, ... }`.
-
-### `GET /api/billing/withdrawals`
-List the authenticated user's withdrawal history.
-
-Query params: `status` (optional filter), `limit` (default 20), `offset` (default 0).
-
-### `GET /api/billing/withdrawals/:id`
-Single withdrawal details.
-
-## Admin Endpoint (separate from user-facing)
-
-### `PATCH /api/admin/withdrawals/:id`
-Advance withdrawal status. Admin-only.
-
-```json
-{ "status": "processing", "tx_signature": "5J..." }
-```
-
-Only transitions:
-- `pending` → `processing` (set `tx_signature`)
-- `processing` → `completed` | `failed`
-
-## Files to Create
-- `/api/billing/withdrawals/index.js` — GET (list), POST
-- `/api/billing/withdrawals/[id].js` — GET single
-- `/api/admin/withdrawals/[id].js` — PATCH (admin only, use existing `requireAdmin()`)
-
-## Verify
-```bash
-# Initiate withdrawal
-curl -X POST /api/billing/withdrawals \
- -H "Cookie: __Host-sid=..." \
- -d '{"amount":1000000,"currency_mint":"EPjF...","chain":"solana","to_address":"7xK..."}'
-
-# Over-withdrawal should 422
-curl -X POST /api/billing/withdrawals \
- -d '{"amount":9999999999,...}'
-# → { error: "insufficient_balance" }
-
-# List
-curl /api/billing/withdrawals -H "Cookie: __Host-sid=..."
-```
diff --git a/tasks/agent-monetization/09-caller-payment-gate.md b/tasks/agent-monetization/09-caller-payment-gate.md
deleted file mode 100644
index cf6d34161..000000000
--- a/tasks/agent-monetization/09-caller-payment-gate.md
+++ /dev/null
@@ -1,71 +0,0 @@
-# Task 09 — Frontend: Caller Payment Gate (Skill Invocation Intercept)
-
-## Goal
-When a caller tries to invoke a priced skill, intercept the request client-side, show them the price, and require payment before the skill executes. After successful payment, resume the skill call with a payment proof token.
-
-## Success Criteria
-- Free skills invoke without any payment prompt
-- Priced skills show a modal with the price before executing
-- Caller can approve (pay) or cancel
-- After payment, skill executes exactly once
-- Payment proof is passed to the skill context so the backend can verify it
-- Works in both the embedded widget and the full agent viewer
-
-## Where to Hook In
-
-The skill invocation path flows through `/src/skills/index.js` (the skill registry runner). Find the `invoke(skill, args, ctx)` or equivalent method.
-
-Before executing, check if the skill has a price:
-1. `GET /api/agents/:agentId/x402/:skill/manifest`
-2. If 404 (not priced) → proceed normally
-3. If 200 (has price) → pause, show payment modal, wait for user confirmation
-4. On confirmation → initiate x402 payment flow → get payment proof
-5. Resume skill with `ctx.paymentProof = proof`
-
-## Payment Modal Component
-
-Create `src/components/payment-gate-modal.jsx`:
-
-```jsx
-// Props: skill, amount, currencySymbol, chain, onPay, onCancel
-// Shows:
-// Title: "This skill requires payment"
-// Body: "[skill] costs [amount] [currency]"
-// Buttons: [Pay] [Cancel]
-// [Pay] triggers the x402 client payment flow
-```
-
-The `[Pay]` button calls the existing x402 client helpers (look in `src/` for x402-related code or `agent-payments-sdk`).
-
-## x402 Client Flow
-
-The client-side x402 flow should:
-1. Call `GET /api/agents/:id/x402/:skill/manifest` → get payment details
-2. Construct and sign the payment on the user's connected wallet
-3. Call `POST /api/agents/:id/x402/:skill/pay` (or the prep/confirm endpoints) with the signed payment
-4. Receive back a `payment_proof` or `intent_id`
-5. Pass this as a header/arg when invoking the skill
-
-Reference the existing `agent-payments-sdk/` and `/api/agents/payments/` for the flow pattern.
-
-## Files to Touch
-- `/src/skills/index.js` — add intercept in invoke path
-- Add `src/components/payment-gate-modal.jsx` — new file
-- `/src/runtime/index.js` — may need to thread `paymentProof` into tool context
-
-## Do NOT Change
-- The skill handler signatures or return format
-- The x402 backend verification logic
-
-## Edge Cases
-- Wallet not connected → show "Connect wallet" before price modal
-- Payment timeout → show error, allow retry
-- Skill returns error after payment → log to console, do NOT re-charge (intent is consumed)
-- Duplicate calls racing → debounce or disable [Pay] button after first click
-
-## Verify
-1. Add a price to a skill via Task 08 UI
-2. Click that skill in the viewer → payment modal appears with correct price
-3. Approve payment → skill runs, output appears
-4. Cancel → skill does not run, no payment
-5. Free skill → no modal, runs immediately
diff --git a/tasks/agent-monetization/10-revenue-dashboard-ui.md b/tasks/agent-monetization/10-revenue-dashboard-ui.md
deleted file mode 100644
index 1d962b04f..000000000
--- a/tasks/agent-monetization/10-revenue-dashboard-ui.md
+++ /dev/null
@@ -1,70 +0,0 @@
-# Task 10 — Frontend: Revenue Dashboard UI
-
-## Goal
-A dashboard page (or panel within the agent management UI) where agent owners can see their earnings: total revenue, per-skill breakdown, and a time-series chart.
-
-## Success Criteria
-- Shows gross/net revenue and payment count for selected time range
-- Per-skill breakdown table with amounts
-- Simple bar or line chart for daily/weekly earnings
-- Date range picker (Last 7d / 30d / 90d / custom)
-- Agent selector dropdown if user has multiple agents (or "All agents" default)
-- Amounts rendered in human-readable USDC (divide lamports by 10^6, show "USDC")
-- Empty state for users with no revenue yet
-
-## Route/Location
-
-Add a route `/dashboard/revenue` (or `/agents/:id/revenue` for per-agent view).
-
-If there's an existing dashboard or billing page, add a "Revenue" section/tab there. Search for `billing`, `dashboard`, or `settings` pages in `src/`.
-
-## Component: `RevenueDashboard`
-
-```
-RevenueDashboard
-├── Header: "Revenue" + date range picker + agent selector
-├── Summary Cards
-│ ├── Gross Earnings: $X.XX USDC
-│ ├── Platform Fees: -$X.XX USDC
-│ ├── Net Earnings: $X.XX USDC
-│ └── Payments: N transactions
-├── Earnings Chart (bar chart, one bar per day/week)
-└── Skill Breakdown Table
- ├── Skill | Net Earnings | Transactions
- └── ...rows...
-```
-
-## Data Source
-`GET /api/billing/revenue` (Task 06).
-
-Use `fetch` with the session cookie. On load, call with default `from=30 days ago`.
-
-Re-fetch when date range or agent filter changes.
-
-## Chart
-Use a minimal vanilla SVG bar chart (no external charting lib) or a simple `<canvas>` bar chart. Match existing project style (no React, use vhtml JSX or plain DOM). Keep it under 100 lines.
-
-## Amount Formatting Helper
-```js
-function formatUSDC(lamports) {
- return (lamports / 1_000_000).toLocaleString('en-US', {
- minimumFractionDigits: 2,
- maximumFractionDigits: 2
- }) + ' USDC';
-}
-```
-
-## Files to Create/Touch
-- `src/components/revenue-dashboard.jsx` — new component
-- Wire into the existing routing/navigation (find where other dashboard routes are registered)
-
-## Do NOT Build
-- Real-time WebSocket updates (polling on page focus is fine)
-- CSV export (future task)
-- Multi-currency support in the chart (show primary currency only)
-
-## Verify
-1. Navigate to revenue dashboard → summary cards show (zeros if no revenue)
-2. Change date range → numbers update
-3. Complete a test payment → earnings appear within one page reload
-4. With multiple agents → agent selector filters correctly
diff --git a/tasks/agent-monetization/11-withdrawal-ui.md b/tasks/agent-monetization/11-withdrawal-ui.md
deleted file mode 100644
index 6198000fb..000000000
--- a/tasks/agent-monetization/11-withdrawal-ui.md
+++ /dev/null
@@ -1,69 +0,0 @@
-# Task 11 — Frontend: Withdrawal UI
-
-## Goal
-UI inside the revenue dashboard for agent owners to request a payout of their earnings to their configured payout wallet.
-
-## Success Criteria
-- Shows available balance (net earnings minus pending withdrawals)
-- Amount input with max = available balance
-- Payout wallet selector (from Task 05 API) with "Add wallet" link
-- Submit creates a withdrawal request and shows confirmation
-- Withdrawal history table below the form
-- Pending/processing withdrawals are clearly indicated
-
-## Component Structure
-
-Add a "Withdraw" section at the bottom of `RevenueDashboard` (Task 10) or as a sibling route `/dashboard/revenue/withdraw`.
-
-```
-Withdraw Earnings
-├── Available balance: $X.XX USDC
-├── Amount: [input, max = available] [Max] button
-├── To wallet: [dropdown of payout wallets] [+ Add wallet]
-├── [Request Withdrawal] button
-│
-└── Withdrawal History
- ├── Date | Amount | Wallet | Status | Tx
- └── ...
-```
-
-## Interactions
-
-**On load:**
-- `GET /api/billing/revenue` → derive available balance (net_total)
-- `GET /api/billing/withdrawals?status=pending,processing` → subtract pending from available
-- `GET /api/billing/payout-wallets` → populate wallet dropdown
-
-**On submit:**
-- Validate: amount > 0, amount ≤ available, wallet selected
-- `POST /api/billing/withdrawals` with `{ amount, currency_mint, chain, to_address }`
-- On success: show "Withdrawal requested. Processing typically takes 1–2 business days."
-- Refresh available balance and history
-
-**"+ Add wallet" link:**
-- Opens the payout wallet form (inline or links to payout-wallets settings)
-
-## Amount Conversion
-- Display in USDC (÷ 10^6), store as lamports (× 10^6) when sending to API
-- [Max] button fills input with full available balance
-
-## Status Display
-| Status | Display |
-|--------|---------|
-| `pending` | "Queued" (yellow badge) |
-| `processing` | "Processing" (blue badge) |
-| `completed` | "Sent" (green badge) + tx hash link |
-| `failed` | "Failed" (red badge) |
-
-For `completed`, show a link to the transaction on Solscan or Basescan depending on chain.
-
-## Files to Touch
-- `src/components/revenue-dashboard.jsx` — add withdrawal section
-- Or add `src/components/withdrawal-panel.jsx` and import it
-
-## Verify
-1. Available balance shows correctly
-2. [Max] fills the amount
-3. Submit with valid amount → success message, history row appears with "Queued"
-4. Submit exceeding balance → inline error "Insufficient balance"
-5. No payout wallet configured → [Request Withdrawal] is disabled with tooltip "Add a payout wallet first"
diff --git a/tasks/agent-monetization/13-agent-marketplace-pricing-display.md b/tasks/agent-monetization/13-agent-marketplace-pricing-display.md
deleted file mode 100644
index d596b2b3a..000000000
--- a/tasks/agent-monetization/13-agent-marketplace-pricing-display.md
+++ /dev/null
@@ -1,70 +0,0 @@
-# Task 13 — Marketplace: Show Pricing on Agent Cards & Detail Pages
-
-## Goal
-When browsing the agent marketplace or an agent's public profile, show callers which skills are priced (and how much) so they know before they invoke anything.
-
-## Success Criteria
-- Agent cards in `/api/marketplace` response include `has_paid_skills: boolean`
-- Agent detail page shows a "Skills" section with price badges
-- Free skills show "Free", priced skills show the amount (e.g., "0.01 USDC")
-- Pricing data is served from the existing `/api/agents/:id/pricing` endpoint (read-only, public)
-
-## API Changes
-
-### Update `GET /api/agents` (marketplace list)
-Add `has_paid_skills` boolean to each agent in the list response.
-
-```sql
--- In the agents list query, add:
-EXISTS (
- SELECT 1 FROM agent_skill_prices asp
- WHERE asp.agent_id = ai.id AND asp.is_active = true
-) AS has_paid_skills
-```
-
-### Update `GET /api/agents/:id` (agent detail)
-Include skill prices in the response:
-
-```json
-{
- "id": "...",
- "name": "...",
- "skills": ["answer-question", "generate-image"],
- "skill_prices": {
- "answer-question": { "amount": 1000000, "currency_mint": "EPjF...", "chain": "solana" },
- "generate-image": null
- }
-}
-```
-
-`null` = free. Only return `is_active = true` prices.
-
-## Frontend Changes
-
-### Agent Card (marketplace grid)
-If `has_paid_skills = true`, add a small "Paid" badge (e.g., 💰 or "$" icon) to the agent card. Keep the badge minimal — don't crowd the card.
-
-### Agent Detail Page
-In the skills list section, for each skill:
-- If `skill_prices[skill]` is non-null: show `0.01 USDC` badge (green)
-- If null: show `Free` badge (gray)
-
-Format amounts the same way as the revenue dashboard: `lamports / 10^6` + " USDC".
-
-## Files to Touch
-- `/api/agents/index.js` (or wherever the marketplace list handler lives) — add `has_paid_skills`
-- `/api/agents/[id].js` — add `skill_prices` to response
-- `src/components/agent-card.jsx` (or equivalent) — add paid badge
-- `src/components/agent-detail.jsx` (or equivalent) — add price badges to skill list
-
-## Do NOT Change
-- Marketplace search/filter logic
-- Agent card layout beyond adding the badge
-- Agent detail sections unrelated to skills
-
-## Verify
-1. Create an agent with a priced skill
-2. Browse marketplace → agent card shows "Paid" indicator
-3. Open agent detail → skills list shows correct price next to each skill
-4. Free skill shows "Free"
-5. Unauthenticated user can see prices (public data)
diff --git a/tasks/agent-monetization/14-sdk-payment-support.md b/tasks/agent-monetization/14-sdk-payment-support.md
deleted file mode 100644
index 457ea4345..000000000
--- a/tasks/agent-monetization/14-sdk-payment-support.md
+++ /dev/null
@@ -1,88 +0,0 @@
-# Task 14 — SDK: Payment Support for Programmatic Callers
-
-## Goal
-Update the TypeScript SDK (`/sdk/`) so that programmatic callers (MCP clients, third-party apps) can discover skill prices, initiate x402 payments, and invoke paid skills — all without a browser UI.
-
-## Success Criteria
-- `agent.getSkillPrices()` returns pricing info for all skills
-- `agent.invokeSkill(skill, args, { paymentOptions })` handles payment automatically when a price is required
-- Payment is skipped if the skill is free
-- Caller can pass a wallet signer to the SDK for signing payments
-- All new methods are documented with JSDoc
-
-## New SDK Methods
-
-### `AgentClient.getSkillPrices(agentId)`
-```ts
-async getSkillPrices(agentId: string): Promise<SkillPrice[]>
-// Calls GET /api/agents/:id/pricing
-// Returns: [{ skill, amount, currencyMint, chain, isActive }]
-```
-
-### `AgentClient.invokeSkill(agentId, skill, args, options?)`
-```ts
-async invokeSkill(
- agentId: string,
- skill: string,
- args: Record<string, unknown>,
- options?: { signer?: WalletSigner }
-): Promise<SkillResult>
-```
-
-Internally:
-1. `GET /api/agents/:id/x402/:skill/manifest`
-2. If 404 (free) → call skill directly
-3. If 200 (priced) → if no `signer` provided → throw `PaymentRequiredError`
-4. If signer provided → build and sign payment → call skill with payment proof
-
-### `PaymentRequiredError`
-```ts
-class PaymentRequiredError extends Error {
- constructor(public readonly manifest: X402Manifest) {
- super(`Skill requires payment: ${manifest.amount} ${manifest.currencySymbol}`);
- }
-}
-```
-
-### `WalletSigner` Interface
-```ts
-interface WalletSigner {
- address: string;
- chain: 'solana' | 'base';
- signPayment(manifest: X402Manifest): Promise<string>; // returns signed payment proof
-}
-```
-
-Callers provide their own signer implementation (Solana: use `@solana/web3.js` Keypair; Base: use `viem` or `ethers`). The SDK doesn't bundle wallet libraries.
-
-## Files to Touch
-- `/sdk/src/agent-client.ts` (or equivalent main client file)
-- `/sdk/src/types.ts` — add `SkillPrice`, `X402Manifest`, `WalletSigner`, `PaymentRequiredError`
-- `/sdk/src/index.ts` — export new types
-
-## Do NOT Change
-- Existing SDK methods
-- SDK build config
-
-## Verify
-```ts
-import { AgentClient } from '@threews/sdk';
-
-const client = new AgentClient({ baseUrl: 'https://three.ws' });
-
-// Discover prices
-const prices = await client.getSkillPrices('agent-uuid');
-// [{ skill: 'answer-question', amount: 1000000, ... }]
-
-// Free skill — no payment needed
-const result = await client.invokeSkill('agent-uuid', 'greet', {});
-
-// Paid skill — no signer → throws PaymentRequiredError
-try {
- await client.invokeSkill('agent-uuid', 'answer-question', { query: 'hello' });
-} catch (e) {
- if (e instanceof PaymentRequiredError) {
- console.log('Need to pay:', e.manifest.amount);
- }
-}
-```
diff --git a/tasks/agent-monetization/18-e2e-tests.md b/tasks/agent-monetization/18-e2e-tests.md
deleted file mode 100644
index 91ca96e27..000000000
--- a/tasks/agent-monetization/18-e2e-tests.md
+++ /dev/null
@@ -1,126 +0,0 @@
-# Task 18 — End-to-End Tests: Agent Monetization Flow
-
-## Goal
-Automated tests that cover the complete monetization flow: set price → caller pays → revenue recorded → owner withdraws. These are integration tests that hit real DB (test schema) and real API handlers.
-
-## Success Criteria
-- All happy-path scenarios pass
-- Key error paths are covered (insufficient balance, wrong owner, replay)
-- Tests are isolated (each test creates its own users/agents, cleans up after)
-- Tests run with `npm test` without side effects on production data
-
-## Test File
-`/tests/agent-monetization.test.js`
-
-Use the existing test framework (Vitest based on the project setup). Reference `/tests/` for existing patterns.
-
-## Test Cases
-
-### 1. Pricing CRUD
-```js
-test('owner can set and read skill price', async () => {
- const { agent, session } = await createTestAgent();
- await setPricing(session, agent.id, 'answer-question', { amount: 1000000, chain: 'solana', ... });
- const prices = await getPricing(agent.id);
- expect(prices[0].amount).toBe(1000000);
-});
-
-test('non-owner gets 403', async () => {
- const { agent } = await createTestAgent();
- const { session: otherSession } = await createTestUser();
- const res = await setPricing(otherSession, agent.id, 'answer-question', { ... });
- expect(res.status).toBe(403);
-});
-```
-
-### 2. x402 Manifest
-```js
-test('manifest returns price when skill is priced', async () => {
- // set price, then fetch manifest
- const manifest = await getManifest(agent.id, 'answer-question');
- expect(manifest.amount).toBe(1000000);
-});
-
-test('manifest returns 404 when skill is not priced', async () => {
- const res = await fetch(`/api/agents/${agent.id}/x402/free-skill/manifest`);
- expect(res.status).toBe(404);
-});
-```
-
-### 3. Revenue Attribution
-```js
-test('consuming an intent creates revenue event', async () => {
- // Create intent, mark paid, consume
- await consumeIntent(intentId, payerAddress);
- const events = await db.query(
- 'SELECT * FROM agent_revenue_events WHERE intent_id = $1', [intentId]
- );
- expect(events.length).toBe(1);
- expect(events[0].fee_amount).toBe(Math.floor(1000000 * 0.025));
- expect(events[0].net_amount).toBe(1000000 - events[0].fee_amount);
-});
-
-test('double-consumption is rejected', async () => {
- await consumeIntent(intentId, payerAddress);
- const res2 = await consumeIntent(intentId, payerAddress);
- expect(res2.status).toBe(409);
-});
-```
-
-### 4. Revenue Dashboard
-```js
-test('revenue endpoint returns correct totals', async () => {
- // Insert test revenue events
- const data = await getRevenue(session);
- expect(data.summary.gross_total).toBeGreaterThan(0);
- expect(data.by_skill.length).toBeGreaterThan(0);
-});
-```
-
-### 5. Withdrawals
-```js
-test('owner can withdraw available balance', async () => {
- // Seed revenue events, then request withdrawal
- const w = await requestWithdrawal(session, { amount: 950000, ... });
- expect(w.status).toBe('pending');
-});
-
-test('over-withdrawal is rejected', async () => {
- const res = await requestWithdrawal(session, { amount: 9999999999, ... });
- expect(res.status).toBe(422);
- expect(res.error).toBe('insufficient_balance');
-});
-```
-
-### 6. Rate Limiting
-```js
-test('payment intent creation is rate-limited', async () => {
- // Send 25 intent requests from the same payer address
- // At least some should return 429
- const results = await Promise.all(Array(25).fill(null).map(() => createIntent(...)));
- expect(results.some(r => r.status === 429)).toBe(true);
-});
-```
-
-## Test Helpers to Create
-
-```js
-// tests/_helpers/monetization.js
-export async function createTestAgent(overrides = {}) { ... }
-export async function setPricing(session, agentId, skill, price) { ... }
-export async function getPricing(agentId) { ... }
-export async function getManifest(agentId, skill) { ... }
-export async function consumeIntent(intentId, payerAddress) { ... }
-export async function getRevenue(session, params = {}) { ... }
-export async function requestWithdrawal(session, body) { ... }
-```
-
-## Files to Create
-- `/tests/agent-monetization.test.js`
-- `/tests/_helpers/monetization.js`
-
-## Verify
-```bash
-npm test -- tests/agent-monetization.test.js
-# All tests pass, no leftover test data in DB
-```
diff --git a/tasks/monetization-feature/01-display-priced-skills.md b/tasks/monetization-feature/01-display-priced-skills.md
deleted file mode 100644
index 19f00332a..000000000
--- a/tasks/monetization-feature/01-display-priced-skills.md
+++ /dev/null
@@ -1,72 +0,0 @@
----
-status: completed
----
-
-# Prompt 1: Display Priced Skills in Marketplace
-
-**Status:** Completed
-
-## Objective
-Modify the agent detail page in the marketplace to visually distinguish between free and paid skills, and display the price for paid skills.
-
-## Explanation
-Currently, the agent detail page lists all skills uniformly. To begin building our monetization feature, users need to be able to see which skills are premium and how much they cost. This involves fetching pricing data along with agent details and updating the UI to render prices and a premium indicator.
-
-## Instructions
-- [x] **Modify the Backend API:**
- - [x] Locate the API endpoint that serves the agent detail data (`/api/marketplace/agents/:id`). You can find this in `api/marketplace/[action].js`.
- - [x] When fetching agent details, also query the `agent_skill_prices` table to get the prices for the agent's skills.
- - [x] Join this pricing data with the agent details response. The agent object should now have a `skill_prices` map or object, like `{ "skill_name": { "amount": 1000000, "currency_mint": "EPjFWdd..." } }`.
-
-- [x] **Update the Frontend UI:**
- - [x] In `src/marketplace.js`, find the `renderDetail` function.
- - [x] This function receives the agent object, which now includes `skill_prices`.
- - [x] Inside the loop that renders the skills (`d-skills` element), check if a price exists for the current skill.
- - [x] If a price exists, render a price badge next to the skill name. Convert the amount from lamports (or the smallest unit) to a human-readable format (e.g., 1,000,000 lamports = 1 USDC).
- - [x] Style the price badge to be visually distinct.
-
-## Code Example (Frontend - `src/marketplace.js`)
-
-Here's how you might modify the skill rendering part within the `renderDetail` function:
-
-```javascript
-// Inside renderDetail function
-
-const skillPrices = a.skill_prices || {};
-$('d-skills').innerHTML = skillsArr.length
- ? skillsArr.map((s) => {
- const name = typeof s === 'string' ? s : (s.name || '');
- const price = skillPrices[name];
- const badge = price
- ? `<span class="price-badge price-paid">${(price.amount / 1e6).toFixed(2)} USDC</span>`
- : `<span class="price-badge price-free">Free</span>`;
- return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;
- }).join(' ')
- : '<div>This Agent has no skills defined.</div>';
-```
-
-## CSS Example
-
-Add these styles to `/marketplace.css` to make the price badges look good.
-
-```css
-.price-badge {
- display: inline-block;
- margin-left: 8px;
- padding: 2px 6px;
- font-size: 10px;
- font-weight: 600;
- border-radius: 4px;
- vertical-align: middle;
-}
-
-.price-free {
- color: #a7f3d0;
- background-color: rgba(52, 211, 153, 0.1);
-}
-
-.price-paid {
- color: #fde047;
- background-color: rgba(253, 224, 71, 0.1);
-}
-```
diff --git a/tasks/monetization-feature/02-add-purchase-button.md b/tasks/monetization-feature/02-add-purchase-button.md
deleted file mode 100644
index e23ae05dd..000000000
--- a/tasks/monetization-feature/02-add-purchase-button.md
+++ /dev/null
@@ -1,110 +0,0 @@
-# Prompt 2: Add Purchase Button for Paid Skills
-
-## Objective
-On the agent detail page, add a dynamic "Purchase" or "Use" button for each skill, depending on whether it's paid and whether the user owns it.
-
-## Explanation
-Now that users can see which skills are paid, the next logical step is to provide a call to action. We'll add a button next to each skill. This button will be disabled for free skills (as they are implicitly available), show "Purchase" for paid skills the user doesn't own, and "Use" or "Unlocked" for paid skills they do own.
-
-## Prequisites
-* You need a way to know which skills the current user owns. This will be built in a later prompt. For now, **assume the user owns no skills**, so the logic will only differentiate between free and paid.
-
-## Instructions
-1. **Locate the UI Code:**
- * Open `src/marketplace.js` and find the `renderDetail` function.
- * Focus on the section that renders the skills list inside the element with the ID `d-skills`.
-
-2. **Modify the Skill Rendering Logic:**
- * For each skill, you're already checking if it has a price.
- * Now, add a button to the rendered HTML for each skill.
- * The button's text and state should be conditional:
- * If the skill is **free** (no price), the button should be disabled and perhaps say "Included".
- * If the skill is **paid**, the button should be enabled and say "Purchase".
- * Add a `data-skill-name` attribute to the button to easily identify which skill it corresponds to when clicked.
-
-## Code Example (Frontend - `src/marketplace.js`)
-
-Here is an example of how to modify the skill rendering logic within the `renderDetail` function.
-
-```javascript
-// Inside renderDetail function, an evolution of the previous prompt's code
-
-const skillPrices = a.skill_prices || {};
-// For now, assume user owns nothing. We will replace this with a real check later.
-const ownedSkills = new Set();
-
-$('d-skills').innerHTML = skillsArr.length
- ? skillsArr.map((s) => {
- const name = typeof s === 'string' ? s : (s.name || '');
- const price = skillPrices[name];
-
- let actionButton;
- if (price) {
- if (ownedSkills.has(name)) {
- actionButton = `<button class="skill-btn" disabled>Unlocked</button>`;
- } else {
- actionButton = `<button class="skill-btn purchase" data-skill-name="${escapeHtml(name)}">Purchase</button>`;
- }
- } else {
- actionButton = `<button class="skill-btn" disabled>Free</button>`;
- }
-
- const priceDisplay = price ? `<span class="price-paid">${(price.amount / 1e6).toFixed(2)} USDC</span>` : ``;
-
- return `<div class="skill-row">
- <span class="skill-name">${escapeHtml(name)} ${priceDisplay}</span>
- ${actionButton}
- </div>`;
- }).join('')
- : '<div>This Agent has no skills defined.</div>';
-```
-
-## CSS Example
-
-Add these styles to `marketplace.css` for the new skill row and buttons.
-
-```css
-.skill-row {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: 8px 0;
- border-bottom: 1px solid rgba(255, 255, 255, 0.05);
-}
-
-.skill-row:last-child {
- border-bottom: none;
-}
-
-.skill-name {
- font-size: 14px;
- color: rgba(255, 255, 255, 0.9);
-}
-
-.skill-btn {
- background-color: #374151;
- color: #d1d5db;
- border: none;
- border-radius: 6px;
- padding: 4px 12px;
- font-size: 12px;
- font-weight: 500;
- cursor: pointer;
- transition: background-color 0.2s;
-}
-
-.skill-btn:disabled {
- background-color: #1f2937;
- color: #6b7280;
- cursor: not-allowed;
-}
-
-.skill-btn.purchase {
- background-color: #3b82f6;
- color: white;
-}
-
-.skill-btn.purchase:hover {
- background-color: #2563eb;
-}
-```
diff --git a/tasks/monetization-feature/02-backend-create-skill-pricing-table.md b/tasks/monetization-feature/02-backend-create-skill-pricing-table.md
deleted file mode 100644
index 679635890..000000000
--- a/tasks/monetization-feature/02-backend-create-skill-pricing-table.md
+++ /dev/null
@@ -1,54 +0,0 @@
----
-status: completed
----
-
-# Prompt 2: Backend - Create Skill Pricing Table
-
-**Status:** Completed
-
-## Objective
-Create the necessary database table to store the prices of agent skills. This is a foundational step for the monetization feature.
-
-## Explanation
-To make skills purchasable, we need a dedicated table in our database (`agent_skill_prices`) that links a skill to a price, currency, and the creator who sets the price. This structure will allow us to easily query for a skill's price and manage payments.
-
-## Instructions
-- [x] **Define the Schema:**
- - [x] Create a new SQL migration file.
- - [x] Define the schema for the `agent_skill_prices` table. It should include the following fields:
- * `id`: Primary key (e.g., UUID).
- * `skill_id`: Foreign key referencing the `skills` table.
- * `creator_id`: Foreign key referencing the `users` table (the user who created the skill and will receive payment).
- * `amount`: The price of the skill in the smallest unit of the currency (e.g., lamports for SOL, or 10^-6 for USDC). Use a `BIGINT` or `NUMERIC` to handle large numbers without precision loss.
- * `currency_mint`: The public key of the SPL token used for payment (e.g., USDC's mint address). Stored as a string.
- * `created_at` / `updated_at`: Timestamps.
-
-- [x] **Apply the Migration:**
- - [x] Run the migration to create the table in your development database.
-
-
-## Code Example (SQL Migration)
-
-```sql
-CREATE TABLE agent_skill_prices (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- skill_id UUID NOT NULL REFERENCES skills(id) ON DELETE CASCADE,
- creator_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- amount BIGINT NOT NULL,
- currency_mint VARCHAR(44) NOT NULL, -- Solana public key length
- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
-
- -- A skill should only have one price set by its creator
- UNIQUE (skill_id, creator_id)
-);
-
--- Create an index for efficient price lookups by skill
-CREATE INDEX idx_agent_skill_prices_on_skill_id ON agent_skill_prices(skill_id);
-
--- Optional: Trigger to auto-update updated_at timestamp
-CREATE TRIGGER set_timestamp
-BEFORE UPDATE ON agent_skill_prices
-FOR EACH ROW
-EXECUTE PROCEDURE trigger_set_timestamp();
-```
diff --git a/tasks/monetization-feature/02-create-skill-pricing-table.md b/tasks/monetization-feature/02-create-skill-pricing-table.md
deleted file mode 100644
index 63885d082..000000000
--- a/tasks/monetization-feature/02-create-skill-pricing-table.md
+++ /dev/null
@@ -1,53 +0,0 @@
----
-title: "Prompt 2: Create `agent_skill_prices` Table Schema"
-status: "completed"
----
-
-# Prompt 2: Create `agent_skill_prices` Table Schema
-
-**Status:** Completed
-
-## Objective
-Define and create the necessary database table to store skill prices set by agent creators.
-
-## Explanation
-Before creators can set prices, we need a place in our database to store this information. This task involves creating a new table, `agent_skill_prices`, that will link an agent and a skill to a specific price in a specific currency. This forms the backbone of our pricing system.
-
-## Instructions
-1. **Locate the schema definition file:** Find the main `schema.sql` file, likely located at `api/_lib/schema.sql`.
-2. **Define the `agent_skill_prices` table:** Add a new `CREATE TABLE` statement to this file. The table should include:
- * `agent_id`: A foreign key referencing the `agents` table.
- * `skill_id`: A string identifier for the skill (e.g., "weather-api", "translation-pro").
- * `amount`: A `BIGINT` to store the price in the smallest denomination of the currency (e.g., lamports for SOL, or 10^-6 for USDC). Using a `BIGINT` avoids floating-point precision issues.
- * `currency_mint`: The public key (as a string) of the SPL token mint for the currency (e.g., `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6T` for USDC on Solana Mainnet).
- * A primary key combining `agent_id` and `skill_id` to ensure each skill on an agent has only one price.
- * Timestamps (`created_at`, `updated_at`).
-3. **Apply the schema:** Run the updated `schema.sql` against your local database to create the table.
-
-## Code Example (`api/_lib/schema.sql`)
-
-```sql
--- ... other table definitions
-
--- Stores prices for agent skills, set by the agent's creator.
-CREATE TABLE IF NOT EXISTS agent_skill_prices (
- agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
- skill_id TEXT NOT NULL,
- amount BIGINT NOT NULL CHECK (amount > 0),
- currency_mint TEXT NOT NULL,
- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
- PRIMARY KEY (agent_id, skill_id)
-);
-
--- Index for efficient lookups
-CREATE INDEX IF NOT EXISTS idx_agent_skill_prices_agent_id ON agent_skill_prices(agent_id);
-
--- Auto-update the 'updated_at' column
--- This assumes a 'trigger_set_timestamp' function is already defined in your database.
-CREATE TRIGGER set_timestamp
-BEFORE UPDATE ON agent_skill_prices
-FOR EACH ROW
-EXECUTE PROCEDURE trigger_set_timestamp();
-
-```
diff --git a/tasks/monetization-feature/02-creator-ui-set-skill-prices.md b/tasks/monetization-feature/02-creator-ui-set-skill-prices.md
deleted file mode 100644
index 9c5e95b6f..000000000
--- a/tasks/monetization-feature/02-creator-ui-set-skill-prices.md
+++ /dev/null
@@ -1,86 +0,0 @@
----
-status: completed
----
-# Prompt 2: Creator UI to Set Skill Prices
-
-**Status:** Not Started
-
-## Objective
-Enhance the agent creation/editing page (`agent-edit.html`) to allow creators to set prices for their custom skills.
-
-## Explanation
-For creators to monetize their work, they need a simple interface to manage skill pricing. This task involves adding a new section to the agent editor that lists the agent's skills and provides input fields for setting a price in USDC. We will focus on USDC on Solana for now.
-
-## Instructions
-1. **Locate the Agent Editor:**
- - Find the agent editor page, likely `agent-edit.html`.
- - Identify the section where agent skills are listed or managed.
-
-2. **Enhance the Skills UI:**
- - For each skill listed, add an input field for the price.
- - The input should be clearly labeled (e.g., "Price (USDC)").
- - Include a toggle or checkbox to mark a skill as "Paid". When enabled, the price input should appear.
- - Add a "Save Prices" button to submit the changes.
-
-3. **Implement Frontend Logic:**
- - In the corresponding JavaScript file (likely `src/agent-edit.js` or similar), add an event listener to the "Save Prices" button.
- - When clicked, collect the pricing data for all skills. The data should be in a format like `[{ skill_name: "...", amount: 500000, currency: "USDC" }, ...]`. Note: 0.5 USDC = 500,000 lamports (assuming 6 decimals for USDC).
- - Send this data to a new backend API endpoint (which will be created in the next prompt).
-
-## Code Example (HTML in `agent-edit.html`)
-
-This is a conceptual example of how the skill pricing inputs could be structured.
-
-```html
-<!-- Inside the skills management section -->
-<div class="skill-list">
- <div class="skill-item">
- <span class="skill-name">PumpFun Tools</span>
- <div class="skill-pricing-controls">
- <label class="toggle-switch">
- <input type="checkbox" class="price-toggle" data-skill="PumpFun Tools">
- <span class="slider"></span>
- </label>
- <div class="price-input-wrapper" style="display: none;">
- <input type="number" class="price-input" min="0" step="0.01" placeholder="0.50">
- <span>USDC</span>
- </div>
- </div>
- </div>
- <!-- ... more skills ... -->
-</div>
-<button id="save-skill-prices-btn">Save Prices</button>
-```
-
-## JavaScript Example (`src/agent-edit.js`)
-
-```javascript
-// Add event listener for the save button
-document.getElementById('save-skill-prices-btn').addEventListener('click', async () => {
- const prices = [];
- document.querySelectorAll('.skill-item').forEach(item => {
- const name = item.querySelector('.skill-name').textContent;
- const toggle = item.querySelector('.price-toggle');
- const input = item.querySelector('.price-input');
-
- if (toggle.checked && input.value) {
- const amountInLamports = parseFloat(input.value) * 1e6; // Convert USDC to lamports
- prices.push({
- skill_name: name,
- amount: amountInLamports,
- currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6a' // USDC mint on Solana
- });
- }
- });
-
- // POST to the new backend endpoint
- await fetch(`/api/agents/${agentId}/skill-prices`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ prices })
- });
-
- // Show a confirmation to the user
- alert('Prices saved!');
-});
-```
diff --git a/tasks/monetization-feature/02-ui-add-purchase-skill-button.md b/tasks/monetization-feature/02-ui-add-purchase-skill-button.md
deleted file mode 100644
index 8c3b193b4..000000000
--- a/tasks/monetization-feature/02-ui-add-purchase-skill-button.md
+++ /dev/null
@@ -1,79 +0,0 @@
----
-status: completed
----
-# Prompt 2: Add "Purchase Skill" Button to UI
-
-**Status:** Not Started
-
-## Objective
-In the agent detail page, for skills that are not free and not yet owned by the user, display a "Purchase" button. This button will be the entry point for the skill acquisition flow.
-
-## Explanation
-Following the display of priced skills, the next logical step is to allow users to buy them. This task focuses on the UI component only. The button's action will be wired up in a subsequent task. We need to check if the user has already purchased the skill.
-
-## Instructions
-1. **Modify the Backend API (`/api/marketplace/agents/:id`):**
- * The API response should include information about which skills the *currently logged-in user* has already purchased. You might add a `purchased_skills` array of skill names to the agent object. You'll need to query your database for user entitlements.
-2. **Update the Frontend UI (`src/marketplace.js`):**
- * In the `renderDetail` function, you now have access to `agent.skill_prices` and `agent.purchased_skills`.
- * When rendering each skill, apply the following logic:
- * If the skill has no price, show the "Free" badge.
- * If the skill has a price and is in the `purchased_skills` array, show a "✅ Owned" badge.
- * If the skill has a price and is NOT in the `purchased_skills` array, show the price badge and a "Purchase" button.
- * The "Purchase" button should have `data-skill-name` and `data-agent-id` attributes to make it easy to handle the click event later.
-
-## Code Example (`src/marketplace.js`)
-
-```javascript
-// Inside renderDetail function
-
-const skillPrices = a.skill_prices || {};
-const purchasedSkills = a.purchased_skills || [];
-
-$('d-skills').innerHTML = skillsArr.length
- ? skillsArr.map((s) => {
- const name = typeof s === 'string' ? s : (s.name || '');
- const price = skillPrices[name];
- let badge;
-
- if (price) {
- if (purchasedSkills.includes(name)) {
- badge = `<span class="price-badge price-owned">✓ Owned</span>`;
- } else {
- const priceInUSDC = (price.amount / 1e6).toFixed(2);
- badge = `<span class="price-badge price-paid">${priceInUSDC} USDC</span>` +
- `<button class="purchase-btn" data-skill-name="${escapeHtml(name)}" data-agent-id="${a.id}">Purchase</button>`;
- }
- } else {
- badge = `<span class="price-badge price-free">Free</span>`;
- }
- return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;
- }).join(' ')
- : '<div>This Agent has no skills defined.</div>';
-```
-
-## CSS Example (`/marketplace.css`)
-```css
-.purchase-btn {
- margin-left: 8px;
- padding: 3px 8px;
- border: 1px solid #fde047;
- background-color: transparent;
- color: #fde047;
- border-radius: 4px;
- cursor: pointer;
- font-size: 10px;
- font-weight: 600;
- transition: background-color 0.2s, color 0.2s;
-}
-
-.purchase-btn:hover {
- background-color: #fde047;
- color: #111;
-}
-
-.price-owned {
- color: #a7f3d0;
- background-color: rgba(52, 211, 153, 0.1);
-}
-```
diff --git a/tasks/monetization-feature/03-backend-api-for-skill-pricing.md b/tasks/monetization-feature/03-backend-api-for-skill-pricing.md
deleted file mode 100644
index 16cefdd56..000000000
--- a/tasks/monetization-feature/03-backend-api-for-skill-pricing.md
+++ /dev/null
@@ -1,78 +0,0 @@
----
-status: completed
----
-
-# Prompt 3: Create API for Skill Pricing
-
-**Status:** Not Started
-
-## Objective
-Create backend API endpoints for creators to set, update, and remove prices for their agent's skills.
-
-## Explanation
-With the database table in place, creators need a way to manage the prices of their skills. We will create a secure API endpoint that allows an agent's owner to define these prices. This endpoint will handle creating new price entries, updating existing ones, and deleting them.
-
-## Instructions
-- **Create a New API Route:**
- - Create a new API file, for example, `/api/agents/[id]/skill-prices.js`.
- - This route will handle `POST`, `PUT`, and `DELETE` requests for a specific agent's skill prices.
- - Ensure the route is protected and can only be accessed by the authenticated owner of the agent.
-
-- **Implement the `POST` Handler (Create/Update):**
- - The `POST` handler will receive a skill name, an amount, and a currency mint in the request body.
- - It should use an `INSERT ... ON CONFLICT` (UPSERT) query to either create a new price entry or update an existing one for the given agent and skill. This is more efficient than checking for existence first.
- - Validate the input data. The amount should be a non-negative integer.
-
-- **Implement the `DELETE` Handler (Remove):**
- - The `DELETE` handler will receive a skill name in the request body or query parameters.
- - It will execute a `DELETE` query to remove the price entry from the `agent_skill_prices` table for that agent and skill.
-
-## Code Example (Backend - `/api/agents/[id]/skill-prices.js`)
-
-```javascript
-// Example using Node.js, Express-like syntax, and `sql` from './_lib/db.js'
-
-import { getSessionUser } from './_lib/auth.js';
-import { sql } from './_lib/db.js';
-import { error, json, method, readJson, wrap } from './_lib/http.js';
-
-export default wrap(async (req, res, id) => {
- if (!method(req, res, ['POST', 'DELETE'])) return;
-
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
-
- const [agent] = await sql`
- SELECT id, user_id FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL
- `;
- if (!agent) return error(res, 404, 'not_found', 'agent not found');
- if (agent.user_id !== user.id) return error(res, 403, 'forbidden', 'not your agent');
-
- const body = await readJson(req);
- const { skill_name } = body;
- if (!skill_name) return error(res, 400, 'validation_error', 'skill_name is required');
-
- if (req.method === 'POST') {
- const { amount, currency_mint } = body;
- if (amount == null || !currency_mint) {
- return error(res, 400, 'validation_error', 'amount and currency_mint are required');
- }
-
- const [price] = await sql`
- INSERT INTO agent_skill_prices (agent_id, skill_name, amount, currency_mint)
- VALUES (${id}, ${skill_name}, ${BigInt(amount)}, ${currency_mint})
- ON CONFLICT (agent_id, skill_name)
- DO UPDATE SET amount = EXCLUDED.amount, currency_mint = EXCLUDED.currency_mint, updated_at = NOW()
- RETURNING *
- `;
- return json(res, 200, { price });
- }
-
- if (req.method === 'DELETE') {
- await sql`
- DELETE FROM agent_skill_prices WHERE agent_id = ${id} AND skill_name = ${skill_name}
- `;
- return json(res, 200, { ok: true });
- }
-});
-```
diff --git a/tasks/monetization-feature/03-backend-api-set-skill-price.md b/tasks/monetization-feature/03-backend-api-set-skill-price.md
deleted file mode 100644
index 08d052f0c..000000000
--- a/tasks/monetization-feature/03-backend-api-set-skill-price.md
+++ /dev/null
@@ -1,73 +0,0 @@
----
-status: completed
----
-
-# Prompt 3: Backend API - Set/Update Skill Price
-
-**Status:** Not Started
-
-## Objective
-Create a secure API endpoint that allows an agent's creator to set or update the price of a skill.
-
-## Explanation
-Now that the database table exists, creators need a way to manage their skill prices. This endpoint will accept a price, skill name, and agent ID. It must be secure, ensuring that only the authenticated user who owns the agent can modify its skill prices.
-
-## Instructions
-- [ ] **Create a new API file:** `api/marketplace/set-skill-price.js`.
-- [ ] **Implement the endpoint logic:**
- - [ ] It should handle `POST` requests.
- - [ ] It must authenticate the user (e.g., via a session or API key).
- - [ ] It needs to verify that the authenticated user is the owner of the agent they are trying to price a skill for.
- - [ ] It will take `agent_id`, `skill_name`, `amount`, and `currency_mint` as input from the request body.
- - [ ] Use an `INSERT ... ON CONFLICT` (or "upsert") query to create or update the price in the `agent_skill_prices` table.
-
-## Code Example (`api/marketplace/set-skill-price.js`)
-
-```javascript
-import { sql } from '../_lib/db.js';
-import { json, method, cors, error, auth } from '../_lib/http.js';
-
-export default async function setSkillPrice(req, res) {
- if (cors(req, res)) return;
- if (!method(req, res, ['POST'])) return;
- const authUser = await auth(req, res);
- if (!authUser) return;
-
- const { agent_id, skill_name, amount, currency_mint } = req.body;
-
- if (!agent_id || !skill_name || !amount || !currency_mint) {
- return error(res, 400, 'bad_request', 'Missing required fields.');
- }
-
- try {
- // First, verify ownership of the agent
- const [agent] = await sql`
- SELECT id FROM agents WHERE id = ${agent_id} AND user_id = ${authUser.id}
- `;
-
- if (!agent) {
- return error(res, 403, 'forbidden', 'You do not own this agent.');
- }
-
- // Now, upsert the price
- await sql`
- INSERT INTO agent_skill_prices (agent_id, skill_name, amount, currency_mint, updated_at)
- VALUES (${agent_id}, ${skill_name}, ${amount}, ${currency_mint}, NOW())
- ON CONFLICT (agent_id, skill_name)
- DO UPDATE SET
- amount = EXCLUDED.amount,
- currency_mint = EXCLUDED.currency_mint,
- updated_at = NOW();
- `;
-
- return json(res, 200, { ok: true, message: 'Price set successfully.' });
-
- } catch (e) {
- console.error('Error setting skill price:', e);
- return error(res, 500, 'server_error', 'Failed to set skill price.');
- }
-}
-```
-
-## Tracking
-- To mark this task as complete, check all boxes in the instructions and change the status in the frontmatter to `Completed`.
diff --git a/tasks/monetization-feature/03-backend-api-set-skill-prices.md b/tasks/monetization-feature/03-backend-api-set-skill-prices.md
deleted file mode 100644
index 64583b832..000000000
--- a/tasks/monetization-feature/03-backend-api-set-skill-prices.md
+++ /dev/null
@@ -1,91 +0,0 @@
----
-status: completed
----
-# Prompt 3: Backend API for Setting Skill Prices
-
-**Status:** Completed
-
-## Objective
-Create a secure backend API endpoint for creators to save or update the prices for their agent's skills.
-
-## Explanation
-This endpoint will receive the pricing data from the creator UI (created in Prompt 2) and persist it to the `agent_skill_prices` database table. It's crucial to ensure that only the agent's owner can modify its skill prices.
-
-## Instructions
-- [x] **Create a New API Route:**
- - [x] In the `api/agents/` directory, create a new file or modify an existing one to handle a `POST` request, for example, `/api/agents/:id/skill-prices`.
-
-- [x] **Implement Authorization:**
- - [x] The endpoint must be protected. Verify the user's session or API token.
- - [x] Check that the authenticated user is the owner of the agent specified by the `:id` parameter. If not, return a `403 Forbidden` error.
-
-- [x] **Handle the Request:**
- - [x] The request body will contain an array of skill prices, like `{ prices: [{ skill_name: "...", amount: 500000, currency_mint: "..." }] }`.
- - [x] Validate the input data. Ensure `amount` is a non-negative number and `currency_mint` is a valid Solana mint address.
-
-- [x] **Database Interaction:**
- - [x] For the given `agent_id`, update the `agent_skill_prices` table.
- - [x] A good approach is to use an "upsert" operation: if a price for a skill exists, update it; otherwise, insert a new row. You could also delete all existing prices for the agent and insert the new ones.
- - [x] The table should store `agent_id`, `skill_name`, `amount`, and `currency_mint`.
-
-- [x] **Return a Response:**
- - [x] On success, return a `200 OK` or `204 No Content` response.
- - [x] On failure (validation error, database error), return an appropriate error code (e.g., `400 Bad Request`, `500 Internal Server Error`) with a descriptive message.
-
-## Code Example (Vercel Serverless Function)
-
-Here's a conceptual example of the API endpoint logic.
-
-```javascript
-// in /api/agents/[id]/skill-prices.js
-import { getAuth } from './_lib/auth';
-import { db } from './_lib/db';
-
-export default async function handler(req, res) {
- if (req.method !== 'POST') {
- return res.status(405).json({ error: 'Method Not Allowed' });
- }
-
- const { id: agentId } = req.query;
- const { prices } = req.body;
-
- // 1. Authorization
- const user = await getAuth(req);
- if (!user) {
- return res.status(401).json({ error: 'Unauthorized' });
- }
-
- const agent = await db.query('SELECT owner_id FROM agents WHERE id = $1', [agentId]);
- if (!agent.rows.length || agent.rows[0].owner_id !== user.id) {
- return res.status(403).json({ error: 'Forbidden' });
- }
-
- // 2. Validation (basic example)
- if (!Array.isArray(prices)) {
- return res.status(400).json({ error: 'Invalid payload' });
- }
-
- // 3. Database Interaction (transaction recommended)
- const client = await db.connect();
- try {
- await client.query('BEGIN');
- // Delete old prices
- await client.query('DELETE FROM agent_skill_prices WHERE agent_id = $1', [agentId]);
- // Insert new prices
- for (const price of prices) {
- await client.query(
- 'INSERT INTO agent_skill_prices (agent_id, skill_name, amount, currency_mint) VALUES ($1, $2, $3, $4)',
- [agentId, price.skill_name, price.amount, price.currency_mint]
- );
- }
- await client.query('COMMIT');
- res.status(204).end();
- } catch (e) {
- await client.query('ROLLBACK');
- console.error(e);
- res.status(500).json({ error: 'Failed to save prices' });
- } finally {
- client.release();
- }
-}
-```
diff --git a/tasks/monetization-feature/03-backend-create-purchase-table.md b/tasks/monetization-feature/03-backend-create-purchase-table.md
deleted file mode 100644
index e0b884379..000000000
--- a/tasks/monetization-feature/03-backend-create-purchase-table.md
+++ /dev/null
@@ -1,48 +0,0 @@
----
-status: completed
----
-
-# Prompt 3: Create Purchases Database Table
-
-**Status:** Not Started
-
-## Objective
-Create a new database table named `skill_purchases` to record and track every time a user buys a skill. This is a critical piece of infrastructure for managing ownership and revenue.
-
-## Explanation
-To know which users have access to which paid skills, we need a permanent record of each successful purchase. This table will link a user, an agent's skill, and the transaction details. It will serve as the source of truth for skill ownership.
-
-## Instructions
-
-1. **Define the Schema:**
- * Create a new SQL migration file or use your database management tool to define the schema for the `skill_purchases` table.
- * The table should include the following columns:
- * `id`: Primary key (e.g., UUID or auto-incrementing integer).
- * `user_id`: Foreign key referencing the `users` table. The ID of the user who made the purchase.
- * `agent_id`: Foreign key referencing the `agents` table. The agent who owns the skill.
- * `skill_name`: The name of the skill that was purchased (e.g., `text-to-speech`).
- * `transaction_signature`: The signature of the on-chain transaction. This is proof of payment.
- * `amount`: The price paid for the skill (in the smallest currency unit, e.g., lamports).
- * `currency_mint`: The mint address of the currency used for payment (e.g., USDC mint).
- * `created_at`: Timestamp of when the purchase was recorded.
-
-2. **Apply the Migration:**
- * Run the migration to create the new table in your database.
-
-## Example SQL Schema (PostgreSQL)
-
-```sql
-CREATE TABLE "skill_purchases" (
- "id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
- "user_id" uuid NOT NULL REFERENCES "users" ("id"),
- "agent_id" uuid NOT NULL REFERENCES "agents" ("id"),
- "skill_name" varchar(255) NOT NULL,
- "transaction_signature" varchar(255) UNIQUE NOT NULL,
- "amount" bigint NOT NULL,
- "currency_mint" varchar(255) NOT NULL,
- "created_at" timestamptz NOT NULL DEFAULT now()
-);
-
-CREATE INDEX "idx_skill_purchases_user_id" ON "skill_purchases" ("user_id");
-CREATE INDEX "idx_skill_purchases_agent_id" ON "skill_purchases" ("agent_id");
-```
diff --git a/tasks/monetization-feature/03-backend-create-skill-purchase-table.md b/tasks/monetization-feature/03-backend-create-skill-purchase-table.md
deleted file mode 100644
index 036437de3..000000000
--- a/tasks/monetization-feature/03-backend-create-skill-purchase-table.md
+++ /dev/null
@@ -1,40 +0,0 @@
----
-status: completed
----
-# Prompt 3: Create Skill Purchases Database Table
-
-**Status:** Not Started
-
-## Objective
-Create a database table to log and verify every time a user purchases a skill for one of their agents.
-
-## Explanation
-Tracking purchases is critical for granting users access to paid skills and for providing creators with sales history. The `skill_purchases` table will act as a ledger, recording which user bought which skill for which of their agents, along with transaction details for verification.
-
-## Instructions
-- **Connect to your database.**
-- **Execute the following SQL statement to create the `skill_purchases` table.**
-
-### SQL Schema
-```sql
-CREATE TABLE skill_purchases (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
- user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- skill_id UUID NOT NULL REFERENCES skills(id) ON DELETE CASCADE,
- price_id UUID NOT NULL REFERENCES agent_skill_prices(id),
- purchase_amount BIGINT NOT NULL,
- purchase_currency_mint VARCHAR(255) NOT NULL,
- transaction_signature VARCHAR(255) UNIQUE NOT NULL, -- For on-chain transaction verification
- purchased_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
-);
-
--- Create indexes for faster queries
-CREATE INDEX idx_skill_purchases_on_agent_id ON skill_purchases(agent_id);
-CREATE INDEX idx_skill_purchases_on_user_id ON skill_purchases(user_id);
-CREATE INDEX idx_skill_purchases_on_skill_id ON skill_purchases(skill_id);
-```
-
-## Verification
-- Verify that the `skill_purchases` table exists in your database with the correct schema.
-- Ensure the indexes are created, as this table could grow large and will be queried frequently to check skill access rights.
diff --git a/tasks/monetization-feature/03-backend-purchase-skill-api.md b/tasks/monetization-feature/03-backend-purchase-skill-api.md
deleted file mode 100644
index 0713b9815..000000000
--- a/tasks/monetization-feature/03-backend-purchase-skill-api.md
+++ /dev/null
@@ -1,58 +0,0 @@
----
-status: completed
----
-# Prompt 3: Backend for Skill Purchase
-
-**Status:** Not Started
-
-## Objective
-Create the backend API endpoint and logic to handle a user's purchase of an agent skill using Solana Pay.
-
-## Explanation
-When a user clicks the "Purchase" button, the frontend will need to request a transaction from the backend. The backend will construct a Solana transaction, sign it, and send it back to the frontend for the user to approve and send to the network.
-
-## Instructions
-1. **Create a New API Endpoint:**
- * Create a new file or use the existing router to handle `POST /api/payments/purchase-skill`.
- * This endpoint should expect an `agentId` and `skillName` in the request body.
-2. **Input Validation:**
- * Verify the user is authenticated.
- * Check that the agent and skill exist.
- * Fetch the skill price from the `agent_skill_prices` table. Ensure the skill is actually for sale.
- * Verify the user does not already own this skill.
-3. **Construct the Solana Transaction:**
- * Use the Solana Web3.js library (`@solana/web3.js`).
- * Create a transaction to transfer the correct amount of USDC (or other currency) from the user's wallet to the agent creator's wallet.
- * You will need the agent creator's wallet address, which should be stored with the agent's data.
- * The transaction should include a memo instruction with the skill name and agent ID for record-keeping.
-4. **Record the Transaction:**
- * Before returning to the user, record the pending transaction in a database table (`skill_purchases`). Mark its status as "pending".
- * Include the transaction signature.
-5. **Return the Transaction:**
- * Serialize the transaction and send it back in the API response. The frontend will then prompt the user to sign and submit it.
- * You will need a separate webhook or confirmation listener to update the purchase status from "pending" to "completed" once the transaction is confirmed on the blockchain.
-
-## API Endpoint (`/api/payments/purchase-skill`)
-
-* **Method:** `POST`
-* **Body:**
- ```json
- {
- "agentId": "agent_id_here",
- "skillName": "skill_name_here",
- "userWallet": "user_public_key_here"
- }
- ```
-* **Success Response (200):**
- ```json
- {
- "transaction": "base64_serialized_transaction_here",
- "signature": "transaction_signature_here"
- }
- ```
-* **Error Response (400/500):**
- ```json
- {
- "error": "Descriptive error message."
- }
- ```
diff --git a/tasks/monetization-feature/03-backend-set-skill-price-api.md b/tasks/monetization-feature/03-backend-set-skill-price-api.md
deleted file mode 100644
index cf487048d..000000000
--- a/tasks/monetization-feature/03-backend-set-skill-price-api.md
+++ /dev/null
@@ -1,62 +0,0 @@
----
-status: completed
----
-
-# Prompt 3: Backend - Create API for Setting Skill Prices
-
-## Objective
-Create a secure API endpoint for agent creators to set or update the prices for their skills.
-
-## Explanation
-Now that the `agent_skill_prices` table exists, we need an API endpoint to allow creators to manage the prices of their skills. This endpoint will receive the skill ID, price, and currency, validate the request, and then insert or update the price in the database. It's crucial that only the creator of a skill can set its price.
-
-## Instructions
-1. **Create the API Route:**
- * Create a new API route, for example, `POST /api/agents/:agentId/skills/:skillId/price`.
- * This route should be protected and require user authentication.
-
-2. **Implement the Endpoint Logic:**
- * In the request handler, first, verify that the authenticated user is the owner of the agent and the skill. This is a critical security check.
- * Validate the incoming request body. It should contain `amount` (as a number) and `currency_mint` (as a string).
- * Implement the database logic to `INSERT` a new price record into `agent_skill_prices`. If a price for that skill by that creator already exists, `UPDATE` the existing record (an "upsert" operation).
- * Return a success response if the operation is successful, or an error response if the user is not authorized or the input is invalid.
-
-## Code Example (Backend API - e.g., using Express.js)
-
-```javascript
-// POST /api/agents/:agentId/skills/:skillId/price
-// (Middleware for authentication and agent ownership should be applied before this handler)
-
-async function setSkillPrice(req, res) {
- const { userId } = req.auth; // From auth middleware
- const { agentId, skillId } = req.params;
- const { amount, currency_mint } = req.body;
-
- // 1. Validate input
- if (typeof amount !== 'number' || !currency_mint || typeof currency_mint !== 'string') {
- return res.status(400).json({ error: 'Invalid input' });
- }
-
- // 2. Verify ownership (this logic depends on your schema)
- const isOwner = await verifySkillOwnership(userId, agentId, skillId);
- if (!isOwner) {
- return res.status(403).json({ error: 'Forbidden' });
- }
-
- // 3. Upsert the price in the database
- try {
- const { rows } = 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 UPDATE SET amount = EXCLUDED.amount, currency_mint = EXCLUDED.currency_mint, updated_at = NOW()
- RETURNING *`,
- [skillId, userId, amount, currency_mint]
- );
- res.status(200).json({ price: rows[0] });
- } catch (error) {
- console.error('Error setting skill price:', error);
- res.status(500).json({ error: 'Internal server error' });
- }
-}
-```
diff --git a/tasks/monetization-feature/03-backend-set-skill-prices-api.md b/tasks/monetization-feature/03-backend-set-skill-prices-api.md
deleted file mode 100644
index 579bcf166..000000000
--- a/tasks/monetization-feature/03-backend-set-skill-prices-api.md
+++ /dev/null
@@ -1,66 +0,0 @@
----
-status: completed
----
-
-# Prompt 3: Backend API to Set Skill Prices
-
-**Status:** Not Started
-
-## Objective
-Create a backend API endpoint that allows agent creators to set or update the price for a specific skill.
-
-## Explanation
-With the database table in place, we need a way for the frontend to communicate pricing information to the server. A secure API endpoint is required for this. The endpoint should ensure that only the owner of an agent can change the prices of its skills.
-
-## Instructions
-- [ ] **Create a new API file or modify an existing one.** A good place could be `api/agent-actions.js` or a new file like `api/agent-pricing.js`.
-- [ ] **Define the endpoint.** Use `POST /api/agents/:id/skills/price`.
-- [ ] **Implement authentication.** The endpoint must be protected. Verify that the authenticated user is the owner of the agent specified by `:id`.
-- [ ] **Validate the request body.** The body should contain `skill_name`, `amount`, and `currency_mint`. Use a library like `zod` for validation.
-- [ ] **Implement the database logic.** The endpoint should perform an "upsert" operation:
- - If a price for the agent's skill already exists, `UPDATE` it.
- - If it doesn't exist, `INSERT` a new row.
-- [ ] **Return a success response.** On successful creation or update, return a `200 OK` or `201 Created` status with the updated pricing information.
-- [ ] **Handle errors.** Return appropriate error codes (e.g., `401 Unauthorized`, `404 Not Found`, `400 Bad Request`, `500 Internal Server Error`).
-
-## Code Example (Express.js-like)
-
-```javascript
-// In api/agent-actions.js or similar
-
-// POST /api/agents/:id/skills/price
-// Body: { "skill_name": "...", "amount": 1000000, "currency_mint": "..." }
-
-export default async function handler(req, res) {
- // 1. Get authenticated user
- const user = await getAuthenticatedUser(req);
- const agentId = req.query.id;
-
- // 2. Verify ownership
- const agent = await db.query('SELECT * FROM agents WHERE id = $1', [agentId]);
- if (!agent || agent.owner_id !== user.id) {
- return res.status(401).json({ error: 'Unauthorized' });
- }
-
- // 3. Validate body
- const { skill_name, amount, currency_mint } = req.body;
- // ... validation logic ...
-
- // 4. Upsert price in DB
- const result = await db.query(
- `INSERT INTO agent_skill_prices (agent_id, skill_name, amount, currency_mint)
- VALUES ($1, $2, $3, $4)
- ON CONFLICT (agent_id, skill_name)
- DO UPDATE SET amount = $3, currency_mint = $4, updated_at = NOW()
- RETURNING *`,
- [agentId, skill_name, amount, currency_mint]
- );
-
- // 5. Return response
- res.status(200).json(result.rows[0]);
-}
-```
-
-## Tracking Completion
-- [ ] Mark this file's status as `Completed` in the frontmatter when done.
-- [ ] Check off all instructions.
diff --git a/tasks/monetization-feature/03-creator-ui-for-skill-pricing.md b/tasks/monetization-feature/03-creator-ui-for-skill-pricing.md
deleted file mode 100644
index d365228c4..000000000
--- a/tasks/monetization-feature/03-creator-ui-for-skill-pricing.md
+++ /dev/null
@@ -1,76 +0,0 @@
----
-title: "Prompt 3: Creator UI for Skill Pricing"
-status: completed
-
-## Objective
-Create a user interface in the agent editor that allows creators to view their agent's skills and set a price for each one.
-
-## Explanation
-To enable skill monetization, creators need a simple and intuitive way to manage the prices of their skills. This task involves adding a new section to the `agent-edit.html` page. This section will list all the skills associated with the agent and provide input fields for setting a price and selecting a currency.
-
-## Instructions
-1. **Locate the agent editor page:** Open the `agent-edit.html` file.
-2. **Add a new "Skill Pricing" section:** Find the area where skills are listed or managed. Add a new section with a clear heading like "Skill Monetization" or "Set Skill Prices".
-3. **Render skills with pricing inputs:**
- * Iterate through the agent's skills.
- * For each skill, display its name.
- * Add an `input[type="number"]` for the price amount.
- * Add a `select` dropdown to choose the currency (for now, we can hardcode USDC on Solana, but it should be extensible).
- * Add a "Save Prices" button.
-4. **Fetch existing prices:** When the page loads, the frontend should fetch the agent's details, including any already-saved skill prices, and populate the input fields with the current values.
-5. **Style the new section:** Ensure the new UI elements are well-styled and fit seamlessly into the existing design of the agent editor.
-
-## Code Example (HTML in `agent-edit.html`)
-
-```html
-<!-- Inside the main form or a relevant section of agent-edit.html -->
-<div class="panel">
- <h3>Skill Monetization</h3>
- <p class="note">Set a price for your skills. Leave blank for free skills. Prices are set in USDC.</p>
- <div id="skill-pricing-list">
- <!-- Skills will be dynamically rendered here by JavaScript -->
- </div>
- <div class="action-row">
- <button type="button" class="btn-primary" id="save-prices-btn">Save Prices</button>
- </div>
- <p id="save-prices-status" class="form-status" hidden></p>
-</div>
-```
-
-## Code Example (JavaScript for `agent-edit.html`)
-
-```javascript
-// In the script that manages agent-edit.html
-
-function renderSkillPricer(agent) {
- const container = document.getElementById('skill-pricing-list');
- const skills = agent.manifest?.skills || [];
- const prices = agent.skill_prices || {};
-
- if (!skills.length) {
- container.innerHTML = '<p class="note">This agent has no skills to price.</p>';
- return;
- }
-
- container.innerHTML = skills.map(skill => {
- const skillId = skill.name || 'unknown-skill';
- const currentPrice = prices[skillId];
- const amount = currentPrice ? (currentPrice.amount / 1e6).toFixed(2) : ''; // Assuming 6 decimal places for USDC
-
- return `
- <div class="skill-price-row" data-skill-id="${escapeHtml(skillId)}">
- <span class="skill-name">${escapeHtml(skillId)}</span>
- <div class="price-input-wrap">
- <input type="number" class="price-input" min="0" step="0.01" placeholder="Free" value="${amount}">
- <span class="currency-label">USDC</span>
- </div>
- </div>
- `;
- }).join('');
-}
-
-// Add event listener for the save button to collect and POST the data.
-document.getElementById('save-prices-btn').addEventListener('click', async () => {
- // ... logic to collect prices from inputs and call the backend API ...
-});
-```
diff --git a/tasks/monetization-feature/03-frontend-skill-purchase-button.md b/tasks/monetization-feature/03-frontend-skill-purchase-button.md
deleted file mode 100644
index 62b60354a..000000000
--- a/tasks/monetization-feature/03-frontend-skill-purchase-button.md
+++ /dev/null
@@ -1,72 +0,0 @@
----
-status: not-started
----
-
-# Prompt 3: Frontend - Add Skill Purchase Button
-
-## Objective
-Add a "Purchase" button for priced skills on the agent detail page to enable users to initiate the buying process.
-
-## Explanation
-With skill prices now displayed, the next step is to provide a clear call-to-action for users to purchase them. This involves replacing the static "Free" or price badge with an interactive "Purchase" button for paid skills. This button will be the entry point for the payment flow.
-
-## Instructions
-1. **Locate the Rendering Logic:**
- * Open `src/marketplace.js` and find the `renderDetail` function.
- * Identify the section where skill badges are currently rendered.
-
-2. **Conditionally Render a Button:**
- * Modify the loop that iterates through the agent's skills.
- * For each skill, check if a price exists in the `a.skill_prices` object.
- * If a price exists, instead of just a text badge, render a `<button>` element.
- * If the skill is free, continue to show the "Free" badge.
-
-3. **Embed Data in the Button:**
- * The purchase button must contain the necessary information to initiate a transaction.
- * Add `data-*` attributes to the button to store the `skill_name` and `agent_id`.
-
-## Code Example (`src/marketplace.js`)
-
-```javascript
-// Inside renderDetail function, modify the skill mapping
-
-const skillPrices = a.skill_prices || {};
-$('d-skills').innerHTML = skillsArr.length
- ? skillsArr.map((s) => {
- const name = typeof s === 'string' ? s : (s.name || '');
- const price = skillPrices[name];
-
- const badge = price
- ? `<button class="purchase-btn" data-skill="${escapeHtml(name)}" data-agent="${a.id}">
- Purchase for ${(price.amount / 1e6).toFixed(2)} USDC
- </button>`
- : `<span class="price-badge price-free">Free</span>`;
-
- return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;
- }).join(' ')
- : '<div>This Agent has no skills defined.</div>';
-```
-
-## CSS Example (`/marketplace.css`)
-
-Add styles for the new purchase button.
-
-```css
-.purchase-btn {
- margin-left: 8px;
- padding: 4px 10px;
- font-size: 12px;
- font-weight: 600;
- border-radius: 6px;
- border: 1px solid #fde047;
- color: #fde047;
- background-color: rgba(253, 224, 71, 0.1);
- cursor: pointer;
- transition: background-color 0.2s, color 0.2s;
-}
-
-.purchase-btn:hover {
- background-color: #fde047;
- color: #111827;
-}
-```
diff --git a/tasks/monetization-feature/03-monetization-page-UI.md b/tasks/monetization-feature/03-monetization-page-UI.md
deleted file mode 100644
index 4f257e77e..000000000
--- a/tasks/monetization-feature/03-monetization-page-UI.md
+++ /dev/null
@@ -1,32 +0,0 @@
----
-status: completed
----
-
-# Prompt 3: Monetization Page UI
-
-## Objective
-Create the user interface for the monetization page, allowing creators to set prices for their agent's skills.
-
-## Explanation
-With the backend ready, we now need a UI that allows agent creators to manage the prices of their skills. This will be a new "Monetization" tab in the agent editor (`agent-edit.html`). The UI will fetch the agent's skills and their current prices, display them in a form, and allow the creator to save changes.
-
-## Instructions
-- [ ] **Add a "Monetization" Tab:**
- - [ ] In `agent-edit.html`, add a new tab to the tab list named "Monetization".
- - [ ] Create a corresponding panel for the monetization content.
-
-- [ ] **Build the Pricing Form:**
- - [ ] In the new panel, create a form that lists all of the agent's skills.
- - [ ] For each skill, display a text input field to enter the price in USDC.
- - [ ] Fetch the current prices from the API endpoint you created earlier (`/api/agents/:id/skills-pricing`) and populate the form.
- - [ ] Add a "Save Prices" button.
-
-- [ ] **Implement Save Functionality:**
- - [ ] When the "Save Prices" button is clicked, collect the data from the form.
- - [ ] For each skill, create a price object `{ skill, amount, currency_mint, chain }`. Remember to convert the USDC amount back to the smallest unit (e.g., multiply by 1,000,000).
- - [ ] Send this data to the backend via a `PUT` request to `/api/agents/:id/skills-pricing`.
- - [ ] Display a success or error message to the user.
-
-- [ ] **Handle Loading and Error States:**
- - [ ] Show a loading indicator while fetching prices.
- - [ ] Display a clear error message if the API call fails.
diff --git a/tasks/monetization-feature/03-paid-skill-badge.md b/tasks/monetization-feature/03-paid-skill-badge.md
deleted file mode 100644
index ff35483b9..000000000
--- a/tasks/monetization-feature/03-paid-skill-badge.md
+++ /dev/null
@@ -1,82 +0,0 @@
-# Prompt 3: Paid Skill Badge in Marketplace List
-
-## Objective
-Add a visual indicator to the agent cards in the main marketplace grid (`/marketplace`) for agents that have one or more paid skills.
-
-## Explanation
-To increase the visibility of monetized agents and help users find premium content, we need to show a badge or icon on the agent cards in the main list view. This tells a user at a glance that an agent offers paid capabilities without needing to click into the detail page.
-
-## Instructions
-
-1. **Modify the Backend API:**
- * Locate the API endpoint that serves the agent list data (`/api/marketplace/agents`). This is in `api/marketplace/[action].js`.
- * In the SQL query that fetches the list of agents, you need to add a check to see if each agent has any active, priced skills.
- * A good way to do this is with a subquery or a `LEFT JOIN` and `COUNT`. An `EXISTS` subquery is often the most performant.
- * The query should return a new boolean field for each agent, e.g., `has_paid_skills`.
-
-2. **Update the Frontend UI:**
- * In `src/marketplace.js`, find the `renderCard` function.
- * This function receives the agent object, which will now include the `has_paid_skills` boolean.
- * Add a conditional block to the card's HTML template. If `has_paid_skills` is true, render a "Paid" or "$" badge.
- * This is typically done in the `stats` section of the card, alongside views and forks.
-
-## Code Example (Backend - SQL in `api/marketplace/[action].js`)
-
-Here's how you can modify the agent list query to include the `has_paid_skills` flag.
-
-```sql
--- Inside the handleList function's SQL query
-
-SELECT
- ai.id, ai.name, ai.description, ai.category, -- ... other fields
- EXISTS (
- SELECT 1 FROM agent_skill_prices asp
- WHERE asp.agent_id = ai.id AND asp.is_active = true AND asp.amount > 0
- ) AS has_paid_skills
-FROM
- agent_identities ai
--- ... rest of the query
-```
-
-## Code Example (Frontend - `src/marketplace.js`)
-
-Modify the `renderCard` function to use the new flag.
-
-```javascript
-function renderCard(a) {
- const date = a.published_at ? formatDate(a.published_at) : '';
- const skills = (a.skills || []).length;
- return `<div class="market-card-agent" data-id="${a.id}">
- <div class="head">
- <div class="avatar">${initial(a.name)}</div>
- <div style="min-width:0;flex:1">
- <div class="title">${escapeHtml(a.name || 'Untitled')}</div>
- <div class="author">${escapeHtml(a.author_name || 'Anonymous')}</div>
- </div>
- </div>
- <div class="desc">${escapeHtml(a.description || '')}</div>
- <div class="stats">
- <span class="stat-pill">⊙ ${a.views_count || 0}</span>
- <span class="stat-pill">⑂ ${a.forks_count || 0}</span>
- ${skills ? `<span class="stat-pill">▤ ${skills}</span>` : ''}
- ${a.has_paid_skills ? `<span class="stat-pill paid-badge">$ Paid</span>` : ''}
- </div>
- <div class="footer">
- <span>${date}</span>
- <span class="cat-pill">${CATEGORY_LABELS[a.category] || a.category || ''}</span>
- </div>
- </div>`;
-}
-```
-
-## CSS Example
-
-Add styles for the new badge in `marketplace.css`.
-
-```css
-.stat-pill.paid-badge {
- color: #fde047;
- border: 1px solid rgba(253, 224, 71, 0.3);
- background-color: rgba(253, 224, 71, 0.1);
-}
-```
diff --git a/tasks/monetization-feature/03-ui-creator-dashboard-for-pricing.md b/tasks/monetization-feature/03-ui-creator-dashboard-for-pricing.md
deleted file mode 100644
index d5b1df646..000000000
--- a/tasks/monetization-feature/03-ui-creator-dashboard-for-pricing.md
+++ /dev/null
@@ -1,31 +0,0 @@
----
-status: completed
----
-
-# Prompt 3: UI - Creator Dashboard for Pricing
-
-**Status:** Not Started
-
-## Objective
-Create a new section in the agent creator dashboard that allows creators to set and manage prices for their skills.
-
-## Explanation
-With the backend ready to store prices, we need a user interface for creators to manage them. This involves adding a new section to the agent edit page where each skill is listed with an input field to set its price.
-
-## Instructions
-- [ ] **Locate the agent edit page's code** (likely in `agent-edit.html` and its corresponding JavaScript file).
-- [ ] **Fetch the agent's skills and any existing prices.**
-- [ ] **For each skill, display its name and an input form.** The form should contain:
- - An input field for the `amount`.
- - A dropdown to select the `currency` (e.g., USDC, SOL). This should be pre-populated with supported currencies.
-- [ ] **Implement a "Save Prices" button.** When clicked, this should:
- - Gather the pricing data for all skills.
- - Make an API call to a new endpoint (`/api/agents/:id/skill-prices`) to save the data.
- - Handle both creating new prices and updating existing ones.
-- [ ] **Provide feedback to the user,** such as a confirmation message on successful save or an error message on failure.
-
-## API Endpoint (`POST /api/agents/:id/skill-prices`)
-You'll need to create this new endpoint. It should:
-- Be authenticated to ensure only the agent's owner can set prices.
-- Accept a payload like: `{ "prices": { "text-to-speech": { "amount": 500000, "currency_mint": "EP..." } } }`
-- Upsert the prices into the `agent_skill_prices` table.
diff --git a/tasks/monetization-feature/04-backend-api-set-skill-price.md b/tasks/monetization-feature/04-backend-api-set-skill-price.md
deleted file mode 100644
index 044da811c..000000000
--- a/tasks/monetization-feature/04-backend-api-set-skill-price.md
+++ /dev/null
@@ -1,89 +0,0 @@
----
-status: completed
----
-
-# Prompt 4: API to Set Skill Prices
-
-**Status:** Not Started
-
-## Objective
-Create a secure backend API endpoint that allows the creator of an agent to set or update the price for one of their agent's skills.
-
-## Explanation
-To enable monetization, creators need a way to manage the prices of their skills. This endpoint will provide that functionality. It must be secure, ensuring that only the agent's owner can change the prices.
-
-## Instructions
-
-1. **Create the API Endpoint:**
- * Create a new API file, e.g., `api/agent/set-skill-price.js`.
- * This endpoint should accept a `POST` request.
-
-2. **Implement Authentication & Authorization:**
- * The endpoint must be protected. Ensure a user is logged in.
- * Verify that the authenticated user is the owner of the agent whose skill price is being set. You will need to fetch the agent's details from the database using the provided `agent_id` and compare the owner's ID with the current user's ID.
-
-3. **Handle the Request Body:**
- * The request body should contain:
- * `agent_id`: The ID of the agent.
- * `skill_name`: The name of the skill to price.
- * `amount`: The price in the smallest currency unit (e.g., lamports).
- * `currency_mint`: The currency's mint address.
-
-4. **Update the Database:**
- * In your `agent_skill_prices` table, perform an "upsert" operation:
- * If a price for that `agent_id` and `skill_name` already exists, **update** it.
- * If it doesn't exist, **insert** a new row.
- * Return a success response.
-
-## Code Example (Node.js / Vercel Serverless Function)
-
-```javascript
-// In /api/agent/set-skill-price.js
-
-import { supabase } from '../_lib/supabase';
-import { authenticate } from '../_lib/auth';
-
-export default async function handler(req, res) {
- if (req.method !== 'POST') {
- return res.status(405).json({ error: 'Method not allowed' });
- }
-
- const user = await authenticate(req);
- if (!user) {
- return res.status(401).json({ error: 'Unauthorized' });
- }
-
- const { agent_id, skill_name, amount, currency_mint } = req.body;
-
- // 1. Verify ownership
- const { data: agent, error: agentError } = await supabase
- .from('agents')
- .select('owner_id')
- .eq('id', agent_id)
- .single();
-
- if (agentError || !agent || agent.owner_id !== user.id) {
- return res.status(403).json({ error: 'You do not own this agent.' });
- }
-
- // 2. Upsert the price
- const { error: priceError } = await supabase
- .from('agent_skill_prices')
- .upsert({
- agent_id,
- skill_name,
- amount,
- currency_mint,
- updated_at: new Date(),
- }, {
- onConflict: 'agent_id, skill_name'
- });
-
- if (priceError) {
- console.error('Error setting skill price:', priceError);
- return res.status(500).json({ error: 'Failed to set skill price.' });
- }
-
- return res.status(200).json({ success: true });
-}
-```
diff --git a/tasks/monetization-feature/04-backend-create-purchase-table.md b/tasks/monetization-feature/04-backend-create-purchase-table.md
deleted file mode 100644
index e06005ed5..000000000
--- a/tasks/monetization-feature/04-backend-create-purchase-table.md
+++ /dev/null
@@ -1,42 +0,0 @@
----
-status: completed
----
-
-# Prompt 4: Backend - Create Purchase History Table
-
-**Status:** Not Started
-
-## Objective
-Create a database table to log every skill purchase, serving as a permanent record of transactions.
-
-## Explanation
-To manage access to paid skills, we need to record who purchased what. The `skill_purchases` table will store the user who made the purchase, the agent and skill they bought, the transaction details (like a Solana transaction signature), and the amount paid. This table is crucial for verifying access and for creator analytics.
-
-## Instructions
-- [ ] **Connect to your database.**
-- [ ] **Execute the following SQL schema to create the `skill_purchases` table.** This schema links a user to a specific agent's skill. It's designed to prevent duplicate purchase records for the same skill and includes a unique transaction signature.
-
-## SQL Schema
-
-```sql
-CREATE TABLE IF NOT EXISTS skill_purchases (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- user_id UUID NOT NULL,
- agent_id UUID NOT NULL,
- skill_name VARCHAR(255) NOT NULL,
- amount_paid BIGINT NOT NULL,
- currency_mint VARCHAR(44) NOT NULL,
- transaction_ref VARCHAR(255) UNIQUE NOT NULL, -- e.g., Solana Tx Signature or Stripe Charge ID
- purchase_date TIMESTAMPTZ DEFAULT NOW(),
-
- -- Ensures a user can only buy a specific skill on an agent once
- UNIQUE (user_id, agent_id, skill_name)
-);
-
--- Add indexes for common query patterns
-CREATE INDEX IF NOT EXISTS idx_skill_purchases_user_id ON skill_purchases(user_id);
-CREATE INDEX IF NOT EXISTS idx_skill_purchases_agent_id ON skill_purchases(agent_id);
-```
-
-## Tracking
-- To mark this task as complete, check the box in the instructions above and change the status in the frontmatter to `Completed`.
diff --git a/tasks/monetization-feature/04-backend-create-purchases-table.md b/tasks/monetization-feature/04-backend-create-purchases-table.md
deleted file mode 100644
index 09b5ec7af..000000000
--- a/tasks/monetization-feature/04-backend-create-purchases-table.md
+++ /dev/null
@@ -1,49 +0,0 @@
----
-status: not-started
----
-
-# Prompt 4: Create Purchases Database Table
-
-**Status:** Not Started
-
-## Objective
-Create a database table (`skill_purchases`) to record which users have purchased which skills.
-
-## Explanation
-To grant users access to paid skills, we need to track their purchases. This table will create an association between a user, an agent's skill, and the transaction details of the purchase.
-
-## Instructions
-- [ ] **Update the Migration Script:**
- - [ ] Add a new `CREATE TABLE` statement to your `scripts/migrate-db.mjs` script.
-- [ ] **Define the Table Schema:**
- - [ ] The `skill_purchases` table should include:
- - `user_id`: Foreign key to the `users` table.
- - `agent_id`: Foreign key to the `agent_identities` table.
- - `skill_name`: The name of the skill purchased.
- - `transaction_signature`: The Solana transaction signature of the purchase.
- - `purchase_amount`: The amount paid.
- - `purchase_currency_mint`: The currency used.
- - `created_at`: A timestamp for the purchase date.
- - [ ] Create a primary key or unique constraint on `(user_id, agent_id, skill_name)`.
-- [ ] **Execute and Verify:**
- - [ ] Run the migration script.
- - [ ] Verify the table is created correctly in your database.
-
-## Code Example (SQL)
-
-```sql
-CREATE TABLE IF NOT EXISTS skill_purchases (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- agent_id UUID NOT NULL,
- skill_name VARCHAR(255) NOT NULL,
- transaction_signature VARCHAR(255) UNIQUE NOT NULL,
- purchase_amount BIGINT NOT NULL,
- purchase_currency_mint VARCHAR(255) NOT NULL,
- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
- -- Foreign key to the prices table at the time of purchase
- FOREIGN KEY (agent_id, skill_name) REFERENCES agent_skill_prices(agent_id, skill_name) ON DELETE SET NULL,
- -- Prevent user from buying the same skill twice
- UNIQUE (user_id, agent_id, skill_name)
-);
-```
diff --git a/tasks/monetization-feature/04-backend-for-saving-skill-prices.md b/tasks/monetization-feature/04-backend-for-saving-skill-prices.md
deleted file mode 100644
index f5ad3ee28..000000000
--- a/tasks/monetization-feature/04-backend-for-saving-skill-prices.md
+++ /dev/null
@@ -1,90 +0,0 @@
----
-title: "Prompt 4: Backend for Saving Skill Prices"
-status: "completed"
----
-
-# Prompt 4: Backend for Saving Skill Prices
-
-**Status:** Completed
-
-## Objective
-Create the backend API endpoint to receive and persist the skill pricing data submitted from the creator UI.
-
-## Explanation
-With the creator UI in place, we now need a secure and efficient API endpoint to handle the data. This endpoint will receive a list of skill prices for a specific agent, validate that the request is coming from the agent's owner, and then atomically update the `agent_skill_prices` table.
-
-## Instructions
-1. **Create a new API route:** Create a file at `api/agents/[agentId]/skills-pricing.js`. This will create a dynamic route that handles requests for specific agents.
-2. **Implement the handler:**
- * The handler should only accept `PUT` requests.
- * It must authenticate the request and ensure a user is logged in.
- * It must validate that the logged-in user is the owner of the agent specified in the URL (`agentId`).
- * It should expect a JSON body with a `prices` array, like `[{ "skill_id": "...", "amount": 1000000, "currency_mint": "..." }]`.
- * Use a database transaction to first `DELETE` all existing prices for the agent and then `INSERT` the new ones. This ensures data consistency.
- * Return a success message on completion or a descriptive error on failure.
-
-## Code Example (`api/agents/[agentId]/skills-pricing.js`)
-
-```javascript
-import { getDb, getSession } from '../_lib/db.js';
-import { json, error } from '../_lib/res.js';
-
-export default async function handler(req, res) {
- if (req.method !== 'PUT') {
- return error(res, 405, 'Method Not Allowed');
- }
-
- const session = await getSession(req, res);
- if (!session.userId) {
- return error(res, 401, 'Unauthorized');
- }
-
- const { agentId } = req.query;
- if (!agentId || typeof agentId !== 'string') {
- return error(res, 400, 'Bad Request: Missing or invalid agentId');
- }
-
- const { prices } = req.body;
- if (!Array.isArray(prices)) {
- return error(res, 400, 'Bad Request: "prices" must be an array');
- }
-
- const db = await getDb();
-
- try {
- // First, verify that the user owns the agent.
- const agent = await db.oneOrNone('SELECT id FROM agent_identities WHERE id = $1 AND user_id = $2 AND deleted_at IS NULL', [agentId, session.userId]);
- if (!agent) {
- return error(res, 403, 'Forbidden: You do not own this agent');
- }
-
- // Use a transaction to update prices atomically.
- await db.tx(async t => {
- // Clear existing prices for this agent.
- await t.none('DELETE FROM agent_skill_prices WHERE agent_id = $1', [agentId]);
-
- if (prices.length === 0) {
- return; // Nothing more to do if the array is empty.
- }
-
- // Use a multi-row insert for efficiency.
- const cs = new t.helpers.ColumnSet(['agent_id', 'skill_id', 'amount', 'currency_mint'], { table: 'agent_skill_prices' });
- const values = prices.map(p => ({
- agent_id: agentId,
- skill_id: p.skill_id,
- amount: p.amount,
- currency_mint: p.currency_mint,
- }));
-
- const query = t.helpers.insert(values, cs);
- await t.none(query);
- });
-
- return json(res, 200, { message: 'Prices updated successfully' });
-
- } catch (err) {
- console.error('Error saving skill prices:', err);
- return error(res, 500, 'Internal Server Error', err.message);
- }
-}
-```
diff --git a/tasks/monetization-feature/04-backend-skill-purchase-api.md b/tasks/monetization-feature/04-backend-skill-purchase-api.md
deleted file mode 100644
index ecea431de..000000000
--- a/tasks/monetization-feature/04-backend-skill-purchase-api.md
+++ /dev/null
@@ -1,29 +0,0 @@
----
-status: completed
----
-
-# Prompt 4: Backend - Skill Purchase API
-
-**Status:** Not Started
-
-## Objective
-Create the backend infrastructure for users to purchase access to a paid skill. This involves creating a Solana Pay-compatible API endpoint.
-
-## Explanation
-When a user wants to use a paid skill, our platform needs to facilitate the transaction. We will create a Solana Pay endpoint that, when called, returns the details of the transaction that the user needs to sign and send.
-
-## Instructions
-- [ ] **Create a new API endpoint, e.g., `POST /api/skills/purchase`**.
-- [ ] **Define the request body.** It should include:
- - `agent_id`: The ID of the agent whose skill is being purchased.
- - `skill_name`: The name of the skill.
- - `account`: The user's Solana public key.
-- [ ] **Implement the endpoint logic:**
- - 1. **Fetch skill price:** Look up the price of the skill in the `agent_skill_prices` table.
- - 2. **Construct the transaction:** Create a Solana transaction that transfers the specified `amount` of the `currency_mint` from the user's `account` to the agent creator's wallet.
- - 3. **Add a memo:** Include a memo in the transaction to identify the purchase (e.g., "Purchase of skill 'text-to-speech' for agent 'AI Assistant'").
- - 4. **Serialize the transaction:** The transaction should be partially signed (if necessary) and serialized.
- - 5. **Return the Solana Pay response:** The response should follow the Solana Pay specification, including the serialized `transaction` and a `message`.
-
-## Solana Pay
-Refer to the official [Solana Pay documentation](https://docs.solanapay.com/spec) for the exact request and response formats. This will ensure compatibility with Solana wallets.
diff --git a/tasks/monetization-feature/04-backend-solana-pay-endpoint.md b/tasks/monetization-feature/04-backend-solana-pay-endpoint.md
deleted file mode 100644
index 930e8df73..000000000
--- a/tasks/monetization-feature/04-backend-solana-pay-endpoint.md
+++ /dev/null
@@ -1,85 +0,0 @@
----
-status: not-started
----
-
-# Prompt 4: Backend - Create Solana Pay Endpoint
-
-## Objective
-Create a backend endpoint that generates a Solana Pay transaction for a skill purchase, allowing for a seamless on-chain payment experience.
-
-## Explanation
-To enable decentralized payments, we will use Solana Pay. This requires a dedicated backend endpoint that, when requested, constructs and returns a Solana transaction tailored to the specific skill purchase. The frontend will then use this to generate a QR code for mobile wallets or to prompt browser extension wallets.
-
-## Instructions
-1. **Create a New API Route:**
- * Create a new file at `/api/payments/solana-pay.js`.
-
-2. **Implement the Endpoint Logic:**
- * The endpoint should handle `POST` requests.
- * It should expect a JSON body containing the `agent_id` and `skill_name`.
- * It needs to fetch the skill's price from the `agent_skill_prices` table.
- * It must identify the recipient's wallet address (the agent creator's address).
- * Using the Solana SDK (`@solana/web3.js`), construct a system transfer transaction.
- * The transaction should transfer the correct `amount` of the specified `currency_mint` from the buyer to the creator.
-
-3. **Return Solana Pay Spec Response:**
- * The endpoint must return a JSON object that conforms to the Solana Pay specification.
- * This includes a base64-encoded, serialized transaction, a `label`, and a `message`.
-
-## Code Example (`/api/payments/solana-pay.js`)
-
-```javascript
-import { sql } from '../_lib/db.js';
-import { json, error, wrap, readJson } from '../_lib/http.js';
-import { getSessionUser } from '../_lib/auth.js';
-import { Connection, PublicKey, SystemProgram, Transaction } from '@solana/web3.js';
-import { z } from 'zod';
-
-const purchaseSchema = z.object({
- agent_id: z.string().uuid(),
- skill_name: z.string().min(1).max(128),
-});
-
-export default wrap(async (req, res) => {
- if (req.method !== 'POST') return error(res, 405, 'method_not_allowed');
-
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized');
-
- const body = await readJson(req);
- const { agent_id, skill_name } = purchaseSchema.parse(body);
-
- // 1. Fetch price and creator's wallet
- const [priceInfo] = await sql`...`; // Get price and creator wallet
- if (!priceInfo) return error(res, 404, 'price_not_found');
-
- // 2. Setup Solana connection
- const connection = new Connection(process.env.SOLANA_RPC_URL);
- const buyer = new PublicKey(user.wallet_address);
- const recipient = new PublicKey(priceInfo.creator_wallet_address);
-
- // 3. Create transaction
- const { blockhash } = await connection.getLatestBlockhash();
- const tx = new Transaction({
- recentBlockhash: blockhash,
- feePayer: buyer,
- }).add(
- SystemProgram.transfer({
- fromPubkey: buyer,
- toPubkey: recipient,
- lamports: priceInfo.amount,
- })
- );
-
- // 4. Serialize and encode
- const serializedTx = tx.serialize({ requireAllSignatures: false });
- const base64Tx = serializedTx.toString('base64');
-
- // 5. Return Solana Pay response
- return json(res, 200, {
- transaction: base64Tx,
- label: '3D-Agent Skill Purchase',
- message: `Purchase '${skill_name}' for Agent`,
- });
-});
-```
diff --git a/tasks/monetization-feature/04-create-payment-intent-api.md b/tasks/monetization-feature/04-create-payment-intent-api.md
deleted file mode 100644
index 79971e163..000000000
--- a/tasks/monetization-feature/04-create-payment-intent-api.md
+++ /dev/null
@@ -1,95 +0,0 @@
-# Prompt 4: Create Payment Intent API
-
-## Objective
-Create a new backend API endpoint that generates a "payment intent." This intent is a secure, server-side record of a pending transaction, including what is being bought, by whom, and for how much.
-
-## Explanation
-Before a user can make a payment on the frontend, the backend needs to create a secure reference for the transaction. This is called a "payment intent." The frontend will request this intent right before showing the payment modal. The intent contains all the necessary details for the frontend to construct the transaction (like the recipient's address and the exact amount), and it provides a unique ID that we can use later to verify the payment's status.
-
-## Instructions
-1. **Create a New API File:**
- * Create a new file at `api/payments/intent.js`. This will house the logic for creating payment intents.
-
-2. **Define the Endpoint Logic:**
- * The endpoint should accept a `POST` request.
- * It must be authenticated, as only logged-in users can purchase skills.
- * The request body should contain the `agent_id` and `skill_name` the user wants to purchase.
-
-3. **Implement the Core Logic:**
- * Look up the agent to ensure it exists and is published.
- * Look up the skill price in the `agent_skill_prices` table using the `agent_id` and `skill_name`. If no price is found, return an error.
- * Look up the agent creator's payout wallet address. For now, this can be stored on the `agent_identities` table or in a related table.
- * Generate a unique ID for this intent. A `uuid` is a good choice.
- * Store the intent details in the `agent_payment_intents` table. This includes the payer's user ID, the agent ID, the amount, the currency, the recipient address, and a status of `'pending'`. Set an expiration time (e.g., 10 minutes).
- * Return the payment intent ID and the necessary details for the frontend to construct the transaction (e.g., recipient address, amount, currency mint, etc.).
-
-4. **Add Vercel Routing:**
- * In `vercel.json`, add a route to direct requests from `/api/payments/intent` to your new serverless function.
-
-## Code Example (Backend - `api/payments/intent.js`)
-
-```javascript
-import { sql } from '../_lib/db.js';
-import { getSessionUser } from '../_lib/auth.js';
-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
-import { nanoid } from 'nanoid';
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
-
- const { agent_id, skill_name } = await readJson(req);
- if (!agent_id || !skill_name) {
- return error(res, 400, 'validation_error', 'agent_id and skill_name are required');
- }
-
- // 1. Fetch skill price and agent owner's payout wallet
- const [priceInfo] = await sql`
- SELECT
- p.amount, p.currency_mint, p.chain,
- a.user_id as owner_user_id
- FROM agent_skill_prices p
- JOIN agent_identities a ON p.agent_id = a.id
- WHERE p.agent_id = ${agent_id}
- AND p.skill = ${skill_name}
- AND p.is_active = true
- `;
-
- if (!priceInfo) {
- return error(res, 404, 'not_found', 'The specified skill is not for sale.');
- }
-
- // For this example, we assume the owner's Solana wallet is on the agent's meta field
- // A better approach would be a dedicated agent_payout_wallets table
- const [agent] = await sql`SELECT meta FROM agent_identities WHERE id = ${agent_id}`;
- const recipient_address = agent.meta?.solana_address;
-
- if (!recipient_address) {
- return error(res, 500, 'configuration_error', 'Agent owner has not configured a payout wallet.');
- }
-
- // 2. Create and store the payment intent
- const intent_id = `pi_${nanoid()}`;
- const expires_at = new Date(Date.now() + 10 * 60 * 1000); // 10 minutes from now
-
- await sql`
- INSERT INTO agent_payment_intents
- (id, payer_user_id, agent_id, currency_mint, amount, status, expires_at, payload)
- VALUES
- (${intent_id}, ${user.id}, ${agent_id}, ${priceInfo.currency_mint}, ${String(priceInfo.amount)}, 'pending', ${expires_at}, ${JSON.stringify({ skill: skill_name, recipient_address })})
- `;
-
- // 3. Return details to the frontend
- return json(res, 201, {
- intent_id,
- recipient_address,
- amount: String(priceInfo.amount),
- currency_mint: priceInfo.currency_mint,
- chain: priceInfo.chain,
- expires_at: expires_at.toISOString(),
- });
-});
-```
diff --git a/tasks/monetization-feature/04-frontend-create-pricebadge-component.md b/tasks/monetization-feature/04-frontend-create-pricebadge-component.md
deleted file mode 100644
index a1849de77..000000000
--- a/tasks/monetization-feature/04-frontend-create-pricebadge-component.md
+++ /dev/null
@@ -1,75 +0,0 @@
----
-status: completed
----
-
-# Prompt 4: Frontend - Create Reusable PriceBadge Component
-
-## Objective
-Develop a reusable UI component to display skill prices consistently across the application.
-
-## Explanation
-To maintain a consistent user experience, we should encapsulate the logic for displaying skill prices into a single, reusable component. This `PriceBadge` component will handle the formatting of the price and the visual distinction between "Free" and paid skills. Creating this component now will save time and prevent code duplication as we build more monetization features.
-
-## Instructions
-1. **Create the Component File:**
- * Create a new file for your component, for example, `src/components/PriceBadge.js`.
- * This component can be a simple function that returns an HTML string or a more complex component if you are using a framework like React or Svelte.
-
-2. **Implement the Component Logic:**
- * The component should accept the price information (e.g., `amount` and `currency`) as props.
- * If the price is missing or zero, it should render a "Free" badge.
- * If a price is provided, it should format the amount (e.g., convert from lamports) and display it with the currency.
- * It should apply the appropriate CSS classes (`price-free` or `price-paid`) based on the price.
-
-3. **Refactor `marketplace.js`:**
- * Import and use the new `PriceBadge` component in the `renderDetail` function in `src/marketplace.js` to replace the inline badge creation logic.
-
-## Code Example (`src/components/PriceBadge.js`)
-
-```javascript
-// A simple functional component that returns an HTML string.
-
-// Mapping of mint addresses to human-readable currency symbols.
-const CURRENCY_SYMBOLS = {
- 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6a': 'USDC',
- 'So11111111111111111111111111111111111111112': 'SOL',
-};
-
-// Divisors to convert from smallest unit to standard unit.
-const CURRENCY_DIVISORS = {
- 'USDC': 1e6,
- 'SOL': 1e9,
-};
-
-export function PriceBadge(price) {
- if (!price || !price.amount) {
- return `<span class="price-badge price-free">Free</span>`;
- }
-
- const symbol = CURRENCY_SYMBOLS[price.currency_mint] || '???';
- const divisor = CURRENCY_DIVISORS[symbol] || 1;
- const formattedAmount = (price.amount / divisor).toFixed(2);
-
- return `
- <span class="price-badge price-paid">
- ${formattedAmount} ${symbol}
- </span>
- `;
-}
-```
-
-### Refactored Usage in `src/marketplace.js`
-
-```javascript
-import { PriceBadge } from './components/PriceBadge.js'; // Adjust path
-
-// ... inside renderDetail function
-const skillPrices = a.skill_prices || {};
-$('d-skills').innerHTML = skillsArr.length
- ? skillsArr.map((s) => {
- const name = typeof s === 'string' ? s : (s.name || '');
- const price = skillPrices[name];
- return `<span class="skill-entry">${escapeHtml(name)}${PriceBadge(price)}</span>`;
- }).join(' ')
- : '<div>This Agent has no skills defined.</div>';
-```
diff --git a/tasks/monetization-feature/04-frontend-skill-pricing-ui.md b/tasks/monetization-feature/04-frontend-skill-pricing-ui.md
deleted file mode 100644
index ddc07c729..000000000
--- a/tasks/monetization-feature/04-frontend-skill-pricing-ui.md
+++ /dev/null
@@ -1,76 +0,0 @@
----
-status: completed
----
-
-# Prompt 4: Frontend - UI for Skill Price Management
-
-## Objective
-Create a user interface in the agent editor page for creators to set and manage the prices of their skills.
-
-## Explanation
-To complement the backend API for setting skill prices, we need a user-friendly interface for creators. This UI will be part of the agent editor, likely in a new "Monetization" or "Skills" tab. It will list the agent's skills and provide input fields for creators to set the price for each one.
-
-## Instructions
-1. **Locate the Agent Editor:**
- * Find the main agent editor component, likely in `agent-edit.html` and its corresponding JavaScript file.
-
-2. **Add a "Monetization" Tab:**
- * Add a new tab to the agent editor for managing monetization settings.
- * Inside this tab, fetch and display a list of the agent's skills.
-
-3. **Create the Pricing Form:**
- * For each skill, display a form with:
- * An input field for the `amount`.
- * A dropdown (`<select>`) for the `currency_mint` (e.g., pre-populated with USDC, BONK, etc.).
- * A "Save" button.
- * When the creator saves a price, make a `POST` request to the API endpoint created in the previous prompt (`/api/agents/:agentId/skills/:skillId/price`).
- * Display feedback to the user on success or failure (e.g., a "Saved!" message or an error alert).
-
-## Code Example (Frontend - `agent-edit.html` structure)
-
-```html
-<!-- Inside the agent editor's tab panel -->
-<div id="monetization-panel" class="edit-panel">
- <h2>Skill Pricing</h2>
- <div id="skill-list-pricing">
- <!-- Skills will be dynamically rendered here -->
- </div>
-</div>
-```
-
-## Code Example (Frontend - JavaScript logic)
-
-```javascript
-// Inside the agent editor's JavaScript file
-
-function renderSkillPricing(skills, agentId) {
- const container = document.getElementById('skill-list-pricing');
- container.innerHTML = skills.map(skill => `
- <div class="skill-price-row">
- <span class="skill-name">${escapeHtml(skill.name)}</span>
- <div class="price-inputs">
- <input type="number" class="price-amount" placeholder="e.g., 1.99" data-skill-id="${skill.id}">
- <select class="price-currency" data-skill-id="${skill.id}">
- <option value="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v">USDC</option>
- <option value="DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263">BONK</option>
- </select>
- <button class="save-price-btn" data-skill-id="${skill.id}">Save</button>
- </div>
- </div>
- `).join('');
-
- container.addEventListener('click', async (e) => {
- if (e.target.matches('.save-price-btn')) {
- const skillId = e.target.dataset.skillId;
- const amountInput = container.querySelector(`.price-amount[data-skill-id="${skillId}"]`);
- const currencySelect = container.querySelector(`.price-currency[data-skill-id="${skillId}"]`);
-
- const amount = parseFloat(amountInput.value) * 1e6; // Convert to lamports
- const currency_mint = currencySelect.value;
-
- // Make API call to POST /api/agents/${agentId}/skills/${skillId}/price
- // ... handle success/error and show feedback ...
- }
- });
-}
-```
diff --git a/tasks/monetization-feature/04-frontend-ui-for-setting-skill-prices.md b/tasks/monetization-feature/04-frontend-ui-for-setting-skill-prices.md
deleted file mode 100644
index 9d8f4078a..000000000
--- a/tasks/monetization-feature/04-frontend-ui-for-setting-skill-prices.md
+++ /dev/null
@@ -1,102 +0,0 @@
----
-status: completed
----
-
-# Prompt 4: Frontend - UI for Setting Skill Prices
-
-**Status:** Not Started
-
-## Objective
-Create a user interface within the agent creation or editing page that allows creators to set prices for their skills.
-
-## Explanation
-Now that the backend can handle skill pricing, we need to provide a way for creators to use it. This task involves designing and building a new section in the UI where a creator can see a list of their agent's skills and attach a price to each one.
-
-## Instructions
-1. **Locate the Agent Editor UI:**
- - Find the HTML file and JavaScript module responsible for the agent editing page (e.g., `agent-edit.html` and `src/agent-edit.js`).
-
-2. **Design the UI Component:**
- - Within the skills section of the agent editor, for each skill listed, add a form input for `price` and a dropdown for `currency`.
- - Initially, the currency can be a static list (e.g., "USDC").
- - Add a "Save Prices" button.
-
-3. **Implement the Component:**
- - When the agent editor loads, it should fetch the agent's details, including the existing `skill_prices`.
- - Populate the input fields with the existing prices for each skill.
- - When the "Save Prices" button is clicked, the UI should gather the pricing data for all skills that have a price set.
-
-## Code Example (HTML in `agent-edit.html`)
-
-This is a conceptual example of what the new HTML might look like.
-
-```html
-<!-- Inside the agent editor form, where skills are listed -->
-<div class="form-section">
- <h3>Skill Monetization</h3>
- <div id="skill-pricing-list">
- <!-- Skills will be rendered here by JavaScript -->
- </div>
- <button type="button" id="save-skill-prices-btn">Save Prices</button>
-</div>
-```
-
-## Code Example (JavaScript in `src/agent-edit.js`)
-
-```javascript
-// ... inside the function that renders the agent editor ...
-
-const skills = agent.skills || [];
-const skillPrices = agent.skill_prices || {};
-const skillPricingList = document.getElementById('skill-pricing-list');
-
-skillPricingList.innerHTML = skills.map(skill => {
- const price = skillPrices[skill.name];
- const amountInUsdc = price ? (price.amount / 1e6).toFixed(2) : '';
- return `
- <div class="skill-price-entry">
- <span class="skill-name">${escapeHtml(skill.name)}</span>
- <div class="price-input-wrap">
- <input
- type="number"
- step="0.01"
- min="0"
- class="price-input"
- data-skill-name="${escapeHtml(skill.name)}"
- placeholder="e.g., 0.99"
- value="${amountInUsdc}"
- />
- <span class="currency-label">USDC</span>
- </div>
- </div>
- `;
-}).join('');
-```
-
-## CSS Example
-
-Add styles to `/agent-edit.css` for the new elements.
-
-```css
-.skill-price-entry {
- display: flex;
- justify-content: space-between;
- align-items: center;
- padding: 8px 0;
- border-bottom: 1px solid #333;
-}
-.price-input-wrap {
- display: flex;
- align-items: center;
- gap: 8px;
-}
-.price-input {
- width: 80px;
- /* ... other styles */
-}
-```
-
-## Definition of Done
-- The UI for setting skill prices is implemented on the agent editing page.
-- Existing prices are correctly displayed when the page loads.
-- The "Save Prices" button is present.
diff --git a/tasks/monetization-feature/04-frontend-ui-for-skill-pricing.md b/tasks/monetization-feature/04-frontend-ui-for-skill-pricing.md
deleted file mode 100644
index a14911f6b..000000000
--- a/tasks/monetization-feature/04-frontend-ui-for-skill-pricing.md
+++ /dev/null
@@ -1,68 +0,0 @@
----
-status: completed
----
-
-# Prompt 4: UI for Skill Pricing
-
-**Status:** Not Started
-
-## Objective
-Build the user interface in the agent editor for creators to set and manage prices for their skills.
-
-## Explanation
-Now that the backend can handle skill pricing, we need to provide a user interface for creators. This UI will be part of the agent editing page. It should list all of the agent's skills and provide input fields for creators to set a price for each one. The UI should be intuitive, allowing for easy adding, updating, and removing of prices.
-
-## Instructions
-- **Locate the Agent Editor UI:**
- - The main file for the agent editor is likely `agent-edit.html`.
- - The corresponding JavaScript that handles the logic is likely in `src/agent-edit.js` or similar.
-
-- **Design the Pricing Section:**
- - Within the agent editor, find the area where skills are listed or managed.
- - For each skill, add a section for pricing. This should include:
- - An input field for the price amount.
- - A dropdown or input to select the currency (e.g., "USDC").
- - A "Save" button to save the price.
- - A "Remove" button to clear the price.
- - The UI should clearly distinguish between free and priced skills.
-
-- **Implement the UI Logic:**
- - When the agent data is loaded, populate the pricing inputs with existing values from the `agent.skill_prices` object.
- - When the "Save" button is clicked, call the `POST /api/agents/[id]/skill-prices` endpoint you created in the previous prompt.
- - When the "Remove" button is clicked, call the `DELETE /api/agents/[id]/skill-prices` endpoint.
- - Provide feedback to the user on success or failure (e.g., a "Saved!" message or an error alert).
-
-## Code Example (Frontend - `agent-edit.html` structure)
-
-This is a conceptual example of the HTML structure. You will need to integrate this into your existing templating or DOM-building logic.
-
-```html
-<!-- Inside the agent editor's skills list -->
-<div class="skill-item">
- <span class="skill-name">greet</span>
- <div class="skill-pricing-form">
- <input type="number" class="skill-price-input" placeholder="e.g., 1.50" value="1.50">
- <select class="skill-currency-select">
- <option value="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6f">USDC</option>
- </select>
- <button class="btn-save-price">Save</button>
- <button class="btn-remove-price">Remove</button>
- </div>
-</div>
-```
-
-## CSS Example
-
-Add styles to `/agent-edit.css` to make the form look clean.
-
-```css
-.skill-pricing-form {
- display: flex;
- align-items: center;
- gap: 8px;
- margin-top: 8px;
-}
-.skill-price-input {
- width: 80px;
-}
-```
diff --git a/tasks/monetization-feature/04-frontend-ui-set-skill-prices.md b/tasks/monetization-feature/04-frontend-ui-set-skill-prices.md
deleted file mode 100644
index ec1d4743e..000000000
--- a/tasks/monetization-feature/04-frontend-ui-set-skill-prices.md
+++ /dev/null
@@ -1,78 +0,0 @@
----
-status: completed
----
-
-# Prompt 4: Frontend - UI for Creators to Set Skill Prices
-
-**Status:** Not Started
-
-## Objective
-Implement a user interface in the agent creation/editing page (`agent-edit.html`) that allows creators to set and view prices for their skills.
-
-## Explanation
-To make the pricing API useful, creators need a user-friendly interface to manage their skill prices. This involves adding form elements to the page where they edit their agent's details. This UI will fetch existing prices and provide input fields to set new ones, calling the API endpoint from the previous prompt.
-
-## Instructions
-- [ ] **Locate the Agent Edit Page:** Open the `agent-edit.html` file and its corresponding JavaScript file (e.g., `src/agent-edit.js`).
-- [ ] **Fetch Existing Prices:** When the page loads and fetches the agent's details, make sure the API response includes the `skill_prices` data.
-- [ ] **Modify the Skill Rendering:** In the area where the agent's skills are listed, add input fields for `amount` and `currency_mint` next to each skill.
-- [ ] **Populate Existing Data:** If a price already exists for a skill, populate the input fields with that data.
-- [ ] **Create a "Save Prices" Button:** Add a button that, when clicked, will gather the pricing data from all the input fields.
-- [ ] **Implement the API Call:**
- - For each skill with a price, call the `POST /api/agents/:id/skills/pricing` endpoint.
- - You can do this individually for each skill or batch them into a single request if your backend supports it.
- - Provide user feedback (e.g., a "Saved!" message or an error notification).
-
-## Code Example (`src/agent-edit.js`)
-
-```javascript
-// Inside the function that renders the agent details for editing
-
-function renderAgentForEditing(agent) {
- // ... existing code to render agent name, description, etc.
-
- const skillsContainer = document.getElementById('skills-editor');
- const skillPrices = agent.skill_prices || {};
-
- skillsContainer.innerHTML = agent.skills.map(skill => {
- const price = skillPrices[skill.name] || {};
- const amountInUnits = price.amount ? price.amount / 1e6 : ''; // Example for USDC (6 decimals)
- const currency = price.currency_mint || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6T'; // Default to USDC
-
- return `
- <div class="skill-price-editor" data-skill-name="${skill.name}">
- <span class="skill-name">${skill.name}</span>
- <input type="number" class="price-amount" placeholder="e.g., 2.50" value="${amountInUnits}">
- <select class="price-currency">
- <option value="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6T" ${currency === 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6T' ? 'selected' : ''}>USDC</option>
- <option value="So11111111111111111111111111111111111111112" ${currency === 'So11111111111111111111111111111111111111112' ? 'selected' : ''}>SOL</option>
- </select>
- </div>
- `;
- }).join('');
-}
-
-// Add event listener for the "Save Prices" button
-document.getElementById('save-prices-btn').addEventListener('click', async () => {
- const agentId = /* get agent id from somewhere */;
- const editors = document.querySelectorAll('.skill-price-editor');
-
- for (const editor of editors) {
- const skill_name = editor.dataset.skillName;
- const amountInUnits = parseFloat(editor.querySelector('.price-amount').value);
- const currency_mint = editor.querySelector('.price-currency').value;
-
- if (!isNaN(amountInUnits) && amountInUnits > 0) {
- const amount = Math.round(amountInUnits * 1e6); // Convert back to smallest unit
-
- await fetch(`/api/agents/${agentId}/skills/pricing`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json', /* + auth headers */ },
- body: JSON.stringify({ skill_name, amount, currency_mint }),
- });
- }
- }
- // Show feedback to user
- alert('Prices saved!');
-});
-```
diff --git a/tasks/monetization-feature/04-ui-show-purchased-skills.md b/tasks/monetization-feature/04-ui-show-purchased-skills.md
deleted file mode 100644
index 5e7a941d2..000000000
--- a/tasks/monetization-feature/04-ui-show-purchased-skills.md
+++ /dev/null
@@ -1,70 +0,0 @@
----
-status: completed
----
-# Prompt 4: UI to Show Purchased Skills
-
-**Status:** Not Started
-
-## Objective
-Update the marketplace and user dashboard to visually distinguish skills that the logged-in user has already purchased.
-
-## Explanation
-To prevent users from accidentally re-purchasing a skill and to provide a clear overview of their entitlements, the UI should reflect their purchase history. This requires fetching the user's purchased skills and using that information to update the rendering of skill badges.
-
-## Instructions
-1. **Create Backend API for User Purchases:**
- - Create a new API endpoint, e.g., `/api/users/me/purchased-skills`, that returns a list of all skill purchases for the currently authenticated user.
- - The response should be an array of objects, like `[{ agent_id: "...", skill_name: "..." }, ...]`.
-
-2. **Fetch Purchased Skills on Frontend:**
- - When a user is logged in, fetch their purchased skills from the new endpoint.
- - Store this information in a client-side data structure that's easy to access, like a `Set` of strings in the format `agent_id:skill_name`.
-
-3. **Update Marketplace UI (`src/marketplace.js`):**
- - In the `renderDetail` function, where the skill badges are rendered, modify the logic.
- - Before rendering a "Purchase" button or a price for a paid skill, check if the user has already purchased it.
- - If the skill is purchased, render a different badge, e.g., "Owned" or a checkmark icon, instead of the price.
-
-4. **Create a "My Skills" Section in Dashboard:**
- - In the user's main dashboard (`dashboard.html` or similar), add a new section or tab called "My Purchased Skills".
- - This section should list all the skills the user has bought, grouped by agent.
- - This provides a centralized view for users to manage their purchased assets.
-
-## Code Example (Frontend - `src/marketplace.js`)
-
-```javascript
-// Assuming `purchasedSkills` is a Set like: new Set(['agent123:PumpFun Tools'])
-const purchasedSkills = await fetchUserPurchases(); // Fetched on page load
-
-// ... inside renderDetail function ...
-
-const skillPrices = a.skill_prices || {};
-$('d-skills').innerHTML = skillsArr.length
- ? skillsArr.map((s) => {
- const name = typeof s === 'string' ? s : (s.name || '');
- const price = skillPrices[name];
- const purchaseKey = `${a.id}:${name}`; // e.g., 'agent123:PumpFun Tools'
-
- let badge;
- if (purchasedSkills.has(purchaseKey)) {
- badge = `<span class="price-badge price-owned">✓ Owned</span>`;
- } else if (price) {
- badge = `<span class="price-badge price-paid">${(price.amount / 1e6).toFixed(2)} USDC</span>`;
- } else {
- badge = `<span class="price-badge price-free">Free</span>`;
- }
-
- return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;
- }).join(' ')
- : '<div>This Agent has no skills defined.</div>';
-
-```
-
-## CSS Example (`marketplace.css`)
-
-```css
-.price-owned {
- color: #86efac; /* A pleasant green */
- background-color: rgba(74, 222, 128, 0.1);
-}
-```
diff --git a/tasks/monetization-feature/05-backend-api-check-skill-access.md b/tasks/monetization-feature/05-backend-api-check-skill-access.md
deleted file mode 100644
index 503f6b237..000000000
--- a/tasks/monetization-feature/05-backend-api-check-skill-access.md
+++ /dev/null
@@ -1,63 +0,0 @@
----
-status: completed
----
-
-# Prompt 5: Backend API - Check Skill Access
-
-**Status:** Not Started
-
-## Objective
-Create a fast, efficient API endpoint to verify if a user has purchased access to a specific skill on a specific agent.
-
-## Explanation
-Before executing a paid skill, the system needs to check if the current user has the right to use it. This endpoint will serve that purpose. It should be highly optimized for speed, as it might be called frequently during agent interactions. It will query the `skill_purchases` table to see if a valid record exists for the given user, agent, and skill.
-
-## Instructions
-- [ ] **Create a new API file:** `api/marketplace/check-skill-access.js`.
-- [ ] **Implement the endpoint logic:**
- - [ ] It should handle `GET` requests.
- - [ ] It must authenticate the user.
- - [ ] It should accept `agent_id` and `skill_name` as query parameters.
- - [ ] It will perform a lookup in the `skill_purchases` table for a matching record (`user_id`, `agent_id`, `skill_name`).
- - [ ] It should return a simple boolean `has_access` in the JSON response.
-
-## Code Example (`api/marketplace/check-skill-access.js`)
-
-```javascript
-import { sql } from '../_lib/db.js';
-import { json, method, cors, error, auth } from '../_lib/http.js';
-
-export default async function checkSkillAccess(req, res) {
- if (cors(req, res)) return;
- if (!method(req, res, ['GET'])) return;
- const authUser = await auth(req, res);
- if (!authUser) return;
-
- const { agent_id, skill_name } = req.query;
-
- if (!agent_id || !skill_name) {
- return error(res, 400, 'bad_request', 'Missing agent_id or skill_name.');
- }
-
- try {
- const [purchase] = await sql`
- SELECT id FROM skill_purchases
- WHERE user_id = ${authUser.id}
- AND agent_id = ${agent_id}
- AND skill_name = ${skill_name}
- LIMIT 1;
- `;
-
- const has_access = !!purchase;
-
- return json(res, 200, { ok: true, has_access });
-
- } catch (e) {
- console.error('Error checking skill access:', e);
- return error(res, 500, 'server_error', 'Failed to check access.');
- }
-}
-```
-
-## Tracking
-- To mark this task as complete, check all boxes in the instructions and change the status in the frontmatter to `Completed`.
diff --git a/tasks/monetization-feature/05-backend-api-initiate-purchase.md b/tasks/monetization-feature/05-backend-api-initiate-purchase.md
deleted file mode 100644
index 205b09361..000000000
--- a/tasks/monetization-feature/05-backend-api-initiate-purchase.md
+++ /dev/null
@@ -1,68 +0,0 @@
----
-status: completed
----
-# Prompt 5: API to Initiate Skill Purchase
-
-**Status:** Not Started
-
-## Objective
-Create a backend endpoint that prepares and returns a transaction for a user to sign to purchase a skill.
-
-## Explanation
-For on-chain payments, the backend should not handle private keys. Instead, it constructs an unsigned transaction and sends it to the client. The user then signs it with their wallet, ensuring a secure, non-custodial process. This endpoint will generate such a transaction.
-
-## Instructions
-- **Create a `POST` endpoint: `/api/skills/:skill_id/purchase`.**
-- **Implement the following logic:**
- 1. **Authentication:** Ensure the user is logged in.
- 2. **Validation:** Check that the skill exists and is for sale.
- 3. **Fetch Data:** Get the skill price, creator's wallet address, and platform fee wallet address.
- 4. **Construct Transaction:** Use the Solana Web3 library (`@solana/web3.js`) to create a transaction with two transfers:
- - One transfer sends the payment from the user to the creator.
- - A second transfer sends the platform fee from the user to the platform wallet.
- 5. **Serialize:** Serialize the transaction, but do not sign it. Base64-encode the serialized transaction.
- 6. **Response:** Return the base64-encoded transaction to the client.
-
-## Code Example (Backend - Solana Pay)
-```javascript
-// POST /api/skills/:skill_id/purchase
-import { createTransfer } from '@solana/pay';
-import { Connection, PublicKey, SystemProgram, Transaction } from '@solana/web3.js';
-
-async function initiatePurchase(req, res) {
- const { skill_id } = req.params;
- const user_id = req.session.userId;
- const user_wallet = new PublicKey(req.body.account); // User's public key from request
-
- // ... Auth, validation ...
- const priceInfo = await db.one('SELECT * FROM agent_skill_prices WHERE skill_id = $1', skill_id);
- const creator = await db.one('SELECT wallet_address FROM users WHERE id = $1', priceInfo.creator_id);
-
- const connection = new Connection(process.env.SOLANA_RPC_URL);
- const creatorWallet = new PublicKey(creator.wallet_address);
- const platformWallet = new PublicKey(process.env.PLATFORM_WALLET);
- const feeAmount = priceInfo.amount * 0.05; // 5% fee
-
- const transaction = new Transaction({
- feePayer: user_wallet,
- recentBlockhash: (await connection.getLatestBlockhash()).blockhash
- });
-
- // Payment to creator
- transaction.add(SystemProgram.transfer({
- fromPubkey: user_wallet,
- toPubkey: creatorWallet,
- lamports: priceInfo.amount,
- }));
-
- // Fee to platform
- transaction.add(SystemProgram.transfer({
- fromPubkey: user_wallet,
- toPubkey: platformWallet,
- lamports: feeAmount,
- }));
-
- const serialized = transaction.serialize({ requireAllSignatures: false });
- return res.json({ transaction: serialized.toString('base64') });
-}
-```
diff --git a/tasks/monetization-feature/05-backend-api-purchase-skill.md b/tasks/monetization-feature/05-backend-api-purchase-skill.md
deleted file mode 100644
index dc12148b4..000000000
--- a/tasks/monetization-feature/05-backend-api-purchase-skill.md
+++ /dev/null
@@ -1,90 +0,0 @@
----
-status: completed
----
-
-# Prompt 5: API to Purchase a Skill
-
-**Status:** Not Started
-
-## Objective
-Create the core backend API endpoint that allows a user to purchase a skill. This endpoint will verify the transaction and record the purchase in the database.
-
-## Explanation
-This is the most critical part of the monetization flow. The user will have confirmed the transaction on the frontend with their wallet. The frontend will then send the transaction signature to this backend endpoint. The backend must verify that the transaction was successful and that the correct amount was transferred to the right recipient before recording the purchase.
-
-## Instructions
-
-1. **Create the API Endpoint:**
- * Create `api/skill/purchase.js` to handle `POST` requests.
-
-2. **Validate the Request:**
- * The request body should include:
- * `agent_id`
- * `skill_name`
- * `transaction_signature`
- * The user must be authenticated.
-
-3. **Verify the Solana Transaction:**
- * Use the Solana RPC `getTransaction` method with the provided `transaction_signature`.
- * Check that the transaction was successful (`err` is null).
- * Fetch the skill price from the `agent_skill_prices` table.
- * Inspect the transaction's post-balances and pre-balances to confirm:
- * The buyer's balance decreased by the correct amount.
- * The seller's (agent owner's) balance increased by the correct amount.
- * The currency mint matches the one specified for the skill.
-
-4. **Record the Purchase:**
- * If transaction verification is successful, insert a new record into the `skill_purchases` table.
- * Store the `user_id`, `agent_id`, `skill_name`, `transaction_signature`, `amount`, and `currency_mint`.
-
-5. **Return a Response:**
- * Return a success message if the purchase was recorded.
- * Return a detailed error if verification fails at any step.
-
-## Code Example (Node.js with `@solana/web3.js`)
-
-```javascript
-// In /api/skill/purchase.js
-
-import { Connection, PublicKey } from '@solana/web3.js';
-import { supabase } from '../_lib/supabase';
-import { authenticate } from '../_lib/auth';
-
-const SOLANA_RPC_URL = process.env.SOLANA_RPC_URL;
-const connection = new Connection(SOLANA_RPC_URL, 'confirmed');
-
-export default async function handler(req, res) {
- const user = await authenticate(req);
- if (!user) return res.status(401).json({ error: 'Unauthorized' });
-
- const { agent_id, skill_name, signature } = req.body;
-
- // 1. Fetch expected price and seller wallet
- // ... (get price from agent_skill_prices and seller wallet from agents table)
-
- // 2. Verify transaction
- try {
- const tx = await connection.getTransaction(signature, { maxSupportedTransactionVersion: 0 });
- if (tx.meta.err) throw new Error('Transaction failed on-chain');
-
- // ... (logic to parse transaction accounts and balances)
- // ... (compare actual transfer amount/wallets with expected price/wallets)
-
- // 3. Record purchase in DB if verification passes
- const { error } = await supabase.from('skill_purchases').insert({
- user_id: user.id,
- agent_id,
- skill_name,
- transaction_signature: signature,
- // ... (amount, currency_mint)
- });
-
- if (error) throw error;
-
- res.status(200).json({ success: true, message: 'Purchase successful!' });
- } catch (err) {
- console.error('Purchase verification failed:', err);
- res.status(400).json({ success: false, error: 'Transaction verification failed.' });
- }
-}
-```
diff --git a/tasks/monetization-feature/05-backend-create-purchases-table.md b/tasks/monetization-feature/05-backend-create-purchases-table.md
deleted file mode 100644
index 70846a195..000000000
--- a/tasks/monetization-feature/05-backend-create-purchases-table.md
+++ /dev/null
@@ -1,58 +0,0 @@
----
-status: completed
----
-
-# Prompt 5: Create Purchase-Tracking Table
-
-**Status:** Not Started
-
-## Objective
-Create the `skill_purchases` table in the database to track which users have purchased access to which skills.
-
-## Explanation
-When a user buys a skill, we need to record that transaction to grant them permanent access. This table will serve as the source of truth for skill ownership. The agent's runtime will check this table to determine if a user is authorized to execute a premium skill.
-
-## Instructions
-- **Create a SQL Migration File:**
- - As before, create a new timestamped migration file, e.g., `YYYYMMDDHHMMSS_create_skill_purchases.sql`.
-
-- **Define the Table Schema:**
- - The table needs to link a user, an agent, and a skill.
- - It should also store details about the purchase transaction for auditing and records.
- - A unique constraint on `user_id`, `agent_id`, and `skill_name` will prevent duplicate purchase records.
-
-## SQL Example
-
-```sql
--- migrations/YYYYMMDDHHMMSS_create_skill_purchases.sql
-
-CREATE TABLE IF NOT EXISTS skill_purchases (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- user_id UUID NOT NULL,
- agent_id UUID NOT NULL,
- skill_name VARCHAR(255) NOT NULL,
-
- -- Purchase details
- purchase_amount BIGINT NOT NULL,
- purchase_currency_mint VARCHAR(255) NOT NULL,
- transaction_signature VARCHAR(255) NOT NULL, -- The on-chain tx signature
-
- purchased_at TIMESTAMPTZ DEFAULT NOW(),
-
- -- Foreign keys
- FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
- FOREIGN KEY (agent_id) REFERENCES agent_identities(id) ON DELETE CASCADE,
-
- -- Each user can only buy a specific skill from a specific agent once
- UNIQUE (user_id, agent_id, skill_name)
-);
-
--- Add indexes for faster lookups
-CREATE INDEX idx_skill_purchases_user_skill ON skill_purchases(user_id, agent_id, skill_name);
-CREATE INDEX idx_skill_purchases_transaction ON skill_purchases(transaction_signature);
-```
-## How to Run
-- Use your migration tool or `psql` to apply this schema change to the database.
- ```bash
- psql -d YOUR_DATABASE_URL -f migrations/YYYYMMDDHHMMSS_create_skill_purchases.sql
- ```
diff --git a/tasks/monetization-feature/05-backend-purchase-initiation-api.md b/tasks/monetization-feature/05-backend-purchase-initiation-api.md
deleted file mode 100644
index 4f637ee91..000000000
--- a/tasks/monetization-feature/05-backend-purchase-initiation-api.md
+++ /dev/null
@@ -1,90 +0,0 @@
----
-status: completed
----
-
-# Prompt 5: Backend - Purchase Initiation API
-
-**Status:** Not Started
-
-## Objective
-Create a backend API endpoint that prepares and returns the necessary information for a client to initiate a Solana Pay transaction.
-
-## Explanation
-To allow users to purchase a skill, the frontend needs to know the price, the recipient, and other transaction details. This endpoint will serve as the first step in the purchase flow. It will look up the skill's price and construct a Solana Pay-compliant response that the frontend can use to generate a QR code or automatically open a wallet.
-
-## Instructions
-- [ ] **Create the Endpoint:** Define a new endpoint, for example, `POST /api/purchase/skill`.
-- [ ] **Request Body:** The endpoint should accept `agent_id` and `skill_name` in the request body.
-- [ ] **Fetch Skill Price:**
- - Query the `agent_skill_prices` table for the price of the requested skill.
- - If the skill is free or the price is not found, return an appropriate error.
-- [ ] **Fetch Creator's Wallet:**
- - Look up the agent's creator from the `agents` table.
- - Get the creator's public key (wallet address) from the `users` or a dedicated `wallets` table. This will be the recipient of the payment.
-- [ ] **Construct Solana Pay Response:**
- - The response should be a JSON object containing:
- - `label`: The name of the store or app (e.g., "3D-Agent Marketplace").
- - `icon`: A URL to an icon for the transaction.
-- [ ] **Integrate with Solana Pay SDK:**
- - Use the `@solana/pay` SDK on the backend.
- - Your endpoint should implement the `GET` portion of the Solana Pay spec. When a wallet pings this URL, it should return the recipient, amount, SPL token, etc.
- - You will also need a `POST` handler on this same endpoint. When the wallet confirms the transaction, it will `POST` the transaction signature here for verification.
-
-## Code Example (Node.js/Express-style Solana Pay)
-
-```javascript
-// in api/purchase/skill.js
-
-import { Keypair, Connection, PublicKey, clusterApiUrl } from '@solana/web3.js';
-import { findReference, FindReferenceError } from '@solana/pay';
-import { db } from '../_lib/db'; // Your database utility
-
-// The GET handler is called by wallets to get transaction details
-async function get(req, res) {
- const { agent_id, skill_name } = req.query;
-
- // 1. Fetch price and creator wallet from DB
- const priceInfo = await db.one(
- `SELECT p.amount, p.currency_mint, a.owner_id
- FROM agent_skill_prices p
- JOIN agents a ON p.agent_id = a.id
- WHERE p.agent_id = $1 AND p.skill_name = $2`,
- [agent_id, skill_name]
- );
-
- const creatorWallet = await db.one('SELECT wallet_address FROM users WHERE id = $1', [priceInfo.owner_id]);
-
- // 2. Respond with Solana Pay GET spec
- res.status(200).json({
- label: "3D-Agent Marketplace",
- icon: "https://your-app.com/icon.png",
- });
-}
-
-// The POST handler is called by wallets after the user approves the transaction
-async function post(req, res) {
- const { account } = req.body;
- if (!account) throw new Error('Missing account');
-
- const { reference } = req.query;
- if (!reference) throw new Error('Missing reference');
-
- const signature = await verifyTransaction(account, reference);
- // Here you would grant the user access to the skill in your DB
- // grantSkillAccess(account, reference.skill_name);
-
- res.status(200).json({ status: 'ok', signature });
-}
-
-
-async function verifyTransaction(account, reference) {
- const connection = new Connection(clusterApiUrl('mainnet-beta'));
-
- // Find the transaction signature from the reference
- const signatureInfo = await findReference(connection, new PublicKey(reference));
-
- // Here you would add more validation, e.g., checking the transaction amount and destination match the skill price.
-
- return signatureInfo.signature;
-}
-```
diff --git a/tasks/monetization-feature/05-backend-solana-pay-endpoint.md b/tasks/monetization-feature/05-backend-solana-pay-endpoint.md
deleted file mode 100644
index 395066201..000000000
--- a/tasks/monetization-feature/05-backend-solana-pay-endpoint.md
+++ /dev/null
@@ -1,59 +0,0 @@
----
-status: not-started
----
-
-# Prompt 5: Backend Solana Pay Endpoint
-
-**Status:** Not Started
-
-## Objective
-Create a backend endpoint that generates a Solana Pay transaction request for purchasing a skill.
-
-## Explanation
-When a user clicks "Buy," the frontend will need to request a transaction from the backend. This endpoint will generate a Solana Pay-compliant response, specifying the recipient wallet (the agent creator's), the amount, the SPL token mint, and a unique reference key for tracking the transaction.
-
-## Instructions
-- [ ] **Create a new API endpoint file** (e.g., `/api/payments/solana-pay.js`).
-- [ ] **Endpoint Logic:**
- - [ ] It should accept a `POST` request with `agentId` and `skillName`.
- - [ ] Authenticate the user.
- - [ ] Fetch the skill price from the `agent_skill_prices` table.
- - [ ] Fetch the agent creator's wallet address from the `agent_identities` or a related table. This may require adding a `solana_wallet` column to `agent_identities` if it doesn't exist.
- - [ ] Generate a unique reference public key (`Keypair.generate()`). This will be used to find the transaction later.
- - [ ] Construct the Solana Pay response object, which includes a `label`, `icon`, `transaction` (URL for the next step), and `message`.
-- [ ] **Return the Solana Pay JSON response.**
-
-## Code Example (Conceptual Node.js)
-
-```javascript
-// In /api/payments/solana-pay.js
-import { Keypair } from '@solana/web3.js';
-// ... other imports
-
-export default wrap(async (req, res) => {
- // ... authentication and validation
- const { agentId, skillName } = await readJson(req);
-
- // 1. Fetch skill price and creator's wallet
- const [priceInfo] = await sql`...`;
- const [agentInfo] = await sql`...`;
- const recipientWallet = agentInfo.solana_wallet;
-
- // 2. Generate a reference keypair
- const reference = new Keypair();
-
- // 3. Construct the Solana Pay response
- const response = {
- label: `3D-Agent Skill Purchase`,
- icon: 'https://3d-agent.com/icon.png',
- // The transaction URL points to another endpoint that builds the actual transaction
- transaction: `${process.env.NEXT_PUBLIC_URL}/api/payments/create-skill-tx?agentId=${agentId}&skillName=${skillName}&reference=${reference.publicKey.toBase58()}`,
- message: `Purchase '${skillName}' for ${(priceInfo.amount / 1e6).toFixed(2)} USDC`
- };
-
- // You might need to store the reference key in cache/DB to validate the next step
- // await cache.set(`tx-ref:${reference.publicKey.toBase58()}`, { ...details });
-
- return json(res, 200, response);
-});
-```
diff --git a/tasks/monetization-feature/05-frontend-solana-pay-integration.md b/tasks/monetization-feature/05-frontend-solana-pay-integration.md
deleted file mode 100644
index ba35d6d46..000000000
--- a/tasks/monetization-feature/05-frontend-solana-pay-integration.md
+++ /dev/null
@@ -1,73 +0,0 @@
----
-status: not-started
----
-
-# Prompt 5: Frontend - Solana Pay Integration
-
-## Objective
-Integrate the frontend "Purchase" button with the backend Solana Pay endpoint to generate and display a payment QR code.
-
-## Explanation
-This task connects the user's purchase action to the on-chain transaction. When a user clicks the "Purchase" button, the frontend will call the new Solana Pay endpoint, retrieve the transaction details, and then use a library to display a QR code. This allows users with mobile wallets to scan and approve the payment seamlessly.
-
-## Instructions
-1. **Add Solana Pay Library:**
- * Include the Solana Pay QR code generation library in your project. You can use the official `@solana/pay` and a QR code library.
- * Run `npm install @solana/pay qrcode`.
-
-2. **Create a Modal Component:**
- * In your main HTML file (e.g., `marketplace.html`), add the structure for a modal dialog that will contain the QR code. It should be hidden by default.
-
-3. **Implement Click Handler:**
- * In `src/marketplace.js`, add a click event listener to the `d-skills` container (or use event delegation).
- * The handler should trigger only for clicks on `.purchase-btn`.
-
-4. **Fetch Transaction and Generate QR:**
- * Inside the click handler, retrieve the `skill_name` and `agent_id` from the button's `data-*` attributes.
- * Make a `POST` request to `/api/payments/solana-pay` with this data.
- * The response will contain the Solana Pay URL. Use the `qrcode` library to generate a QR code from this URL.
- * Inject the QR code into your modal and display it.
-
-## Code Example (`src/marketplace.js`)
-
-```javascript
-import QRCode from 'qrcode';
-
-// ... other code ...
-
-async function handlePurchaseClick(e) {
- if (!e.target.matches('.purchase-btn')) return;
-
- const btn = e.target;
- const { skill, agent } = btn.dataset;
-
- // Show a loading spinner
- btn.disabled = true;
-
- try {
- const res = await fetch('/api/payments/solana-pay', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ agent_id: agent, skill_name: skill }),
- });
-
- if (!res.ok) throw new Error('Failed to create transaction');
-
- const { transaction, message } = await res.json();
- const solanaPayUrl = `solana:${transaction}?label=${encodeURIComponent(message)}`;
-
- // Generate QR and show modal
- const qrCanvas = document.getElementById('qr-canvas');
- await QRCode.toCanvas(qrCanvas, solanaPayUrl, { width: 256 });
- document.getElementById('payment-modal').style.display = 'block';
-
- } catch (err) {
- console.error('Purchase failed:', err);
- // Show an error message
- } finally {
- btn.disabled = false;
- }
-}
-
-$('d-skills').addEventListener('click', handlePurchaseClick);
-```
diff --git a/tasks/monetization-feature/05-payment-modal-ui.md b/tasks/monetization-feature/05-payment-modal-ui.md
deleted file mode 100644
index b66ff271b..000000000
--- a/tasks/monetization-feature/05-payment-modal-ui.md
+++ /dev/null
@@ -1,138 +0,0 @@
-# Prompt 5: Payment Modal UI
-
-## Objective
-Create the HTML structure and CSS styling for a reusable payment modal that will guide the user through the skill purchase process.
-
-## Explanation
-A modal is a focused UI element that overlays the page, perfect for multi-step processes like payments. We need a clean, clear modal that can display the item being purchased, connect to a wallet, show the price, and provide clear action buttons. For now, we will just build the static UI components. The logic will be wired up in subsequent prompts.
-
-## Instructions
-1. **Add HTML to `marketplace.html`:**
- * At the bottom of the `<body>` in `marketplace.html`, add the HTML for the modal overlay and the modal itself.
- * The modal should be hidden by default (`hidden` attribute or `display: none`).
- * Include sections for:
- * A title (e.g., "Unlock Skill").
- * A close button.
- * The skill name and agent name.
- * The price.
- * A placeholder for wallet connection status.
- * A primary action button (e.g., "Pay Now").
- * A footer for status messages.
-
-2. **Add CSS to `marketplace.css`:**
- * Create styles for the modal overlay to cover the screen with a semi-transparent background.
- * Style the modal container itself: centered, with a border, background, and rounded corners.
- * Style the internal elements: title, price display, buttons, etc.
- * Use flexbox or grid for layout.
-
-## Code Example (HTML - add to `marketplace.html`)
-
-```html
-<!-- At the end of the <body>, after the submit modal -->
-
-<!-- Payment Modal -->
-<div class="market-modal-overlay" id="payment-modal-overlay" hidden aria-modal="true" role="dialog" aria-labelledby="payment-modal-title">
- <div class="market-modal">
- <div class="market-modal-head">
- <h2 id="payment-modal-title">Unlock Skill</h2>
- <button class="market-modal-close" id="payment-modal-close" aria-label="Close">×</button>
- </div>
- <div class="payment-modal-body">
- <p>You are purchasing access to the following skill:</p>
- <div class="payment-item">
- <strong id="payment-skill-name"></strong>
- <span>from agent</span>
- <em id="payment-agent-name"></em>
- </div>
-
- <div class="payment-price">
- <span>Total</span>
- <strong id="payment-price-display"></strong>
- </div>
-
- <div class="payment-wallet-area" id="payment-wallet-area">
- <!-- Wallet connection status and button will be rendered here by JS -->
- <button class="btn-primary" id="payment-connect-wallet-btn">Connect Wallet</button>
- </div>
-
- <button class="btn-primary payment-confirm-btn" id="payment-confirm-btn" disabled>Confirm Purchase</button>
-
- <div class="payment-status" id="payment-status" role="status" aria-live="polite"></div>
- </div>
- </div>
-</div>
-```
-
-## Code Example (CSS - add to `marketplace.css`)
-
-```css
-/* Payment Modal Styles */
-.payment-modal-body {
- padding: 16px;
- font-size: 14px;
- color: rgba(255, 255, 255, 0.7);
-}
-
-.payment-item {
- background-color: rgba(255, 255, 255, 0.05);
- border: 1px solid rgba(255, 255, 255, 0.1);
- border-radius: 8px;
- padding: 12px;
- margin: 16px 0;
- text-align: center;
-}
-
-#payment-skill-name {
- display: block;
- font-size: 16px;
- font-weight: 600;
- color: #fff;
-}
-
-.payment-item > span {
- font-size: 12px;
- color: rgba(255, 255, 255, 0.5);
-}
-
-#payment-agent-name {
- display: block;
- font-size: 12px;
- font-style: normal;
-}
-
-.payment-price {
- display: flex;
- justify-content: space-between;
- align-items: baseline;
- padding: 12px 0;
- border-top: 1px solid rgba(255, 255, 255, 0.1);
- border-bottom: 1px solid rgba(255, 255, 255, 0.1);
-}
-
-#payment-price-display {
- font-size: 20px;
- font-weight: 700;
- color: #fde047;
-}
-
-.payment-wallet-area {
- margin: 20px 0;
- padding: 16px;
- background-color: rgba(0, 0, 0, 0.2);
- border-radius: 8px;
- text-align: center;
-}
-
-.payment-confirm-btn {
- width: 100%;
- padding: 12px;
- font-size: 16px;
-}
-
-.payment-status {
- margin-top: 16px;
- font-size: 12px;
- text-align: center;
- min-height: 1.2em;
-}
-```
diff --git a/tasks/monetization-feature/05-solana-payment-setup.md b/tasks/monetization-feature/05-solana-payment-setup.md
deleted file mode 100644
index ba1247d25..000000000
--- a/tasks/monetization-feature/05-solana-payment-setup.md
+++ /dev/null
@@ -1,78 +0,0 @@
----
-status: completed
----
-
-# Prompt 5: Frontend - Solana Wallet Connection for Payments
-
-## Objective
-Integrate a Solana wallet adapter to allow users to connect their wallets, which is the first step in enabling payments for skills.
-
-## Explanation
-To purchase skills, users will need to connect their Solana wallet (like Phantom or Solflare) to the platform. We will use the official Solana wallet-adapter library to provide a smooth and familiar connection experience for users. This prompt focuses on adding a "Connect Wallet" button and managing the wallet connection state.
-
-## Instructions
-1. **Install Dependencies:**
- * Add the required Solana wallet-adapter libraries to your project's dependencies in `package.json`. You'll need `@solana/wallet-adapter-base`, `@solana/wallet-adapter-react` (or a vanilla JS equivalent), and adapters for popular wallets like `@solana/wallet-adapter-wallets`.
-
-2. **Add a "Connect Wallet" Button:**
- * In the main navigation header of the marketplace (`marketplace.html`), add a "Connect Wallet" button.
- * This button will be visible to users who are not yet connected.
-
-3. **Implement the Wallet Connection Logic:**
- * Initialize the wallet adapter provider.
- * When the "Connect Wallet" button is clicked, trigger the wallet adapter's connection modal.
- * Once connected, the button should change to show the user's truncated public key and a "Disconnect" option.
- * Store the connection state and the user's public key in a global state so that it can be accessed by other components (like the purchase modal that will be built later).
-
-## Code Example (Frontend - `marketplace.js` or a new module)
-
-```javascript
-import { WalletAdapterNetwork } from '@solana/wallet-adapter-base';
-import { ConnectionProvider, WalletProvider } from '@solana/wallet-adapter-react';
-import { WalletModalProvider, WalletMultiButton } from '@solana/wallet-adapter-react-ui';
-import {
- GlowWalletAdapter,
- PhantomWalletAdapter,
- SlopeWalletAdapter,
- SolflareWalletAdapter,
- TorusWalletAdapter,
-} from '@solana/wallet-adapter-wallets';
-import { clusterApiUrl } from '@solana/web3.js';
-import React, { useMemo } from 'react';
-
-// (This example uses React, but the same principles apply to a vanilla JS implementation)
-
-function App() {
- const network = WalletAdapterNetwork.Devnet;
- const endpoint = useMemo(() => clusterApiUrl(network), [network]);
-
- const wallets = useMemo(
- () => [
- new PhantomWalletAdapter(),
- new SolflareWalletAdapter(),
- // ... other wallets
- ],
- [network]
- );
-
- return (
- <ConnectionProvider endpoint={endpoint}>
- <WalletProvider wallets={wallets} autoConnect>
- <WalletModalProvider>
- {/* Your app components */}
- <WalletMultiButton />
- </WalletModalProvider>
- </WalletProvider>
- </ConnectionProvider>
- );
-}
-```
-
-## HTML Example (`marketplace.html`)
-
-```html
-<!-- In the marketplace header -->
-<div class="wallet-adapter-button-container">
- <!-- The wallet adapter button will be rendered here -->
-</div>
-```
diff --git a/tasks/monetization-feature/05-ui-skill-purchase-flow.md b/tasks/monetization-feature/05-ui-skill-purchase-flow.md
deleted file mode 100644
index f6ef7f843..000000000
--- a/tasks/monetization-feature/05-ui-skill-purchase-flow.md
+++ /dev/null
@@ -1,29 +0,0 @@
----
-status: completed
----
-
-# Prompt 5: UI - Skill Purchase Flow
-
-**Status:** Not Started
-
-## Objective
-Integrate the frontend of the agent detail page with the skill purchase API to allow users to buy skills.
-
-## Explanation
-Now that the backend can generate a purchase transaction, we need to add a "Buy" button for paid skills in the UI. When a user clicks this button, it should initiate the purchase flow using the Solana Pay API.
-
-## Instructions
-- [ ] **Modify the `renderDetail` function in `src/marketplace.js`** (or equivalent file).
-- [ ] **For paid skills, instead of just showing a price badge, render a "Buy" button.**
-- [ ] **Add an event listener to the "Buy" button.** On click, it should:
- - 1. **Get the user's wallet address.** Use the connected wallet's public key.
- - 2. **Make a `POST` request** to the `/api/skills/purchase` endpoint created in the previous prompt.
- - 3. **Receive the Solana Pay transaction** from the API.
- - 4. **Use the wallet adapter** to ask the user to sign and send the transaction.
- - 5. **Handle the transaction states:**
- - Display a "processing" indicator.
- - On confirmation, show a success message and update the UI to show the skill as "owned".
- - On failure, show an error message.
-
-## Tracking Owned Skills
-You'll need a way to know which skills the user already owns. A new table, `user_owned_skills`, might be necessary, or you can check on-chain for past transactions. For now, a simple client-side state update after purchase is sufficient.
diff --git a/tasks/monetization-feature/06-backend-api-fulfill-purchase.md b/tasks/monetization-feature/06-backend-api-fulfill-purchase.md
deleted file mode 100644
index 01846071a..000000000
--- a/tasks/monetization-feature/06-backend-api-fulfill-purchase.md
+++ /dev/null
@@ -1,63 +0,0 @@
----
-status: completed
----
-# Prompt 6: API to Fulfill Skill Purchase
-
-**Status:** Not Started
-
-## Objective
-Create an endpoint to verify a signed transaction and officially record a skill purchase in the database.
-
-## Explanation
-After the user signs and broadcasts a transaction, the client will send the transaction signature to the backend. This endpoint will receive the signature, confirm the transaction on the Solana blockchain, and if it's valid and successful, record the purchase in the `skill_purchases` table.
-
-## Instructions
-- **Create a `POST` endpoint: `/api/skills/fulfill_purchase`.**
-- **The request body should include `skill_id`, `agent_id`, and `signature`.**
-- **Implement the following logic:**
- 1. **Authentication:** Ensure user is logged in.
- 2. **Transaction Verification:**
- - Use the `signature` to query the Solana blockchain.
- - Confirm the transaction has been finalized.
- - Parse the transaction details to ensure it matches the expected payments (correct amounts to creator and platform from the correct user). This prevents replay attacks or forged requests.
- 3. **Database Update:** If verification passes, insert a new record into the `skill_purchases` table.
- 4. **Response:** Return a success message.
-
-## Code Example (Backend)
-```javascript
-// POST /api/skills/fulfill_purchase
-import { Connection } from '@solana/web3.js';
-
-async function fulfillPurchase(req, res) {
- const { skill_id, agent_id, signature } = req.body;
- const user_id = req.session.userId;
-
- // ... Auth, validation ...
-
- const connection = new Connection(process.env.SOLANA_RPC_URL);
- try {
- const tx = await connection.getParsedTransaction(signature, 'finalized');
- if (!tx) {
- return res.status(404).json({ error: 'Transaction not found or not finalized.' });
- }
-
- // ...
- // Add robust logic here to parse tx.transaction.message.instructions
- // and verify it matches the expected purchase details.
- // This is a critical security step.
- // ...
-
- const query = `
- INSERT INTO skill_purchases (agent_id, user_id, skill_id, price_id, purchase_amount, purchase_currency_mint, transaction_signature)
- VALUES ($1, $2, $3, ...);
- `;
- await db.none(query, [agent_id, user_id, skill_id, ...]);
-
- return res.status(200).json({ success: true, message: 'Purchase complete.' });
-
- } catch (error) {
- console.error('Fulfillment error:', error);
- return res.status(500).json({ error: 'Failed to fulfill purchase.' });
- }
-}
-```
diff --git a/tasks/monetization-feature/06-backend-api-list-purchased-skills.md b/tasks/monetization-feature/06-backend-api-list-purchased-skills.md
deleted file mode 100644
index aaccae95e..000000000
--- a/tasks/monetization-feature/06-backend-api-list-purchased-skills.md
+++ /dev/null
@@ -1,78 +0,0 @@
----
-status: not-started
----
-
-# Prompt 6: API to List Purchased Skills
-
-**Status:** Not Started
-
-## Objective
-Create a backend API endpoint that returns a list of all skills a specific user has purchased.
-
-## Explanation
-The frontend needs a way to know which skills the current user owns so it can update the UI accordingly (e.g., change a "Purchase" button to "Owned" or "Unlocked"). This endpoint provides that data.
-
-## Instructions
-
-1. **Create the API Endpoint:**
- * Create a new endpoint, for example, `/api/user/purchased-skills.js`.
- * This should handle `GET` requests.
-
-2. **Authentication:**
- * The endpoint must be protected. The user must be logged in to view their own purchased skills.
-
-3. **Query the Database:**
- * Fetch the authenticated user's ID.
- * Query the `skill_purchases` table for all records where `user_id` matches the current user's ID.
- * You might want to join with the `agents` table to get more details about the agent whose skill was purchased.
-
-4. **Format and Return the Data:**
- * Return an array of purchased skill objects. Each object could contain `agent_id`, `agent_name`, `skill_name`, and `purchased_at`.
-
-## Code Example (Node.js / Vercel Serverless Function)
-
-```javascript
-// In /api/user/purchased-skills.js
-
-import { supabase } from '../_lib/supabase';
-import { authenticate } from '../_lib/auth';
-
-export default async function handler(req, res) {
- const user = await authenticate(req);
- if (!user) {
- return res.status(401).json({ error: 'Unauthorized' });
- }
-
- const { data, error } = await supabase
- .from('skill_purchases')
- .select(`
- skill_name,
- created_at,
- agent:agents (
- id,
- name,
- avatar_uri
- )
- `)
- .eq('user_id', user.id);
-
- if (error) {
- console.error('Error fetching purchased skills:', error);
- return res.status(500).json({ error: 'Failed to fetch purchased skills.' });
- }
-
- // Format the data to be more convenient for the client
- const formattedData = data.reduce((acc, purchase) => {
- const agentId = purchase.agent.id;
- if (!acc[agentId]) {
- acc[agentId] = [];
- }
- acc[agentId].push(purchase.skill_name);
- return acc;
- }, {});
- // Result format: { "agent_id_1": ["skill_1", "skill_2"], "agent_id_2": ["skill_3"] }
-
-
- return res.status(200).json(formattedData);
-}
-```
diff --git a/tasks/monetization-feature/06-backend-payment-verification.md b/tasks/monetization-feature/06-backend-payment-verification.md
deleted file mode 100644
index 451abc8e6..000000000
--- a/tasks/monetization-feature/06-backend-payment-verification.md
+++ /dev/null
@@ -1,75 +0,0 @@
----
-status: not-started
----
-
-# Prompt 6: Backend - Payment Verification and Skill Unlock
-
-## Objective
-Verify completed Solana transactions and record skill purchases to grant users access.
-
-## Explanation
-After a user approves a payment, the backend must confirm the transaction on-chain and then "unlock" the skill for them. This involves creating a record that permanently links the user to their purchased skill, ensuring they have access in the future.
-
-## Instructions
-1. **Create a `user_purchased_skills` Table:**
- * Create a new migration file.
- * Define a table to store successful purchases. It should include `user_id`, `agent_id`, `skill_name`, `transaction_signature`, and `created_at`.
-
-2. **Add a Verification Endpoint (or logic):**
- * The Solana Pay transaction can include a `memo` with a unique reference ID for the purchase.
- * Create a new endpoint, e.g., `/api/payments/verify`, that the frontend can call after the user signs the transaction.
- * Alternatively, you can have a backend service that polls or uses a webhook to find transactions addressed to the creator's wallet.
-
-3. **Implement Verification Logic:**
- * When the verification is triggered, the backend should:
- * Receive the transaction signature.
- * Use the Solana SDK (`connection.getTransaction(signature)`) to fetch the transaction details from the blockchain.
- * Validate that the transaction transferred the correct amount of the correct currency to the correct recipient.
- * Check that this transaction signature has not already been processed.
-
-4. **Insert Purchase Record:**
- * If the transaction is valid, insert a new row into the `user_purchased_skills` table.
-
-## SQL Example for Table
-
-```sql
-CREATE TABLE user_purchased_skills (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- user_id UUID NOT NULL REFERENCES users(id),
- agent_id UUID NOT NULL REFERENCES agents(id),
- skill_name VARCHAR(128) NOT NULL,
- transaction_signature VARCHAR(128) NOT NULL UNIQUE,
- purchase_price NUMERIC(20, 0) NOT NULL,
- purchase_currency VARCHAR(64) NOT NULL,
- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
-);
-
-CREATE INDEX idx_user_purchased_skills_user_id ON user_purchased_skills(user_id);
-```
-
-## Code Snippet (Verification Logic)
-
-```javascript
-// Inside the verification endpoint
-const { signature } = req.body;
-
-const tx = await connection.getTransaction(signature, { maxSupportedTransactionVersion: 0 });
-
-if (!tx) {
- return error(res, 404, 'transaction_not_found');
-}
-
-// ... deep validation of transaction details ...
-// 1. Check recipient address
-// 2. Check transfer amount
-// 3. Check currency mint (if SPL token)
-
-// If valid, insert into the database
-await sql`
- INSERT INTO user_purchased_skills (user_id, agent_id, skill_name, transaction_signature, ...)
- VALUES (...)
-`;
-
-// Return success to the client
-return json(res, 200, { success: true, message: 'Skill unlocked!' });
-```
diff --git a/tasks/monetization-feature/06-backend-skill-access-control.md b/tasks/monetization-feature/06-backend-skill-access-control.md
deleted file mode 100644
index d9dfd46c3..000000000
--- a/tasks/monetization-feature/06-backend-skill-access-control.md
+++ /dev/null
@@ -1,31 +0,0 @@
----
-status: not-started
----
-
-# Prompt 6: Backend - Skill Access Control
-
-**Status:** Not Started
-
-## Objective
-Implement a mechanism to check if a user has purchased a skill before allowing them to use it.
-
-## Explanation
-Once a user has purchased a skill, our backend needs to enforce that only paying users can access it. This involves adding an access control check to the API endpoint that executes a skill.
-
-## Instructions
-- [ ] **Create a new database table: `user_skill_access`**. It should contain:
- - `id`: Primary key.
- - `user_id`: Foreign key to the user.
- - `agent_id`: Foreign key to the agent.
- - `skill_name`: The name of the skill.
- - `expires_at`: A timestamp for subscription-based access (optional for now).
-- [ ] **After a successful purchase, record the access in this table.** The purchase confirmation step should write a new entry to `user_skill_access`.
-- [ ] **Locate the API endpoint that executes skills** (e.g., `/api/agent/invoke`).
-- [ ] **Before executing a skill, add a check:**
- - 1. Is the skill a paid skill? Look up its price.
- - 2. If it is paid, does the user have a valid entry in the `user_skill_access` table?
- - 3. If the user does not have access, return a `402 Payment Required` error with a message like "You need to purchase this skill to use it."
- - 4. If the user has access, proceed with executing the skill.
-
-## 402 Payment Required
-Using the `402` HTTP status code is the standard way to indicate that a resource is behind a paywall. This is a key part of the [x402 protocol](https://402.wtf/).
diff --git a/tasks/monetization-feature/06-backend-solana-webhook.md b/tasks/monetization-feature/06-backend-solana-webhook.md
deleted file mode 100644
index 8bc71d49e..000000000
--- a/tasks/monetization-feature/06-backend-solana-webhook.md
+++ /dev/null
@@ -1,71 +0,0 @@
----
-status: not-started
----
-
-# Prompt 6: Backend Solana Transaction Confirmation
-
-**Status:** Not Started
-
-## Objective
-Create a backend endpoint that verifies a Solana transaction signature, and if valid, records the skill purchase in the database.
-
-## Explanation
-After a user approves a transaction with their wallet, the wallet will submit it to the network. The frontend will get the transaction signature and send it to our backend. This endpoint will confirm the transaction on-chain, check that the details (amount, recipient) are correct, and then insert a record into the `skill_purchases` table.
-
-## Instructions
-- [ ] **Create a new API endpoint file** (e.g., `/api/payments/confirm-tx.js`).
-- [ ] **Endpoint Logic:**
- - [ ] Accept a `POST` request with a `transactionSignature`.
- - [ ] Authenticate the user.
- - [ ] Use the Solana RPC API (`@solana/web3.js`) to fetch the confirmed transaction details.
- - [ ] **Crucially, verify:**
- - The transaction was successful.
- - The transfer destination matches the agent creator's wallet.
- - The transfer amount and mint match the skill's price.
- - The transaction includes the unique `reference` key from the Solana Pay request.
- - [ ] If all checks pass, `INSERT` a new row into the `skill_purchases` table.
-- [ ] **Return a success or failure response** to the frontend.
-
-## Code Example (Conceptual Node.js)
-
-```javascript
-import { Connection } from '@solana/web3.js';
-// ...
-
-const connection = new Connection(process.env.SOLANA_RPC_URL);
-
-export default wrap(async (req, res) => {
- const user = await getSessionUser(req);
- // ...
- const { signature, agentId, skillName } = await readJson(req);
-
- // 1. Fetch transaction
- const tx = await connection.getParsedTransaction(signature, 'confirmed');
- if (!tx || tx.meta.err) {
- return error(res, 400, 'Transaction not confirmed or failed.');
- }
-
- // 2. Fetch expected price and recipient
- const [priceInfo] = await sql`...`;
- const [agentInfo] = await sql`...`;
-
- // 3. Verify transaction details (this part is complex and requires parsing instructions)
- // You need to find the correct spl-token transfer instruction and check its `info`.
- const transferInstruction = tx.transaction.message.instructions.find(...)
- const sentAmount = transferInstruction.info.amount;
- const recipient = transferInstruction.info.destination;
- const mint = transferInstruction.info.mint;
-
- if (recipient !== agentInfo.solana_wallet || sentAmount < priceInfo.amount || mint !== priceInfo.currency_mint) {
- return error(res, 400, 'Transaction details do not match.');
- }
-
- // 4. Record purchase
- await sql`
- INSERT INTO skill_purchases (user_id, agent_id, skill_name, ...)
- VALUES (${user.id}, ${agentId}, ${skillName}, ...);
- `;
-
- return json(res, 200, { message: 'Purchase successful!' });
-});
-```
diff --git a/tasks/monetization-feature/06-frontend-purchase-button-and-modal.md b/tasks/monetization-feature/06-frontend-purchase-button-and-modal.md
deleted file mode 100644
index c2dc9df11..000000000
--- a/tasks/monetization-feature/06-frontend-purchase-button-and-modal.md
+++ /dev/null
@@ -1,81 +0,0 @@
----
-status: completed
----
-
-# Prompt 6: Frontend - "Purchase Skill" Button & Modal
-
-**Status:** Not Started
-
-## Objective
-On the agent detail page, display a "Purchase" button for paid skills, which, when clicked, opens a modal with a Solana Pay QR code for the transaction.
-
-## Explanation
-Now that the backend can prepare a purchase transaction, the frontend needs to trigger it. This involves changing the UI to show a clear call-to-action for purchasing a skill. Using a modal with a QR code is a standard and user-friendly way to handle crypto payments, as it works seamlessly for both desktop (scanning with a mobile wallet) and mobile users (opening a wallet app directly).
-
-## Instructions
-- [ ] **Modify Skill Rendering Logic:** In `src/marketplace.js` (inside `renderDetail`), update the logic that creates skill badges.
- - If a skill has a price and is not yet owned by the user, render a `<button class="purchase-btn">`.
- - Store the `agent_id` and `skill_name` in data attributes on the button (e.g., `data-agent-id="..."`, `data-skill-name="..."`).
-- [ ] **Create a Modal:** In `marketplace.html`, add the HTML structure for a modal dialog. It should be hidden by default and contain an element for the QR code and some instructional text.
-- [ ] **Add Event Listener:**
- - Attach a click event listener to the `.purchase-btn` buttons.
- - When a button is clicked, prevent the default action, and read the `agent_id` and `skill_name` from the data attributes.
-- [ ] **Implement Solana Pay QR Code Generation:**
- - Use the `@solana/pay` frontend library.
- - Inside the event listener, construct the URL for the purchase API (`/api/purchase/skill?agent_id=...&skill_name=...`). This URL is what the wallet will interact with.
- - Use the library to generate a QR code from this URL.
- - Append the generated QR code (it's an `<img>` or `<canvas>` element) to the modal and display the modal.
-
-## Code Example (`src/marketplace.js`)
-```javascript
-import { createQR } from '@solana/pay';
-import { escapeHtml } from './utils'; // Assuming you have this
-
-// ... inside renderDetail function
-$('d-skills').innerHTML = skillsArr.map(s => {
- const name = s.name || s;
- const price = skillPrices[name];
- const isOwned = userOwnedSkills.includes(name); // Assume you have this data
-
- let badge;
- if (isOwned) {
- badge = `<span class="price-badge price-owned">Owned</span>`;
- } else if (price) {
- badge = `<button class="purchase-btn" data-agent-id="${a.id}" data-skill-name="${name}">
- ${(price.amount / 1e6).toFixed(2)} USDC
- </button>`;
- } else {
- badge = `<span class="price-badge price-free">Free</span>`;
- }
- return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;
-}).join(' ');
-
-// Add the event listener after rendering
-addPurchaseButtonListeners();
-
-
-function addPurchaseButtonListeners() {
- const qrCodeContainer = document.getElementById('qr-code-container');
- const purchaseModal = document.getElementById('purchase-modal');
-
- document.querySelectorAll('.purchase-btn').forEach(button => {
- button.addEventListener('click', (event) => {
- const agentId = event.target.dataset.agentId;
- const skillName = event.target.dataset.skillName;
-
- // URL for the API endpoint from Prompt 5
- const url = new URL(`${window.location.origin}/api/purchase/skill`);
- url.searchParams.append('agent_id', agentId);
- url.searchParams.append('skill_name', skillName);
-
- // Generate QR Code
- const qr = createQR(url, 256, 'transparent'); // size, background
-
- // Display modal
- qrCodeContainer.innerHTML = '';
- qr.append(qrCodeContainer);
- purchaseModal.style.display = 'block';
- });
- });
-}
-```
diff --git a/tasks/monetization-feature/06-frontend-purchase-skill-flow.md b/tasks/monetization-feature/06-frontend-purchase-skill-flow.md
deleted file mode 100644
index 908bf374e..000000000
--- a/tasks/monetization-feature/06-frontend-purchase-skill-flow.md
+++ /dev/null
@@ -1,72 +0,0 @@
----
-status: not-started
----
-
-# Prompt 6: Frontend - Purchase Skill Flow
-
-## Objective
-Implement the frontend flow for a user to purchase a skill, including a confirmation modal that shows the price and triggers the transaction.
-
-## Explanation
-When a user clicks on a paid skill they don't own, we need to present them with a purchase confirmation modal. This modal will display the skill's name, price, and ask for confirmation. Upon confirmation, it will initiate a Solana transaction to transfer the required amount from the user's wallet to the creator's wallet.
-
-## Instructions
-1. **Create the Purchase Modal:**
- * Design and create a modal component that can be dynamically shown when a purchase is initiated.
- * The modal should clearly display the skill name, price, and currency.
- * It should have "Confirm Purchase" and "Cancel" buttons.
-
-2. **Trigger the Modal:**
- * In the agent detail view in the marketplace, add a "Purchase" button next to paid skills that the user doesn't own.
- * When this button is clicked, open the purchase modal and populate it with the skill's data.
-
-3. **Handle the Transaction:**
- * When the "Confirm Purchase" button is clicked, use the connected wallet adapter to create and sign a Solana transaction.
- * The transaction will be a simple SPL token transfer from the user's wallet to the skill creator's wallet.
- * Display feedback to the user while the transaction is being processed and after it has been confirmed or failed.
-
-## Code Example (Frontend - Transaction Logic)
-
-```javascript
-import { useConnection, useWallet } from '@solana/wallet-adapter-react';
-import { getAssociatedTokenAddress, createTransferInstruction } from '@solana/spl-token';
-import { Transaction, PublicKey } from '@solana/web3.js';
-
-// Inside your purchase confirmation handler
-
-const { connection } = useConnection();
-const { publicKey, sendTransaction } = useWallet();
-
-async function handlePurchase(skill) {
- if (!publicKey) {
- alert('Please connect your wallet first.');
- return;
- }
-
- const { amount, currency_mint, creator_wallet } = skill.price;
-
- const fromTokenAccount = await getAssociatedTokenAddress(new PublicKey(currency_mint), publicKey);
- const toTokenAccount = await getAssociatedTokenAddress(new PublicKey(currency_mint), new PublicKey(creator_wallet));
-
- const transaction = new Transaction().add(
- createTransferInstruction(
- fromTokenAccount,
- toTokenAccount,
- publicKey,
- amount
- )
- );
-
- try {
- const signature = await sendTransaction(transaction, connection);
- await connection.confirmTransaction(signature, 'processed');
-
- // After successful transaction, call the backend to record the purchase
- // ...
-
- } catch (error) {
- console.error('Transaction failed:', error);
- alert('Transaction failed. Please try again.');
- }
-}
-```
diff --git a/tasks/monetization-feature/06-trigger-payment-modal.md b/tasks/monetization-feature/06-trigger-payment-modal.md
deleted file mode 100644
index bda177a50..000000000
--- a/tasks/monetization-feature/06-trigger-payment-modal.md
+++ /dev/null
@@ -1,112 +0,0 @@
-# Prompt 6: Trigger Payment Modal
-
-## Objective
-Wire up the "Purchase" buttons on the agent detail page to open the payment modal and pre-fill it with the correct skill and price information by fetching a payment intent from the backend.
-
-## Explanation
-With the modal UI and the payment intent API in place, we can now connect them. When a user clicks "Purchase" on a specific skill, the frontend should:
-1. Prevent any default action.
-2. Call the `/api/payments/intent` endpoint with the agent ID and skill name.
-3. Use the response to populate the payment modal's UI.
-4. Display the modal to the user.
-
-## Instructions
-1. **Add Event Listener:**
- * In `src/marketplace.js`, modify the `renderDetail` function.
- * After rendering the skills, add a single event listener to the `d-skills` container. Use event delegation to catch clicks on `.purchase` buttons. This is more efficient than adding a listener to every button.
-
-2. **Implement the Click Handler:**
- * The handler function should be `async`.
- * Get the `skill-name` from the button's `data-skill-name` attribute.
- * Show a loading state (e.g., disable the button, change its text).
- * `POST` to `/api/payments/intent` with the current agent's ID (`detailState.agent.id`) and the skill name. Remember to include credentials.
-
-3. **Populate and Show the Modal:**
- * On a successful API response, grab the modal elements.
- * Populate the skill name, agent name, and price fields using the data from the payment intent. Format the price correctly.
- * Store the `intent_id` and other relevant data from the response in a variable or on a DOM element for the next step (payment).
- * Remove the `hidden` attribute from the modal overlay to show it.
- * Reset the loading state of the purchase button.
-
-4. **Handle Modal Closing:**
- * Add event listeners to the modal's close button and overlay to hide the modal when clicked.
-
-## Code Example (Frontend - `src/marketplace.js`)
-
-```javascript
-// Add this new function to marketplace.js
-
-function bindPurchaseFlow() {
- const skillsContainer = $('d-skills');
- if (!skillsContainer) return;
-
- skillsContainer.addEventListener('click', async (e) => {
- if (!e.target.matches('.purchase')) return;
-
- const btn = e.target;
- const skillName = btn.dataset.skillName;
- if (!skillName || !detailState.agent) return;
-
- btn.disabled = true;
- btn.textContent = 'Preparing...';
-
- try {
- const res = await fetch('/api/payments/intent', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- credentials: 'include',
- body: JSON.stringify({
- agent_id: detailState.agent.id,
- skill_name: skillName,
- }),
- });
- const intent = await res.json();
- if (!res.ok) throw new Error(intent.error_description || 'Failed to create payment intent.');
-
- openPaymentModal(intent, skillName);
-
- } catch (err) {
- console.error('Payment intent failed', err);
- // You could show a toast notification here
- } finally {
- btn.disabled = false;
- btn.textContent = 'Purchase';
- }
- });
-}
-
-function openPaymentModal(intent, skillName) {
- // Store intent for later use
- document.getElementById('payment-modal-overlay').dataset.intentId = intent.intent_id;
-
- // Populate modal
- $('payment-skill-name').textContent = skillName;
- $('payment-agent-name').textContent = detailState.agent.name;
- const priceInUSDC = (Number(intent.amount) / 1e6).toFixed(2);
- $('payment-price-display').textContent = `${priceInUSDC} USDC`;
-
- // Show modal
- $('payment-modal-overlay').hidden = false;
-}
-
-function closePaymentModal() {
- $('payment-modal-overlay').hidden = true;
-}
-
-
-// --- Inside the init() or similar setup function ---
-// Call bindPurchaseFlow whenever the detail view is shown
-// For example, inside loadDetail after rendering:
-// renderDetail(a, aJ.data.bookmarked);
-// bindPurchaseFlow();
-
-// Add listeners for closing the modal
-$('payment-modal-close').addEventListener('click', closePaymentModal);
-$('payment-modal-overlay').addEventListener('click', (e) => {
- if (e.target.id === 'payment-modal-overlay') {
- closePaymentModal();
- }
-});
-```
-
-**Note:** You will need to call `bindPurchaseFlow()` at the appropriate time, likely after the detail view has been rendered by the `loadDetail` function, to ensure the buttons exist in the DOM.
diff --git a/tasks/monetization-feature/06-ui-add-purchase-button.md b/tasks/monetization-feature/06-ui-add-purchase-button.md
deleted file mode 100644
index e0de7db23..000000000
--- a/tasks/monetization-feature/06-ui-add-purchase-button.md
+++ /dev/null
@@ -1,71 +0,0 @@
----
-status: not-started
----
-
-# Prompt 6: UI - Add "Purchase" Button for Priced Skills
-
-**Status:** Not Started
-
-## Objective
-Update the agent detail page UI to display a "Purchase" or "Buy" button next to skills that are not free and have not yet been purchased by the user.
-
-## Explanation
-Following on from Prompt 1 where we displayed the price, we now need to add a call to action. This involves checking if the user already owns the skill. We will use the `check-skill-access` API endpoint created in the previous step. The button's state will depend on three factors: is the skill priced, and does the user own it?
-
-## Instructions
-- [ ] **Modify `src/marketplace.js`:**
- - [ ] In the `renderDetail` function, before rendering the skills list, fetch the user's access status for all skills on the current agent. You can create a new function for this that calls your `/api/marketplace/check-skill-access` endpoint for each skill.
- - [ ] Store the owned skills in a `Set` for quick lookups.
- - [ ] In the `map` function that renders each skill, add a condition:
- - If `price` exists and the skill is in the `ownedSkills` set, show an "Owned" badge.
- - If `price` exists and the skill is *not* in the `ownedSkills` set, render a purchase button.
- - If the skill is free, show the "Free" badge as before.
-
-## Code Example (`src/marketplace.js`)
-
-```javascript
-// A new helper function to get all owned skills for an agent
-async function getOwnedSkills(agentId, skills) {
- const owned = new Set();
- // In a real app, you might want a single API call for this,
- // but for now, parallel checks are fine.
- await Promise.all(skills.map(async (s) => {
- const name = typeof s === 'string' ? s : s.name;
- try {
- const res = await fetch(`/api/marketplace/check-skill-access?agent_id=${agentId}&skill_name=${name}`);
- const data = await res.json();
- if (data.has_access) {
- owned.add(name);
- }
- } catch (e) { console.error('Failed to check skill access', e); }
- }));
- return owned;
-}
-
-// Inside renderDetail function, before rendering skills
-const skillsArr = a.skills ? (Array.isArray(a.skills) ? a.skills : Object.values(a.skills)) : [];
-const ownedSkills = await getOwnedSkills(a.id, skillsArr);
-
-const skillPrices = a.skill_prices || {};
-$('d-skills').innerHTML = skillsArr.length
- ? skillsArr.map((s) => {
- const name = typeof s === 'string' ? s : (s.name || '');
- const price = skillPrices[name];
-
- let badgeOrButton = `<span class="price-badge price-free">Free</span>`;
- if (price) {
- if (ownedSkills.has(name)) {
- badgeOrButton = `<span class="price-badge price-owned">✓ Owned</span>`;
- } else {
- badgeOrButton = `<button class="purchase-btn" data-agent-id="${a.id}" data-skill-name="${name}">
- Buy for ${(price.amount / 1e6).toFixed(2)} USDC
- </button>`;
- }
- }
- return `<span class="skill-entry">${escapeHtml(name)}${badgeOrButton}</span>`;
- }).join(' ')
- : '<div>This Agent has no skills defined.</div>';
-```
-
-## Tracking
-- To mark this task as complete, check all boxes in the instructions and change the status in the frontmatter to `Completed`.
diff --git a/tasks/monetization-feature/06-uiux-design-purchase-modal.md b/tasks/monetization-feature/06-uiux-design-purchase-modal.md
deleted file mode 100644
index 533980282..000000000
--- a/tasks/monetization-feature/06-uiux-design-purchase-modal.md
+++ /dev/null
@@ -1,64 +0,0 @@
----
-status: not-started
----
-
-# Prompt 6: UI/UX - Design the Skill Purchase Modal
-
-## Objective
-Design a clear, user-friendly modal for purchasing skills, which will serve as the blueprint for frontend implementation.
-
-## Explanation
-A well-designed purchase modal is critical for conversion. It needs to be simple, trustworthy, and provide all necessary information at a glance. Before writing code, we should define the components and layout of this modal. This design task ensures that the subsequent implementation is fast and aligned with the user's needs.
-
-## Instructions
-1. **Sketch the Modal Layout:**
- * Create a wireframe or a simple mockup of the purchase modal. This can be done with a tool like Figma, or even a drawing on paper.
- * The modal should be triggered by clicking on a paid skill.
-
-2. **Define Modal Components:**
- * The modal must include:
- * **Header:** "Purchase Skill: [Skill Name]"
- * **Skill Description:** A brief explanation of what the skill does.
- * **Price Display:** The price in a clear format (e.g., "5.00 USDC").
- * **Creator Info:** The name or avatar of the skill creator.
- * **Call to Action (CTA):** A primary button like "Purchase with Solana Pay" or "Buy Now".
- * **Balance Check (Optional but Recommended):** Display the user's current USDC balance.
- * **Close Button:** An 'X' in the corner to dismiss the modal.
- * **Status Area:** A space to show transaction progress (e.g., "Generating QR Code...", "Awaiting Confirmation...").
-
-3. **Document the User Flow:**
- * Describe the steps a user takes:
- 1. User clicks a paid skill.
- 2. The purchase modal appears.
- 3. User clicks "Purchase".
- 4. A Solana Pay QR code is displayed.
- 5. User scans with their wallet and approves.
- 6. The modal shows a confirmation message.
- 7. The modal closes, and the UI updates to show the skill as "Owned".
-
-## Design Mockup Example
-
-(This can be a simple text-based layout or a link to a visual design)
-
-```
-+-------------------------------------------------+
-| Purchase Skill: Rug-Pull Detection [X] |
-+-------------------------------------------------+
-| |
-| Flags high-risk tokens using on-chain data to |
-| help you avoid potential scams. |
-| |
-| Created by: @skill_creator_1 |
-| |
-| ----------------------------------------------- |
-| |
-| Price: 5.00 USDC |
-| Your Balance: 23.45 USDC |
-| |
-+-------------------------------------------------+
-| [ Purchase with Solana Pay ] |
-| |
-| Status: Waiting for user action... |
-+-------------------------------------------------+
-```
-This design document will guide the implementation in the next prompt.
diff --git a/tasks/monetization-feature/07-backend-list-purchased-skills-api.md b/tasks/monetization-feature/07-backend-list-purchased-skills-api.md
deleted file mode 100644
index 40a6c4596..000000000
--- a/tasks/monetization-feature/07-backend-list-purchased-skills-api.md
+++ /dev/null
@@ -1,53 +0,0 @@
----
-status: not-started
----
-
-# Prompt 7: API to List Purchased Skills
-
-**Status:** Not Started
-
-## Objective
-Create an API endpoint that allows a logged-in user to see a list of all the skills they have purchased.
-
-## Explanation
-The frontend needs a way to know which skills the current user owns. This is useful for updating the UI on agent detail pages (e.g., showing "Owned" instead of "Buy") and for displaying a list of all purchased skills on the user's profile page.
-
-## Instructions
-- [ ] **Create a new API endpoint file** (e.g., `/api/users/my-skills.js`).
-- [ ] **Endpoint Logic:**
- - [ ] Handle a `GET` request.
- - [ ] Authenticate the user to get their `user_id`.
- - [ ] Query the `skill_purchases` table for all records matching the `user_id`.
- - [ ] The query should return the `agent_id` and `skill_name` for each purchase.
-- [ ] **Return the list of purchased skills as a JSON array.** For efficiency, you might return an object structure that's easy for the frontend to look up, e.g., `{ "agent_id:skill_name": true }`.
-
-## Code Example (Node.js + @vercel/postgres)
-
-```javascript
-// In /api/users/my-skills.js
-
-import { sql } from '../_lib/db.js';
-import { getSessionUser } from '../_lib/auth.js';
-// ...
-
-export default wrap(async (req, res) => {
- if (req.method !== 'GET') return error(res, 405, 'method not allowed');
-
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized');
-
- const { rows } = await sql`
- SELECT agent_id, skill_name
- FROM skill_purchases
- WHERE user_id = ${user.id};
- `;
-
- // Create a lookup map for easy access on the frontend
- const purchasedSkillsLookup = {};
- for (const row of rows) {
- purchasedSkillsLookup[`${row.agent_id}:${row.skill_name}`] = true;
- }
-
- return json(res, 200, { purchased: purchasedSkillsLookup });
-});
-```
diff --git a/tasks/monetization-feature/07-frontend-add-purchase-button.md b/tasks/monetization-feature/07-frontend-add-purchase-button.md
deleted file mode 100644
index ea2ecb311..000000000
--- a/tasks/monetization-feature/07-frontend-add-purchase-button.md
+++ /dev/null
@@ -1,93 +0,0 @@
----
-status: not-started
----
-
-# Prompt 7: Add Purchase Button to UI
-
-**Status:** Not Started
-
-## Objective
-Update the agent detail page in the marketplace to display a "Purchase" or "Unlock" button next to paid skills that the user has not yet purchased.
-
-## Explanation
-Now that the backend can identify priced skills, we need to provide a clear call-to-action for the user. This prompt focuses on the UI changes required to show the correct button based on the skill's price and the user's purchase history. This is the first step in building the frontend purchasing flow.
-
-## Instructions
-
-1. **Fetch User's Purchased Skills:**
- * In `src/marketplace.js`, when the marketplace page loads, make a call to the new `/api/user/purchased-skills` endpoint if the user is logged in.
- * Store the returned list of purchased skills in a variable accessible by the `renderDetail` function.
-
-2. **Modify the `renderDetail` Function:**
- * Inside the `renderDetail` function, you already have logic to display a price badge. Now, extend that logic.
- * For each skill, perform the following checks:
- a. Does the skill have a price? (`skillPrices[name]`)
- b. If it has a price, has the current user already purchased this skill for this agent? (Check against the list of purchased skills).
- * Render the UI conditionally:
- * If the skill has no price, show the "Free" badge.
- * If the skill has a price and the user **has not** purchased it, show the price and a "Purchase" button.
- * If the skill has a price and the user **has** purchased it, show an "Owned" or "Unlocked" badge and disable or hide the purchase button.
-
-## Code Example (Frontend - `src/marketplace.js`)
-
-```javascript
-// In src/marketplace.js, assuming `userPurchases` is fetched and available
-
-// Inside renderDetail function
-const userPurchasesForThisAgent = userPurchases[a.id] || [];
-const skillPrices = a.skill_prices || {};
-
-$('d-skills').innerHTML = skillsArr.length
- ? skillsArr.map((s) => {
- const name = typeof s === 'string' ? s : (s.name || '');
- const price = skillPrices[name];
- let badge = `<span class="price-badge price-free">Free</span>`;
-
- if (price) {
- const isPurchased = userPurchasesForThisAgent.includes(name);
- const priceDisplay = (price.amount / 1e6).toFixed(2);
-
- if (isPurchased) {
- badge = `<span class="price-badge price-owned">✓ Owned</span>`;
- } else {
- badge = `
- <span class="price-badge price-paid">${priceDisplay} USDC</span>
- <button class="btn-purchase" data-agent-id="${a.id}" data-skill-name="${name}">
- Purchase
- </button>
- `;
- }
- }
- return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;
- }).join(' ')
- : '<div>This Agent has no skills defined.</div>';
-
-// Add event listeners for the new buttons after setting innerHTML
-document.querySelectorAll('.btn-purchase').forEach(btn => {
- btn.addEventListener('click', handlePurchaseClick);
-});
-```
-
-## CSS Example (add to `/marketplace.css`)
-
-```css
-.btn-purchase {
- margin-left: 8px;
- padding: 3px 8px;
- font-size: 10px;
- background-color: #fde047;
- color: #1c1917;
- border: none;
- border-radius: 4px;
- cursor: pointer;
- font-weight: 600;
- transition: background-color 0.2s;
-}
-.btn-purchase:hover {
- background-color: #facc15;
-}
-.price-owned {
- color: #a7f3d0;
- background-color: rgba(52, 211, 153, 0.1);
-}
-```
diff --git a/tasks/monetization-feature/07-frontend-implement-purchase-modal-ui.md b/tasks/monetization-feature/07-frontend-implement-purchase-modal-ui.md
deleted file mode 100644
index 5fa1bdb10..000000000
--- a/tasks/monetization-feature/07-frontend-implement-purchase-modal-ui.md
+++ /dev/null
@@ -1,92 +0,0 @@
----
-status: not-started
----
-
-# Prompt 7: Frontend - Implement Skill Purchase Modal UI
-
-## Objective
-Build the HTML and CSS for the skill purchase modal based on the design defined in the previous prompt.
-
-## Explanation
-With the UI/UX design for the purchase modal complete, we can now translate it into a functional frontend component. This task focuses on building the structure and styling of the modal, without yet wiring it up to the Solana Pay logic. This separation of concerns allows us to perfect the visual presentation first.
-
-## Instructions
-1. **Add Modal HTML to `marketplace.html`:**
- * Add the HTML structure for a modal to the bottom of your `marketplace.html` file. It should be hidden by default (e.g., with `display: none`).
- * Use clear and semantic element IDs for the dynamic parts of the modal (e.g., `purchase-modal-skill-name`, `purchase-modal-price`, `purchase-modal-cta`).
-
-2. **Create CSS for the Modal:**
- * In `/public/marketplace.css`, add styles for the modal container, backdrop, header, content, and buttons.
- * Ensure the modal is centered, has a professional appearance, and is responsive to different screen sizes.
-
-3. **Add JavaScript to Show/Hide the Modal:**
- * In `src/marketplace.js`, add a function to populate and show the modal when a paid skill is clicked.
- * Add event listeners for the close button and backdrop to hide the modal.
-
-## Code Example (HTML in `marketplace.html`)
-
-```html
-<!-- Add at the end of the body -->
-<div id="purchase-modal-backdrop" class="modal-backdrop" style="display: none;">
- <div id="purchase-modal" class="modal">
- <div class="modal-header">
- <h2 id="purchase-modal-title">Purchase Skill</h2>
- <button id="purchase-modal-close" class="modal-close-btn">&times;</button>
- </div>
- <div class="modal-body">
- <p id="purchase-modal-description"></p>
- <div class="creator-info">Created by: <span id="purchase-modal-creator"></span></div>
- <hr />
- <div class="price-details">
- <span>Price:</span>
- <strong id="purchase-modal-price"></strong>
- </div>
- <div class="status-area" id="purchase-modal-status"></div>
- </div>
- <div class="modal-footer">
- <button id="purchase-modal-cta" class="cta-button">Purchase</button>
- </div>
- </div>
-</div>
-```
-
-## Code Example (JavaScript in `src/marketplace.js`)
-
-```javascript
-// Function to open the modal
-function showPurchaseModal(skillName, price, description, creator) {
- $('purchase-modal-title').textContent = `Purchase Skill: ${skillName}`;
- $('purchase-modal-description').textContent = description;
- $('purchase-modal-creator').textContent = creator;
- $('purchase-modal-price').textContent = `${(price.amount / 1e6).toFixed(2)} USDC`;
-
- // Store data for the purchase action
- const cta = $('purchase-modal-cta');
- cta.dataset.skillName = skillName;
- cta.dataset.amount = price.amount;
- cta.dataset.mint = price.currency_mint;
-
- $('purchase-modal-backdrop').style.display = 'flex';
-}
-
-// Add event listeners for showing/hiding
-document.addEventListener('DOMContentLoaded', () => {
- // Hide modal logic
- const backdrop = $('purchase-modal-backdrop');
- $('purchase-modal-close').addEventListener('click', () => backdrop.style.display = 'none');
- backdrop.addEventListener('click', (e) => {
- if (e.target === backdrop) {
- backdrop.style.display = 'none';
- }
- });
-
- // Show modal logic (example, needs to be integrated with skill list rendering)
- $('d-skills').addEventListener('click', (e) => {
- const skillEntry = e.target.closest('.skill-entry.paid'); // Add .paid class to priced skills
- if (skillEntry) {
- // Fetch skill details from data attributes or an in-memory object
- // showPurchaseModal(skillName, price, ...);
- }
- });
-});
-```
diff --git a/tasks/monetization-feature/07-solana-wallet-adapter.md b/tasks/monetization-feature/07-solana-wallet-adapter.md
deleted file mode 100644
index 241b0fdd7..000000000
--- a/tasks/monetization-feature/07-solana-wallet-adapter.md
+++ /dev/null
@@ -1,77 +0,0 @@
-# Prompt 7: Integrate Solana Wallet Adapter
-
-## Objective
-Integrate the Solana Wallet Adapter into the marketplace page to enable users to connect their Solana wallets (like Phantom, Solflare, etc.).
-
-## Explanation
-To accept payments on the Solana blockchain, our web application needs to communicate with the user's wallet. The Solana Wallet Adapter is a suite of libraries that provides a standardized way to connect to various wallets, get the user's public key, and request transaction signatures. This is the foundation for our payment flow.
-
-## Instructions
-1. **Add Script Tags:**
- * Open `marketplace.html`.
- * In the `<head>` section, add script tags to import the necessary Wallet Adapter libraries from a CDN (like unpkg). You will need `wallet-adapter-base`, `wallet-adapter-solana`, and `wallet-adapter-wallets`. You should also include the CSS for the adapter's UI components.
-
-2. **Initialize the Wallet Adapter:**
- * In `src/marketplace.js`, create a new function to initialize the wallet adapter.
- * Instantiate the wallets you want to support (e.g., `PhantomWalletAdapter`, `SolflareWalletAdapter`).
- * Create a `Connection` object pointing to the Solana cluster you're using (e.g., 'mainnet-beta' or 'devnet').
- * Use these to create the main wallet adapter instance.
-
-3. **Render the Wallet Button:**
- * The wallet adapter library provides a pre-built UI component for a "Connect Wallet" button.
- * In your initialization code, create an instance of this button and append it to the `payment-wallet-area` in your payment modal.
-
-4. **Listen for Connection Changes:**
- * The adapter emits events when a user connects or disconnects.
- * Add event listeners to update the UI accordingly. For instance, when a user connects, you can show their public key and change the button to "Disconnect." You should also enable the "Confirm Purchase" button.
-
-## Code Example (`marketplace.html`)
-
-Add these scripts and the link tag to the `<head>` of your `marketplace.html`.
-
-```html
-<!-- In <head> of marketplace.html -->
-<link rel="stylesheet" href="https://unpkg.com/@solana/wallet-adapter-react-ui/styles.css" />
-
-<script src="https://unpkg.com/@solana/web3.js@latest/lib/index.iife.js"></script>
-<script src="https://unpkg.com/@solana/wallet-adapter-base@latest/lib/index.iife.js"></script>
-<script src="https://unpkg.com/@solana/wallet-adapter-wallets@latest/lib/index.iife.js"></script>
-<script src="https://unpkg.com/@solana/wallet-adapter-react@latest/lib/index.iife.js"></script>
-<script src="https://unpkg.com/@solana/wallet-adapter-react-ui@latest/lib/index.iife.js"></script>
-```
-
-## Code Example (`src/marketplace.js`)
-
-```javascript
-// Add these variables and functions to the top level of marketplace.js
-
-const { Connection, clusterApiUrl } = solanaWeb3;
-const { WalletAdapterBase } = solanaWalletAdapterBase;
-const { getPhantomWallet, getSolflareWallet } = solanaWalletAdapterWallets;
-const { WalletModalProvider, WalletMultiButton } = solanaWalletAdapterReactUi;
-
-let solanaConnection;
-let wallet; // This will hold our wallet adapter instance
-
-function initWalletAdapter() {
- solanaConnection = new Connection(clusterApiUrl('mainnet-beta'));
-
- const wallets = [
- getPhantomWallet(),
- getSolflareWallet(),
- ];
-
- // The library is React-based, but we can use it imperatively.
- // This is a simplified, non-React setup.
- // A proper implementation would require a bit more work to integrate with a non-React app.
-
- // For now, let's create a simpler, custom connection flow in the next prompt.
- // The official components are difficult to use without React.
-
- console.log('Solana Wallet Adapter concept initialized.');
-}
-
-// In your main init() function, call initWalletAdapter();
-```
-
-**Correction & Simplification:** The official Solana Wallet Adapter UI libraries are heavily based on React, making them cumbersome to use in a vanilla JS project. The next prompt will focus on a simplified, custom implementation for connecting the wallet and signing the transaction, using the base adapter libraries without the UI components. This prompt serves to get the necessary scripts included in the project.
diff --git a/tasks/monetization-feature/07-ui-handling-402-payment-required.md b/tasks/monetization-feature/07-ui-handling-402-payment-required.md
deleted file mode 100644
index 184030463..000000000
--- a/tasks/monetization-feature/07-ui-handling-402-payment-required.md
+++ /dev/null
@@ -1,26 +0,0 @@
----
-status: not-started
----
-
-# Prompt 7: UI - Handling 402 Payment Required
-
-**Status:** Not Started
-
-## Objective
-Update the frontend to gracefully handle the `402 Payment Required` error from the backend and guide the user to purchase the skill.
-
-## Explanation
-When a user tries to use a paid skill they don't own, the backend will block them. The UI should catch this specific error and show a helpful message, such as a popup that prompts them to buy the skill.
-
-## Instructions
-- [ ] **In the part of your frontend code that calls the skill execution endpoint, add error handling.**
-- [ ] **Specifically check for a `402` status code in the response.**
-- [ ] **If a `402` error is received:**
- - 1. **Prevent the default error message** from being shown.
- - 2. **Display a modal or a notification** to the user.
- - 3. **The message should be clear,** e.g., "This is a premium skill. To use it, you need to purchase it first."
- - 4. **Include a "Purchase Skill" button** in the modal, which should trigger the purchase flow designed in a previous prompt.
- - 5. **Optionally, include a "Cancel" button** to close the modal.
-
-## User Experience
-This is a critical part of the user experience. Instead of a generic "Error" message, we are creating a clear call to action that guides the user through the monetization funnel.
diff --git a/tasks/monetization-feature/07-ui-purchase-modal.md b/tasks/monetization-feature/07-ui-purchase-modal.md
deleted file mode 100644
index 8e5d15a88..000000000
--- a/tasks/monetization-feature/07-ui-purchase-modal.md
+++ /dev/null
@@ -1,68 +0,0 @@
----
-status: not-started
----
-
-# Prompt 7: UI - Create Purchase Modal
-
-**Status:** Not Started
-
-## Objective
-Design and implement a modal dialog that appears when a user clicks the "Buy" button, presenting them with payment options.
-
-## Explanation
-A modal provides a focused, clean user experience for the payment process. This first version of the modal will be simple. It will confirm the skill being purchased and its price, and for now, it will present a Solana Pay QR code for the transaction. This separates the payment step from the main UI and prepares us for adding more payment methods later.
-
-## Instructions
-- [ ] **Add HTML for the modal to `marketplace.html`:**
- - [ ] Create a hidden `div` that will serve as the modal container.
- - [ ] Inside, add elements for a title, skill name, price, a container for a QR code, and a close button.
-- [ ] **Add CSS for the modal in `marketplace.css`:**
- - [ ] Style the modal to overlay the page content with a dark backdrop.
- - [ ] Center the modal content and style the text and QR code container.
-- [ ] **Add JavaScript logic in `src/marketplace.js`:**
- - [ ] Create a function `showPurchaseModal(agentId, skillName, price)`.
- - [ ] Attach a click event listener to the `d-skills` container that delegates to `.purchase-btn` clicks.
- - [ ] When a purchase button is clicked, call `showPurchaseModal` with the relevant data from the button's `data-` attributes.
- - [ ] The function will populate and display the modal.
-
-## HTML Example (`marketplace.html`)
-```html
-<!-- Add this somewhere inside the <body> tag -->
-<div id="purchaseModal" class="modal-hidden">
- <div class="modal-content">
- <span class="modal-close-btn">&times;</span>
- <h2>Purchase Skill</h2>
- <p>You are about to buy the skill:</p>
- <p id="modalSkillName" class="modal-skill-name"></p>
- <p>for</p>
- <p id="modalSkillPrice" class="modal-skill-price"></p>
- <div id="modalQrCode"></div>
- <p class="modal-hint">Scan with a Solana Pay compatible wallet.</p>
- </div>
-</div>
-```
-
-## CSS Example (`marketplace.css`)
-```css
-.modal-hidden { display: none; }
-#purchaseModal {
- position: fixed; z-index: 1000; left: 0; top: 0;
- width: 100%; height: 100%;
- background-color: rgba(0,0,0,0.6);
- display: flex; align-items: center; justify-content: center;
-}
-.modal-content {
- background-color: #1a1a1a; color: #fff;
- padding: 2rem; border-radius: 8px;
- width: 90%; max-width: 400px;
- text-align: center;
- position: relative;
-}
-.modal-close-btn {
- position: absolute; top: 10px; right: 15px;
- font-size: 28px; font-weight: bold; cursor: pointer;
-}
-```
-
-## Tracking
-- To mark this task as complete, check all boxes in the instructions and change the status in the frontmatter to `Completed`.
diff --git a/tasks/monetization-feature/08-backend-create-purchase-transaction-api.md b/tasks/monetization-feature/08-backend-create-purchase-transaction-api.md
deleted file mode 100644
index 798e78a08..000000000
--- a/tasks/monetization-feature/08-backend-create-purchase-transaction-api.md
+++ /dev/null
@@ -1,74 +0,0 @@
----
-status: not-started
----
-
-# Prompt 8: Backend - Create Purchase Transaction API
-
-## Objective
-Create a backend API endpoint to generate Solana Pay transaction requests for skill purchases.
-
-## Explanation
-To allow users to buy skills, we need an API that can create a Solana Pay transaction on demand. This endpoint will be called by the frontend when a user clicks the "Purchase" button. It will generate a unique transaction reference and return the necessary details for the frontend to display a Solana Pay QR code.
-
-## Instructions
-1. **Create the API Endpoint:**
- * Create a new file, e.g., `api/payments/create-transaction.js`.
- * This endpoint should accept `skill_id` and the `buyer_wallet_address` as input.
- * It should be a `POST` request and require authentication.
-
-2. **Implement the Logic:**
- * Fetch the skill's price from the `agent_skill_prices` table.
- * Fetch the creator's wallet address from the `users` table.
- * Use the Solana Pay SDK to construct a transaction that transfers the correct amount of USDC from the buyer to the creator.
- * Generate a unique reference public key for this transaction. This is crucial for tracking the payment status later.
- * Store the pending transaction details (e.g., reference, skill_id, buyer_id) in a new `skill_purchases` table.
- * Return the Solana Pay URL (`solana:....`) and the `reference` public key to the frontend.
-
-## Code Example (`api/payments/create-transaction.js`)
-
-```javascript
-import { Keypair } from '@solana/web3.js';
-import { createQR, encodeURL } from '@solana/pay';
-// ... other imports for db, etc.
-
-export default async function handler(req, res) {
- if (req.method !== 'POST') {
- return res.status(405).json({ error: 'Method Not Allowed' });
- }
-
- const { skillId, buyerAddress } = req.body;
- const userId = req.session.userId; // Assuming you have auth middleware
-
- if (!userId) {
- return res.status(401).json({ error: 'Unauthorized' });
- }
-
- // 1. Fetch skill price and creator's wallet
- const { price, creatorWallet } = await getSkillPriceAndCreator(skillId);
- if (!price) {
- return res.status(404).json({ error: 'Skill not found or not for sale' });
- }
-
- // 2. Generate a reference keypair for the transaction
- const reference = new Keypair().publicKey;
-
- // 3. Store pending purchase
- await recordPendingPurchase(userId, skillId, reference.toBase58());
-
- // 4. Create Solana Pay URL
- const url = encodeURL({
- recipient: creatorWallet,
- amount: new BigNumber(price.amount / 1e6), // Convert to decimal representation
- splToken: new PublicKey(price.currency_mint),
- reference,
- label: `Skill Purchase: ${skillName}`,
- memo: `SKILL:${skillId}`,
- });
-
- // 5. Return details to frontend
- res.status(200).json({
- solanaPayUrl: url.toString(),
- reference: reference.toBase58(),
- });
-}
-```
diff --git a/tasks/monetization-feature/08-backend-creator-earnings-api.md b/tasks/monetization-feature/08-backend-creator-earnings-api.md
deleted file mode 100644
index dda6ff47f..000000000
--- a/tasks/monetization-feature/08-backend-creator-earnings-api.md
+++ /dev/null
@@ -1,76 +0,0 @@
----
-status: not-started
----
-
-# Prompt 8: Backend - Creator Earnings API Endpoint
-
-## Objective
-Create a secure API endpoint to provide detailed earnings data for the logged-in creator.
-
-## Explanation
-This endpoint is the backbone of the Creator Earnings Dashboard. It needs to securely authenticate the user, query the database for all their sales, calculate summary statistics, and return the data in a clean, organized format for the frontend to consume.
-
-## Instructions
-1. **Create the API Route:**
- * Create a new file: `/api/users/earnings.js`.
-
-2. **Implement Authentication:**
- * The endpoint must be protected. Use your existing session management (e.g., `getSessionUser`) to get the `userId` of the requester.
- * If the user is not authenticated, return a `401 Unauthorized` error.
-
-3. **Query the Database:**
- * Write a SQL query to fetch sales data for the authenticated `userId`.
- * You will need to join several tables:
- * Start with a table that records sales or royalty payments (e.g., `royalty_ledger`).
- * Join with `agent_skill_prices` or a similar table to get skill details.
- * Join with `agents` to get agent names.
- * The query should select all necessary columns: date, skill name, agent name, price, currency, and payment status.
- * Order the results by date, descending.
-
-4. **Calculate Summary Data:**
- * After fetching the rows, use code to calculate the total revenue and the amount pending payout.
- * This is often more efficient than running separate aggregate SQL queries.
-
-5. **Format and Return the Response:**
- * Structure the response as a JSON object containing the summary figures and an array of the detailed transaction history.
-
-## Code Example (`/api/users/earnings.js`)
-
-```javascript
-import { sql } from '../_lib/db.js';
-import { getSessionUser } from '../_lib/auth.js';
-import { json, error, wrap } from '../_lib/http.js';
-
-export default wrap(async (req, res) => {
- if (req.method !== 'GET') return error(res, 405);
-
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized');
-
- const sales = await sql`
- SELECT
- r.created_at,
- s.skill_name,
- a.name AS agent_name,
- r.price_usd,
- r.status
- FROM royalty_ledger r
- JOIN agent_skill_prices s ON s.id = r.skill_price_id
- JOIN agents a ON a.id = s.agent_id
- WHERE r.author_user_id = ${user.id}
- ORDER BY r.created_at DESC
- LIMIT 100;
- `;
-
- const total_revenue = sales.reduce((sum, r) => sum + Number(r.price_usd), 0);
- const pending_payout = sales
- .filter(r => r.status === 'pending')
- .reduce((sum, r) => sum + Number(r.price_usd), 0);
-
- return json(res, 200, {
- total_revenue,
- pending_payout,
- history: sales,
- });
-});
-```
diff --git a/tasks/monetization-feature/08-connect-wallet-button.md b/tasks/monetization-feature/08-connect-wallet-button.md
deleted file mode 100644
index 7a555b38c..000000000
--- a/tasks/monetization-feature/08-connect-wallet-button.md
+++ /dev/null
@@ -1,106 +0,0 @@
-# Prompt 8: Connect Wallet Button Logic
-
-## Objective
-Implement the logic for a custom "Connect Wallet" button inside the payment modal, abandoning the difficult-to-integrate React components from the previous prompt.
-
-## Explanation
-Since the pre-built UI components for the Solana Wallet Adapter are React-based, we'll create our own simple connection flow. This gives us more control and avoids pulling in a large framework. The flow will be:
-1. User clicks our custom "Connect Wallet" button.
-2. We'll attempt to connect to a wallet provider found in the browser (e.g., Phantom).
-3. On success, we'll update the UI to show the user's wallet address and enable the payment button.
-
-## Instructions
-1. **Modify the Wallet Initialization:**
- * In `src/marketplace.js`, adjust the `initWalletAdapter` function. Instead of trying to render a React component, we will just prepare the adapter instances.
-
-2. **Create the Connect Button Logic:**
- * Add an event listener to the `#payment-connect-wallet-btn` inside the `openPaymentModal` function (or a separate setup function).
- * When clicked, the handler should try to connect to the wallet adapter.
- * Use `wallet.connect().catch(...)` to handle connection errors gracefully.
-
-3. **Update UI on Connection Status Change:**
- * Create a function, e.g., `updateWalletUI()`, that checks the wallet adapter's state (`wallet.connected`, `wallet.publicKey`).
- * If connected:
- * Hide the "Connect Wallet" button.
- * Display the user's public key (shortened for readability).
- * Show a "Disconnect" button.
- * Enable the "Confirm Purchase" button.
- * If disconnected:
- * Show the "Connect Wallet" button.
- * Hide the public key and disconnect button.
- * Disable the "Confirm Purchase" button.
- * Call this function after connecting/disconnecting and when the modal is first opened.
-
-4. **Add Disconnect Logic:**
- * Add an event listener to the "Disconnect" button to call `wallet.disconnect()`.
-
-## Code Example (Frontend - `src/marketplace.js`)
-
-```javascript
-// --- At the top of the file ---
-const { Connection, clusterApiUrl } = solanaWeb3;
-const { PhantomWalletAdapter } = solanaWalletAdapterWallets;
-
-let solanaConnection;
-let wallet; // Our single wallet adapter instance
-
-// --- Initialization ---
-function initWalletAdapter() {
- solanaConnection = new Connection(clusterApiUrl('mainnet-beta'));
- wallet = new PhantomWalletAdapter(); // We'll specifically use Phantom for simplicity
-
- // Listen for connection changes
- wallet.on('connect', () => {
- console.log('Wallet connected!');
- updateWalletUI();
- });
- wallet.on('disconnect', () => {
- console.log('Wallet disconnected!');
- updateWalletUI();
- });
-}
-
-// --- UI Update Logic ---
-function updateWalletUI() {
- const walletArea = $('payment-wallet-area');
- const confirmBtn = $('payment-confirm-btn');
-
- if (wallet.connected) {
- const pubKey = wallet.publicKey.toBase58();
- walletArea.innerHTML = `
- <p>Connected: <strong>${pubKey.slice(0, 4)}...${pubKey.slice(-4)}</strong></p>
- <button class="btn-secondary" id="payment-disconnect-btn">Disconnect</button>
- `;
- $('payment-disconnect-btn').addEventListener('click', () => wallet.disconnect());
- confirmBtn.disabled = false;
- } else {
- walletArea.innerHTML = `
- <button class="btn-primary" id="payment-connect-wallet-btn">Connect Phantom Wallet</button>
- `;
- $('payment-connect-wallet-btn').addEventListener('click', async () => {
- const btn = $('payment-connect-wallet-btn');
- btn.textContent = 'Connecting...';
- btn.disabled = true;
- try {
- await wallet.connect();
- } catch (error) {
- console.error("Failed to connect wallet", error);
- btn.textContent = 'Connect Phantom Wallet'; // Reset on failure
- btn.disabled = false;
- }
- });
- confirmBtn.disabled = true;
- }
-}
-
-// --- In the main `init()` function ---
-initWalletAdapter();
-
-// --- When opening the modal ---
-function openPaymentModal(intent, skillName) {
- // ... (previous code to populate skill name, price, etc.)
-
- updateWalletUI(); // Set the initial state of the wallet UI
- $('payment-modal-overlay').hidden = false;
-}
-```
diff --git a/tasks/monetization-feature/08-frontend-purchase-modal-with-solana.md b/tasks/monetization-feature/08-frontend-purchase-modal-with-solana.md
deleted file mode 100644
index aefa6c7ba..000000000
--- a/tasks/monetization-feature/08-frontend-purchase-modal-with-solana.md
+++ /dev/null
@@ -1,84 +0,0 @@
----
-status: not-started
----
-
-# Prompt 8: Frontend - Purchase Modal with Solana Pay
-
-**Status:** Not Started
-
-## Objective
-Create a user interface that allows users to purchase a skill NFT using their Solana wallet.
-
-## Explanation
-With the backend ready to generate purchase transactions, we need a frontend to initiate the process. This involves creating a purchase button that, when clicked, opens a modal with a Solana Pay QR code. Users can scan this with their mobile wallet or use a browser extension to approve the transaction.
-
-## Instructions
-1. **Modify the `renderDetail` Function:**
- - In `src/marketplace.js`, within the skill rendering loop, if a skill has a price, display a "Purchase" button instead of the price badge.
-
-2. **Create the Purchase Modal:**
- - Design a modal that will display the Solana Pay QR code.
- - The modal should show the skill name, price, and a spinning loader while waiting for the transaction.
-
-3. **Implement the Purchase Flow:**
- - When a "Purchase" button is clicked:
- - Open the purchase modal.
- - Make a `POST` request to your `/api/skills/purchase` endpoint, sending the user's connected wallet address, the agent ID, and the skill name.
- - The API will respond with a Solana Pay transaction request.
- - Use a Solana Pay QR code generation library to render the QR code in the modal.
- - **Listen for Transaction Confirmation:**
- - The frontend should poll for the transaction's signature on the Solana blockchain.
- - Once the transaction is confirmed, update the UI to show a success message and change the skill's button to "Owned".
-
-## Code Example (JavaScript in `src/marketplace.js`)
-
-```javascript
-// ... inside the skill rendering loop in renderDetail ...
-
-if (price) {
- const purchaseBtn = document.createElement('button');
- purchaseBtn.className = 'purchase-skill-btn';
- purchaseBtn.textContent = `Purchase for ${(price.amount / 1e6).toFixed(2)} USDC`;
- purchaseBtn.onclick = () => openPurchaseModal(a.id, name);
- skillEntry.appendChild(purchaseBtn);
-}
-
-// ... new function to handle the purchase flow ...
-
-async function openPurchaseModal(agentId, skillName) {
- const modal = document.getElementById('purchase-modal');
- const qrCodeContainer = document.getElementById('qr-code');
- modal.hidden = false;
-
- const userWallet = /* get connected wallet address */;
-
- try {
- const response = await fetch('/api/skills/purchase', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ user_account: userWallet, agent_id: agentId, skill_name: skillName }),
- });
- const { transaction, message } = await response.json();
-
- // Create a Solana Pay URL
- const solanaPayUrl = `solana:${encodeURIComponent(transaction)}`;
-
- // Generate and display the QR code
- const qr = QRCode.create(solanaPayUrl, { size: 256 });
- qrCodeContainer.innerHTML = '';
- qr.append(qrCodeContainer);
-
- // ... add logic to poll for the transaction signature ...
-
- } catch (error) {
- console.error('Purchase failed:', error);
- // show error in modal
- }
-}
-```
-
-## Definition of Done
-- A "Purchase" button appears next to paid skills in the marketplace.
-- Clicking the button opens a modal displaying a Solana Pay QR code.
-- After the transaction is confirmed, the UI updates to reflect skill ownership.
-- The entire flow is functional on Solana devnet.
diff --git a/tasks/monetization-feature/10-frontend-add-purchase-button.md b/tasks/monetization-feature/10-frontend-add-purchase-button.md
deleted file mode 100644
index 7775e457b..000000000
--- a/tasks/monetization-feature/10-frontend-add-purchase-button.md
+++ /dev/null
@@ -1,49 +0,0 @@
----
-status: not-started
----
-# Prompt 10: Add Purchase Button to Marketplace
-
-**Status:** Not Started
-
-## Objective
-In the marketplace agent detail page, add a "Purchase" button next to skills that are not free.
-
-## Explanation
-Now that skills can have prices, the marketplace UI must be updated to allow users to initiate a purchase. This task modifies the existing skill rendering logic to include a "Purchase" button, which will be wired up in subsequent tasks.
-
-## Instructions
-1. **Open `src/marketplace.js` and locate the `renderDetail` function.**
-2. **Modify the skill rendering loop.** The agent details from the API should already include pricing information from Prompt #1.
-3. **Update the logic that generates the skill badge:**
- - If a skill is free, continue showing the "Free" badge.
- - If a skill has a price and has **not** been purchased by the user, show the price and a "Purchase" button.
- - If a skill has a price and **has** been purchased, show the price and an "Owned" indicator.
-4. You will need a way to know which skills the user already owns for a given agent. This may require an API modification to include a list of purchased `skill_id`s in the agent detail payload.
-
-## Code Example (Frontend - `src/marketplace.js`, modified `renderDetail`)
-```javascript
-// Inside renderDetail function
-const skillPrices = a.skill_prices || {};
-const ownedSkills = a.owned_skills || []; // Assumes API now provides this array of skill names
-
-$('d-skills').innerHTML = skillsArr.length
- ? skillsArr.map((s) => {
- const name = typeof s === 'string' ? s : (s.name || '');
- const price = skillPrices[name];
-
- let badgeHtml = '';
- if (price) {
- const priceDisplay = `${(price.amount / 1e6).toFixed(2)} USDC`;
- if (ownedSkills.includes(name)) {
- badgeHtml = `<span class="price-badge price-owned">Owned</span> <span class="price-display">${priceDisplay}</span>`;
- } else {
- badgeHtml = `<span class="price-display">${priceDisplay}</span> <button class="purchase-btn" data-skill-name="${name}">Purchase</button>`;
- }
- } else {
- badgeHtml = `<span class="price-badge price-free">Free</span>`;
- }
-
- return `<span class="skill-entry">${escapeHtml(name)}${badgeHtml}</span>`;
- }).join(' ')
- : '<div>This Agent has no skills defined.</div>';
-```
diff --git a/tasks/monetization-feature/11-frontend-monetization-tab.md b/tasks/monetization-feature/11-frontend-monetization-tab.md
deleted file mode 100644
index 872024f70..000000000
--- a/tasks/monetization-feature/11-frontend-monetization-tab.md
+++ /dev/null
@@ -1,58 +0,0 @@
----
-status: not-started
----
-
-# Prompt 11: Frontend Monetization Tab
-
-**Status:** Not Started
-
-## Objective
-Add a new "Monetization" tab or section to the agent creation/editing page.
-
-## Explanation
-Agent creators need a dedicated area to manage the pricing of their skills. The first step is to create the UI container for these settings. This involves adding a new tab to the navigation on the agent editor page.
-
-## Instructions
-- [ ] **Identify the agent editor file:**
- - [ ] Locate the main HTML file for editing an agent (e.g., `agent-edit.html`).
-- [ ] **Add a new navigation tab:**
- - [ ] In the HTML, find the tab navigation structure.
- - [ ] Add a new tab link labeled "Monetization".
-- [ ] **Create the content pane:**
- - [ ] Add a corresponding content `div` for the monetization tab. This `div` will initially be hidden and shown only when the "Monetization" tab is active.
- - [ ] This pane will house the skill pricing UI, which will be built in the next prompt.
-- [ ] **Implement the tab switching logic:**
- - [ ] In the corresponding JavaScript file, add or update the event listeners to handle showing and hiding the new monetization pane when its tab is clicked.
-
-## Code Example (HTML in `agent-edit.html`)
-
-```html
-<!-- ... inside agent-edit.html ... -->
-
-<div class="tabs">
- <a href="#" class="tab-link active" data-tab="profile">Profile</a>
- <a href="#" class="tab-link" data-tab="avatar">Avatar</a>
- <a href="#" class="tab-link" data-tab="skills">Skills</a>
- <!-- New Tab -->
- <a href="#" class="tab-link" data-tab="monetization">Monetization</a>
-</div>
-
-<div class="tab-content">
- <div id="tab-profile" class="tab-pane active">
- <!-- ... profile content ... -->
- </div>
- <div id="tab-avatar" class="tab-pane">
- <!-- ... avatar content ... -->
- </div>
- <div id="tab-skills" class="tab-pane">
- <!-- ... skills content ... -->
- </div>
- <!-- New Pane -->
- <div id="tab-monetization" class="tab-pane">
- <h2>Skill Pricing</h2>
- <p>Set prices for your premium skills here.</p>
- <!-- UI for pricing will go here in the next step -->
- <div id="skill-pricing-list"></div>
- </div>
-</div>
-```
diff --git a/tasks/monetization-feature/12-frontend-price-management-ui.md b/tasks/monetization-feature/12-frontend-price-management-ui.md
deleted file mode 100644
index a4691e128..000000000
--- a/tasks/monetization-feature/12-frontend-price-management-ui.md
+++ /dev/null
@@ -1,59 +0,0 @@
----
-status: not-started
----
-
-# Prompt 12: Frontend Price Management UI
-
-**Status:** Not Started
-
-## Objective
-Build the user interface within the "Monetization" tab for agent creators to view their skills and set prices for them.
-
-## Explanation
-This task involves dynamically generating a list of the agent's skills in the monetization tab. Each skill will have input fields for a price and currency, allowing the creator to manage their premium offerings.
-
-## Instructions
-- [ ] **Locate the agent editor's JavaScript file.**
-- [ ] **Fetch and Display Skills:**
- - [ ] When the monetization tab is loaded, use the agent's data (which should already be loaded on the page) to get the list of skills.
- - [ ] Also, get the existing `skill_prices` for the agent.
- - [ ] Dynamically generate HTML to list each skill.
- - [ ] For each skill, create:
- - The skill name (as a label).
- - An `input` field for the `amount`.
- - A `select` dropdown for the `currency_mint` (e.g., with an option for USDC).
-- [ ] **Populate Existing Prices:**
- - [ ] If a skill already has a price set, populate the input fields with the existing data.
-- [ ] **Add a "Save" button** for each skill or a single "Save All Prices" button for the page.
-
-## Code Example (JavaScript)
-
-```javascript
-// In the agent editor's JS file, in a function that renders the monetization tab
-
-function renderMonetizationTab(agent) {
- const container = document.getElementById('skill-pricing-list');
- const skills = agent.skills || [];
- const prices = agent.skill_prices || {};
-
- if (skills.length === 0) {
- container.innerHTML = '<p>Add skills in the "Skills" tab first.</p>';
- return;
- }
-
- container.innerHTML = skills.map(skillName => {
- const price = prices[skillName] || { amount: 0, currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6T' };
- const priceInUsdc = price.amount / 1e6;
-
- return `
- <div class="skill-price-entry" data-skill-name="${skillName}">
- <label>${skillName}</label>
- <input type="number" class="price-input" value="${priceInUsdc}" min="0" step="0.01">
- <select class="currency-input">
- <option value="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6T">USDC</option>
- </select>
- </div>
- `;
- }).join('') + '<button id="save-prices-btn">Save Prices</button>';
-}
-```
diff --git a/tasks/monetization-feature/13-free-trials-for-skills.md b/tasks/monetization-feature/13-free-trials-for-skills.md
deleted file mode 100644
index f95a27945..000000000
--- a/tasks/monetization-feature/13-free-trials-for-skills.md
+++ /dev/null
@@ -1,25 +0,0 @@
----
-status: not-started
----
-
-# Prompt 13: Free Trials for Skills
-
-**Status:** Not Started
-
-## Objective
-Allow creators to offer a limited-time free trial for their paid skills.
-
-## Explanation
-Free trials are a great way for users to experience the value of a premium skill before committing to a purchase. We can implement this by granting temporary access.
-
-## Instructions
-- [ ] **Modify the `agent_skill_prices` table.**
- - Add a `trial_period_days` column.
-- [ ] **Update the creator dashboard UI.**
- - Add a checkbox and an input field for creators to enable a free trial and set its duration.
-- [ ] **On the agent detail page, show a "Start Free Trial" button** for skills that have one.
-- [ ] **When a user clicks "Start Free Trial":**
- - Make an API call to a new endpoint (e.g., `POST /api/skills/start-trial`).
- - This endpoint adds an entry to the `user_skill_access` table with an `expires_at` date set to `now() + trial_period_days`. It should also record that this is a trial.
- - Add a `is_trial` boolean column to `user_skill_access`. A user should only be ableto start a trial for a specific skill once.
-- [ ] **The access control logic will now automatically handle trial access** due to the `expires_at` check.
diff --git a/tasks/monetization-feature/13-frontend-js-sign-transaction.md b/tasks/monetization-feature/13-frontend-js-sign-transaction.md
deleted file mode 100644
index ad6e93fee..000000000
--- a/tasks/monetization-feature/13-frontend-js-sign-transaction.md
+++ /dev/null
@@ -1,59 +0,0 @@
----
-status: not-started
----
-# Prompt 13: Sign and Send Transaction from Frontend
-
-**Status:** Not Started
-
-## Objective
-Implement the logic to have the user's wallet sign the transaction received from the backend and broadcast it to the Solana network.
-
-## Explanation
-This is the core of the on-chain interaction. The frontend acts as a bridge between the backend (which creates the transaction) and the user's wallet (which holds the keys and signs). A successful broadcast returns a transaction signature.
-
-## Instructions
-- **This task builds on the previous one, using the `transaction` string.**
-- **Create a `signAndSendTransaction` function.**
-- **Inside this function:**
- 1. **Deserialize the Transaction:** The backend sent a base64-encoded string. You need to decode it and reconstruct the `Transaction` object.
- 2. **Sign the Transaction:** Use the `signTransaction` method from the wallet adapter. This will prompt the user in their wallet UI.
- 3. **Send the Transaction:** Use `connection.sendRawTransaction` to broadcast the signed transaction to the network.
- 4. **Confirm the Transaction:** Use `connection.confirmTransaction` to wait for the transaction to be finalized on the blockchain. This returns the signature.
- 5. **Fulfill the Purchase:** Call the backend fulfillment endpoint (`/api/skills/fulfill_purchase`) with the transaction signature.
-
-## Code Example (Frontend - using `@solana/wallet-adapter` hooks)
-```javascript
-import { Connection, Transaction } from '@solana/web3.js';
-// const { publicKey, signTransaction } = useWallet();
-// const connection = new Connection(...);
-
-async function signAndSendTransaction(base64Transaction) {
- if (!publicKey || !signTransaction) return;
-
- try {
- // 1. Deserialize
- const transactionBuffer = Buffer.from(base64Transaction, 'base64');
- const transaction = Transaction.from(transactionBuffer);
-
- // 2. Sign
- const signedTransaction = await signTransaction(transaction);
-
- // 3. Send
- const signature = await connection.sendRawTransaction(
- signedTransaction.serialize()
- );
-
- // 4. Confirm
- await connection.confirmTransaction(signature);
-
- console.log('Transaction successful with signature:', signature);
-
- // 5. Fulfill (call backend)
- await fulfillPurchaseOnBackend(signature);
-
- } catch (error) {
- console.error('Signing failed:', error);
- alert('Transaction was not approved or failed to send.');
- }
-}
-```
diff --git a/tasks/monetization-feature/13-unlock-skill-ui.md b/tasks/monetization-feature/13-unlock-skill-ui.md
deleted file mode 100644
index d2e71f113..000000000
--- a/tasks/monetization-feature/13-unlock-skill-ui.md
+++ /dev/null
@@ -1,99 +0,0 @@
-# Prompt 13: Update UI to Permanently Unlock Skill
-
-## Objective
-After a successful purchase, update the agent detail page UI to show the newly purchased skill as "Unlocked," and ensure this state persists on page reload.
-
-## Explanation
-Currently, after a successful payment, the modal closes, but the underlying page doesn't change. The "Purchase" button for the skill is still visible. We need to update the state of our application to reflect the new ownership and re-render the skill list to change the button to "Unlocked."
-
-This requires two parts:
-1. A way to keep track of unlocked skills in the frontend's state.
-2. A re-rendering mechanism to update the UI when that state changes.
-
-## Instructions
-1. **Introduce a Frontend State for Unlocked Skills:**
- * In `src/marketplace.js`, create a global set or array to store the names of skills the user has unlocked in the current session. For example: `let unlockedSkills = new Set();`
-
-2. **Update State After Purchase:**
- * In the `handlePurchase` function, after the backend confirmation is successful, add the newly purchased skill's name to your `unlockedSkills` set.
-
-3. **Create a Re-render Function:**
- * Refactor the skill-rendering logic from the `renderDetail` function into its own standalone function, e.g., `renderSkillList(agent)`.
- * This new function should take the agent object as an argument, access the global `unlockedSkills` set, and generate the HTML for the skills section, correctly showing "Unlocked" buttons for the skills in the set.
- * The original `renderDetail` function will now call `renderSkillList(agent)` to render the skills initially.
-
-4. **Trigger Re-render After Purchase:**
- * After adding the skill to the `unlockedSkills` set in `handlePurchase`, call your new `renderSkillList(detailState.agent)` function. This will immediately update the UI on the page behind the modal, before it closes.
-
-## Code Example (Frontend - `src/marketplace.js`)
-
-```javascript
-// --- At the top of the file ---
-let unlockedSkills = new Set(); // In a real app, this would be populated from an API call on load
-
-
-// --- New function, refactored from renderDetail ---
-function renderSkillList(agent) {
- const skillsContainer = $('d-skills');
- if (!skillsContainer) return;
-
- const skillsArr = Array.isArray(agent.capabilities.skills) ? agent.capabilities.skills : agent.skills || [];
- const skillPrices = agent.skill_prices || {};
-
- skillsContainer.innerHTML = skillsArr.length
- ? skillsArr.map((s) => {
- const name = typeof s === 'string' ? s : (s.name || '');
- const price = skillPrices[name];
-
- let actionButton;
- if (unlockedSkills.has(name)) {
- actionButton = `<button class="skill-btn" disabled>Unlocked</button>`;
- } else if (price) {
- actionButton = `<button class="skill-btn purchase" data-skill-name="${escapeHtml(name)}">Purchase</button>`;
- } else {
- actionButton = `<button class="skill-btn" disabled>Free</button>`;
- }
-
- const priceDisplay = price ? `<span class="price-paid">${(price.amount / 1e6).toFixed(2)} USDC</span>` : ``;
-
- return `<div class="skill-row">
- <span class="skill-name">${escapeHtml(name)} ${priceDisplay}</span>
- ${actionButton}
- </div>`;
- }).join('')
- : '<div>This Agent has no skills defined.</div>';
-}
-
-// --- Modify the original renderDetail function ---
-function renderDetail(a, bookmarked) {
- // ... all the existing code to render name, description, etc.
-
- // Replace the old innerHTML logic for skills with a call to the new function
- renderSkillList(a);
-
- // ... rest of the function
-}
-
-// --- Update the handlePurchase function ---
-async function handlePurchase() {
- // ... inside the successful payment logic, after backend confirmation
- try {
- // ...
- const verifyBody = await verifyRes.json();
- if (!verifyRes.ok) throw new Error(verifyBody.error_description);
-
- statusEl.textContent = 'Success! Skill unlocked.';
- statusEl.classList.add('ok');
-
- // *** NEW CODE HERE ***
- const skillName = intent.payload.skill; // Assuming intent has skill name
- unlockedSkills.add(skillName);
- renderSkillList(detailState.agent); // Re-render the skills on the page
-
- setTimeout(closePaymentModal, 2000);
- } catch (error) {
- // ...
- }
-}
-```
-**Note:** This only persists the "unlocked" state for the current session. The next set of prompts will address fetching this data from the server so it persists across reloads.
diff --git a/tasks/monetization-feature/14-frontend-ui-purchase-flow.md b/tasks/monetization-feature/14-frontend-ui-purchase-flow.md
deleted file mode 100644
index 012418f67..000000000
--- a/tasks/monetization-feature/14-frontend-ui-purchase-flow.md
+++ /dev/null
@@ -1,58 +0,0 @@
----
-status: not-started
----
-# Prompt 14: Frontend UI for Purchase Flow
-
-**Status:** Not Started
-
-## Objective
-Provide clear, real-time feedback to the user throughout the entire purchase process.
-
-## Explanation
-A user should never be left wondering what's happening, especially when money is involved. This task is about updating the UI to reflect the state of the purchase: preparing, waiting for signature, sending, confirming, and success or failure.
-
-## Instructions
-1. **Refactor the purchase logic from the previous tasks.**
-2. **When the "Purchase" button is clicked:**
- - Immediately disable the button and show a loading spinner or "Preparing..." text.
-3. **When waiting for the user to sign in their wallet:**
- - Update the status message to "Please approve the transaction in your wallet...".
-4. **After the transaction is signed and being sent:**
- - Change the message to "Sending transaction...".
-5. **While confirming the transaction on the blockchain:**
- - Update to "Confirming transaction on the blockchain...".
-6. **Upon success:**
- - Show a success message (e.g., "Purchase Complete!").
- - Replace the "Purchase" button with an "Owned" badge.
-7. **On any failure (user rejects, network error, etc.):**
- - Show a descriptive error message.
- - Re-enable the "Purchase" button so the user can try again.
-
-## Code Example (UI state management)
-```javascript
-// In the purchase button click handler
-const purchaseButton = event.target;
-
-function setButtonState(btn, text, disabled) {
- btn.textContent = text;
- btn.disabled = disabled;
-}
-
-try {
- setButtonState(purchaseButton, 'Preparing...', true);
- const { transaction } = await fetchFromApi(...);
-
- setButtonState(purchaseButton, 'Approve in wallet...', true);
- const signature = await signAndSend(transaction); // This function internally would update state too
-
- setButtonState(purchaseButton, 'Confirming...', true);
- await fulfillOnBackend(signature);
-
- // Replace button with "Owned" badge
- purchaseButton.outerHTML = `<span class="price-badge price-owned">Owned</span>`;
-
-} catch (error) {
- alert(`Failed: ${error.message}`);
- setButtonState(purchaseButton, 'Purchase', false); // Reset on failure
-}
-```
diff --git a/tasks/monetization-feature/15-frontend-add-buy-button.md b/tasks/monetization-feature/15-frontend-add-buy-button.md
deleted file mode 100644
index ace72a6ea..000000000
--- a/tasks/monetization-feature/15-frontend-add-buy-button.md
+++ /dev/null
@@ -1,53 +0,0 @@
----
-status: not-started
----
-
-# Prompt 15: Add "Buy" Button to Marketplace
-
-**Status:** Not Started
-
-## Objective
-Modify the agent detail page in the marketplace to show a "Buy" button next to paid skills that the user has not yet purchased.
-
-## Explanation
-This is the call-to-action for users. Instead of just showing a price, we need to provide an interactive button that initiates the purchase flow. The button's state should depend on whether the user is logged in and whether they already own the skill.
-
-## Instructions
-- [ ] **Update Frontend Data Fetching:**
- - [ ] When the marketplace page loads, in addition to fetching agent details, also make a call to the `/api/users/my-skills` endpoint (from Prompt 7) to get a list of the user's purchased skills. Store this in a local variable. This should only be done if the user is logged in.
-- [ ] **Modify the `renderDetail` function in `src/marketplace.js`:**
- - [ ] Inside the loop that renders skills, you now have access to both the `skillPrices` and the `userPurchases`.
- - [ ] Add a new function or logic to determine the button's state for each skill:
- - If the skill is free: show a "Free" badge.
- - If the skill is paid and the user owns it: show an "Owned" badge or a disabled button.
- - If the skill is paid and the user does *not* own it: show an active "Buy for X USDC" button.
- - If the user is not logged in: the "Buy" button should prompt them to sign in.
-- [ ] **Add `data-` attributes to the button** to store the `agentId` and `skillName`, which will be needed to start the purchase flow.
-
-## Code Example (JavaScript in `src/marketplace.js`)
-
-```javascript
-// Assumes `userPurchases` is a lookup map like { "agent_id:skill_name": true }
-const skillPrices = a.skill_prices || {};
-const userPurchases = state.mySkills || {}; // state.mySkills is fetched on load
-
-$('d-skills').innerHTML = skillsArr.map(s => {
- const name = s.name || s;
- const price = skillPrices[name];
- const purchaseKey = `${a.id}:${name}`;
- const isOwned = userPurchases[purchaseKey];
-
- let badgeOrButton;
- if (isOwned) {
- badgeOrButton = `<span class="price-badge price-owned">Owned</span>`;
- } else if (price) {
- badgeOrButton = `<button class="btn-buy" data-agent-id="${a.id}" data-skill-name="${name}">
- Buy for ${(price.amount / 1e6).toFixed(2)} USDC
- </button>`;
- } else {
- badgeOrButton = `<span class="price-badge price-free">Free</span>`;
- }
-
- return `<span class="skill-entry">${escapeHtml(name)}${badgeOrButton}</span>`;
-}).join(' ');
-```
diff --git a/tasks/monetization-feature/16-frontend-purchase-modal.md b/tasks/monetization-feature/16-frontend-purchase-modal.md
deleted file mode 100644
index 92f2be0de..000000000
--- a/tasks/monetization-feature/16-frontend-purchase-modal.md
+++ /dev/null
@@ -1,61 +0,0 @@
----
-status: not-started
----
-
-# Prompt 16: Frontend Purchase Modal
-
-**Status:** Not Started
-
-## Objective
-Create a modal dialog on the frontend that appears when a user clicks the "Buy" button, displaying a Solana Pay QR code for the transaction.
-
-## Explanation
-The purchase modal is the heart of the user-facing payment flow. It needs to be clean, clear, and easy to use. It will fetch the Solana Pay transaction request from our backend and display it as a QR code that mobile wallets can scan, or provide a link for desktop wallets.
-
-## Instructions
-- [ ] **Add a hidden modal to `marketplace.html`:**
- - [ ] Create the HTML structure for the modal, including a space for the QR code, a title, price details, and a close button. Initially, it should be hidden with CSS.
-- [ ] **Add a click listener for the `.btn-buy` buttons.**
-- [ ] **When a "Buy" button is clicked:**
- - [ ] Get the `agentId` and `skillName` from the button's `data-` attributes.
- - [ ] Show the modal and display a loading spinner.
- - [ ] Make a `POST` request to your `/api/payments/solana-pay` endpoint.
- - [ ] The backend will respond with a Solana Pay URL (the `transaction` field from Prompt 5).
-- [ ] **Generate and Display QR Code:**
- - [ ] Use a client-side QR code generation library (like `qr-code-styling`) to turn the Solana Pay URL into a QR code and display it in the modal.
- - [ ] Also provide a clickable link for desktop users.
-
-## Code Example (JavaScript using a QR library)
-
-```javascript
-import QRCodeStyling from 'qr-code-styling';
-
-// ... listener for .btn-buy clicks ...
-async function onBuyClick(agentId, skillName) {
- showModal(); // Show modal with a loading state
- const modalBody = document.getElementById('purchase-modal-body');
-
- try {
- const res = await fetch('/api/payments/solana-pay', {
- method: 'POST',
- body: JSON.stringify({ agentId, skillName }),
- });
- const solanaPayRequest = await res.json();
- const solanaPayUrl = solanaPayRequest.transaction; // This is the URL to encode
-
- const qrCode = new QRCodeStyling({
- width: 300,
- height: 300,
- data: solanaPayUrl,
- // ... styling options
- });
-
- modalBody.innerHTML = ''; // Clear loader
- qrCode.append(modalBody);
- modalBody.innerHTML += `<a href="${solanaPayUrl}">Open in Wallet</a>`;
-
- } catch (err) {
- modalBody.innerHTML = 'Error creating transaction. Please try again.';
- }
-}
-```
diff --git a/tasks/monetization-feature/16-reflect-unlocked-skills-ui.md b/tasks/monetization-feature/16-reflect-unlocked-skills-ui.md
deleted file mode 100644
index 3d95b6e04..000000000
--- a/tasks/monetization-feature/16-reflect-unlocked-skills-ui.md
+++ /dev/null
@@ -1,78 +0,0 @@
-# Prompt 16: Reflect Unlocked Skills on Page Load
-
-## Objective
-Update the frontend to call the new `/api/agents/:id/unlocked-skills` endpoint when the agent detail page loads, and use this data to correctly display the "Unlocked" state for skills.
-
-## Explanation
-The frontend now has an API to get the user's permanent skill entitlements. We need to call this API when the detail page loads and populate our `unlockedSkills` set from its response. This will ensure that the UI accurately reflects the user's purchase history from the moment the page becomes visible.
-
-## Instructions
-1. **Locate the Frontend Logic:**
- * Open `src/marketplace.js` and find the `loadDetail` function. This is the main function that orchestrates the loading of the agent detail page.
-
-2. **Fetch Unlocked Skills:**
- * Inside `loadDetail`, after fetching the main agent details, make another `fetch` call to your new endpoint: `/api/agents/${id}/unlocked-skills`.
- * Remember to include `credentials: 'include'` so the backend knows who the user is.
- * This call can be made in parallel with the other agent detail calls (like versions and similar agents) using `Promise.all` for better performance.
-
-3. **Populate the State:**
- * When the API call returns, it will have a JSON object like `{ skills: ["skill1", "skill2"] }`.
- * Take this array of skill names and use it to initialize your global `unlockedSkills` set.
-
-4. **Ensure Correct Render Order:**
- * Make sure that you populate the `unlockedSkills` set *before* you call the `renderSkillList` function. The `Promise.all` approach ensures this naturally. `loadDetail` should await all necessary data before it proceeds to render.
-
-## Code Example (Frontend - `src/marketplace.js`)
-
-```javascript
-// At the top of the file, initialize the set
-let unlockedSkills = new Set();
-
-
-// Modify the loadDetail function
-async function loadDetail(id) {
- els.discovery.hidden = true;
- els.detail.hidden = false;
- els.detail.scrollIntoView({ behavior: 'instant', block: 'start' });
-
- // Reset for the new page
- unlockedSkills = new Set();
-
- try {
- // Use Promise.all to fetch everything concurrently
- const [aR, vR, sR, unlockedR] = await Promise.all([
- fetch(`${API}/agents/${id}`),
- fetch(`${API}/agents/${id}/versions`),
- fetch(`${API}/agents/${id}/similar`),
- fetch(`${API}/agents/${id}/unlocked-skills`, { credentials: 'include' })
- ]);
-
- const aJ = await aR.json();
- if (!aR.ok) {
- renderDetailError(aJ?.error_description || 'Agent not found');
- return;
- }
-
- // Populate the unlocked skills set
- const unlockedData = await unlockedR.json();
- if (unlockedData.skills) {
- unlockedSkills = new Set(unlockedData.skills);
- }
-
- const a = aJ.data.agent;
- detailState = { agent: a, bookmarked: !!aJ.data.bookmarked };
-
- // Now render everything with the correct data
- renderDetail(a, aJ.data.bookmarked);
- renderVersions((await vR.json())?.data?.versions || []);
- renderSimilar((await sR.json())?.data?.items || []);
-
- // Fire-and-forget view counter.
- fetch(`${API}/agents/${id}/view`, { method: 'POST' }).catch(() => {});
- } catch (err) {
- console.error('[marketplace] detail', err);
- renderDetailError('Failed to load agent.');
- }
-}
-```
-With this change, `renderDetail` will call `renderSkillList`, which will now have access to the correctly populated `unlockedSkills` set, ensuring the UI is correct from the very first render.
diff --git a/tasks/monetization-feature/17-frontend-purchase-confirmation.md b/tasks/monetization-feature/17-frontend-purchase-confirmation.md
deleted file mode 100644
index 3e39696bc..000000000
--- a/tasks/monetization-feature/17-frontend-purchase-confirmation.md
+++ /dev/null
@@ -1,54 +0,0 @@
----
-status: not-started
----
-
-# Prompt 17: Frontend Purchase Confirmation
-
-**Status:** Not Started
-
-## Objective
-Implement client-side logic to detect when a purchase is complete and provide feedback to the user.
-
-## Explanation
-After the user approves the transaction in their wallet, the frontend needs to know when the transaction is confirmed on the blockchain so it can close the purchase modal and update the UI. This is typically done by polling the backend or using a WebSocket.
-
-## Instructions
-- [ ] **Start Polling after Displaying QR Code:**
- - [ ] Once the purchase modal is shown, start a polling mechanism (e.g., using `setInterval`).
- - [ ] The polling function will make a request to a new backend endpoint (e.g., `GET /api/payments/check-status?reference=...`), passing the unique `reference` public key that was part of the Solana Pay request.
-- [ ] **Backend Status Check Endpoint:**
- - [ ] Create the `/api/payments/check-status` endpoint.
- - [ ] It will take a `reference` public key as a query parameter.
- - [ ] It should use the Solana `getSignaturesForAddress` RPC method to see if that reference key has been used in a recent transaction.
- - [ ] If a signature is found, the purchase is likely complete. The endpoint can then do the full confirmation (like in Prompt 6) and record the purchase. It should return `{ status: 'confirmed' }`.
- - [ ] If no signature is found, it should return `{ status: 'pending' }`.
-- [ ] **Handle Confirmation on Frontend:**
- - [ ] When the polling function receives a `'confirmed'` status:
- - Stop the polling (`clearInterval`).
- - Show a success message in the modal.
- - Close the modal after a short delay.
- - Trigger a UI update to change the "Buy" button to "Owned".
-
-## Code Example (Frontend Polling)
-
-```javascript
-// After showing the QR code in the modal...
-
-const reference = new URL(solanaPayUrl).searchParams.get('reference');
-const pollInterval = setInterval(async () => {
- try {
- const res = await fetch(`/api/payments/check-status?reference=${reference}`);
- const { status } = await res.json();
-
- if (status === 'confirmed') {
- clearInterval(pollInterval);
- // Show success animation/message
- showSuccessAndCloseModal();
- // Refresh user's skills to update the UI
- fetchUserSkillsAndUpdateUI();
- }
- } catch (err) {
- // Handle errors, maybe stop polling after too many failures
- }
-}, 2000); // Poll every 2 seconds
-```
diff --git a/tasks/monetization-feature/17-frontend-ui-marketplace-purchased-indicator.md b/tasks/monetization-feature/17-frontend-ui-marketplace-purchased-indicator.md
deleted file mode 100644
index a64cfbfd3..000000000
--- a/tasks/monetization-feature/17-frontend-ui-marketplace-purchased-indicator.md
+++ /dev/null
@@ -1,39 +0,0 @@
----
-status: not-started
----
-# Prompt 17: "Owned" Indicator in Marketplace
-
-**Status:** Not Started
-
-## Objective
-Refine the marketplace UI to clearly show when a paid skill has already been purchased for the currently viewed agent.
-
-## Explanation
-This is a follow-up to Prompt #10. The goal is to prevent users from re-purchasing skills they already own. The "Purchase" button should be replaced with a non-interactive "Owned" badge or similar indicator.
-
-## Instructions
-1. **Ensure the agent detail API endpoint (`/api/marketplace/agents/:id`) includes information about which skills are owned.**
- - This endpoint should return an array of skill names or IDs that have been purchased for this specific agent, for example, `owned_skills: ["translator", "weather_forecast"]`.
-2. **In `src/marketplace.js`, within the `renderDetail` function, use this `owned_skills` array.**
-3. **When rendering the list of skills, check if the current skill's name exists in the `owned_skills` array.**
-4. **Use conditional logic:**
- - If `owned_skills.includes(skill.name)`, render the "Owned" badge.
- - Otherwise, render the "Purchase" button for the priced skill.
-
-## Code Example (Revisiting `src/marketplace.js`)
-```javascript
-// Inside renderDetail, assuming 'a' is the agent object from the API
-const ownedSkills = a.owned_skills || [];
-
-// ... inside the skill mapping logic ...
-const isOwned = ownedSkills.includes(name);
-
-if (price && isOwned) {
- badgeHtml = `<span class="price-badge price-owned">Owned</span>`;
-} else if (price && !isOwned) {
- badgeHtml = `<button class="purchase-btn" data-skill-name="${name}">Purchase</button>`;
-} else {
- badgeHtml = `<span class="price-badge price-free">Free</span>`;
-}
-```
-This provides an intuitive user experience and prevents accidental duplicate purchases.
diff --git a/tasks/monetization-feature/17-revenue-dashboard-page.md b/tasks/monetization-feature/17-revenue-dashboard-page.md
deleted file mode 100644
index f2afa7445..000000000
--- a/tasks/monetization-feature/17-revenue-dashboard-page.md
+++ /dev/null
@@ -1,76 +0,0 @@
-# Prompt 17: Creator Revenue Dashboard Page
-
-## Objective
-Create a new "Revenue" tab and page within the main user dashboard area (`/dashboard`) for agent creators to track their earnings.
-
-## Explanation
-Creators need a central place to see how much money their agents are making. We will add a new section to the existing dashboard for this purpose. This first step involves creating the basic page structure, adding the navigation tab, and ensuring it can be routed to. The content of the dashboard will be filled in by later prompts.
-
-## Instructions
-1. **Locate Dashboard Files:**
- * The main dashboard files are likely `public/dashboard/dashboard.js` and a corresponding HTML file (e.g., `pump-dashboard.html` or similar - check file list). You will need to modify both.
-
-2. **Add Navigation Tab:**
- * In the HTML file for the dashboard, find the navigation menu/sidebar.
- * Add a new link/tab for "Revenue." Give it a `data-tab="revenue"` attribute to work with the existing JavaScript-based routing. Choose a suitable icon.
-
-3. **Add a Page Container:**
- * In the same HTML file, in the main content area, add a new container `div` for the revenue page. It should have `id="page-revenue"` and be hidden by default (`style="display:none"`), consistent with the other dashboard pages.
-
-4. **Implement JavaScript Routing:**
- * In `public/dashboard/dashboard.js`, find the routing logic. There should be a map or switch statement that links `data-tab` values to rendering functions.
- * Add a new entry for `'revenue'` that maps to a new function, `renderRevenue`.
-
-5. **Create the `renderRevenue` Function:**
- * Create a new `async function renderRevenue(root)` in `dashboard.js`.
- * For now, this function should just render the basic structure of the revenue page inside the `root` element (which will be the main content area).
- * Include a title, a brief description, and placeholders for where the stats and transaction list will go.
-
-## Code Example (HTML - in dashboard file)
-
-```html
-<!-- In the sidebar/nav menu -->
-<a href="#" data-tab="revenue"><span class="icon">💰</span> Revenue</a>
-
-<!-- In the main content area, with the other pages -->
-<div class="content page" id="page-revenue" style="display:none">
- <!-- Content will be rendered here by dashboard.js -->
-</div>
-```
-
-## Code Example (JavaScript - `public/dashboard/dashboard.js`)
-
-```javascript
-// --- In the tabs mapping object ---
-const tabs = {
- avatars: renderAvatars,
- // ... other tabs
- revenue: renderRevenue, // Add this line
- account: renderAccount,
-};
-
-// --- Add the new rendering function ---
-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 id="revenue-content">
- <div class="panel">
- <div class="panel-body">
- <div class="empty">
- <div class="icon">📈</div>
- Loading revenue data...
- </div>
- </div>
- </div>
- </div>
- `;
-
- // In the next prompts, we will fetch data and fill this content.
- // e.g., loadRevenueStats();
- // e.g., loadRevenueEvents();
-}
-```
-With these changes, users will be able to click on the "Revenue" tab and see the basic placeholder page, setting the stage for the data-rich components to come.
diff --git a/tasks/monetization-feature/18-frontend-update-skill-state.md b/tasks/monetization-feature/18-frontend-update-skill-state.md
deleted file mode 100644
index fa015dc64..000000000
--- a/tasks/monetization-feature/18-frontend-update-skill-state.md
+++ /dev/null
@@ -1,60 +0,0 @@
----
-status: not-started
----
-
-# Prompt 18: Frontend UI State Update Post-Purchase
-
-**Status:** Not Started
-
-## Objective
-Ensure the UI on the agent detail page correctly updates to reflect a newly purchased skill without requiring a full page reload.
-
-## Explanation
-After a user successfully buys a skill, the "Buy" button for that skill should immediately change to an "Owned" badge. This provides instant feedback and prevents the user from accidentally trying to buy the same skill again.
-
-## Instructions
-- [ ] **Refactor UI Update Logic:**
- - [ ] Make sure your logic for rendering the skills list and their buttons is in a reusable function (e.g., `updateSkillDisplay(agent, purchases)`).
-- [ ] **Trigger UI Update:**
- - [ ] After the purchase is confirmed (in the logic from Prompt 17), you need to update the local state that holds the user's purchased skills.
- - [ ] You can do this in two ways:
- 1. **Optimistic Update:** Immediately add the new skill's key (`agent_id:skill_name`) to your local `userPurchases` object and re-render. This is fast but could be wrong if there's a server error.
- 2. **Refetch:** Call the `/api/users/my-skills` endpoint again to get the canonical list of purchases from the server, then re-render. This is more reliable.
-- [ ] **Call the Rendering Function:**
- - [ ] After updating the local `userPurchases` data, call your reusable rendering function to redraw the skills list. The logic you wrote in Prompt 15 should now automatically show the "Owned" badge for the new skill.
-
-## Code Example (JavaScript)
-
-```javascript
-// state.mySkills is the object holding user's purchases, e.g., { "agentId:skillName": true }
-// state.currentAgent is the agent being viewed
-
-async function handlePurchaseSuccess(agentId, skillName) {
- // Option 2: Refetch data for reliability
- try {
- const response = await fetch('/api/users/my-skills');
- const data = await response.json();
- state.mySkills = data.purchased; // Update global state
- } catch (err) {
- console.error("Failed to refresh user's skills:", err);
- // Fallback or show error
- }
-
- // Now re-render the skills section
- renderSkillsForAgent(state.currentAgent, state.mySkills);
-}
-
-function renderSkillsForAgent(agent, purchases) {
- // This is the rendering logic from Prompt 15, now in its own function
- const skillsContainer = document.getElementById('d-skills');
- // ... logic to build the innerHTML for skills based on purchases ...
- skillsContainer.innerHTML = '...';
-}
-
-// In the purchase confirmation logic (from Prompt 17)...
-if (status === 'confirmed') {
- clearInterval(pollInterval);
- showSuccessAndCloseModal();
- handlePurchaseSuccess(agentIdBeingPurchased, skillNameBeingPurchased);
-}
-```
diff --git a/tasks/monetization-feature/22-frontend-payment-error-handling.md b/tasks/monetization-feature/22-frontend-payment-error-handling.md
deleted file mode 100644
index 86902fdf6..000000000
--- a/tasks/monetization-feature/22-frontend-payment-error-handling.md
+++ /dev/null
@@ -1,58 +0,0 @@
----
-status: not-started
----
-
-# Prompt 22: Frontend Payment Error Handling
-
-**Status:** Not Started
-
-## Objective
-Improve the user experience by providing clear feedback in the purchase modal when a payment fails or times out.
-
-## Explanation
-Things can go wrong during the payment process. The user might close the modal, their transaction might fail on-chain, or our backend confirmation might time out. The UI needs to handle these cases gracefully instead of leaving the user in a loading state.
-
-## Instructions
-- [ ] **Implement a Timeout:**
- - [ ] In the polling logic from Prompt 17, add a timeout mechanism. For example, if the purchase is not confirmed after 2 minutes, stop polling.
-- [ ] **Handle API Errors:**
- - [ ] Wrap all `fetch` calls in the purchase flow in `try...catch` blocks.
- - [ ] If an API call fails (e.g., to create the transaction or check the status), display a clear error message in the modal.
-- [ ] **Display Specific Messages:**
- - [ ] Provide different messages for different states:
- - "Transaction timed out. Please check your wallet and try again."
- - "Could not create transaction. Please refresh the page."
- - "Payment failed. The transaction was not successful on the network."
-- [ ] **Add a "Try Again" Button:**
- - [ ] When an error occurs, it's helpful to show a "Try Again" button that restarts the purchase process for that skill.
-
-## Code Example (Frontend Polling with Timeout)
-
-```javascript
-const reference = new URL(solanaPayUrl).searchParams.get('reference');
-let pollCount = 0;
-const maxPolls = 60; // 2 minutes if polling every 2 seconds
-
-const pollInterval = setInterval(async () => {
- pollCount++;
- if (pollCount > maxPolls) {
- clearInterval(pollInterval);
- showErrorInModal("Transaction timed out. Please check your wallet.");
- return;
- }
-
- try {
- const res = await fetch(`/api/payments/check-status?reference=${reference}`);
- if (!res.ok) throw new Error('Status check failed');
- const { status } = await res.json();
-
- if (status === 'confirmed') {
- clearInterval(pollInterval);
- handlePurchaseSuccess(...);
- }
- } catch (err) {
- clearInterval(pollInterval);
- showErrorInModal("An error occurred. Please try again.");
- }
-}, 2000);
-```
diff --git a/tasks/monetization-feature/22-skill-gating-preview.md b/tasks/monetization-feature/22-skill-gating-preview.md
deleted file mode 100644
index 46d36611c..000000000
--- a/tasks/monetization-feature/22-skill-gating-preview.md
+++ /dev/null
@@ -1,26 +0,0 @@
----
-status: not-started
----
-# Prompt 22: Skill Gating and Previews
-
-**Status:** Not Started
-
-## Objective
-Allow creators to offer a limited "preview" or trial of a paid skill to encourage purchases.
-
-## Explanation
-Letting users try before they buy can significantly increase conversion rates. This feature involves defining what a "preview" means (e.g., 3 free uses) and implementing the logic to track and enforce this limit.
-
-## Instructions
-1. **Backend: Modify the `agent_skill_prices` table.**
- - Add new columns: `is_trial_allowed BOOLEAN DEFAULT FALSE` and `trial_uses INTEGER DEFAULT 3`.
-2. **Backend: Create a new table `skill_trial_usage`.**
- - Columns: `id`, `agent_id`, `skill_id`, `uses_left`.
-3. **Backend: Update the skill execution logic (from Prompt 15).**
- - If a skill is paid and not purchased, check if a trial is allowed and if the agent has remaining trial uses.
- - If so, allow execution and decrement the `uses_left` in `skill_trial_usage`.
- - If uses are 0, block execution and message "Your trial for this skill has ended. Please purchase to continue."
-4. **Frontend: Update the Creator Dashboard** to allow creators to enable/disable trials for their skills.
-5. **Frontend: Update the Marketplace UI.**
- - Display a "Trial available" badge on skills that offer a preview.
- - When a user tries a skill, show how many uses are left.
diff --git a/tasks/monetization-feature/22-withdrawal-api.md b/tasks/monetization-feature/22-withdrawal-api.md
deleted file mode 100644
index 774a35411..000000000
--- a/tasks/monetization-feature/22-withdrawal-api.md
+++ /dev/null
@@ -1,87 +0,0 @@
-# Prompt 22: Withdrawal API
-
-## Objective
-Create a backend API endpoint that allows a creator to request a withdrawal of their available balance to their configured payout wallet.
-
-## Explanation
-The final step in the money-out flow is the withdrawal. A creator with a positive balance and a configured payout wallet should be able to request a payout. This API will not perform the transfer instantly. Instead, it will log the request in a new `agent_withdrawals` table with a 'pending' status. A separate process (manual for now, but could be a cron job later) would then execute the on-chain transfers and update the status.
-
-## Instructions
-1. **Create a New API File:**
- * Create `/api/billing/withdraw.js`.
-
-2. **Define the Endpoint Logic:**
- * The `POST` endpoint must be authenticated.
- * It does not need a request body; it should attempt to withdraw the user's *entire* available balance.
-
-3. **Implement Core Logic:**
- * **Get Balance and Wallet:** In a single transaction for consistency (`BEGIN`/`COMMIT`):
- * Calculate the user's current balance by summing `net_amount` from `agent_revenue_events` and subtracting the sum of `amount` from `agent_withdrawals` (for 'pending' or 'completed' requests).
- * Fetch the user's configured payout wallet from `agent_payout_wallets`.
- * **Validate:**
- * If the balance is zero or less, return an error.
- * If the payout wallet is not configured, return an error.
- * **Create Withdrawal Record:**
- * If validation passes, `INSERT` a new row into the `agent_withdrawals` table.
- * The row should contain the `user_id`, the calculated `amount` (the entire balance), the `currency_mint` (USDC), the `chain` (Solana), the `to_address` from their payout wallet, and a `status` of 'pending'.
- * **Return Success:**
- * Return a 201 status with a success message indicating that the withdrawal request has been submitted.
-
-## Code Example (Backend - `/api/billing/withdraw.js`)
-
-```javascript
-import { sql } from '../_lib/db.js';
-import { getSessionUser } from '../_lib/auth.js';
-import { cors, json, method, wrap, error } from '../_lib/http.js';
-
-const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6a';
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized');
-
- try {
- const [result] = await sql.transaction(async (tx) => {
- // Get Payout Wallet
- const [wallet] = await tx`
- SELECT address FROM agent_payout_wallets WHERE user_id = ${user.id} AND chain = 'solana' LIMIT 1
- `;
- if (!wallet) throw new Error('Payout wallet not configured.');
-
- // Calculate available balance
- const [revenue] = await tx`
- SELECT SUM(rev.net_amount) as total_earned
- FROM agent_revenue_events rev JOIN agent_identities ai ON rev.agent_id = ai.id
- WHERE ai.user_id = ${user.id}
- `;
- const [withdrawn] = await tx`
- SELECT SUM(amount) as total_withdrawn
- FROM agent_withdrawals
- WHERE user_id = ${user.id} AND status IN ('pending', 'completed')
- `;
- const balance = BigInt(revenue.total_earned || 0) - BigInt(withdrawn.total_withdrawn || 0);
-
- if (balance <= 0) throw new Error('Insufficient balance to withdraw.');
-
- // Insert pending withdrawal record
- const [withdrawal] = await tx`
- INSERT INTO agent_withdrawals (user_id, amount, currency_mint, chain, to_address, status)
- VALUES (${user.id}, ${balance}, ${USDC_MINT}, 'solana', ${wallet.address}, 'pending')
- RETURNING id, amount, created_at
- `;
- return withdrawal;
- });
-
- return json(res, 201, {
- message: `Withdrawal request for ${Number(result.amount) / 1e6} USDC submitted successfully.`,
- withdrawal_id: result.id,
- });
-
- } catch (e) {
- return error(res, 400, 'withdrawal_error', e.message);
- }
-});
-```
diff --git a/tasks/monetization-feature/23-creator-analytics-dashboard.md b/tasks/monetization-feature/23-creator-analytics-dashboard.md
deleted file mode 100644
index b3d6e8fe2..000000000
--- a/tasks/monetization-feature/23-creator-analytics-dashboard.md
+++ /dev/null
@@ -1,59 +0,0 @@
----
-status: not-started
----
-
-# Prompt 23: Frontend - Creator Analytics Dashboard
-
-## Objective
-Provide creators with a dedicated analytics dashboard to help them understand their sales performance and identify trends.
-
-## Explanation
-Beyond a simple list of sales, a true analytics dashboard empowers creators with visual data. Charts and key metrics can help them understand which of their skills are most popular, what times they see the most sales, and their overall growth trajectory. This helps them make better decisions and ultimately leads to more high-quality content on your platform.
-
-## Instructions
-1. **Choose a Charting Library:**
- * Select a JavaScript charting library to easily create interactive charts. Good options include Chart.js, D3.js, or ECharts.
- * Install your chosen library: `npm install chart.js`.
-
-2. **Update the Backend Earnings Endpoint:**
- * Modify `/api/users/earnings`.
- * In addition to the transaction list, the API should return data pre-aggregated for charts. For example, a time-series of sales per day for the last 30 days.
- * `SELECT DATE_TRUNC('day', created_at) AS day, SUM(price_usd) AS daily_revenue FROM royalty_ledger WHERE ... GROUP BY day ORDER BY day;`
- * Also, add an aggregation for sales by skill:
- * `SELECT skill_name, COUNT(*) as sales_count, SUM(price_usd) as total_revenue FROM ... GROUP BY skill_name;`
-
-3. **Enhance the `earnings.html` UI:**
- * Add `<canvas>` elements to your earnings page where the charts will be rendered.
- * Create sections for "Sales Over Time" and "Top Performing Skills".
-
-4. **Implement Frontend Charting Logic:**
- * In `src/earnings.js`, after fetching the data from the API:
- * Initialize a new chart using the canvas element for "Sales Over Time". Use the time-series data from the API to populate the chart's labels (dates) and data (revenue).
- * Create a second chart (e.g., a bar or pie chart) for "Top Performing Skills". Use the skill aggregation data to show which skills are generating the most sales or revenue.
-
-## Chart.js Example (`src/earnings.js`)
-
-```javascript
-import Chart from 'chart.js/auto';
-
-// After fetching the API data which includes a 'sales_over_time' array
-const data = await response.json();
-
-const ctx = document.getElementById('sales-over-time-chart').getContext('2d');
-new Chart(ctx, {
- type: 'line',
- data: {
- labels: data.sales_over_time.map(d => new Date(d.day).toLocaleDateString()),
- datasets: [{
- label: 'Daily Revenue (USD)',
- data: data.sales_over_time.map(d => d.daily_revenue),
- borderColor: 'rgba(52, 211, 153, 1)',
- tension: 0.1,
- fill: true,
- }]
- },
- options: {
- // ... chart options
- }
-});
-```
diff --git a/tasks/monetization-feature/23-fullstack-notifications.md b/tasks/monetization-feature/23-fullstack-notifications.md
deleted file mode 100644
index 7f9051129..000000000
--- a/tasks/monetization-feature/23-fullstack-notifications.md
+++ /dev/null
@@ -1,41 +0,0 @@
----
-status: not-started
----
-
-# Prompt 23: User Notifications
-
-**Status:** Not Started
-
-## Objective
-Implement a notification system to inform users about successful purchases and to inform creators about sales.
-
-## Explanation
-Notifications are a key part of a good user experience. A user should get a clear confirmation that their purchase was successful, and a creator should be excited to learn they've made a sale.
-
-## Instructions
-- [ ] **Create a `notifications` Database Table:**
- - [ ] The table should store `user_id`, a `message`, a `read` status (boolean), a `link`, and a `created_at` timestamp.
-- [ ] **Backend - Generate Notifications:**
- - [ ] In the payment confirmation endpoint (from Prompt 6), after successfully recording a purchase in `skill_purchases`, insert two new rows into the `notifications` table:
- 1. One for the **buyer**, with a message like "You successfully purchased the skill 'X' for agent 'Y'." The link should go to the agent's page.
- 2. One for the **creator** (the agent's `user_id`), with a message like "You made a sale! User 'Z' bought your skill 'X'." The link could go to their earnings dashboard.
-- [ ] **Frontend - Display Notifications:**
- - [ ] Create a new API endpoint `GET /api/notifications` that fetches the user's unread notifications.
- - [ ] In the main application layout, add a notification bell icon.
- - [ ] When the page loads, call the new endpoint. If there are unread notifications, show a badge on the bell icon.
- - [ ] When the user clicks the icon, display the notifications in a dropdown menu.
-
-## Code Example (Backend Notification Insert)
-
-```sql
--- After inserting into skill_purchases...
--- The buyer is `user.id`, the creator is `agent.user_id`
-
--- Notification for the buyer
-INSERT INTO notifications (user_id, message, link)
-VALUES (${buyerId}, 'You successfully purchased skill ${skillName}.', '/marketplace/agent/${agentId}');
-
--- Notification for the creator
-INSERT INTO notifications (user_id, message, link)
-VALUES (${creatorId}, 'You sold your skill ${skillName}!', '/agent/edit/${agentId}/monetization');
-```
diff --git a/tasks/monetization-feature/23-withdrawal-ui.md b/tasks/monetization-feature/23-withdrawal-ui.md
deleted file mode 100644
index 95a2451dd..000000000
--- a/tasks/monetization-feature/23-withdrawal-ui.md
+++ /dev/null
@@ -1,135 +0,0 @@
-# Prompt 23: Withdrawal UI
-
-## Objective
-Create the user interface in the Revenue Dashboard for creators to see their current balance and request a withdrawal.
-
-## Explanation
-This UI component will tie together the balance calculation and the withdrawal API. It should clearly display the creator's withdrawable balance and provide a simple button to initiate the payout process. It should also include a section to display the history of their withdrawal requests.
-
-## Instructions
-1. **Locate Frontend Dashboard Code:**
- * Open `public/dashboard/dashboard.js`.
-
-2. **Add Withdrawal UI Section:**
- * In the `renderRevenue` function, add a new panel for "Withdrawals" below the Payout Settings.
- * This panel should contain:
- * A display for the "Available Balance" (this will use the same data from the stats API).
- * A "Request Withdrawal" button. This button should be disabled if the balance is zero.
- * A placeholder for a table to show withdrawal history.
-
-3. **Implement Withdrawal Request Logic:**
- * Add a `click` listener to the "Request Withdrawal" button.
- * When clicked, it should make a `POST` request to the `/api/billing/withdraw` endpoint.
- * While the request is pending, disable the button and show a "Processing..." message.
- * On success, display a success message (e.g., using a toast notification) and update the balance to show $0.00.
- * On error, display the error message from the API.
-
-4. **Implement Withdrawal History:**
- * Create a new API endpoint `/api/billing/withdrawals` that fetches a user's withdrawal history from the `agent_withdrawals` table (paginated).
- * Create a function `loadWithdrawalHistory()` in `dashboard.js`.
- * This function should fetch from the new endpoint and render the results in a table, showing the date, amount, status (`pending`, `completed`, `failed`), and destination address for each withdrawal.
-
-## Code Example (Frontend UI - in `renderRevenue` function of `dashboard.js`)
-
-```javascript
-// In renderRevenue function, after the payout settings panel
-root.innerHTML += `
- <div class="panel">
- <div class="panel-header"><h2>Withdrawals</h2></div>
- <div class="panel-body" id="withdrawal-container">
- <div class="withdrawal-balance-area">
- <span>Available Balance</span>
- <strong id="withdrawal-balance-display">Loading...</strong>
- </div>
- <button class="btn btn-primary" id="request-withdrawal-btn" disabled>Request Withdrawal</button>
- <span class="form-status" id="withdrawal-status"></span>
- </div>
- </div>
- <div class="panel">
- <div class="panel-header"><h3>Withdrawal History</h3></div>
- <div class="panel-body no-pad">
- <table id="withdrawal-history-table">
- <thead><tr><th>Date</th><th>Amount</th><th>Status</th><th>Address</th></tr></thead>
- <tbody><tr><td colspan="4">Loading history...</td></tr></tbody>
- </table>
- </div>
- </div>
-`;
-
-// In your main stats loading logic, also update the balance display here
-function renderRevenueStats(stats) {
- // ...
- const balanceEl = document.getElementById('withdrawal-balance-display');
- balanceEl.textContent = formatUSDC(stats.current_balance);
- const withdrawalBtn = document.getElementById('request-withdrawal-btn');
- if (Number(stats.current_balance) > 0) {
- withdrawalBtn.disabled = false;
- }
-}
-
-// Then, add the event listener
-document.getElementById('request-withdrawal-btn').addEventListener('click', handleWithdrawalRequest);
-
-loadWithdrawalHistory(); // Also call this
-```
-
-## Code Example (Frontend JS - new functions in `dashboard.js`)
-
-```javascript
-async function handleWithdrawalRequest() {
- if (!confirm('Are you sure you want to withdraw your entire available balance?')) return;
-
- const btn = document.getElementById('request-withdrawal-btn');
- const status = document.getElementById('withdrawal-status');
-
- btn.disabled = true;
- status.textContent = 'Submitting request...';
-
- try {
- const res = await fetch('/api/billing/withdraw', {
- method: 'POST',
- credentials: 'include',
- });
- const body = await res.json();
- if (!res.ok) throw new Error(body.error_description || 'Request failed.');
-
- status.textContent = body.message; // Success message from API
- // Refresh all revenue data
- const stats = await api.getRevenueStats();
- renderRevenueStats(stats);
- loadWithdrawalHistory();
-
- } catch (e) {
- status.textContent = `Error: ${e.message}`;
- btn.disabled = false; // Re-enable on failure
- }
-}
-
-async function loadWithdrawalHistory() {
- const tbody = document.querySelector('#withdrawal-history-table tbody');
- try {
- // Assume you create this API endpoint
- const res = await fetch('/api/billing/withdrawals', { credentials: 'include' });
- const { withdrawals } = await res.json();
-
- if (!withdrawals.length) {
- tbody.innerHTML = '<tr><td colspan="4" style="text-align:center;">No withdrawal history.</td></tr>';
- return;
- }
-
- const formatUSDC = (amount) => `${(Number(amount) / 1e6).toFixed(2)} USDC`;
- tbody.innerHTML = withdrawals.map(w => `
- <tr>
- <td>${new Date(w.created_at).toLocaleString()}</td>
- <td>${formatUSDC(w.amount)}</td>
- <td><span class="status-badge ${w.status}">${w.status}</span></td>
- <td>${esc(w.to_address.slice(0, 4))}...${esc(w.to_address.slice(-4))}</td>
- </tr>
- `).join('');
-
- } catch (e) {
- tbody.innerHTML = `<tr><td colspan="4" class="err">Failed to load history.</td></tr>`;
- }
-}
-```
-You will also need to add some basic CSS for `.status-badge`.
diff --git a/tasks/monetization-feature/24-notifications-on-purchase.md b/tasks/monetization-feature/24-notifications-on-purchase.md
deleted file mode 100644
index 8d9fb4d1c..000000000
--- a/tasks/monetization-feature/24-notifications-on-purchase.md
+++ /dev/null
@@ -1,44 +0,0 @@
----
-status: not-started
----
-# Prompt 24: Purchase Notifications for Creators
-
-**Status:** Not Started
-
-## Objective
-Implement a system to notify creators in real-time or via email when one of their skills is sold.
-
-## Explanation
-Instant feedback is highly motivating for creators. A notification system can encourage them to engage more with the platform and build more skills.
-
-## Instructions
-1. **Choose a notification delivery method.** Options include:
- - WebSockets for real-time in-app notifications.
- - An email service (e.g., SendGrid, Mailgun) for email notifications.
-2. **Integrate the chosen service into your backend.**
-3. **Modify the purchase fulfillment endpoint (`/api/skills/fulfill_purchase` from Prompt 6).**
-4. **After successfully recording a purchase in the database, trigger the notification.**
- - Get the creator's user details (e.g., email address, or user ID for WebSocket targeting).
- - Send a notification with details like "Your skill '[Skill Name]' was just purchased!"
-
-## Code Example (Backend - Conceptual Email Notification)
-```javascript
-// In fulfillPurchase, after the purchase is saved to DB
-import { sendEmail } from './email-service';
-
-// ...
-await db.none('INSERT INTO skill_purchases ...');
-
-// Get creator info
-const skill = await db.one('SELECT name, creator_id FROM skills WHERE id = $1', skill_id);
-const creator = await db.one('SELECT email FROM users WHERE id = $1', skill.creator_id);
-
-// Send notification
-await sendEmail({
- to: creator.email,
- subject: 'You made a sale!',
- body: `Congratulations! Your skill "${skill.name}" was just purchased on three.ws.`
-});
-// ...
-```
-This creates a positive feedback loop for creators.
diff --git a/tasks/pump-dashboard-real-apis/01-featured-agent-real-data.md b/tasks/pump-dashboard-real-apis/01-featured-agent-real-data.md
deleted file mode 100644
index 19a9bae2d..000000000
--- a/tasks/pump-dashboard-real-apis/01-featured-agent-real-data.md
+++ /dev/null
@@ -1,34 +0,0 @@
-# 01 — Featured Agent panel: replace hardcoded "Agent CZ" with real data
-
-## Problem
-[pump-dashboard.html](../../pump-dashboard.html) lines ~485–497 hard‑code the Featured Agent panel:
-- `id="featured-agent-name"` defaults to "Agent CZ"
-- `id="featured-agent-desc"` is a hardcoded sentence
-- `id="featured-agent-link"` points at `/agent-detail.html?id=cz`
-- `id="featured-agent-avatar"` is empty
-
-This is fake data shipped to production and violates [CLAUDE.md](../../CLAUDE.md) rule #1 (no placeholders).
-
-## Outcome
-On first paint of the Dashboard page, the Featured Agent card shows a **real** agent selected from the platform, with avatar image, real display name, real one‑line bio, and a link to that agent's real detail page.
-
-## Selection rule (no fakery)
-Pick "featured" deterministically from real data:
-1. Prefer the agent with the highest aggregate `agent_revenue_events.net_total` over the last 30 days (join `agent_identities` to filter `deleted_at IS NULL` and visibility = public).
-2. If revenue data is empty for the window, fall back to the most-recently-created public agent (`ORDER BY created_at DESC LIMIT 1`).
-
-Do NOT hardcode agent ids, names, or fallback sample agents.
-
-## Implementation
-1. Add a real endpoint `GET /api/agents/featured` in `api/agents/featured.js` using the `sql` helper from [api/_lib/db.js](../../api/_lib/db.js). Return `{ data: { id, slug, display_name, bio, avatar_url, detail_url } }` or 404 when there are zero agents in the DB.
-2. In [pump-dashboard.html](../../pump-dashboard.html), remove the hardcoded `Agent CZ` text and "/agent-detail.html?id=cz" href. On `DOMContentLoaded` and on every nav into the Dashboard page, call `apiFetch('/api/agents/featured')` and render:
- - avatar via `<img>` into `#featured-agent-avatar` (use the real `avatar_url`; if the agent has no avatar persisted, render the initials in a styled div — never a stock placeholder image)
- - `display_name`, `bio`, and the real `detail_url`
-3. Real loading state (CSS skeleton or "Loading…" text) and real error state ("No agents available yet" only when 404). Do not fake a delay.
-
-## Definition of done
-- `curl http://localhost:3000/api/agents/featured` returns a real row from the database.
-- Browser network tab shows that request succeeding on dashboard load.
-- Removing all rows from `agent_identities` shows the real empty state, not a stub agent.
-- No string "Agent CZ" or `id=cz` anywhere in the changed HTML.
-- `npm test` green; run **completionist** subagent on changed files.
diff --git a/tasks/pump-dashboard-real-apis/02-wallet-snapshot-real.md b/tasks/pump-dashboard-real-apis/02-wallet-snapshot-real.md
deleted file mode 100644
index 15dec8992..000000000
--- a/tasks/pump-dashboard-real-apis/02-wallet-snapshot-real.md
+++ /dev/null
@@ -1,32 +0,0 @@
-# 02 — Wallet Snapshot panel: real wallet connect + real balances
-
-## Problem
-[pump-dashboard.html](../../pump-dashboard.html) lines ~499–511 render only a "Connect wallet to see your holdings" empty state with a button that does nothing. This is a non‑functional placeholder.
-
-## Outcome
-Clicking **Connect Wallet** opens the user's real Solana wallet (Phantom is already installed in the rest of this codebase — see [src/wallet.js](../../src/wallet.js)). On approval, the panel renders the connected address, native SOL balance, USD value, and the top SPL token holdings with logos and USD values. Disconnect button restores the empty state.
-
-## Use what already exists — don't reinvent
-- Wallet connect: reuse [src/wallet.js](../../src/wallet.js) (`connectPhantom`, listeners) — `import` it as an ES module from the dashboard. Do **not** call `window.solana` directly here.
-- Balances: call `POST /api/wallet/balances` with `{ chain: 'solana', address }` — implementation already exists at [api/wallet/balances.js](../../api/wallet/balances.js) and uses Helius RPC + Jupiter price API server‑side. **Do not re‑hit Helius from the browser**; that endpoint owns the API key.
-
-## Implementation
-1. Convert the inline `<script>` block in pump-dashboard.html to also import [src/wallet.js](../../src/wallet.js) (or move dashboard JS into a module under [src/pump/dashboard-wallet.js](../../src/pump/dashboard-wallet.js) and load via `<script type="module">`). Vite already handles modules.
-2. Wire the Connect Wallet button:
- - On click → `connectPhantom()` from [src/wallet.js](../../src/wallet.js).
- - On connected event → fetch `/api/wallet/balances` with the connected address.
- - Render: short address (linked to `solscan.io/account/<addr>`), SOL native balance + USD, then a list of up to the top 10 token holdings sorted by USD value (symbol, amount formatted with token decimals, USD value, logo `<img>` from the API response).
- - Show a real "Disconnect" button that calls `provider.disconnect()` and restores the connect state.
-3. Real states only:
- - Connecting → spinner / "Connecting…" while the wallet popup is open.
- - 503 `not_configured` from `/api/wallet/balances` → render the upstream error string returned by the endpoint (do not fabricate a fallback list).
- - Empty token list → "No SPL tokens" line; do not invent rows.
-4. If the user has previously connected (Phantom auto‑connect), pre‑populate the panel on page load — the listener in [src/wallet.js](../../src/wallet.js) already exposes the connected address.
-
-## Definition of done
-- Real Phantom popup appears on click and approval is required.
-- Network tab shows `POST /api/wallet/balances` succeeding with the real address.
-- SOL value matches `solscan.io/account/<addr>` to within rounding.
-- Disconnect actually disconnects the wallet (verify by clicking Connect again — popup re‑appears).
-- No string `"Connect wallet to see your holdings"` left in the rendered DOM after a successful connect.
-- `npm test` green; **completionist** subagent run on changed files.
diff --git a/tasks/pump-dashboard-real-apis/03-market-chart-real.md b/tasks/pump-dashboard-real-apis/03-market-chart-real.md
deleted file mode 100644
index 7fadd2788..000000000
--- a/tasks/pump-dashboard-real-apis/03-market-chart-real.md
+++ /dev/null
@@ -1,32 +0,0 @@
-# 03 — Market Chart panel: render a real price chart
-
-## Problem
-[pump-dashboard.html](../../pump-dashboard.html) lines ~513–526 render only an empty state with the literal text "Chart data loading..." — there is no chart, no fetch, and no library wired up. This is a placeholder shipped to production.
-
-## Outcome
-The Market Chart panel renders a real price line/candle chart for the currently selected token (the `<select>` in the panel — task 04 owns populating that selector, but this task must work against any valid token mint passed to it). The chart updates when the selector changes.
-
-## Data source (real, no mocks)
-Use [api/pump/curve.js](../../api/pump/curve.js) for live PumpFun bonding-curve tokens (price + market cap). For graduated / non-PumpFun tokens use Birdeye OHLC via a new server-side proxy `GET /api/pump/price-history?mint=<mint>&interval=15m&from=<unix>&to=<unix>` that wraps `https://public-api.birdeye.so/defi/ohlcv?address=<mint>&type=15m&time_from=…&time_to=…` using `BIRDEYE_API_KEY` (already referenced in [api/pump/dashboard.js](../../api/pump/dashboard.js)). Never hit Birdeye from the browser — the key stays server-side.
-
-Return shape from the new endpoint:
-```json
-{ "data": [ { "t": 1714867200, "o": 0.0, "h": 0.0, "l": 0.0, "c": 0.0, "v": 0.0 }, ... ] }
-```
-
-## Implementation
-1. Add `api/pump/price-history.js` — Vercel function that proxies Birdeye OHLCV. Validate `mint` is base58 and in `[32,44]` chars before calling upstream; rate-limit per IP using the existing `limits` helper in [api/_lib/rate-limit.js](../../api/_lib/rate-limit.js).
-2. In [pump-dashboard.html](../../pump-dashboard.html), replace the empty state block with a `<canvas id="market-chart">` sized to fill the panel body.
-3. Render the chart with a tiny vanilla canvas line plot (no new dependency required). No fake animations, no `setTimeout` frame stalls — draw once per data load and on resize via `ResizeObserver`. Required visual: x-axis time ticks (every ~6 segments, formatted as `HH:mm` for ≤24h windows, `MMM d` otherwise), y-axis price ticks (5 evenly spaced, formatted with adaptive decimals), a hairline crosshair on hover that displays time + close at the cursor.
-4. Wire the panel `<select>` change event (and an initial load) to call `/api/pump/price-history` for the selected mint with the last 24 hours, plus `/api/pump/curve?mint=…` for a live "spot" overlay when the token is a PumpFun token.
-5. Real states only:
- - Loading: render a skeleton grid in the canvas — do **not** display "Chart data loading…" forever.
- - Empty (`data: []`): write "No trades in the selected window" centered in the canvas.
- - Upstream 4xx/5xx: render the upstream error message returned by `/api/pump/price-history`. Never silently fall back to fake data.
-
-## Definition of done
-- Selecting a real graduated token (e.g. paste a known mainnet mint into the selector via task 04 or via DOM) renders a real line chart with real OHLC values; numbers match Birdeye's UI for the same window.
-- Selecting a live PumpFun token renders the price-history series and an overlaid live spot price from `/api/pump/curve`.
-- Network tab shows `/api/pump/price-history` succeeding; no calls to `public-api.birdeye.so` originate from the browser.
-- `BIRDEYE_API_KEY` missing → endpoint returns 503 `not_configured` and the panel surfaces it; no silent fallback.
-- `npm test` green; **completionist** subagent run on changed files.
diff --git a/tasks/pump-dashboard-real-apis/04-market-chart-token-selector.md b/tasks/pump-dashboard-real-apis/04-market-chart-token-selector.md
deleted file mode 100644
index fc75fbb18..000000000
--- a/tasks/pump-dashboard-real-apis/04-market-chart-token-selector.md
+++ /dev/null
@@ -1,33 +0,0 @@
-# 04 — Market Chart token selector: real trending-token list
-
-## Problem
-[pump-dashboard.html](../../pump-dashboard.html) line ~519 contains a `<select>` whose only option is the literal placeholder `<option>Top Token</option>`. There is no fetch, no token mint, and the chart cannot be driven. Placeholder data shipped to production.
-
-## Outcome
-On Dashboard load, the selector is populated with **real** trending Solana tokens (symbol + short mint), and changing it dispatches a `chart:tokenChange` CustomEvent on the document carrying `{ mint, symbol }` so the chart panel (task 03) consumes it. The default selected option must be the top trending token returned by the API — **never** a hardcoded fallback like SOL or USDC.
-
-## Data source (real, no mocks)
-Add a server-side proxy `GET /api/pump/trending?limit=25` that calls Birdeye `https://public-api.birdeye.so/defi/token_trending?sort_by=rank&sort_type=asc&offset=0&limit=25&chain=solana` using `BIRDEYE_API_KEY` (the same key wired in [api/pump/dashboard.js](../../api/pump/dashboard.js)). Never expose the key to the browser.
-
-Returned shape:
-```json
-{ "data": [ { "mint": "...", "symbol": "...", "name": "...", "logo": "https://…", "price_usd": 0.0, "rank": 1 }, ... ] }
-```
-
-## Implementation
-1. Add `api/pump/trending.js` (Vercel function). Validate query params, rate-limit with `limits.publicIp` from [api/_lib/rate-limit.js](../../api/_lib/rate-limit.js), and return upstream errors verbatim (no fallback list).
-2. In [pump-dashboard.html](../../pump-dashboard.html):
- - On `DOMContentLoaded` and on every nav into the Dashboard page, call `/api/pump/trending?limit=25` and replace the `<select>` options with the real list. Each `<option value="<mint>">` shows `#<rank> <SYMBOL> (<short mint>)`.
- - On `change`, dispatch `document.dispatchEvent(new CustomEvent('chart:tokenChange', { detail: { mint, symbol } }))`.
- - Auto-select the first item and dispatch the event so the chart paints immediately on load.
-3. Real states:
- - Loading: a single disabled `<option>Loading trending tokens…</option>` while the request is in flight (replaced when it resolves — no `setTimeout` smoothing).
- - Error / 503: a single disabled `<option>` displaying the upstream error string, plus an inline retry button next to the select. Do not silently render a hardcoded list.
- - Empty (`data: []`): single disabled `<option>No trending tokens right now</option>`.
-
-## Definition of done
-- Network tab shows `/api/pump/trending` succeeding; no Birdeye calls from the browser.
-- The selector contains 25 real trending tokens with valid mainnet mints; clicking one dispatches the event.
-- `BIRDEYE_API_KEY` missing → endpoint returns 503 `not_configured`; the selector surfaces the error and never renders a fake list.
-- No string `"Top Token"` remains in the HTML.
-- `npm test` green; **completionist** subagent run on changed files.
diff --git a/tasks/pump-dashboard-real-apis/05-vanity-generator-real-keypair.md b/tasks/pump-dashboard-real-apis/05-vanity-generator-real-keypair.md
deleted file mode 100644
index 59f099afa..000000000
--- a/tasks/pump-dashboard-real-apis/05-vanity-generator-real-keypair.md
+++ /dev/null
@@ -1,33 +0,0 @@
-# 05 — Vanity Address Generator: replace `Math.random()` simulation with real ed25519 keypairs
-
-## Problem
-[pump-dashboard.html](../../pump-dashboard.html) lines ~1849–1906 implement the Vanity Generator using `Math.random()` to pick base58 characters and produce an "address" string that is **not** a real keypair — it has no corresponding private key. The code itself even labels it a demo and tells the user to "use the Rust vanity generator for production keypairs". This is shipped to a production page and violates [CLAUDE.md](../../CLAUDE.md) rule #1 (no mocks/placeholders).
-
-## Outcome
-The Vanity Generator produces **real** Solana keypairs in a Web Worker until prefix/suffix match. On match, the panel renders the public address and offers a "Reveal Secret Key" toggle plus a "Download keypair JSON" button (Solana CLI `id.json` array format). The attempts/sec readout reflects real throughput from the worker, not a `requestAnimationFrame` smear.
-
-## Use what already exists
-- `@noble/curves` is already a project dependency (see [package.json](../../package.json)) — use `import { ed25519 } from '@noble/curves/ed25519'` for fast keypair generation in a worker.
-- `bs58` is already a dependency — use it to base58-encode the 32-byte public key.
-- `crypto.getRandomValues` for the 32-byte seed.
-
-Do NOT introduce a server-side keygen endpoint — keys must never leave the user's browser.
-
-## Implementation
-1. Create `src/pump/vanity-worker.js` as an ES module Web Worker:
- - On `start` message → loop: generate a 32-byte seed via `crypto.getRandomValues`, derive `ed25519.getPublicKey(seed)`, base58-encode it, test prefix/suffix (case-sensitive — base58 is case-significant). Post `progress` messages with `{ attempts }` every ~250ms. On match, post `match` with `{ publicKey, secretKeyBytes: Array.from(64ByteSecretKey) }` where the 64-byte form is `[seed(32) || publicKey(32)]` (Solana CLI format). On `stop` message → break the loop.
-2. In [pump-dashboard.html](../../pump-dashboard.html):
- - Replace the `generateBatch`/`startVanity`/`stopVanity` block with a real worker driver. Spawn the worker on Start, terminate on Stop or on match.
- - Show real attempts/sec computed from worker `progress` deltas.
- - On match, show the real public address and two real buttons:
- - **Reveal secret key** toggles a base58-encoded secret display with a copy-to-clipboard button.
- - **Download keypair JSON** triggers a download of the 64-byte secret as a JSON array (Solana `solana-keygen` import format).
- - Validate prefix/suffix inputs against the base58 alphabet (`123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz`); reject invalid characters with a real toast — do not silently strip.
-3. Remove the line that says "This is a demo. Use the Rust vanity generator for production keypairs." and remove the `base58chars` lookup that sat alongside the simulation.
-
-## Definition of done
-- Open the panel, set prefix `pump` (4 chars), click Generate. After it matches, copy the address into `solana-keygen pubkey -` after pasting the downloaded JSON, and confirm the printed pubkey equals what the UI showed.
-- Worker terminates on Stop and on match — no zombie workers (verify in DevTools → Application → Workers).
-- The string `Math.random` no longer appears in the vanity code path.
-- The string `"this is a demo"` no longer appears anywhere in the file.
-- `npm test` green; **completionist** subagent run on changed files.
diff --git a/tasks/pump-dashboard-real-apis/06-custom-agents-table-real.md b/tasks/pump-dashboard-real-apis/06-custom-agents-table-real.md
deleted file mode 100644
index cdd076ee4..000000000
--- a/tasks/pump-dashboard-real-apis/06-custom-agents-table-real.md
+++ /dev/null
@@ -1,45 +0,0 @@
-# 06 — Custom Agents table: replace hardcoded "My Cool Agent" with real list
-
-## Problem
-[pump-dashboard.html](../../pump-dashboard.html) lines ~926–934 ship a hardcoded sample row into production:
-
-```html
-<tr>
- <td>My Cool Agent</td>
- <td>agent-xyz.vrm</td>
- <td>2024-07-29</td>
- <td><button class="btn btn-sm">Edit</button> <button class="btn btn-danger btn-sm">Delete</button></td>
-</tr>
-```
-
-Plus a stub second row "No custom agents yet." that's always visible regardless of state. Buttons do nothing. This violates [CLAUDE.md](../../CLAUDE.md) rule #6 (no fallback sample arrays) and rule #4 (no stubs).
-
-## Outcome
-Navigating to **Animations** loads the real list of the signed-in user's agents from `GET /api/agents` and renders one row per agent: display name, model file basename, creation date, and working **Edit** + **Delete** buttons. Empty list = a single empty-state row with the real "No custom agents yet." message.
-
-## Endpoints to use (already exist)
-- List: `GET /api/agents` — see [api/agents.js](../../api/agents.js) (returns the user's agents).
-- Delete: `DELETE /api/agents/:id` — see [api/agents/[id].js](../../api/agents/[id].js).
-- Edit page: `/agent-edit.html?id=<id>` — already exists.
-
-If `/api/agents` does not currently return a `model_url`/`model_filename` field, extend [api/agents.js](../../api/agents.js) to include it from `agent_identities.meta` — do not invent a synthetic filename in the frontend.
-
-## Implementation
-1. Delete the hardcoded `<tr>` and the duplicate empty row.
-2. On nav into the Animations page (and once on initial DOMContentLoaded if Animations is the active page), call `apiFetch('/api/agents')`. Populate `#custom-agents-table` with one row per agent:
- - Name → `display_name`
- - Model → basename of `meta.model_url` or the stored filename; if none, render `—`.
- - Created → `new Date(created_at).toLocaleDateString()` — real date only.
- - Edit → anchor to `/agent-edit.html?id=<id>`.
- - Delete → calls `DELETE /api/agents/<id>`, on 200 re-runs the list fetch; on 4xx/5xx surfaces the upstream error string via `toast`.
-3. Real states:
- - Loading: single row "Loading agents…" while the fetch is in flight.
- - Empty: single row "No custom agents yet." (only when the API returns `data: []`).
- - 401: single row with a real "Sign in to manage your agents" link to `/login.html`.
-4. The "+ Add Agent" button (`onclick="addCustomAgent()"`) currently calls a non-existent function — wire it to `window.location.href = '/agent-edit.html?new=1'` (or the real create path used elsewhere in this codebase — verify by reading [agent-edit.html](../../agent-edit.html)).
-
-## Definition of done
-- Real network call to `/api/agents` populates the table; the row count matches what `GET /api/agents` returned.
-- Deleting an agent removes its row and the next page reload still shows it gone (DB persistence verified).
-- No string "My Cool Agent" or "agent-xyz.vrm" anywhere in the HTML.
-- `npm test` green; **completionist** subagent run on changed files.
diff --git a/tasks/pump-dashboard-real-apis/07-dashboard-stat-cards-real.md b/tasks/pump-dashboard-real-apis/07-dashboard-stat-cards-real.md
deleted file mode 100644
index 9234ef4eb..000000000
--- a/tasks/pump-dashboard-real-apis/07-dashboard-stat-cards-real.md
+++ /dev/null
@@ -1,40 +0,0 @@
-# 07 — Dashboard stat cards: add the cards that `updateDashboard()` already targets, and wire them to real data
-
-## Problem
-[pump-dashboard.html](../../pump-dashboard.html) `updateDashboard()` (lines ~1188–1200) writes to DOM IDs that **do not exist on the page**:
-- `stat-bot-status`
-- `stat-bot-mode`
-- `stat-claims`
-- `stat-watches`
-- `stat-uptime`
-
-`updateUptime()` (lines ~1202–1211) also writes to `stat-uptime`. The reads silently no-op every 10 seconds. The user gets zero visibility into bot state. This is dead wiring shipped to production.
-
-## Outcome
-The Dashboard page renders a stat-card row at the top with five cards — **Bot Status**, **Mode**, **Claims Detected**, **Active Watches**, **Uptime** — that update from the real `GET /api/healthz` payload every 10 seconds (the existing poll). Numbers match what `curl /api/healthz` returns.
-
-## Endpoint
-[api/healthz.js](../../api/healthz.js) is the source of truth. If it does not currently expose `monitor.running`, `monitor.mode`, `monitor.claimsDetected`, `watches.total`, and `uptime`, extend it to include them — read real values from the Postgres tables (`pump_claims`, `watches`, plus a process uptime) using the existing `sql` helper. **Do not synthesize values in the frontend** and **do not return constants** from the endpoint.
-
-## Implementation
-1. In [api/healthz.js](../../api/healthz.js), confirm/extend the response shape:
- ```json
- {
- "ok": true,
- "uptime": 12345,
- "monitor": { "running": true, "mode": "live", "claimsDetected": 42 },
- "watches": { "total": 3 }
- }
- ```
- `claimsDetected` = `SELECT count(*) FROM pump_claims`. `watches.total` = `SELECT count(*) FROM watches WHERE deleted_at IS NULL`. `monitor.running` = whether the bot worker process has reported a heartbeat in the last 60s (table `bot_heartbeat`); if no such table exists yet, add the migration in [migrations/](../../migrations/) and write a real heartbeat from [workers/](../../workers/). No hardcoded `running: true`.
-2. In [pump-dashboard.html](../../pump-dashboard.html), insert a `.stats-grid` block at the top of `#page-dashboard` containing five `.stat-card` divs with IDs `stat-bot-status`, `stat-bot-mode`, `stat-claims`, `stat-watches`, `stat-uptime` (the same IDs the JS already targets). Reuse the existing `.stat-card` CSS already defined in this file.
-3. Real states:
- - Before first response: each card value renders `—` (em dash), not `0` or fake numbers.
- - On API disconnect (the existing `updateApiStatus('error')` path): cards keep their last real value, but flip to a muted color and show a small "stale" badge (real, not faked).
-
-## Definition of done
-- Cards visibly update on page load and again 10s later.
-- Numbers match `curl http://localhost:3000/api/healthz` exactly.
-- Stop the bot worker → within ~60s, `Bot Status` flips to `Stopped` based on real heartbeat absence.
-- No hardcoded `running: true` in the codebase response.
-- `npm test` green; **completionist** subagent run on changed files.
diff --git a/tasks/pump-dashboard-real-apis/08-revenue-page-real.md b/tasks/pump-dashboard-real-apis/08-revenue-page-real.md
deleted file mode 100644
index 75de020d2..000000000
--- a/tasks/pump-dashboard-real-apis/08-revenue-page-real.md
+++ /dev/null
@@ -1,43 +0,0 @@
-# 08 — Revenue page: render real `/api/billing/revenue` data
-
-## Problem
-[pump-dashboard.html](../../pump-dashboard.html) lines ~545–547 contain only:
-
-```html
-<div class="content page" id="page-revenue" style="display:none">
- <!-- Content will be rendered here by dashboard.js -->
-</div>
-```
-
-There is no `dashboard.js`. The Revenue tab is empty. This is a half-finished feature shipped to production and violates [CLAUDE.md](../../CLAUDE.md) (definition of done — feature must be reachable).
-
-## Outcome
-Selecting **Revenue** from the sidebar fetches `GET /api/billing/revenue` (already implemented in [api/billing/revenue.js](../../api/billing/revenue.js)) and renders:
-- Summary stat-card row: gross, fees, net, payment count, currency mint, chain.
-- "By skill" table sorted by net descending.
-- Time-series chart (canvas line plot, daily granularity, last 30 days by default).
-- Filter controls: agent picker (populated from `GET /api/agents`), granularity selector (day/week/month), date range pickers (`from`, `to`).
-
-## Endpoints to use (already exist)
-- `GET /api/billing/revenue?agent_id=…&granularity=day&from=…&to=…` — see [api/billing/revenue.js](../../api/billing/revenue.js). Returns `{ summary, by_skill, timeseries }`.
-- `GET /api/agents` — see [api/agents.js](../../api/agents.js).
-
-## Implementation
-1. Build the markup inside `#page-revenue` directly — keep the same `.panel` / `.stats-grid` / table styling already in this file. No external `dashboard.js` script; inline this with the rest of the dashboard JS, or extract a real ES module like `src/pump/dashboard-revenue.js` and import it.
-2. On nav into the Revenue page (and once on initial DOMContentLoaded if it's the active page), parallel-fetch:
- - `GET /api/billing/revenue` with current filter state.
- - `GET /api/agents` to populate the agent picker.
-3. Render numbers with the correct decimals derived from `summary.currency_mint`. For SPL token mints, look up decimals via `getAccountInfo` through `/api/wallet/balances` or a dedicated mint-info endpoint — **do not hardcode 6** for any mint other than the canonical USDC mint, and do not assume SOL.
-4. Time-series chart: vanilla canvas line (no new dependency). Re-use the canvas approach from task 03 if that task is also being done; otherwise self-contain it here. No fake animation, no `setTimeout` smoothing.
-5. Real states:
- - Loading: skeleton stat cards + a "Loading…" line in the chart canvas.
- - 401: render "Sign in to view revenue" + link to `/login.html`.
- - Empty (`payment_count === 0`): render real "No revenue events in this window" — do not invent rows.
-6. Add a "Refresh" button next to the filters that re-fetches with the current filter state.
-
-## Definition of done
-- Network tab shows real `/api/billing/revenue` and `/api/agents` calls succeeding.
-- Numbers match a direct `curl /api/billing/revenue` for the same filters.
-- Changing granularity from day → month re-fetches and re-renders the chart with fewer, larger buckets.
-- The HTML comment `<!-- Content will be rendered here by dashboard.js -->` is gone.
-- `npm test` green; **completionist** subagent run on changed files.
diff --git a/tasks/pump-dashboard-real-apis/09-api-keys-management-real.md b/tasks/pump-dashboard-real-apis/09-api-keys-management-real.md
deleted file mode 100644
index 1ecd5f273..000000000
--- a/tasks/pump-dashboard-real-apis/09-api-keys-management-real.md
+++ /dev/null
@@ -1,33 +0,0 @@
-# 09 — API Keys page: real list / create / revoke flow
-
-## Problem
-[pump-dashboard.html](../../pump-dashboard.html) lines ~844–877 are **static documentation only** — a hardcoded table of endpoints and a description of how to authenticate. There is no list of the user's keys, no way to create a key, and no way to revoke. The `api-endpoint-display` is the only dynamic element. This is a half-finished feature — the user cannot actually obtain or manage credentials.
-
-## Outcome
-The API Keys page, in addition to keeping the endpoint reference table, gains a real **Your Keys** section showing the signed-in user's API keys with: name, prefix, scopes, created-at, last-used-at, and a Revoke button. A **Create New Key** form (name + scope checkboxes + optional expiry) calls `POST /api/api-keys`, then opens a modal that displays the plaintext token **once** with a Copy button and a clear "you won't see this again" note.
-
-## Endpoints (already exist)
-- List: `GET /api/api-keys` — see [api/api-keys.js](../../api/api-keys.js).
-- Create: `POST /api/api-keys` with `{ name, scope, expires_at? }`. Returns `{ data: { ..., token } }` with the plaintext token (never persisted).
-- Revoke: `DELETE /api/api-keys/<id>` — see [api/api-keys/[id].js](../../api/api-keys/[id].js).
-- Allowed scopes per [api/api-keys.js](../../api/api-keys.js): `avatars:read`, `avatars:write`, `avatars:delete`, `profile`.
-
-## Implementation
-1. Add a `Your Keys` panel above the existing Available Endpoints table on `#page-api`.
-2. Render keys in a real table: Name, Prefix (masked, e.g. `sk_live_abc123…`), Scopes (comma list), Created, Last Used (relative time, "never" when null), Expires (real date or `—`), Actions (Revoke).
-3. Revoke flow:
- - Click → `confirm(...)` → `DELETE /api/api-keys/<id>` → on 200, refresh the list. On error, surface upstream error string via `toast`.
-4. Create flow:
- - Form with: Name (required, ≤80 chars), Scope checkboxes (all four allowed scopes from the API), Expiry (optional `<input type="datetime-local">`, converted to ISO 8601 UTC for the request).
- - On submit → `POST /api/api-keys` → on 201, open a modal that displays the plaintext `token` returned by the server, with Copy-to-Clipboard. Closing the modal refreshes the list. On error, surface upstream error.
-5. Real states:
- - 401: render "Sign in to manage keys" + `/login.html` link instead of the table.
- - 429: surface "Too many requests, try again shortly" — do not retry automatically.
- - Empty list: "You haven't created any API keys yet." — no fake row.
-6. **Never** display or log the plaintext token after the create-modal is closed. The list view must use only `prefix`.
-
-## Definition of done
-- Create a key in the UI; copy it; `curl -H "X-API-Key: <token>" http://localhost:3000/api/v1/status` succeeds and the key's `last_used_at` updates on next list refresh.
-- Revoke the key; the same `curl` returns 401.
-- Refresh the page → the plaintext token is gone (only the prefix remains).
-- `npm test` green; **completionist** subagent run on changed files.
diff --git a/tasks/pump-dashboard-real-apis/10-config-validate-connection.md b/tasks/pump-dashboard-real-apis/10-config-validate-connection.md
deleted file mode 100644
index 57b4d6748..000000000
--- a/tasks/pump-dashboard-real-apis/10-config-validate-connection.md
+++ /dev/null
@@ -1,31 +0,0 @@
-# 10 — Configuration page: real connection validation on Save
-
-## Problem
-[pump-dashboard.html](../../pump-dashboard.html) `saveConfig()` (lines ~1917–1935) writes the four config fields (API URL, WS URL, API Key, RPC URL) to `localStorage` and toasts "Configuration saved & reconnecting". It then calls `connectApi()` and `connectWebSocket()`, but the user gets **no per-field validation feedback** — invalid RPC URLs, wrong API keys, etc. fail silently in the global status indicators and the user is left guessing. There is also no test of the **Solana RPC** endpoint at all.
-
-## Outcome
-Each field gains an inline status pill ("OK", "Failed: <reason>") that updates after Save runs real probes:
-- **API URL**: `GET <apiUrl>/api/healthz` → expects `{ ok: true }`.
-- **API Key**: `GET <apiUrl>/api/v1/status` with `X-API-Key` header → 200 = OK, 401/403 = Failed with status text.
-- **WS URL**: open the socket, wait up to 3s for `onopen`, then close. Anything else = Failed.
-- **RPC URL**: JSON-RPC `getHealth` (and `getVersion` for display) — `{ "jsonrpc":"2.0","id":1,"method":"getHealth" }` → result `"ok"` = OK, otherwise Failed with the RPC error.
-
-All probes run in parallel, then results render against each field. Saving still always persists to `localStorage` so the user can come back; but any failed probe must show the real failure inline, not be hidden.
-
-## Implementation
-1. Refactor `saveConfig()` to:
- - Persist to `localStorage` immediately (existing behaviour).
- - Update `state.*` and `api-endpoint-display` (existing behaviour).
- - `Promise.all([probeApi(), probeApiKey(), probeWs(), probeRpc()])` — each helper returns `{ ok: boolean, detail: string }`.
- - Write each result into a new `<div class="status-pill">` element placed adjacent to its input field. Use the existing color classes (`green`, `red`, `yellow`).
-2. Add real probe helpers above `saveConfig()`. They MUST hit the real endpoints — no canned success.
-3. The WS probe must close the socket after success/timeout to avoid leaking a connection (the page-level `connectWebSocket()` flow continues to own the long-lived socket).
-4. Also run all four probes once on `DOMContentLoaded` so the page reflects current connectivity at load.
-5. The "Save & Reconnect" button shows a real spinner while probes are in flight; re-enables on completion. No `setTimeout` fake delay.
-
-## Definition of done
-- Enter a known-bad RPC URL → save → RPC pill turns red and shows the real RPC error string.
-- Enter a known-good Helius RPC URL → pill turns green within ~1s.
-- Revoke the API key (via task 09's UI or directly in DB) → pill turns red with "401 unauthorized".
-- All four pills reflect real, live state — verifiable by toggling each endpoint independently.
-- `npm test` green; **completionist** subagent run on changed files.
diff --git a/tasks/pump-dashboard-real-apis/11-tts-speech-real.md b/tasks/pump-dashboard-real-apis/11-tts-speech-real.md
deleted file mode 100644
index 58c0104ea..000000000
--- a/tasks/pump-dashboard-real-apis/11-tts-speech-real.md
+++ /dev/null
@@ -1,29 +0,0 @@
-# 11 — Animations page: wire Speech input to real TTS
-
-## Problem
-[pump-dashboard.html](../../pump-dashboard.html) `agentAction('speak')` (lines ~1086–1091) builds an `{ type: 'speak', text }` action and posts it via `iframe.contentWindow.postMessage(...)` to `/agent-embed.html?id=<agentId>`. There is no proof that the embed handles `speak` with a real TTS path — and even if it does, it isn't wired here in a verifiable way. The Speech control may silently no-op. The form is shipped to a production page so it must produce real audible output backed by a real TTS API.
-
-## Outcome
-Typing into the Speech field and clicking **Speak** plays real audio (the agent's voice) and triggers the agent's lip-sync, every time. On error (rate limit, missing API key, etc.) the user sees the real upstream error.
-
-## Endpoints (already exist)
-- ElevenLabs proxy: [api/tts/eleven.js](../../api/tts/eleven.js) (consumes `ELEVENLABS_API_KEY` server-side and streams audio).
-- The agent embed: [agent-embed.html](../../agent-embed.html) — verify it listens for `agent:action` `speak` and renders both audio + lip-sync.
-
-## Implementation
-1. Open [agent-embed.html](../../agent-embed.html) and confirm the `speak` action handler:
- - POSTs `{ text, voice_id }` to `/api/tts/eleven` (or returns the audio URL via streaming).
- - Plays the returned audio with `<audio>` and drives the avatar's viseme/lip-sync from it.
- If any of that is missing or stubbed (`throw 'not implemented'`, `setTimeout` fake speech, browser `speechSynthesis` fallback, etc.), implement it for real. Use the same agent's stored `voice_id` (read from `agent_identities.meta.voice_id` via `GET /api/agents/:id`); if no voice id is set, surface the real error "agent has no voice configured" — do not fall back to a default voice silently.
-2. In [pump-dashboard.html](../../pump-dashboard.html):
- - On Speak click: validate `text` is non-empty, then post the `agent:action` message exactly as today, **but also** set up a one-time `window.addEventListener('message', …)` listener for the iframe's reply (`agent:action:result` with `{ ok, error? }`) and toast the real error if `ok === false`. No silent failures.
- - Add a real "Stop" button that posts `{ type: 'speak:stop' }` to the iframe; the embed must support that and stop playback.
-3. Disable the Speak button while audio is playing; re-enable on `agent:action:result` or on the audio `ended` event reported back from the iframe. No `setTimeout` re-enable.
-
-## Definition of done
-- Type "hello world" + Speak → real audio plays through speakers, sourced from `/api/tts/eleven`. Verify in DevTools network tab.
-- Lip-sync visibly moves on the avatar in the iframe.
-- With `ELEVENLABS_API_KEY` removed from `.env`, click Speak → real upstream 503/missing-config error surfaces in a toast; nothing silently succeeds.
-- The Stop button cuts audio mid-utterance.
-- No use of `window.speechSynthesis` anywhere (browser TTS is not the platform's voice).
-- `npm test` green; **completionist** subagent run on changed files.
diff --git a/tasks/site-overhaul/A-health/A06-reconcile-home-variants.md b/tasks/site-overhaul/A-health/A06-reconcile-home-variants.md
deleted file mode 100644
index 3a08eda43..000000000
--- a/tasks/site-overhaul/A-health/A06-reconcile-home-variants.md
+++ /dev/null
@@ -1,27 +0,0 @@
-# A06 — Reconcile the homepage variants
-
-**Track:** Health · **Size:** M · **Priority:** P1
-
-## Goal
-There are 5+ home pages: `home.html`, `home-v2`, `home-v3`, `home-v4`, `home-classic`. Pick the
-canonical one, make `/` serve it, and redirect or delete the rest. One front door.
-
-## Why it matters
-Multiple half-maintained homepages dilute the brand, fragment SEO, and guarantee inconsistency.
-The audit identifies `pages/home-v4.html` ("Give your AI a body") as the current canonical.
-
-## Context
-- Files: `pages/home.html`, `pages/home-v2.html`, `pages/home-v3.html`, `pages/home-v4.html`, `pages/home-classic.html`.
-- Routing: `vite.config.js` (dev) + `vercel.json` (prod) define `/`, `/home`, `/home-v2…`.
-- Note: Track C (C01) will rewrite the canonical home's copy for newcomers — coordinate so you converge on **one** file C01 then edits.
-
-## Scope
-- Confirm the canonical (default to `home-v4.html` unless you find a clearly better/newer one) and make `/` and `/home` serve it in both dev and prod routing.
-- For the others: `301` redirect to `/` if they have inbound links/SEO value, otherwise delete the file and its routes. Don't leave orphaned routes (`A07` covers the broader orphan sweep).
-- Update any internal links pointing at a non-canonical variant.
-
-## Definition of done
-- `/`, `/home`, and every former variant URL all resolve to the single canonical homepage (directly or via redirect). No variant renders a different, competing design.
-
-## Verify
-- Hit `/`, `/home`, `/home-v2`, `/home-v3`, `/home-classic` in dev — all land on the canonical page or redirect to it. `grep -rn "home-v2\|home-v3\|home-classic" pages public src` shows no live internal links.
diff --git a/tasks/site-overhaul/B-ui-uniformity/B02-kill-dead-token-systems.md b/tasks/site-overhaul/B-ui-uniformity/B02-kill-dead-token-systems.md
deleted file mode 100644
index 4f0ef435d..000000000
--- a/tasks/site-overhaul/B-ui-uniformity/B02-kill-dead-token-systems.md
+++ /dev/null
@@ -1,26 +0,0 @@
-# B02 — Delete the competing/dead token systems
-
-**Track:** UI Uniformity · **Size:** M · **Priority:** P0 · **Depends on:** B01
-
-## Goal
-Remove or migrate the 7 redundant CSS token systems so only the B01 canonical set remains.
-
-## Why it matters
-Eight design languages on one site is the root cause of the inconsistency. Each dead system is
-also dead weight shipped to users.
-
-## Context (systems found in the audit)
-- Migrate-then-delete: `--mk-*` ([public/marketplace.css](public/marketplace.css)), `--pd-*` ([public/pump-dashboard.css](public/pump-dashboard.css)), `--t-*` (`public/theme.css`), `--sdk-*` ([public/avatar-sdk.css](public/avatar-sdk.css)).
-- Likely pure-dead, verify then delete: `--ibm-*` ([public/ibm.css](public/ibm.css)), `--gx-*` ([public/galaxy.css](public/galaxy.css)), `--ho-*` (`public/home-overhaul.css`), `--saas-*` (`public/home-saas.css`).
-
-## Scope
-- For each system: grep for actual usage. If a page uses it, map its tokens to the canonical B01 tokens and update the page's CSS to consume the canonical names. If unused, delete the file and remove its `<link>`/import references.
-- Preserve intentional *aesthetic* differences (e.g. the IBM galaxy's distinct look) by expressing them as a **theme layer on top of** the canonical tokens, not a parallel system.
-- Remove the now-dead `<link rel="stylesheet">` tags from the HTML pages.
-
-## Definition of done
-- `grep -rEn "\-\-(mk|pd|t|sdk|ibm|gx|ho|saas)-" public pages src` returns nothing (or only inside a documented theme file that itself maps to canonical tokens).
-- No page links a deleted CSS file. Visual output unchanged or improved.
-
-## Verify
-- Load marketplace, pump-dashboard, avatar-sdk, and an IBM page in dev — each still looks right, now on canonical tokens.
diff --git a/tasks/site-overhaul/C-ux-newcomers/C01-homepage-plain-language.md b/tasks/site-overhaul/C-ux-newcomers/C01-homepage-plain-language.md
deleted file mode 100644
index ca33f7e92..000000000
--- a/tasks/site-overhaul/C-ux-newcomers/C01-homepage-plain-language.md
+++ /dev/null
@@ -1,32 +0,0 @@
-# C01 — Rewrite the homepage for a non-crypto first-timer
-
-**Track:** UX for Newcomers · **Size:** M · **Priority:** P0 · **Depends on:** A06 (one canonical home)
-
-## Goal
-Rewrite the canonical homepage so a person who has never touched crypto immediately understands
-what three.ws is, what they can make, and why they'd want to — with crypto demoted to an
-optional, clearly-labeled layer.
-
-## Why it matters
-The UX audit scored the homepage 3/10 for newcomers: the hero leads with "Mint it on Solana,"
-lists `Metaplex Core / MCP / A2A` as features with no explanation, and the "crypto is optional"
-truth is buried in the pricing FAQ. The creation tools themselves are great (8/10) — the problem
-is the front door turns normal people away before they reach them.
-
-## Context
-- Canonical home: [pages/home-v4.html](pages/home-v4.html) (hero "Give your AI a body").
-- The real, plain value: *make a 3D avatar from a selfie, give it an AI brain, embed it anywhere.* Crypto (ownership, payments) is an optional add-on.
-- Honesty rule (memory): marketing visuals must be honest examples, no fake live data.
-
-## Scope
-- Rewrite the hero + the 4-step flow in plain language. Lead with the outcome a normal person wants. Move "mint/Solana/on-chain" into an explicitly **optional** section ("Want to own it on-chain or get paid? That's optional — here's how").
-- Replace bare jargon tokens (`Metaplex Core`, `MCP`, `A2A`) with plain descriptions; link them to the glossary (C04).
-- Add a one-line, prominent "**No crypto needed to start.**" reassurance (promotes the buried FAQ — see C08).
-- Keep it honest: any numbers/visuals must be real (tie to the activity feed if showing live data).
-- Use the unified design system (Track B) — don't reintroduce the home-only orange (B08).
-
-## Definition of done
-- A non-crypto reader can state, after 10 seconds, what three.ws lets them make and that crypto is optional. No unexplained jargon above the fold. Clear primary CTA into `/create`.
-
-## Verify
-- Read it cold as a non-crypto user; confirm comprehension. `npm run dev`, check responsive 320/768/1440, working CTAs, no console errors.
diff --git a/tasks/site-overhaul/C-ux-newcomers/C02-what-is-threews-usecases.md b/tasks/site-overhaul/C-ux-newcomers/C02-what-is-threews-usecases.md
deleted file mode 100644
index 7991a54be..000000000
--- a/tasks/site-overhaul/C-ux-newcomers/C02-what-is-threews-usecases.md
+++ /dev/null
@@ -1,29 +0,0 @@
-# C02 — "What is three.ws?" + concrete use-cases page
-
-**Track:** UX for Newcomers · **Size:** M · **Priority:** P1
-
-## Goal
-A plain-language explainer page that answers "what is this and who is it for?" with 3–4 concrete,
-relatable use-cases — and link it from the nav and homepage.
-
-## Why it matters
-The audit found users have "no idea these are all part of one platform" (avatar creator,
-animation, AI chatbot, embeddable widget, optional tokens, paid APIs, 3D worlds). Concrete
-use-cases convert abstract capability into "oh, I could use this for X."
-
-## Context
-- The platform's capabilities are real and listed in the route inventory; the gap is *framing*.
-- Suggested use-cases (validate against real features): (1) a customer-service avatar embedded on a website, (2) a streamer/creator avatar for YouTube/Twitch, (3) a 3D character for a community/token, (4) a personal AI agent with a face.
-- There is a `/start` and `/features` page already — coordinate so this doesn't duplicate (C05 rewrites `/features`).
-
-## Scope
-- New page (`pages/what-is.html` or repurpose `/start`) with: a one-paragraph plain definition, the 3–4 use-cases as cards (each: who, what they build, the steps, a live example/CTA), and a "start free" CTA.
-- Each use-case links to the actual flow that achieves it (`/create`, `/scan`, embed, etc.).
-- Add a nav entry ("What is three.ws?" or "Use cases") and link from the homepage.
-- Built on Track B components; honest examples only.
-
-## Definition of done
-- The page exists, is linked from nav + home, and each use-case is real and actionable (its CTA reaches a working flow).
-
-## Verify
-- Click each use-case CTA — lands on the right working surface. Non-crypto reader can name a use-case that applies to them.
diff --git a/tasks/site-overhaul/C-ux-newcomers/C04-glossary-and-tooltips.md b/tasks/site-overhaul/C-ux-newcomers/C04-glossary-and-tooltips.md
deleted file mode 100644
index 328fa8da0..000000000
--- a/tasks/site-overhaul/C-ux-newcomers/C04-glossary-and-tooltips.md
+++ /dev/null
@@ -1,27 +0,0 @@
-# C04 — Plain-language glossary + hover-tooltip system
-
-**Track:** UX for Newcomers · **Size:** M · **Priority:** P1
-
-## Goal
-A reusable "explain this term" tooltip component plus a `/glossary` page, so every unavoidable
-piece of jargon has a one-line plain-language definition on hover/tap and a deeper link.
-
-## Why it matters
-The audit catalogued jargon appearing in user-facing copy with zero explanation: **x402, USDC,
-Solana, Metaplex Core, on-chain, ERC-8004, mint, bonding curve, graduation, MCP, A2A, skills,
-brain, rig**. A glossary + inline tooltips lets you keep necessary terms without losing newcomers.
-
-## Context
-- Terms and their locations are enumerated in the UX audit; they appear across `/features`, `/home-v4`, `/pricing`, dashboard, `/club`, agent edit.
-- Build the tooltip as a shared component (Track B styling) so any page can wrap a term: e.g. `<span data-term="x402">x402</span>` auto-enhanced.
-
-## Scope
-- Shared tooltip module (`src/shared/term-tooltip.js` + styles) reading definitions from one `src/shared/glossary.js` map (term → {short, long, link}). Accessible: keyboard-focusable, `aria-describedby`, dismissible, mobile tap support.
-- `/glossary` page rendering the full map (also serves SEO).
-- Wrap the jargon on the highest-traffic surfaces (home, features, dashboard, agent edit). Definitions must be **plain** ("x402 = a way to charge a tiny payment when someone uses your agent — like a paywall for APIs"), not circular.
-
-## Definition of done
-- Hovering/focusing any wrapped term shows a plain definition; `/glossary` lists them; the top surfaces have their jargon wrapped.
-
-## Verify
-- Keyboard-tab to a term, confirm the tooltip opens and is screen-reader labeled. Non-crypto reader understands each definition.
diff --git a/tasks/site-overhaul/C-ux-newcomers/C05-features-page-core-vs-optional.md b/tasks/site-overhaul/C-ux-newcomers/C05-features-page-core-vs-optional.md
deleted file mode 100644
index c8d042910..000000000
--- a/tasks/site-overhaul/C-ux-newcomers/C05-features-page-core-vs-optional.md
+++ /dev/null
@@ -1,27 +0,0 @@
-# C05 — Rewrite `/features`: Core vs Optional, use-case-driven
-
-**Track:** UX for Newcomers · **Size:** M · **Priority:** P1 · **Depends on:** C04
-
-## Goal
-Restructure the features page into two clear sections — **Core (works today, no crypto)** and
-**Optional (on-chain, payments, tokens)** — with use-case-driven, plain descriptions.
-
-## Why it matters
-The audit scored `/features` **1/10** for newcomers: "Very High" jargon density, no plain
-explanations, crypto presented as the headline. It's the page that most alienates normal users.
-
-## Context
-- [pages/features.html](pages/features.html). Current copy: "x402 Paid Skills — Charge per call in USDC over the x402 protocol… signed and on-chain auditable" (four jargon sentences, no plain meaning).
-- Glossary/tooltips from C04 handle the unavoidable terms inline.
-
-## Scope
-- Reorganize into **Core** (create avatars, 70+ animations, AI brain/chat, embed anywhere, dashboard) and **Optional / Advanced** (on-chain identity, x402 payments, token launch). Lead each feature with what it does for the user, then how.
-- Rewrite every jargon-heavy blurb into plain language; wrap residual terms with C04 tooltips.
-- Add a "no crypto needed for Core" banner.
-- Use Track B components.
-
-## Definition of done
-- `/features` clearly separates free-core from optional-crypto; every feature blurb is comprehensible to a non-crypto reader; residual jargon is tooltip-explained.
-
-## Verify
-- Non-crypto read-through: reader can identify which features need crypto and which don't, and what each does.
diff --git a/tasks/site-overhaul/C-ux-newcomers/C07-wallet-money-explainer-wizard.md b/tasks/site-overhaul/C-ux-newcomers/C07-wallet-money-explainer-wizard.md
deleted file mode 100644
index 5866d29d4..000000000
--- a/tasks/site-overhaul/C-ux-newcomers/C07-wallet-money-explainer-wizard.md
+++ /dev/null
@@ -1,28 +0,0 @@
-# C07 — Wallet & money explainer + setup wizard
-
-**Track:** UX for Newcomers · **Size:** M · **Priority:** P2 · **Depends on:** C04
-
-## Goal
-When (and only when) a user opts into a crypto feature, give them a plain-language explainer and
-a step-by-step wizard: what a Solana wallet is, what USDC is, what fees are, how to get set up,
-and how withdrawals work.
-
-## Why it matters
-The audit: monetization says "Withdrawals land in your Solana wallet" but never explains what a
-wallet is, how to get one, which wallet, or what USDC/fees are. Users hit a money wall with no
-ladder.
-
-## Context
-- Friction points: homepage step 4 (monetize), `/club` tipping, agent-edit token launch, dashboard Monetize/Portfolio/Tokens.
-- Wallet auth already exists (the `authenticate-wallet` skill; "Sign in with Solana"). This task is the *education + guided setup* layer, not new auth.
-
-## Scope
-- A reusable "before you go on-chain" explainer (modal or page) covering: what a wallet is (plain), recommended wallet(s), what USDC is, what fees are (~cents on Solana), and that nothing here costs anything until they choose to transact.
-- A wizard that walks a first-timer through connecting a wallet and (optionally) funding it — reuse the existing `fund`/`authenticate-wallet` flows; don't reinvent.
-- Gate it: only surfaces when the user opts into a crypto action. Never blocks the free core.
-
-## Definition of done
-- Opting into any crypto feature presents a clear explainer + guided setup; a non-crypto user can follow it without prior knowledge; the free product is untouched.
-
-## Verify
-- As a non-crypto user, click "monetize"/"deploy on-chain" — the explainer/wizard appears, terms are plain, and the path to a connected wallet works.
diff --git a/tasks/site-overhaul/C-ux-newcomers/C08-crypto-optional-messaging.md b/tasks/site-overhaul/C-ux-newcomers/C08-crypto-optional-messaging.md
deleted file mode 100644
index 039508394..000000000
--- a/tasks/site-overhaul/C-ux-newcomers/C08-crypto-optional-messaging.md
+++ /dev/null
@@ -1,26 +0,0 @@
-# C08 — "Crypto is optional" messaging, promoted everywhere
-
-**Track:** UX for Newcomers · **Size:** S · **Priority:** P2
-
-## Goal
-Surface the (currently buried) truth that the core product works with no wallet, and frame every
-crypto feature as explicit opt-in across the site.
-
-## Why it matters
-The audit found a great FAQ answer — "Do I need crypto to use three.ws? No…" — buried in
-`/pricing`. Promoting it removes the single biggest false barrier for normal users.
-
-## Context
-- Source copy: [pages/pricing.html](pages/pricing.html) FAQ ("The web component, dashboard, and API work without a wallet. Crypto unlocks: on-chain identity, payable skills, payouts.").
-- Crypto features should read as optional add-ons, not prerequisites.
-
-## Scope
-- Add a concise, consistent "No crypto required to start — it's optional" message to: homepage (C01), `/features` (C05), the create flow, and the dashboard first-run.
-- Wherever a crypto action appears, label it "Optional" with a one-line plain benefit + a "what's this?" tooltip (C04).
-- Keep the message honest and identical in tone everywhere (one reusable snippet/component).
-
-## Definition of done
-- The "crypto is optional" message appears on the top entry surfaces; every crypto action is labeled optional with a plain benefit.
-
-## Verify
-- A non-crypto user, on home/features/create/dashboard, can plainly see they can use the product without a wallet.
diff --git a/tasks/site-overhaul/D-new-features/D01-command-palette.md b/tasks/site-overhaul/D-new-features/D01-command-palette.md
deleted file mode 100644
index a26af618a..000000000
--- a/tasks/site-overhaul/D-new-features/D01-command-palette.md
+++ /dev/null
@@ -1,29 +0,0 @@
-# D01 — Site-wide command palette (⌘K)
-
-**Track:** New Features · **Size:** M · **Priority:** P1
-
-## Goal
-A universal `⌘K` / `Ctrl-K` command palette to jump to any route, search agents/avatars/coins,
-run actions (create, deploy, embed), and open docs — from anywhere on the site.
-
-## Why it matters
-With 200+ routes, discoverability is a real problem. A command palette is the single highest-
-leverage navigation upgrade and a hallmark of top-tier products (Linear, Vercel). It also makes
-the sprawling surface feel intentional.
-
-## Context
-- Routes are enumerable from the router config; agents/avatars/coins are queryable via existing APIs (`/api/agents`, discover endpoints, pump search).
-- Shared nav is global ([public/nav.js](public/nav.js)) — a natural mount point so it's available everywhere.
-- Track B components for styling; honest data only (real search results).
-
-## Scope
-- A global palette component (keyboard-opened, accessible, focus-trapped) mounted via the nav so every page gets it.
-- Sources: static routes/pages, live agent/avatar/coin search (debounced, real API), quick actions, docs/glossary entries.
-- Keyboard nav, recent/suggested items, empty + loading + error states.
-- Mobile affordance (a search button in the nav opens the same palette).
-
-## Definition of done
-- `⌘K` opens the palette on any page; typing finds routes, real agents/coins, actions, and docs; selecting navigates/acts; all states designed; fully keyboard-accessible.
-
-## Verify
-- `npm run dev`; open the palette on 5 different pages, search a real agent and a real coin, run "create avatar," navigate via keyboard only.
diff --git a/tasks/site-overhaul/D-new-features/D02-notifications-activity-center.md b/tasks/site-overhaul/D-new-features/D02-notifications-activity-center.md
deleted file mode 100644
index 3a4bc7972..000000000
--- a/tasks/site-overhaul/D-new-features/D02-notifications-activity-center.md
+++ /dev/null
@@ -1,28 +0,0 @@
-# D02 — Unified notifications / activity center
-
-**Track:** New Features · **Size:** M · **Priority:** P2 · **Builds on:** the feed bus
-
-## Goal
-A per-user notifications/activity center in the nav: launches, sales/tips, agent events,
-follows, system messages — built on the existing site-wide feed bus, not a new system.
-
-## Why it matters
-Engagement and retention depend on a reason to come back. The platform already has a feed bus
-(`feed:events` on Redis) powering the site-wide FOMO ticker — extend it into a personalized,
-persistent inbox.
-
-## Context
-- Memory: live activity feed uses the Redis `feed:events` bus (API + multiplayer producers), nav-loaded widget `public/feed.js`; **extend the event shape, don't fork it.**
-- Personalization needs a per-user filter/store on top of the existing events.
-
-## Scope
-- A nav bell with unread count opening a panel of the user's relevant events (their agents' launches/sales/tips, follows, system notices).
-- Persist read/unread per user; mark-all-read; deep links to the relevant surface.
-- Reuse `feed:events`; add only the fields/filtering needed (per memory, extend the shape). Real events only — no fabricated notifications.
-- Designed empty ("You're all caught up"), loading, error states.
-
-## Definition of done
-- Signed-in users see real, personalized notifications from the existing bus, with unread state and deep links; the global ticker still works unchanged.
-
-## Verify
-- Trigger a real event (e.g. a launch) and confirm it appears for the relevant user with a working deep link; unread count updates.
diff --git a/tasks/site-overhaul/D-new-features/D03-agent-template-gallery.md b/tasks/site-overhaul/D-new-features/D03-agent-template-gallery.md
deleted file mode 100644
index 6808b4345..000000000
--- a/tasks/site-overhaul/D-new-features/D03-agent-template-gallery.md
+++ /dev/null
@@ -1,27 +0,0 @@
-# D03 — Agent template gallery / "clone this agent"
-
-**Track:** New Features · **Size:** M · **Priority:** P1 · **Pairs with:** C02 use-cases
-
-## Goal
-A gallery of ready-made agent templates (customer-service bot, streamer companion, community
-mascot, etc.) that a user can clone in one click and customize — turning the blank-page problem
-into a pick-and-go.
-
-## Why it matters
-The audit's #1 newcomer gap is "what's an agent and why would I make one?" Templates answer it by
-example and collapse time-to-first-agent. It also directly supports the C02 use-cases.
-
-## Context
-- Agent creation/registration exists (`agent-identities`, the create/deploy flows). A template is a pre-filled agent config (persona, brain, skills, sample avatar) the user can fork.
-- Discover/marketplace surfaces exist to host the gallery; reuse Track B cards.
-
-## Scope
-- Define a template schema + a curated, real set (no fake data — each template is a working agent config). Store them where the app can read them (DB table or a versioned JSON the build ships).
-- A gallery surface (under `/discover` or a new `/templates`) with cards, preview, and "Use this template" → creates a real editable agent from the template.
-- Each template maps to a C02 use-case and explains who it's for.
-
-## Definition of done
-- A user can browse templates, preview one, and clone it into a real, editable agent in their account; every template is genuinely functional.
-
-## Verify
-- Clone 2 templates; confirm they produce working agents pre-filled correctly and are independently editable.
diff --git a/tasks/site-overhaul/D-new-features/D08-fiat-onramp-path.md b/tasks/site-overhaul/D-new-features/D08-fiat-onramp-path.md
deleted file mode 100644
index 231c1ba9e..000000000
--- a/tasks/site-overhaul/D-new-features/D08-fiat-onramp-path.md
+++ /dev/null
@@ -1,30 +0,0 @@
-# D08 — Fiat-friendly on-ramp for non-crypto users
-
-**Track:** New Features · **Size:** L · **Priority:** P2 · **Depends on:** C07
-
-## Goal
-Give non-crypto users a path to participate in the optional paid/monetization features without
-already understanding wallets — e.g. card-funded USDC via the existing fund flow, with crypto
-abstracted as far as possible.
-
-## Why it matters
-The audit's deepest barrier: monetization assumes a funded Solana wallet. For the platform to
-serve "anyone," there must be a fiat-to-usable path. This is what lets a normal creator actually
-earn or pay without a crypto crash-course.
-
-## Context
-- A `fund` skill/flow exists (onramp/buy USDC). Wallet auth exists. This task wires a **guided, plain-language** funding path into the product UX and abstracts the mechanics.
-- Verify what onramp providers/keys are configured (`.env`, `vercel env`) before designing — use the real one. No mocks.
-- Coordinate with C07 (wallet explainer) so the education and the on-ramp are one coherent flow.
-
-## Scope
-- A funding entry point at the moment a user needs balance (pay/tip/launch), using the real configured on-ramp; show fees/amounts honestly; confirm balance on completion.
-- Abstract jargon: present it as "add funds," with the crypto detail available but not required reading.
-- Handle the unfunded/failed/pending states with designed UI.
-- If a provider isn't configured, surface a clear path (and flag to the founder which env/keys are needed) rather than faking it.
-
-## Definition of done
-- A non-crypto user can go from "I want to tip/launch/pay" to a funded balance through a guided, real on-ramp, with honest fees and designed states.
-
-## Verify
-- Run the funding flow end-to-end against the real provider (test mode if available); confirm balance updates and the gated action then succeeds.
diff --git a/tasks/skills-marketplace/00-overview.md b/tasks/skills-marketplace/00-overview.md
deleted file mode 100644
index eda1ffa8e..000000000
--- a/tasks/skills-marketplace/00-overview.md
+++ /dev/null
@@ -1,51 +0,0 @@
-# Skills Marketplace — Implementation Overview
-
-A community skills marketplace embedded in the chat UI, allowing users to browse, install,
-publish, and rate skill packs that extend the LLM's tool capabilities.
-
-## Task execution order
-
-Run each task in a **new chat** in the order listed. Each task is self-contained with full
-context, but later tasks depend on earlier ones being merged.
-
-| # | File | What it builds | Depends on |
-|---|------|----------------|------------|
-| 01 | `01-db-schema.md` | Postgres tables: `marketplace_skills`, `skill_installs`, `skill_ratings` + basic seed data | nothing |
-| 02 | `02-skills-api.md` | REST API: `/api/skills/` (list, create, install, rate) | 01 |
-| 03 | `03-marketplace-modal.md` | `SkillsMarketplaceModal.svelte` — full browse + publish UI | 01, 02 |
-| 04 | `04-chat-integration.md` | Wire modal into `App.svelte` toolbar | 03 |
-| 05 | `05-seed-and-categories.md` | 15 seed skills + `/api/skills/categories` endpoint + modal update | 02, 03 |
-| 06 | `06-skill-detail-and-ratings.md` | Expanded detail panel + star rating widget | 03, 04, 05 |
-| 07 | `07-installed-skills-toolbar.md` | Active skill chip strip above chat input | 04 |
-
-## Feature summary
-
-### For users
-- **Browse** community skills by category (Finance, Developer, Utility, etc.) with search + sort
-- **Install** a skill with one click — it immediately appears as an active LLM tool
-- **See** installed skills as chips above the input bar, removable with ×
-- **Rate** skills 1–5 stars
-- **Publish** your own skill: name, description, category, and a JSON tool definition
-
-### Architecture
-- Skills are stored in `marketplace_skills` (Postgres). The `schema_json` column holds a JSON
- array in the exact shape of the existing `curatedToolPacks` in `tools.js`.
-- When installed, a skill is written to the `toolSchema` Svelte store (persisted in localStorage).
- The existing LLM tool pipeline reads from this store — no changes to `convo.js` or `providers.js`
- are needed.
-- The community marketplace API lives at `/api/skills/`. System skills have `author_id = null`.
-
-### Files created/modified
-New files:
-- `/api/_lib/migrations/2026-04-30-skills-marketplace.sql`
-- `/api/_lib/migrations/2026-04-30-skills-seed.sql`
-- `/api/skills/index.js`
-- `/api/skills/[id].js`
-- `/api/skills/[id]/install.js`
-- `/api/skills/[id]/rate.js`
-- `/api/skills/categories.js`
-- `/chat/src/SkillsMarketplaceModal.svelte`
-
-Modified files:
-- `/api/_lib/schema.sql` (append new tables)
-- `/chat/src/App.svelte` (import + button + modal instance + chip strip + removeSkill)
diff --git a/tasks/skills-marketplace/01-db-schema.md b/tasks/skills-marketplace/01-db-schema.md
deleted file mode 100644
index c95070b0c..000000000
--- a/tasks/skills-marketplace/01-db-schema.md
+++ /dev/null
@@ -1,85 +0,0 @@
-# Task 01 — DB Schema: Skills Marketplace Tables
-
-## Goal
-Add the database tables required to back a community skills marketplace. When done, the schema
-should support: publishing skills, browsing/searching them, installing them per-user, and basic
-ratings. This is a migration-only task — no API or UI changes.
-
-## Context
-- Project: `/workspaces/3D-Agent`
-- DB: Neon serverless PostgreSQL
-- Migration files live in `/api/_lib/migrations/` as dated SQL files (e.g. `2026-04-30-chat-admin-key.sql`)
-- The existing schema is at `/api/_lib/schema.sql` (~900 lines). Read it first to understand conventions
- (id format, timestamps, foreign keys, naming style).
-- Auth/user table is `users(id uuid pk, email, display_name, ...)`.
-- Today's date: 2026-04-30.
-
-## What to build
-
-### 1. Migration file
-Create `/api/_lib/migrations/2026-04-30-skills-marketplace.sql` with the following tables:
-
-**`marketplace_skills`**
-```
-id uuid primary key default gen_random_uuid()
-author_id uuid references users(id) on delete set null
-name text not null
-slug text not null unique -- url-safe, e.g. "tradingview-charts"
-description text not null
-category text not null default 'general'
--- JSON array matching the existing ToolPack schema used in /chat/src/tools.js:
--- each element: { clientDefinition: {...}, type, function: { name, description, parameters } }
-schema_json jsonb not null
-tags text[] not null default '{}'
-is_public boolean not null default true
-install_count integer not null default 0
-created_at timestamptz not null default now()
-updated_at timestamptz not null default now()
-```
-
-**`skill_installs`** — tracks which users have installed which skills
-```
-id uuid primary key default gen_random_uuid()
-user_id uuid references users(id) on delete cascade
-skill_id uuid references marketplace_skills(id) on delete cascade
-installed_at timestamptz not null default now()
-unique(user_id, skill_id)
-```
-
-**`skill_ratings`**
-```
-id uuid primary key default gen_random_uuid()
-user_id uuid references users(id) on delete cascade
-skill_id uuid references marketplace_skills(id) on delete cascade
-rating smallint not null check (rating between 1 and 5)
-created_at timestamptz not null default now()
-unique(user_id, skill_id)
-```
-
-### 2. Indexes
-Add indexes for the common query patterns:
-- `marketplace_skills(category)`
-- `marketplace_skills(author_id)`
-- `marketplace_skills(install_count desc)` (for "popular" sort)
-- `marketplace_skills(created_at desc)` (for "new" sort)
-- `skill_installs(user_id)`
-
-### 3. Update /api/_lib/schema.sql
-Append the same table definitions (without `IF NOT EXISTS` guards — the schema.sql is the
-canonical reference, not a runnable migration) to the bottom of `/api/_lib/schema.sql`.
-Keep the same formatting style as the rest of the file.
-
-### 4. Seed data
-Add 5 seed rows to `marketplace_skills` in the migration file so there's something to browse.
-Re-use the skill schemas from `/chat/src/tools.js` `curatedToolPacks` — translate each pack's
-`schema` array directly into the `schema_json` column value. The 5 packs in tools.js are:
-`tradingview`, `web-search`, `calculator`, `qr-code`, and any others present in that file.
-Set `author_id = null` (system skills), `is_public = true`.
-
-Use `ON CONFLICT (slug) DO NOTHING` so the seeds are idempotent.
-
-## Verification
-After writing the files:
-1. Read both files back and confirm the SQL is syntactically correct.
-2. Confirm foreign key references match actual table/column names in schema.sql.
-3. Confirm the jsonb seed data is valid JSON (no JS template literals or unquoted strings).
diff --git a/tasks/skills-marketplace/02-skills-api.md b/tasks/skills-marketplace/02-skills-api.md
deleted file mode 100644
index 5e85ca78c..000000000
--- a/tasks/skills-marketplace/02-skills-api.md
+++ /dev/null
@@ -1,118 +0,0 @@
-# Task 02 — API: Skills Marketplace Endpoints
-
-## Goal
-Build the REST API for the skills marketplace. When done, the chat frontend can list skills,
-search/filter them, install/uninstall them, publish new ones, and fetch install state.
-
-## Prerequisites
-Task 01 (DB schema) must be merged first. The `marketplace_skills`, `skill_installs`, and
-`skill_ratings` tables must exist.
-
-## Context
-- Project: `/workspaces/3D-Agent`
-- API layer: Vercel serverless functions in `/api/` (ESM, Node 24)
-- Shared libs in `/api/_lib/`:
- - `db.js` — Neon client, tagged-template `sql`. Read it to see exact export shape.
- - `auth.js` — `requireAuth(req)` throws on failure, returns `{ userId }`. Also `optionalAuth(req)`.
- Read it — the actual export names may differ slightly.
- - `http.js` — `json(res, data, status?)`, `error(res, msg, status?)`, CORS headers. Read it.
- - `rate-limit.js` — pre-built limiters. Read it for available exports.
- - `validate.js` — Zod helpers. Read it.
-- Existing similar endpoint to study: `/api/marketplace/[action].js` — read it for patterns.
-- Auth cookies: `credentials: 'include'` from the browser.
-
-## Endpoints to build
-
-Create `/api/skills/index.js` (handles `/api/skills` GET + POST) and
-`/api/skills/[id].js` (handles `/api/skills/:id` GET/PUT/DELETE) and
-`/api/skills/[id]/install.js` (POST to install, DELETE to uninstall) and
-`/api/skills/[id]/rate.js` (POST to rate).
-
-### GET /api/skills
-Query params: `?q=`, `?category=`, `?sort=popular|new|az`, `?cursor=` (uuid for keyset pagination),
-`?limit=` (default 20, max 50), `?installed=true` (filter to skills installed by authed user).
-
-Response:
-```json
-{
- "skills": [
- {
- "id": "uuid",
- "name": "TradingView Charts",
- "slug": "tradingview-charts",
- "description": "...",
- "category": "finance",
- "tags": ["charts", "trading"],
- "install_count": 42,
- "avg_rating": 4.5,
- "rating_count": 12,
- "author": { "id": "uuid", "display_name": "Alice" },
- "installed": true,
- "created_at": "iso8601"
- }
- ],
- "next_cursor": "uuid-or-null"
-}
-```
-
-`installed` field: true/false if user is authenticated, omitted if not.
-`author` is null for system skills (author_id IS NULL).
-
-### POST /api/skills
-Requires auth. Publish a new skill.
-
-Request body:
-```json
-{
- "name": "My Tool",
- "slug": "my-tool",
- "description": "Does X",
- "category": "utility",
- "tags": ["tag1"],
- "schema_json": [...],
- "is_public": true
-}
-```
-
-Validate: name 2–80 chars, slug matches `/^[a-z0-9-]+$/` max 60 chars, unique slug,
-description max 500 chars, schema_json is an array with at least 1 item, each item has
-`function.name` (string) and `function.parameters` (object).
-
-Response: `{ skill: { ...full row, author: {...} } }` with 201.
-
-### GET /api/skills/:id
-Returns full skill including `schema_json`. `installed` field present if authed.
-
-### PUT /api/skills/:id
-Requires auth. Only the author (or admin) can edit. Updates name/description/tags/is_public/schema_json.
-Slug is immutable after publish.
-
-### DELETE /api/skills/:id
-Requires auth. Only the author can delete. Also deletes all installs for that skill.
-Returns 204.
-
-### POST /api/skills/:id/install
-Requires auth. Installs skill for the current user. Increments `install_count` atomically.
-Idempotent (409 → treat as success, or just upsert). Returns `{ installed: true }`.
-
-### DELETE /api/skills/:id/install
-Requires auth. Uninstalls. Decrements `install_count` (floor at 0). Returns `{ installed: false }`.
-
-### POST /api/skills/:id/rate
-Requires auth. Upserts a rating (1–5). Returns `{ avg_rating, rating_count }`.
-
-## Implementation notes
-- All endpoints must set CORS headers via the shared `http.js` helper — look at how other
- endpoints do it.
-- Use keyset pagination (cursor = last seen id) not offset.
-- The `avg_rating` field is computed via a JOIN or subquery against `skill_ratings`, not stored.
-- Apply `rate-limit.js` to POST endpoints (use the lightest available limiter for authenticated
- users — read the file to pick the right one).
-- Do not write any UI code.
-- Do not modify existing files other than adding the new `/api/skills/` files.
-
-## Verification
-1. Read each file back and confirm there are no syntax errors.
-2. Confirm all SQL uses the tagged-template `sql` from `db.js` (no raw string concatenation).
-3. Confirm auth is checked on every mutating endpoint.
-4. Confirm pagination is correct (cursor-based, not offset).
diff --git a/tasks/skills-marketplace/03-marketplace-modal.md b/tasks/skills-marketplace/03-marketplace-modal.md
deleted file mode 100644
index 69bb6316c..000000000
--- a/tasks/skills-marketplace/03-marketplace-modal.md
+++ /dev/null
@@ -1,108 +0,0 @@
-# Task 03 — UI: SkillsMarketplaceModal.svelte
-
-## Goal
-Build a Svelte modal component for the skills marketplace. It lives at
-`/chat/src/SkillsMarketplaceModal.svelte`. When done, users can browse community skills,
-search/filter by category, install/uninstall, rate, and publish their own skills — all from
-within the chat UI.
-
-## Prerequisites
-Tasks 01 and 02 must be complete (DB + API exist and are functional).
-
-## Context
-- Framework: Svelte 4 (not SvelteKit — plain Svelte components)
-- Styling: Tailwind CSS utility classes (same as the rest of the chat UI)
-- Existing components to study and reuse:
- - `/chat/src/Modal.svelte` — base modal wrapper, `export let open = false`
- - `/chat/src/ToolPackModal.svelte` — current (simple) tool pack modal — read it fully; the
- new component replaces the behaviour but not the file
- - `/chat/src/Button.svelte` — read it
- - `/chat/src/stores.js` — `toolSchema` (persisted writable of tool group array), `currentUser`,
- `notify()` — read the full file
-- The `toolSchema` store shape: an array of `{ name: string, schema: ToolDef[] }`.
- Each `ToolDef` matches the shape in `/chat/src/tools.js`.
-- API base: `/api/skills/` (built in Task 02).
-- This component does NOT import from `tools.js` — it fetches from the API instead.
-
-## Component spec
-
-### Props
-```svelte
-export let open = false; // bind:open from parent
-```
-
-### State (internal)
-- `view`: `'browse' | 'publish'` — tabs at the top
-- `skills`: array of skill objects from the API
-- `loading`: boolean
-- `searchQuery`: string (debounced, 300ms)
-- `selectedCategory`: string | null
-- `categories`: string[] derived from loaded skills
-- `page`: cursor string for pagination
-- `hasMore`: boolean
-- `publishForm`: `{ name, slug, description, category, tags, schemaText, isPublic }`
-- `publishError`: string | null
-- `publishLoading`: boolean
-
-### Layout
-
-#### Header
-- Tab bar: "Browse" | "Publish" — switching sets `view`
-- Close button (calls `open = false`)
-
-#### Browse view
-Left sidebar (~180px wide on desktop, collapsible to icons on narrow):
-- "All" category + dynamic list of categories from loaded skills
-- Show install count next to each category
-
-Main panel:
-- Search input at top (debounced)
-- Sort dropdown: Popular | Newest | A–Z
-- Skill card grid (2 cols desktop, 1 col mobile). Each card:
- - Name + category badge
- - Description (truncated at 2 lines)
- - Install count + avg rating (⭐ n.n, or "No ratings yet")
- - Author name (or "System" if null)
- - **Install / Remove button** — calls `/api/skills/:id/install` (POST) or DELETE
- - Optimistically toggles, rolls back on error
- - On install: appends the skill's `schema_json` to `toolSchema` store as `{ name, schema }`
- - On uninstall: removes from `toolSchema` by name match
- - Clicking anywhere else on the card opens an inline expanded view (below the card row)
- showing full description, tags, and a 1–5 star rating widget.
-
-Load more: "Load more" button at bottom (fetches next page using cursor).
-
-#### Publish view
-A form to publish a new skill:
-- Name input
-- Slug input (auto-derived from name, editable, shows live preview: `/skills/{slug}`)
-- Description textarea
-- Category input (text, with datalist suggestions from existing categories)
-- Tags input (comma-separated, shown as pills)
-- Schema editor: a `<textarea>` pre-filled with a JSON starter template
- (one tool entry matching the ToolDef shape). Monospace font.
- Below it, a "Validate JSON" button that parses and shows a green checkmark or red error.
-- Public/Private toggle
-- Submit button — POST to `/api/skills`
-
-On success: switch to Browse view, show a success notification via `notify()`, scroll to
-the new skill.
-
-### Error handling
-- API errors: show inline error message (not modal) next to the failing action
-- Auth required: if `$currentUser` is null, show "Sign in to install skills" inline — no redirect
-
-### No external dependencies
-Do not import any library not already in `/chat/package.json`. Use native `fetch`.
-
-## File to create
-`/chat/src/SkillsMarketplaceModal.svelte`
-
-## Verification
-1. Read back the file and confirm it is valid Svelte 4 syntax.
-2. Confirm `toolSchema` is correctly imported from `./stores.js` and updated on install/uninstall.
-3. Confirm the Publish form auto-derives slug from name (lowercase, replace spaces with `-`,
- strip non-alphanumeric except `-`).
-4. Confirm no hardcoded skills — all data comes from the `/api/skills` fetch.
-5. Confirm the component compiles (run `cd /workspaces/3D-Agent/chat && npm run build` and fix
- any errors before declaring done).
diff --git a/tasks/skills-marketplace/04-chat-integration.md b/tasks/skills-marketplace/04-chat-integration.md
deleted file mode 100644
index d57672d70..000000000
--- a/tasks/skills-marketplace/04-chat-integration.md
+++ /dev/null
@@ -1,98 +0,0 @@
-# Task 04 — Chat Integration: Wire Marketplace into Chat UI
-
-## Goal
-Replace the existing "Tool Packs" button/modal in the chat toolbar with the new Skills
-Marketplace modal. Installed skills from the marketplace must surface as active tools in the
-LLM conversation exactly like the current hardcoded tool packs.
-
-## Prerequisites
-Tasks 01, 02, and 03 must be complete.
-
-## Context — what exists today
-
-### ToolPackModal (current)
-- `/chat/src/ToolPackModal.svelte` — simple modal that installs hardcoded packs from `tools.js`
- into the `toolSchema` store. It stays in the codebase (don't delete it) but is no longer
- the primary entry point.
-
-### App.svelte (main chat component, ~63KB)
-- Located at `/chat/src/App.svelte`
-- Read the **entire file** before making any changes — it is large and dense.
-- Find where `ToolPackModal` is imported and rendered.
-- Find where the toolbar button that opens it is rendered.
-- Find where `toolSchema` is consumed to build the tool list sent to the LLM.
-
-### stores.js
-- `toolSchema` — persisted writable, shape: `Array<{ name: string, schema: ToolDef[] }>`
-- The new `SkillsMarketplaceModal` (Task 03) already writes to this store on install/uninstall.
-
-## Changes to make
-
-### 1. App.svelte — swap modal and button
-
-Find the import of `ToolPackModal` and add an import for `SkillsMarketplaceModal`:
-```js
-import SkillsMarketplaceModal from './SkillsMarketplaceModal.svelte';
-```
-
-Find the state variable that controls the ToolPackModal's `open` prop (it will be something
-like `let showToolPacks = false`). Add a parallel variable:
-```js
-let showSkillsMarketplace = false;
-```
-
-Find the toolbar button that opens ToolPackModal. Add a second button immediately after it:
-```svelte
-<button
- class="..." <!-- match the style of the existing tool-packs button exactly -->
- on:click={() => (showSkillsMarketplace = true)}
- title="Skills Marketplace"
->
- <!-- Use an appropriate icon from feather.js — "grid" or "package" works -->
- <svelte:component this={Icon} name="grid" size={16} />
- <span class="hidden sm:inline">Skills</span>
-</button>
-```
-
-Add the modal instance near the ToolPackModal instance:
-```svelte
-<SkillsMarketplaceModal bind:open={showSkillsMarketplace} />
-```
-
-### 2. Sync on open — pre-populate installed state
-When `showSkillsMarketplace` becomes true, the modal should show which skills are already
-installed (i.e. present in `toolSchema`). The `SkillsMarketplaceModal` already handles this by
-comparing API results against `$toolSchema` on the Browse fetch — no extra wiring needed.
-
-### 3. Verify toolSchema → LLM tools pipeline
-Search `App.svelte` for where `toolSchema` is read to build the tool array sent to the LLM
-provider (it likely maps over `$toolSchema` and flattens `.schema` arrays). Confirm it still
-works correctly — the marketplace installs skills in the same format as the existing ToolPackModal
-(`{ name, schema: ToolDef[] }`), so no change should be needed. If the pipeline looks different,
-document exactly what you found and adjust accordingly.
-
-### 4. Active skills indicator
-Find where the toolbar shows the count of active tools (if any). Update it to include
-marketplace-installed skills in the count. If no such indicator exists, add a simple badge
-on the Skills button showing `$toolSchema.length` when > 0:
-```svelte
-{#if $toolSchema.length > 0}
- <span class="ml-1 rounded-full bg-indigo-500 px-1.5 py-0.5 text-[10px] text-white">
- {$toolSchema.length}
- </span>
-{/if}
-```
-
-## Constraints
-- **Surgical changes only.** Touch only the lines needed. Do not reformat, refactor, or clean up
- unrelated code in App.svelte.
-- Do not remove or break the existing ToolPackModal — it should still work.
-- Do not change `stores.js`, `tools.js`, `convo.js`, or `providers.js`.
-- Match the exact class/style convention of the surrounding toolbar buttons.
-
-## Verification
-1. Run `cd /workspaces/3D-Agent/chat && npm run build` — must complete with no errors.
-2. Read back the changed section of App.svelte and confirm the new button and modal binding are
- present and syntactically correct.
-3. Confirm `ToolPackModal` is still imported and rendered (not removed).
-4. Confirm `showSkillsMarketplace` is initialised to `false`.
diff --git a/tasks/skills-marketplace/05-seed-and-categories.md b/tasks/skills-marketplace/05-seed-and-categories.md
deleted file mode 100644
index 5cf88ba87..000000000
--- a/tasks/skills-marketplace/05-seed-and-categories.md
+++ /dev/null
@@ -1,105 +0,0 @@
-# Task 05 — Seed Skills & Category Taxonomy
-
-## Goal
-Populate the skills marketplace with a rich set of seed skills so it is immediately useful when
-users open it. Also standardise the category list and add a categories endpoint. This task is
-primarily data + a small API addition.
-
-## Prerequisites
-Tasks 01 and 02 must be complete.
-
-## Part A — Expanded seed data migration
-
-Create `/api/_lib/migrations/2026-04-30-skills-seed.sql`.
-
-This migration inserts ready-to-use skills into `marketplace_skills`. All rows: `author_id = null`,
-`is_public = true`. Use `ON CONFLICT (slug) DO NOTHING` for idempotency.
-
-### Canonical categories (use exactly these strings)
-`finance`, `productivity`, `developer`, `data`, `media`, `utility`, `ai`
-
-### Skills to seed (build full valid `schema_json` for each)
-
-The `schema_json` must be a valid JSON array of tool definitions. Each element shape:
-```json
-{
- "clientDefinition": {
- "id": "unique-string",
- "name": "ToolName",
- "description": "...",
- "arguments": [{ "name": "arg", "type": "string", "description": "..." }],
- "body": "// JavaScript that returns { contentType, content } or a JSON-serialisable value"
- },
- "type": "function",
- "function": {
- "name": "ToolName",
- "description": "When to use this tool — written for the LLM",
- "parameters": {
- "type": "object",
- "properties": { "arg": { "type": "string", "description": "..." } },
- "required": ["arg"]
- }
- }
-}
-```
-
-**Skills to create:**
-
-1. **tradingview-charts** (finance) — interactive TradingView price chart iframe
-2. **web-search** (utility) — DuckDuckGo search returning abstract + top topics
-3. **qr-code** (utility) — renders a QR code image via `api.qrserver.com`
-4. **calculator** (utility) — safe `eval`-less expression evaluator (use Function constructor)
-5. **markdown-preview** (productivity) — renders user-supplied markdown as styled HTML in an iframe
-6. **color-palette** (media) — given a theme description, generates a 5-colour palette as swatches
-7. **json-formatter** (developer) — pretty-prints and validates JSON input
-8. **regex-tester** (developer) — tests a regex against input, highlights matches
-9. **unit-converter** (utility) — converts between common units (length, weight, temperature, etc.)
-10. **mermaid-diagram** (developer) — renders a Mermaid.js diagram in an iframe using the CDN build
-11. **csv-table** (data) — renders CSV input as an HTML table with sorting
-12. **world-clock** (utility) — shows current time in N timezones side-by-side
-13. **image-from-url** (media) — renders an image URL in a resizable preview iframe
-14. **base64-codec** (developer) — encodes/decodes base64
-15. **word-counter** (productivity) — counts words, chars, sentences, reading time
-
-For each skill's `body`: write actual working JavaScript (not pseudocode). The body runs in the
-browser sandbox and returns a value. For HTML-rendering tools, return `{ contentType: 'text/html', content: htmlString }`.
-
-## Part B — Categories API endpoint
-
-Create `/api/skills/categories.js` handling `GET /api/skills/categories`.
-
-No auth required.
-
-Response:
-```json
-{
- "categories": [
- { "slug": "finance", "label": "Finance", "count": 4 },
- { "slug": "productivity", "label": "Productivity", "count": 3 },
- ...
- ]
-}
-```
-
-Query: count of `is_public = true` skills per category, ordered by count desc.
-Include only categories with at least 1 public skill.
-
-Derive `label` from `slug` by title-casing.
-
-Cache-Control: `public, max-age=60` (categories change rarely).
-
-## Part C — Update SkillsMarketplaceModal to use categories API
-
-In `/chat/src/SkillsMarketplaceModal.svelte` (created in Task 03):
-
-Replace the client-side category derivation with a fetch to `/api/skills/categories` when the
-modal opens. This gives accurate counts even before skills are loaded.
-
-Change the existing `onMount` (or `$: if (open)` reactive block) to also fetch categories in
-parallel with the skills list fetch.
-
-## Verification
-1. Confirm the migration file is valid SQL (no JS syntax, proper JSON escaping in string literals).
-2. Confirm all 15 seed skills have valid `schema_json` — parse each manually.
-3. Run `cd /workspaces/3D-Agent/chat && npm run build` — must pass.
-4. Confirm categories endpoint returns correct structure.
diff --git a/tasks/skills-marketplace/06-skill-detail-and-ratings.md b/tasks/skills-marketplace/06-skill-detail-and-ratings.md
deleted file mode 100644
index 522bc285a..000000000
--- a/tasks/skills-marketplace/06-skill-detail-and-ratings.md
+++ /dev/null
@@ -1,99 +0,0 @@
-# Task 06 — UI: Skill Detail Panel & Ratings
-
-## Goal
-Add an expanded detail view inside the marketplace modal and a working star-rating widget.
-When a user clicks a skill card, a side panel (or inline expansion) shows full details,
-all tags, schema preview, author info, and lets the user leave a 1–5 star rating.
-
-## Prerequisites
-Tasks 01, 02, 03, 04, and 05 must be complete and building cleanly.
-
-## Context
-- File to edit: `/chat/src/SkillsMarketplaceModal.svelte`
-- Read the entire current file before changing anything.
-- API endpoints available (from Task 02):
- - `GET /api/skills/:id` — full skill including `schema_json`
- - `POST /api/skills/:id/rate` body `{ rating: 1-5 }` → `{ avg_rating, rating_count }`
-- `currentUser` store from `./stores.js` — null if not signed in
-- `notify` function from `./stores.js`
-
-## Changes
-
-### 1. SkillDetailPanel — inline expansion
-
-When the user clicks anywhere on a skill card (not the Install/Remove button), toggle an
-inline expansion directly below that card row. Only one card can be expanded at a time.
-
-The expanded panel contains:
-
-**Left column (60%)**
-- Full description (no truncation)
-- Tags as pills (styled with `bg-slate-100 text-slate-600 text-[11px] px-2 py-0.5 rounded-full`)
-- Author section: "By {author.display_name}" or "By the 3D-Agent team" if system skill
-- Install count + created date ("Published {relative date}")
-
-**Right column (40%)**
-- **Rating widget**: 5 stars, filled/empty based on `avg_rating`. If user is logged in and
- hasn't rated yet, the stars are interactive (hover highlights, click submits). Show current
- user's rating in a different colour if they've already rated.
- - On click: POST to `/api/skills/:id/rate`, update displayed avg/count on success.
- - If not logged in: stars are display-only with tooltip "Sign in to rate"
-- Schema preview: a `<pre>` block showing the first tool's `function.name` and
- `function.description`, and a list of its parameter names. **Do not show the full schema JSON**
- (it can be large). Just a human-readable summary.
-- If there are multiple tools in the schema, show "and N more tools" after the first.
-
-**Action row** (below both columns)
-- Same Install/Remove button as the card (redundant but more prominent)
-- A "Copy slug" button that writes the skill slug to clipboard and shows a brief "Copied!" toast
-
-### 2. Star rating component — extract as inline sub-component
-
-Write the star rating logic as a `<StarRating>` component defined inline in the file using
-Svelte's component syntax (not a separate file). Props:
-```svelte
-<!-- internal component -->
-let { value, interactive, onRate } = ...
-```
-
-If Svelte 4 doesn't support `$props()`, use `export let` props.
-
-Stars should animate on hover (scale 1.1 with CSS transition).
-
-### 3. Relative date helper
-
-Add a small helper function `relativeDate(isoString)` at the top of the `<script>` block:
-```js
-function relativeDate(iso) {
- const diff = Date.now() - new Date(iso).getTime();
- const days = Math.floor(diff / 86400000);
- if (days === 0) return 'today';
- if (days === 1) return 'yesterday';
- if (days < 30) return `${days} days ago`;
- if (days < 365) return `${Math.floor(days / 30)} months ago`;
- return `${Math.floor(days / 365)} years ago`;
-}
-```
-
-### 4. Loading state for detail fetch
-
-When a card is clicked, immediately show a skeleton loader in the expanded area while
-`GET /api/skills/:id` loads. The skeleton should be a simple grey animated pulse div
-(use `animate-pulse bg-slate-200 rounded` Tailwind classes).
-
-### 5. Keyboard accessibility
-- Pressing Escape while the detail panel is open should close it (not the whole modal).
-- The expanded card should have `role="region"` and `aria-label="{skill.name} details"`.
-
-## Constraints
-- All changes go in `SkillsMarketplaceModal.svelte` only. No new files.
-- Do not change any API files.
-- Do not change `App.svelte`.
-
-## Verification
-1. Run `cd /workspaces/3D-Agent/chat && npm run build` — must pass with no errors.
-2. Read back the changed file and confirm:
- - Only one card can be expanded at a time (clicking another card collapses the previous).
- - The rating POST is only triggered when the user is authenticated.
- - The "Copy slug" uses `navigator.clipboard.writeText` with a fallback.
- - The skeleton loader disappears once the detail fetch resolves.
diff --git a/tasks/skills-marketplace/07-installed-skills-toolbar.md b/tasks/skills-marketplace/07-installed-skills-toolbar.md
deleted file mode 100644
index ee95bd4b7..000000000
--- a/tasks/skills-marketplace/07-installed-skills-toolbar.md
+++ /dev/null
@@ -1,69 +0,0 @@
-# Task 07 — UI: Installed Skills Toolbar Chip Strip
-
-## Goal
-When one or more skills are installed (i.e. `$toolSchema.length > 0`), show a horizontal strip
-of chips just above the chat input bar listing each installed skill by name, with an × to remove
-it. This makes the active skill set visible at a glance without opening the modal.
-
-## Prerequisites
-Tasks 01–04 must be complete and building cleanly.
-
-## Context
-- File to edit: `/chat/src/App.svelte` (read the entire file first)
-- `toolSchema` store: `Array<{ name: string, schema: ToolDef[] }>` from `./stores.js`
-- Find where the chat input component (`<Input ...>` or equivalent) is rendered. The chip strip
- goes immediately above it, inside the same container.
-- The input area likely has classes like `border-t`, `px-4 py-2`, or similar — match the spacing.
-
-## What to build
-
-### Chip strip
-Add this block immediately above the chat input render point in App.svelte:
-
-```svelte
-{#if $toolSchema.length > 0}
- <div class="flex flex-wrap gap-1.5 px-4 pt-2 pb-0">
- {#each $toolSchema as group}
- <span class="inline-flex items-center gap-1 rounded-full border border-indigo-200 bg-indigo-50 px-2.5 py-0.5 text-[11px] font-medium text-indigo-700">
- {group.name}
- <button
- class="ml-0.5 rounded-full p-0.5 text-indigo-400 hover:bg-indigo-100 hover:text-indigo-600"
- on:click={() => removeSkill(group.name)}
- aria-label="Remove {group.name}"
- >
- <!-- feather x icon, 10px -->
- </button>
- </span>
- {/each}
- <button
- class="text-[11px] text-slate-400 hover:text-slate-600"
- on:click={() => (showSkillsMarketplace = true)}
- >
- + Add skill
- </button>
- </div>
-{/if}
-```
-
-### removeSkill helper
-Add this function in the App.svelte `<script>` block (near the other tool-related logic):
-```js
-function removeSkill(name) {
- toolSchema.update(groups => groups.filter(g => g.name !== name));
-}
-```
-
-### Icon
-Use the existing `feather.js` / `Icon` component pattern already used in App.svelte for the
-× icon (look at how other small × close buttons are done in the file and match exactly).
-
-## Constraints
-- Surgical: only add the chip strip block and the `removeSkill` function. Nothing else.
-- Do not change the layout of the input area itself.
-- `showSkillsMarketplace` is already declared in App.svelte from Task 04 — do not re-declare it.
-
-## Verification
-1. Run `cd /workspaces/3D-Agent/chat && npm run build` — must pass.
-2. Confirm the chip strip only renders when `$toolSchema.length > 0`.
-3. Confirm clicking × removes only that group from `toolSchema`.
-4. Confirm "+ Add skill" opens the marketplace modal.
diff --git a/tasks/task-01-test-runtime-tool-loop.md b/tasks/task-01-test-runtime-tool-loop.md
deleted file mode 100644
index 50216b982..000000000
--- a/tasks/task-01-test-runtime-tool-loop.md
+++ /dev/null
@@ -1,49 +0,0 @@
-# Task: Write Tests for the Agent Runtime Tool Loop
-
-## Context
-
-This is the `three.ws` 3D agent platform. The agent runtime lives in `src/runtime/`. It drives all LLM-powered agent behavior: sending messages to Claude, executing tool calls, and emitting protocol events. This core flow has **zero test coverage**.
-
-## Goal
-
-Write a vitest test suite for the agent runtime tool loop. Tests should live at `tests/src/runtime.test.js`.
-
-## Files to Read First
-
-- `src/runtime/index.js` (~236 lines) — the main runtime class and tool loop (`MAX_TOOL_ITERATIONS=8`)
-- `src/runtime/tools.js` (~174 lines) — `BUILTIN_TOOLS` definitions (wave, lookAt, play_clip, setExpression, speak, remember)
-- `src/runtime/providers.js` (~116 lines) — `AnthropicProvider` and `NullProvider`
-- `src/agent-protocol.js` — `AgentProtocol` event bus, `ACTION_TYPES`
-- `tests/src/agent-protocol.test.js` — existing test for reference on style/setup
-
-## What to Test
-
-### Tool loop behavior (`src/runtime/index.js`)
-1. Sends user message to provider and gets a response
-2. When provider returns a tool call, the runtime dispatches `perform-skill` on the protocol and calls the tool handler
-3. Tool loop terminates after `MAX_TOOL_ITERATIONS` (8) even if provider keeps returning tool calls
-4. When provider returns a text response (no tool call), loop ends and `speak` action is emitted
-5. `think` actions are emitted when provider streams thinking steps (if applicable)
-6. Error in tool handler emits `skill-error` on protocol and does not crash the loop
-
-### Built-in tools (`src/runtime/tools.js`)
-7. `speak` tool emits `speak` action on protocol with correct text/sentiment payload
-8. `remember` tool emits `remember` action on protocol with the provided memory entry
-9. `lookAt` tool emits `look-at` action with the correct target
-10. `setExpression` tool emits `emote` action with trigger and weight
-
-### NullProvider (`src/runtime/providers.js`)
-11. `NullProvider.complete()` returns an empty/noop response without calling any API
-
-## Approach
-
-- Use `NullProvider` (or a mock) to avoid real API calls — keep tests fully offline
-- Mock `AgentProtocol` or use a real instance and assert emitted events via `protocol.on()`
-- Use `vi.fn()` for tool handlers to assert they were called with correct args
-- Follow the existing test style in `tests/src/agent-protocol.test.js`
-
-## Success Criteria
-
-- `npm test tests/src/runtime.test.js` passes with all tests green
-- No real HTTP calls made during tests
-- Each test is isolated (no shared mutable state between tests)
diff --git a/tasks/task-02-test-mcp-server.md b/tasks/task-02-test-mcp-server.md
deleted file mode 100644
index 0f6f74093..000000000
--- a/tasks/task-02-test-mcp-server.md
+++ /dev/null
@@ -1,58 +0,0 @@
-# Task: Write Tests for the MCP Server
-
-## Context
-
-This is the `three.ws` 3D agent platform. The MCP server (`api/mcp.js`, 1,201 lines) implements the Model Context Protocol (MCP 2025-06-18) over JSON-RPC 2.0. It exposes 14 tools to external AI systems. It has **zero test coverage** despite being a critical external-facing API.
-
-## Goal
-
-Write a vitest test suite for the MCP server. Tests should live at `tests/api/mcp.test.js`.
-
-## Files to Read First
-
-- `api/mcp.js` — the full MCP server (read this carefully before writing any tests)
-- `api/_lib/auth.js` — `authenticateBearer()`, `getSessionUser()`
-- `tests/api/llm-anthropic.test.js` — existing API test for reference on style and how to mock Vercel serverless handlers
-- `tests/api/agents.test.js` — another reference for request/response mocking patterns
-
-## What to Test
-
-### Protocol layer
-1. `POST /api/mcp` with `method: "initialize"` returns protocol version, server info, and tool list
-2. `POST /api/mcp` with unknown method returns JSON-RPC error `-32601` (method not found)
-3. `POST /api/mcp` with malformed JSON returns JSON-RPC parse error `-32700`
-4. `DELETE /api/mcp` returns 200 (stateless session termination no-op)
-5. `GET /api/mcp` returns 405 (SSE not yet implemented)
-
-### Authentication
-6. `tools/call` without auth token returns 401 or appropriate JSON-RPC error
-7. `tools/call` with a valid bearer JWT succeeds for tools that require no scope
-8. `tools/call` for `list_my_avatars` (requires `avatars:read` scope) with a token lacking that scope returns a permission error
-
-### Tool: `search_public_avatars`
-9. Returns a list of agents when database has results (mock the DB call)
-10. Returns empty list when no results found
-
-### Tool: `validate_model`
-11. Returns validation results for a valid model URL (mock `safeFetchModel`)
-12. Returns SSRF error when URL resolves to a private IP address
-
-### Tool: `render_avatar`
-13. Returns HTML snippet containing `<model-viewer>` for a valid GLB URL
-
-### x402 payment flow
-14. Unauthenticated request for a paid tool returns 402 with `WWW-Authenticate` header
-15. Request with valid `X-PAYMENT` header passes payment check and proceeds to tool
-
-## Approach
-
-- Mock the Neon DB client to avoid real database calls
-- Mock `safeFetchModel` for model-related tools
-- Use the same request/response mock pattern as `tests/api/agents.test.js`
-- Create a helper `makeRpcRequest(method, params, authHeader?)` to reduce boilerplate
-
-## Success Criteria
-
-- `npm test tests/api/mcp.test.js` passes with all tests green
-- No real network or database calls
-- Auth paths (no token, wrong scope, valid token) all covered
diff --git a/tasks/task-03-test-auth-flow.md b/tasks/task-03-test-auth-flow.md
deleted file mode 100644
index e2adb89c3..000000000
--- a/tasks/task-03-test-auth-flow.md
+++ /dev/null
@@ -1,58 +0,0 @@
-# Task: Write Tests for the Auth Flow
-
-## Context
-
-This is the `three.ws` 3D agent platform. Authentication is handled by three systems: email/password sessions (`api/auth/[action].js`), SIWE/Ethereum wallet sign-in (`api/auth/siwe/[action].js`), and OAuth 2.1 with PKCE (`api/oauth/[action].js`). The shared auth helpers live in `api/_lib/auth.js` (291 lines). Some partial tests exist but critical paths are uncovered.
-
-## Goal
-
-Write or extend vitest tests for the auth flow. Check what already exists at `tests/api/oauth-authorize.test.js`, `tests/api/oauth-token.test.js`, and `tests/api/siwe.test.js`, then fill gaps. New tests go in the same files or new ones in `tests/api/`.
-
-## Files to Read First
-
-- `api/_lib/auth.js` — all auth helpers: `getSessionUser`, `authenticateBearer`, `mintAccessToken`, `issueRefreshToken`, `rotateRefreshToken`, `createSession`, `csrfTokenFor`, `verifyCsrfToken`, `hashPassword`, `verifyPassword`
-- `api/auth/[action].js` — login, logout, register, password reset, email verify
-- `api/auth/siwe/[action].js` — SIWE nonce + verify
-- `api/oauth/[action].js` — authorize, token, register, revoke, introspect
-- `tests/api/oauth-authorize.test.js` — read this first to understand what's already tested
-- `tests/api/oauth-token.test.js` — same
-- `tests/api/siwe.test.js` — same
-
-## What to Test (fill gaps only — don't duplicate existing coverage)
-
-### Auth helpers (`api/_lib/auth.js`)
-1. `mintAccessToken()` produces a JWT with correct `sub`, `scope`, `aud`, `exp` claims
-2. `authenticateBearer()` returns the token payload for a valid JWT
-3. `authenticateBearer()` throws/rejects for an expired JWT
-4. `authenticateBearer()` throws/rejects for a tampered JWT signature
-5. `csrfTokenFor()` + `verifyCsrfToken()` round-trip succeeds
-6. `verifyCsrfToken()` fails for a mismatched session
-
-### Email/password auth (`api/auth/[action].js`)
-7. `POST /api/auth/login` with valid credentials returns session cookie
-8. `POST /api/auth/login` with wrong password returns 401
-9. `POST /api/auth/register` creates user and returns session cookie
-10. `POST /api/auth/logout` clears session cookie
-
-### SIWE (`api/auth/siwe/[action].js`)
-11. `GET /api/auth/siwe/nonce` returns a fresh nonce and stores it (mock DB)
-12. `POST /api/auth/siwe/verify` with a valid EIP-4361 message + signature creates a session (mock signature verification)
-13. `POST /api/auth/siwe/verify` with an already-used nonce returns 401
-
-### OAuth 2.1 (fill gaps in existing tests)
-14. `POST /api/oauth/token` with `refresh_token` grant rotates the token and returns a new access token
-15. `POST /api/oauth/token` with a revoked refresh token returns 400
-16. `POST /api/oauth/introspect` returns `{ active: true }` for a valid token and `{ active: false }` for expired
-
-## Approach
-
-- Mock Neon DB with `vi.mock` or a test DB fixture
-- Mock `bcrypt`/`hashPassword` for speed in unit tests
-- For SIWE, mock the signature verification function — don't reconstruct real EIP-4361 signatures
-- JWT tests can use a test secret; real JWTs are fine to mint in tests
-
-## Success Criteria
-
-- All new/updated test files pass with `npm test`
-- No real DB or network calls
-- Auth error paths (wrong password, expired token, reused nonce) all covered
diff --git a/tasks/task-04-test-memory-system.md b/tasks/task-04-test-memory-system.md
deleted file mode 100644
index 7ea985cc0..000000000
--- a/tasks/task-04-test-memory-system.md
+++ /dev/null
@@ -1,60 +0,0 @@
-# Task: Write Tests for the Memory System
-
-## Context
-
-This is the `three.ws` 3D agent platform. Agents have a two-layer memory system:
-
-1. **Runtime store** (`src/agent-memory.js`, 260 lines) — in-memory with localStorage sync and async backend sync. Supports 4 entry types (`USER`, `FEEDBACK`, `PROJECT`, `REFERENCE`), salience × recency scoring, expiration, and fire-and-forget sync to the backend API.
-2. **Backend API** (`api/agent-memory.js`, 188 lines) — CRUD endpoints storing to `agent_memories` Postgres table.
-
-Both have **zero test coverage**.
-
-## Goal
-
-Write vitest test suites:
-- `tests/src/agent-memory.test.js` for the runtime store
-- `tests/api/agent-memory.test.js` for the backend API
-
-## Files to Read First
-
-- `src/agent-memory.js` — `AgentMemory` class: `add()`, `query()`, `_scheduleSync()`, localStorage integration, expiration
-- `api/agent-memory.js` — GET (list), POST (create), PUT (update), DELETE (soft-delete) handlers
-- `tests/src/manifest.test.js` — example of how to test a src/ module
-- `tests/api/agents.test.js` — example of how to mock API handler tests
-
-## What to Test
-
-### Runtime store (`src/agent-memory.js`)
-
-1. `add(entry)` stores entry in memory and returns an id
-2. `query({ type: 'USER' })` returns only USER-type entries
-3. `query({ tags: ['foo'] })` returns only entries with matching tags
-4. `query({ limit: 2 })` returns at most 2 results
-5. `query({ since: timestamp })` excludes entries older than the timestamp
-6. Expired entries (where `expiresAt` is in the past) are excluded from `query()` results
-7. Entries are sorted by salience × recency score (higher salience appears first)
-8. `add()` schedules a backend sync (assert `_scheduleSync` was called or that fetch was queued)
-9. On init, existing entries are loaded from localStorage if present
-10. `add()` persists entry to localStorage immediately
-
-### Backend API (`api/agent-memory.js`)
-
-11. `GET /api/agent-memory?agent_id=<id>` returns entries for that agent (mock DB)
-12. `GET /api/agent-memory` without auth returns 401
-13. `POST /api/agent-memory` creates a new memory entry and returns it with an `id`
-14. `POST /api/agent-memory` with missing required fields returns 400
-15. `PUT /api/agent-memory?id=<id>` updates the entry content/salience
-16. `DELETE /api/agent-memory?id=<id>` soft-deletes (sets `deleted_at`, not a hard row delete)
-17. Agent can only read/write their own memories (cross-agent access returns 403)
-
-## Approach
-
-- For runtime tests: mock `localStorage` with `vi.stubGlobal('localStorage', ...)` and mock `fetch` with `vi.stubGlobal('fetch', ...)`
-- For API tests: mock the Neon DB client; use the same req/res mock pattern as `tests/api/agents.test.js`
-- Use `vi.useFakeTimers()` for testing expiration and scheduling behavior
-
-## Success Criteria
-
-- `npm test tests/src/agent-memory.test.js tests/api/agent-memory.test.js` passes
-- No real localStorage, network, or DB calls
-- Expiration, scoring, and cross-agent isolation all explicitly covered
diff --git a/tasks/task-05-test-skills-registry.md b/tasks/task-05-test-skills-registry.md
deleted file mode 100644
index 4b7268550..000000000
--- a/tasks/task-05-test-skills-registry.md
+++ /dev/null
@@ -1,55 +0,0 @@
-# Task: Write Tests for the Skills Registry
-
-## Context
-
-This is the `three.ws` 3D agent platform. The skill system (`src/agent-skills.js`, 459 lines) is the plugin layer that lets agents perform actions beyond LLM text generation. External skills are loaded from URLs (IPFS, Arweave, HTTPS), gated by a trust mode (`any`, `owned-only`, `whitelist`), and executed with a rich context object. This file has **zero test coverage**.
-
-## Goal
-
-Write a vitest test suite at `tests/src/agent-skills.test.js`.
-
-## Files to Read First
-
-- `src/agent-skills.js` — `SkillRegistry` class: `install(spec, { bundleBase })`, trust modes, dependency loading, handler execution
-- `src/agent-protocol.js` — `AgentProtocol`, `ACTION_TYPES` (skills emit `perform-skill`, `skill-done`, `skill-error`)
-- `src/skill-manifest.js` — skill manifest format
-- `tests/src/agent-protocol.test.js` — reference for test style
-
-## What to Test
-
-### Installation & trust
-1. `install(spec)` in `any` trust mode accepts any skill regardless of origin
-2. `install(spec)` in `owned-only` mode rejects a skill whose origin doesn't match the agent owner
-3. `install(spec)` in `whitelist` mode rejects skills not in the whitelist
-4. `install(spec)` in `whitelist` mode accepts a skill that is on the whitelist
-5. Installing a skill with `dependencies` triggers recursive loading of each dependency URL (mock fetch)
-6. Installing the same skill name twice does not duplicate it in the registry
-
-### Skill execution
-7. Calling an installed skill invokes its `handler` with `(args, ctx)`
-8. The `ctx` object passed to the handler contains `speak`, `remember`, `fetch`, and `call`
-9. A successful handler result emits `skill-done` on the protocol with `{ skill, result: { success: true } }`
-10. A handler that throws emits `skill-error` on the protocol with the error message
-11. `ctx.speak(text)` emits a `speak` action on the protocol
-12. `ctx.remember(entry)` emits a `remember` action on the protocol
-
-### Skill lookup
-13. After installing, the skill is discoverable via the registry (e.g., `registry.get(name)` or equivalent)
-14. Requesting an uninstalled skill returns null/undefined (no crash)
-
-### Manifest loading
-15. A skill spec loaded from `ipfs://` URL is fetched and normalized correctly (mock fetch + IPFS gateway)
-16. A skill spec loaded from `https://` URL is fetched and normalized correctly (mock fetch)
-
-## Approach
-
-- Mock `fetch` with `vi.stubGlobal('fetch', ...)` to return fixture skill manifests
-- Use a real `AgentProtocol` instance and assert emitted events
-- Keep fixture skill specs minimal: `{ name, description, signature: [], handler: vi.fn() }`
-- Trust mode tests need a mock "agent owner" identity — pass it as constructor arg or mock the identity module
-
-## Success Criteria
-
-- `npm test tests/src/agent-skills.test.js` passes
-- Trust modes, dependency loading, execution lifecycle, and error handling all covered
-- No real network calls
diff --git a/tasks/task-07-erc8004-optimistic-registration.md b/tasks/task-07-erc8004-optimistic-registration.md
deleted file mode 100644
index 5c45bcd7f..000000000
--- a/tasks/task-07-erc8004-optimistic-registration.md
+++ /dev/null
@@ -1,46 +0,0 @@
-# Task: Eliminate the 15-Minute ERC-8004 Registration Delay
-
-## Context
-
-This is the `three.ws` 3D agent platform. When a user registers an agent on-chain via the ERC-8004 contract, the agent doesn't appear in the discovery index until the next cron job run (every 15 minutes). This is a poor UX — the user expects to see their agent immediately after paying gas and confirming the transaction.
-
-The cron job (`api/cron/[name].js`, function `handleErc8004Crawl`) polls the chain for `Registered` events in block ranges and inserts them into the `erc8004_registrations` Postgres table. The frontend registration happens in `src/erc8004/agent-registry.js` via `registerAgent()`.
-
-## Goal
-
-After a successful on-chain registration, immediately write the registration to the `erc8004_registrations` table via an API call — don't wait for the crawler.
-
-## Approach
-
-### Step 1 — Add a backend endpoint
-
-Create `api/erc8004/register-confirm.js` (new file):
-
-- Method: `POST /api/erc8004/register-confirm`
-- Auth: session cookie or bearer with `avatars:write` scope
-- Body: `{ chainId, txHash, agentId, metadataUri, ownerAddress }`
-- Verify the transaction: call the chain's RPC (`eth_getTransactionReceipt`) to confirm the tx was mined and emitted a `Registered` event from the expected contract address
-- If confirmed: upsert the row into `erc8004_registrations` (use `ON CONFLICT DO NOTHING` so the crawler never overwrites it)
-- Return `{ success: true }` or an error if the tx isn't mined yet
-
-You can find chain RPC URLs and registry contract addresses in `api/_lib/erc8004-chains.js`. The `Registered` event topic hash is `keccak256("Registered(uint256,string,address)")` — you can hardcode this.
-
-### Step 2 — Call the endpoint from the frontend
-
-In `src/erc8004/agent-registry.js`, after the transaction is confirmed (the code already waits for receipt), add a call to `POST /api/erc8004/register-confirm` with the tx details.
-
-### Step 3 — Trigger metadata enrichment immediately
-
-The crawler has a second phase: `erc8004EnrichMetadata()` which fetches `metadata_uri` and populates the agent's name/description/image. After inserting the row in step 1, immediately fetch and upsert the metadata in the same request handler (reuse whatever logic `erc8004EnrichMetadata` uses, or inline a simple version).
-
-## Constraints
-
-- Do not modify the crawler — it should continue to work as a safety net for any registrations that slip through
-- The `ON CONFLICT DO NOTHING` upsert in the endpoint means the crawler never causes duplicates
-- Keep the endpoint lightweight — if the tx isn't mined yet, return a clear error (don't poll)
-
-## Success Criteria
-
-- After calling `registerAgent()` in the frontend, the agent appears in the discovery index within ~5 seconds (one tx confirmation)
-- No duplicate rows when the crawler later processes the same registration
-- The `api/erc8004/register-confirm.js` file is ≤ 100 lines
diff --git a/tasks/task-08-voice-chat-integration.md b/tasks/task-08-voice-chat-integration.md
deleted file mode 100644
index 6231fb9d2..000000000
--- a/tasks/task-08-voice-chat-integration.md
+++ /dev/null
@@ -1,55 +0,0 @@
-# Task: Wire Voice Chat into the Main Agent Widget
-
-## Context
-
-This is the `three.ws` 3D agent platform. The main `<agent-3d>` web component (`src/element.js`) currently uses the Web Speech API for voice via `src/runtime/speech.js`. There is a separate, more capable voice system in `agent-voice-chat/` (Express + Socket.io, with Claude/Groq/OpenAI providers, conversation memory, and encryption). The floating widget UI already has a TTS toggle button but it just toggles Web Speech API on/off.
-
-The goal is to upgrade the floating widget's voice button so it opens a proper voice session backed by the `agent-voice-chat` server, with clear visual feedback.
-
-## Files to Read First
-
-- `src/runtime/speech.js` (406 lines) — current Web Speech API wrapper
-- `src/element.js` — `<agent-3d>` custom element; find where the TTS button is wired up
-- `agent-voice-chat/server.js` — Socket.io server entry point; understand the event protocol
-- `agent-voice-chat/room-manager.js` — how voice rooms/sessions are created
-- `agent-voice-chat/providers/` — stt.js, tts.js, claude.js; understand the pipeline
-
-## What to Build
-
-### 1. Voice session client (`src/runtime/voice-client.js`, new file)
-
-A thin Socket.io client that:
-- Connects to the `agent-voice-chat` server URL (configurable, defaults to same origin + `/voice`)
-- `start(agentId, config)` — joins a room for the given agent
-- `stop()` — leaves the room, disconnects socket
-- Captures microphone audio and sends chunks to the server via `audio:chunk` event
-- Receives `agent:speak` events from the server (text + TTS audio) and plays them
-- Fires a `voiceStateChange` CustomEvent on the element with `{ state: 'listening' | 'thinking' | 'speaking' | 'idle' }`
-
-Keep it under 150 lines. Do not re-implement TTS/STT — the server handles all of that.
-
-### 2. Wire it into `src/element.js`
-
-In the `<agent-3d>` element:
-- When the TTS button is clicked and `agent-voice-chat` server is available: use `VoiceClient` instead of `Speech`
-- When `agent-voice-chat` is not configured (no `voice-server` attribute): fall back to the existing Web Speech API behavior (no regression)
-- Add `voice-server` attribute to the element: `<agent-3d voice-server="https://..." ...>`
-- Show a visual indicator: button ring color changes based on `voiceStateChange` state (`listening` = green, `thinking` = yellow, `speaking` = blue, `idle` = gray)
-
-### 3. Update the floating widget HTML
-
-The TTS button currently has this title: `"TTS off — click to enable voice"`. Update it so when voice is active it reads `"Voice active — click to stop"`. Wire the visual state ring to the button's CSS.
-
-## Constraints
-
-- Do not modify `agent-voice-chat/` server code
-- Do not remove or break the existing Web Speech API fallback
-- Do not add Socket.io to the main bundle if `voice-server` attribute is absent — lazy-import it
-- Keep `voice-client.js` focused: connect, stream audio, receive speech. No UI logic in it.
-
-## Success Criteria
-
-- `<agent-3d voice-server="/voice" ...>` uses the voice chat server for voice
-- `<agent-3d ...>` (no attribute) falls back to Web Speech API as before
-- Visual states (idle/listening/thinking/speaking) are reflected on the TTS button
-- No new bundle size cost when the `voice-server` attribute is absent
diff --git a/tasks/task-10-agent-to-agent-communication.md b/tasks/task-10-agent-to-agent-communication.md
deleted file mode 100644
index cda2e9261..000000000
--- a/tasks/task-10-agent-to-agent-communication.md
+++ /dev/null
@@ -1,77 +0,0 @@
-# Task: Agent-to-Agent Communication via Skills
-
-## Context
-
-This is the `three.ws` 3D agent platform. Agents execute skills via `src/agent-skills.js`. Each skill handler receives a context object `ctx` with helpers like `ctx.speak()`, `ctx.remember()`, `ctx.fetch()`. Currently, there is no way for one agent to delegate work to another agent programmatically.
-
-The event bus (`src/agent-protocol.js`) is local to a single `<agent-3d>` element. The backend has agent data via `GET /api/agents/:id`. The MCP server (`api/mcp.js`) already has a `search_public_avatars` tool.
-
-## Goal
-
-Add `ctx.call(agentId, message)` to the skill execution context so skills can send a message to another agent and receive its response. This enables delegation: a user-facing agent can hand off specialized tasks (e.g., a trading agent calling a research agent).
-
-## What to Build
-
-### 1. Backend endpoint: `api/agent-delegate.js` (new file)
-
-`POST /api/agent-delegate`
-
-- Auth: bearer with any valid scope (agent-to-agent calls are authenticated as the calling agent's session)
-- Body: `{ fromAgentId, toAgentId, message, context? }`
-- Looks up `toAgentId` in the DB, loads its manifest (system prompt, model config)
-- Runs a single LLM turn: sends `message` to the target agent's configured Claude model with the target agent's system prompt
-- Returns `{ response: string, agentId: toAgentId }`
-- Rate limit: 10 delegate calls per agent per minute (use existing `limits` helper)
-- Do not recurse: if the delegated turn itself tries to call `agent-delegate`, reject with 400
-
-### 2. Add `ctx.call()` to `src/agent-skills.js`
-
-In the skill context builder (wherever `ctx` is assembled), add:
-
-```js
-ctx.call = async (agentId, message) => {
- const res = await fetch('/api/agent-delegate', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json', ...authHeaders },
- body: JSON.stringify({ fromAgentId: currentAgentId, toAgentId: agentId, message })
- })
- if (!res.ok) throw new Error(`Delegate call failed: ${res.status}`)
- const { response } = await res.json()
- return response
-}
-```
-
-### 3. Add `call_agent` to the MCP tool catalog (`api/mcp.js`)
-
-Add a new MCP tool so external AI systems can also use agent-to-agent delegation:
-
-```json
-{
- "name": "call_agent",
- "description": "Send a message to another three.ws agent and get its response. Use this to delegate specialized tasks.",
- "inputSchema": {
- "type": "object",
- "properties": {
- "agent_id": { "type": "string", "description": "The agent's ID" },
- "message": { "type": "string", "description": "The message to send" }
- },
- "required": ["agent_id", "message"]
- }
-}
-```
-
-Scope required: `avatars:read`. Implementation: call `POST /api/agent-delegate` internally.
-
-## Constraints
-
-- No recursion: the delegate endpoint must check for a `X-Delegate-Depth` header and reject if depth > 0
-- The delegated agent uses its own system prompt and model config — not the calling agent's
-- Do not stream the delegate response — return it as a complete string
-- `api/agent-delegate.js` should be ≤ 80 lines
-
-## Success Criteria
-
-- A skill can call `await ctx.call('agent-id-123', 'What is the market cap of SOL?')` and receive a string response
-- The MCP `call_agent` tool works via `POST /api/mcp`
-- Recursive delegation (A → B → A) is rejected with a clear error
-- Rate limiting is enforced (11th call within a minute returns 429)
diff --git a/tasks/walk/01-walk-avatar-url-param.md b/tasks/walk/01-walk-avatar-url-param.md
deleted file mode 100644
index e78976707..000000000
--- a/tasks/walk/01-walk-avatar-url-param.md
+++ /dev/null
@@ -1,24 +0,0 @@
-# Task 01 — Walk Page: ?avatar= URL Parameter Support
-
-## Priority: URGENT
-
-## Objective
-The existing `/walk` page must fully support loading any avatar by ID via the `?avatar=<uuid>` query parameter. When the URL `/walk?avatar=bacff13e-b64b-4ac0-860d-44f0168ad23b` is opened, the page must fetch that avatar's GLB from the three.ws avatar API, load it into the Three.js scene, and begin the walk experience with that avatar immediately — no login required to view.
-
-## Scope
-- File: `pages/walk.html` and its corresponding JS entry (likely `src/walk.js` or inline script in that page)
-- On page load, parse `new URLSearchParams(location.search).get('avatar')`
-- Fetch `/api/avatars/<id>` to resolve the avatar's GLB URL
-- Load the GLB into the existing Three.js walk scene using the existing loader pipeline
-- If no `?avatar=` param, fall back to the current default avatar (do not break the default flow)
-- If the avatar ID is invalid or the fetch fails, show a real error state with a "try another avatar" CTA — no silent failures
-
-## Definition of Done
-- `https://three.ws/walk?avatar=bacff13e-b64b-4ac0-860d-44f0168ad23b` loads that specific avatar and it walks
-- Network tab shows a real API call to `/api/avatars/<id>`
-- Works on mobile (joystick controls) and desktop (WASD/arrow keys)
-- No console errors
-- No mocks, no hardcoded avatar paths
-
-## 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.
diff --git a/tasks/walk/03-walk-embed-iframe.md b/tasks/walk/03-walk-embed-iframe.md
deleted file mode 100644
index f00f6be11..000000000
--- a/tasks/walk/03-walk-embed-iframe.md
+++ /dev/null
@@ -1,26 +0,0 @@
-# Task 03 — Walk Embed: Iframe-Ready Walking Avatar
-
-## Priority: URGENT
-
-## Objective
-Create a dedicated embeddable walk page at `/walk-embed` (new file `pages/walk-embed.html`) that is stripped of all navigation, footer, and chrome — just the Three.js canvas, the joystick, and the avatar. This page must be safe to embed in any `<iframe>` on any origin.
-
-## Scope
-- New file: `pages/walk-embed.html` + `src/walk-embed.js`
-- Route: add `/walk-embed` to `vercel.json` routes
-- Accepts `?avatar=<uuid>` — loads that avatar via real API
-- Accepts `?bg=<hex>` — sets canvas background color (default transparent/black)
-- Accepts `?controls=joystick|keyboard|none` — enables appropriate controls
-- Accepts `?autoplay=true` — avatar walks forward on load without user input
-- No nav, no footer, no login prompts
-- Sets `frame-ancestors *` in response headers (or ensure vercel.json doesn't block iframes)
-- Communicates with parent window via `postMessage`: emits `{ type: 'walk:ready' }` when loaded, `{ type: 'walk:position', x, z }` on each position update
-
-## Definition of Done
-- `<iframe src="https://three.ws/walk-embed?avatar=<id>">` embeds cleanly on a blank HTML page
-- Avatar loads and walks with joystick on mobile, WASD on desktop
-- postMessage events verified in browser console of the parent page
-- No X-Frame-Options or CSP blocking the embed
-
-## 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.
diff --git a/tasks/walk/04-walk-embed-sdk.md b/tasks/walk/04-walk-embed-sdk.md
deleted file mode 100644
index 1564a04aa..000000000
--- a/tasks/walk/04-walk-embed-sdk.md
+++ /dev/null
@@ -1,27 +0,0 @@
-# Task 04 — Walk Embed SDK: One-Line JS Embed
-
-## Priority: URGENT
-
-## Objective
-Build a JavaScript embed SDK (`public/walk-embed-sdk.js`) that anyone can drop into their website with a single `<script>` tag to embed a walking avatar. Similar to how Intercom or Drift embed — one script, zero configuration required, avatar appears as a floating 3D character on the page.
-
-## Scope
-- File: `public/walk-embed-sdk.js` (must be bundled, no external deps at runtime)
-- Usage: `<script src="https://three.ws/walk-embed-sdk.js" data-avatar="<uuid>"></script>`
-- Script reads `data-avatar` attribute from its own `<script>` tag
-- Injects a fixed-position `<iframe>` (bottom-right corner, 200×300px default) pointing to `/walk-embed?avatar=<id>&controls=none&autoplay=true`
-- Exposes `window.ThreeWalkAvatar` global: `{ mount(el), unmount(), setAvatar(id), setSize(w,h), setPosition('bottom-left'|...) }`
-- Accepts optional `data-position`, `data-width`, `data-height` attributes on the script tag
-- Listens for `postMessage` from the iframe and re-emits as `CustomEvent` on `document`: `new CustomEvent('walk:position', { detail: { x, z } })`
-- Works on any website (no framework dependencies)
-- Minified build goes to `dist/walk-embed-sdk.min.js` — add a Vite build config entry for this
-
-## Definition of Done
-- Drop the script tag on a blank `index.html` → avatar appears floating in corner
-- `window.ThreeWalkAvatar.setAvatar('new-id')` swaps avatar live
-- `window.ThreeWalkAvatar.setPosition('bottom-left')` moves it
-- Zero console errors on host page
-- Bundle < 10 KB (it's just an iframe injector)
-
-## 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.
diff --git a/tasks/walk/21-embed-page-walking-avatar.md b/tasks/walk/21-embed-page-walking-avatar.md
deleted file mode 100644
index 07daae52c..000000000
--- a/tasks/walk/21-embed-page-walking-avatar.md
+++ /dev/null
@@ -1,34 +0,0 @@
-# Task 21 — Embed Page: Walking Avatar Mode for /embed
-
-## Priority: URGENT
-
-## Objective
-Extend the existing `/embed` page (`pages/embed.html` → `public/embed/`) to support a "walking avatar" embed mode in addition to whatever current modes exist. The embed snippet generator UI must offer a "Walking" option alongside Static/Idle/Chat.
-
-## Scope
-- Files: `pages/embed.html`, `pages/a-embed.html`, `pages/agent-embed.html`, `pages/avatar-embed.html`, `src/agent-embed-modal.js` (audit all and apply changes consistently)
-- Add new embed mode `walking` to whatever mode enum exists in the embed system
-- Walking mode embed snippet:
- ```html
- <iframe src="https://three.ws/walk-embed?avatar=<id>&controls=joystick&autoplay=true" width="320" height="480" style="border:0;border-radius:16px"></iframe>
- ```
- (uses the embed page from task 03)
-- Generator UI:
- - Mode toggle (Static | Idle | Chat | Walking)
- - When Walking selected, expose: controls (joystick/keyboard/none), background (color picker), size (S/M/L/custom), autoplay (toggle), environment (dropdown from task 18)
- - Live preview pane on the right showing the embed exactly as it would render
- - "Copy snippet" button → real copy to clipboard via `navigator.clipboard.writeText`
-- Add a second snippet variant for the JS embed SDK from task 04:
- ```html
- <script src="https://three.ws/walk-embed-sdk.js" data-avatar="<id>"></script>
- ```
-
-## Definition of Done
-- Open `https://three.ws/embed?avatar=<id>` → Walking mode is selectable
-- Live preview accurately reflects the snippet
-- Snippet copies to clipboard
-- Pasting snippet into a fresh `index.html` renders the walking avatar correctly
-- No console errors
-
-## Rules
-Complete 100%. No stubs. No fake data. Real preview, real copy, real embed. Wire end-to-end.
diff --git a/tasks/wallet-transactions/01-wallet-provider-store.md b/tasks/wallet-transactions/01-wallet-provider-store.md
deleted file mode 100644
index 684f64c29..000000000
--- a/tasks/wallet-transactions/01-wallet-provider-store.md
+++ /dev/null
@@ -1,50 +0,0 @@
-# Task 01 — Wallet Provider Store
-
-## Goal
-Expose a reactive Svelte store that tracks which wallet is currently connected (type, address, chainId). Tool bodies and other components can read this store instead of parsing `currentUser` or polling `window.solana`/`window.ethereum` directly.
-
-## Context
-- `chat/src/stores.js` holds all app-wide Svelte stores. `currentUser` already exists but only holds the server-side user record — it does not carry which wallet type is connected or the live provider reference.
-- `chat/src/walletAuth.js` exports `signInWithEVM()` and `signInWithSolana()`. Both return `{ user, wallet }` where `wallet = { type: 'evm'|'solana', address, chainId? }`.
-- `chat/src/WalletConnect.svelte` calls those functions and then calls `loadCurrentUser()` but does not persist the wallet object anywhere.
-- Tool bodies (eval'd JavaScript strings in `tools.js`) run in the browser and can call `import { get } from 'svelte/store'` or read a plain `window.__wallet` global.
-
-## Changes Required
-
-### 1. `chat/src/stores.js`
-Add after the `currentUser` store definition:
-
-```js
-export const walletProvider = writable(null);
-// Shape: { type: 'solana'|'evm', address: string, chainId?: number|string } | null
-```
-
-Add a helper used by tool bodies:
-```js
-export function getConnectedWallet() {
- return get(walletProvider);
-}
-```
-
-Also expose it as a browser global so eval'd tool bodies can access it without imports:
-At the bottom of the file add:
-```js
-if (typeof window !== 'undefined') {
- walletProvider.subscribe(w => { window.__wallet = w; });
-}
-```
-
-### 2. `chat/src/WalletConnect.svelte`
-- Import `walletProvider` from `./stores.js`
-- After successful `signInWithEVM()`: call `walletProvider.set(wallet)`
-- After successful `signInWithSolana()`: call `walletProvider.set(wallet)`
-- On sign-out (when `signOut()` is called): call `walletProvider.set(null)`
-
-### 3. `chat/src/walletAuth.js`
-No changes needed — `signInWithEVM` and `signInWithSolana` already return the `wallet` object with the right shape. The WalletConnect component is responsible for storing it.
-
-## Verification
-- After connecting a Solana wallet, `window.__wallet` in the browser console should be `{ type: 'solana', address: '...' }`.
-- After connecting an EVM wallet, `window.__wallet.type === 'evm'` and `window.__wallet.chainId` is present.
-- After sign-out, `window.__wallet === null`.
-- No other stores or components should be changed.
diff --git a/tasks/wallet-transactions/02-tx-approval-modal.md b/tasks/wallet-transactions/02-tx-approval-modal.md
deleted file mode 100644
index adcc39c8a..000000000
--- a/tasks/wallet-transactions/02-tx-approval-modal.md
+++ /dev/null
@@ -1,68 +0,0 @@
-# Task 02 — Transaction Approval Modal
-
-## Goal
-Create a `TxApprovalModal.svelte` component that shows transaction details and Ask/Reject buttons before any wallet transaction executes. Wire it into `App.svelte` via a global `window.requestWalletApproval(details)` function that returns a Promise — tool bodies call this function to pause execution until the user approves or rejects.
-
-## Context
-- Tool bodies in `tools.js` are eval'd JavaScript strings that run in the browser. They can call `window.*` globals freely.
-- `chat/src/Choice.svelte` shows a similar "pause and wait for user input" pattern — study its props and how `Toolcall.svelte` renders it for reference style.
-- `chat/src/Modal.svelte` is an existing modal shell — use it as the outer wrapper.
-- `chat/src/Button.svelte` is the standard button component.
-- `chat/src/App.svelte` is where global UI overlays are mounted (search for where `<Notifications />` is rendered — add the modal nearby).
-
-## `TxApprovalModal.svelte` — New File at `chat/src/TxApprovalModal.svelte`
-
-Props:
-```js
-export let details; // { network, from, to, amount, token, memo?, estimatedFee? }
-export let onApprove; // () => void
-export let onReject; // () => void
-```
-
-UI layout (use existing Tailwind classes that match the app's dark slate aesthetic):
-- Title: "Approve Transaction"
-- Network badge: e.g. "Solana" or "Ethereum / Base / etc."
-- Table of rows: From, To, Amount, Token, Memo (if present), Estimated Fee (if present)
-- Long addresses: truncate to first 6 + `…` + last 4 chars
-- Two full-width buttons at bottom: "Reject" (secondary/outline) and "Approve" (primary/accent)
-- Disabled state on both buttons while a `pending` flag is true (set true on Approve click, to prevent double-submit)
-
-## `App.svelte` Changes
-
-1. Import `TxApprovalModal`.
-2. Add reactive vars:
- ```js
- let txApprovalDetails = null;
- let txApprovalResolve = null;
- let txApprovalReject = null;
- ```
-3. In `onMount` (or a top-level `if (typeof window !== 'undefined')` block), assign:
- ```js
- window.requestWalletApproval = (details) => new Promise((resolve, reject) => {
- txApprovalDetails = details;
- txApprovalResolve = resolve;
- txApprovalReject = reject;
- });
- ```
-4. Mount the modal conditionally in the template:
- ```svelte
- {#if txApprovalDetails}
- <TxApprovalModal
- details={txApprovalDetails}
- onApprove={() => { txApprovalResolve(); txApprovalDetails = null; }}
- onReject={() => { txApprovalReject(new Error('User rejected transaction')); txApprovalDetails = null; }}
- />
- {/if}
- ```
- Render this at the very end of the `<body>` content so it overlays everything.
-
-## Verification
-- Open the browser console and run:
- ```js
- window.requestWalletApproval({ network: 'Solana', from: 'ABC123', to: 'XYZ789', amount: 1.5, token: 'SOL' })
- .then(() => console.log('approved'))
- .catch(e => console.log('rejected:', e.message));
- ```
- The modal should appear. Clicking Approve logs "approved". Clicking Reject logs "rejected: User rejected transaction".
-- The modal must be centered/overlaid on the full viewport with a dark backdrop.
-- No existing functionality in App.svelte should change.
diff --git a/tasks/wallet-transactions/03-tx-result-display.md b/tasks/wallet-transactions/03-tx-result-display.md
deleted file mode 100644
index 59e6178fd..000000000
--- a/tasks/wallet-transactions/03-tx-result-display.md
+++ /dev/null
@@ -1,94 +0,0 @@
-# Task 03 — Transaction Result Display in Toolcall
-
-## Goal
-Add a `tx_result` display type to `Toolcall.svelte` so wallet transaction tool results render as a clean status card (hash, explorer link, amount, status badge) instead of raw JSON.
-
-## Context
-- `chat/src/Toolcall.svelte` already handles `image`, `webpage`, `markdown`, and `choice` display types by checking `toolresponse.content.contentType`.
-- Tool bodies return `{ contentType: 'application/tx-result', content: { ... } }` to trigger this display type.
-- Explorer base URLs by network:
- - `solana` mainnet: `https://solscan.io/tx/`
- - `solana` devnet: `https://solscan.io/tx/?cluster=devnet`
- - EVM chain 1 (Ethereum): `https://etherscan.io/tx/`
- - EVM chain 8453 (Base): `https://basescan.org/tx/`
- - EVM chain 10 (Optimism): `https://optimistic.etherscan.io/tx/`
- - EVM chain 42161 (Arbitrum): `https://arbiscan.io/tx/`
- - EVM chain 137 (Polygon): `https://polygonscan.com/tx/`
-
-## Expected `content` Shape
-```js
-{
- status: 'success' | 'failed' | 'pending',
- txHash: string, // Solana signature or EVM 0x... hash
- network: string, // 'solana' | 'ethereum' | 'base' | etc.
- chainId?: number, // EVM only
- from: string,
- to: string,
- amount: string, // human-readable, e.g. "1.5"
- token: string, // e.g. "SOL", "USDC", "ETH"
- explorerUrl: string, // full URL to block explorer
-}
-```
-
-## Changes to `chat/src/Toolcall.svelte`
-
-### 1. Detection logic
-In the reactive block that sets `displayType`, add:
-```js
-} else if (contentType === 'application/tx-result') {
- displayType = 'tx_result';
-}
-```
-
-### 2. Template block
-In the `{#if !collapsable || toolcall.expanded}` section, add a new branch after the `'choice'` block:
-
-```svelte
-{:else if toolresponse && displayType === 'tx_result'}
- <div class="flex flex-col rounded-b-lg border border-t-0 border-slate-200 px-5 py-4 gap-3">
- <!-- Status badge -->
- <div class="flex items-center gap-2">
- {#if displayedContent.status === 'success'}
- <span class="rounded-full bg-emerald-100 px-2.5 py-0.5 text-xs font-medium text-emerald-700">Confirmed</span>
- {:else if displayedContent.status === 'pending'}
- <span class="rounded-full bg-yellow-100 px-2.5 py-0.5 text-xs font-medium text-yellow-700">Pending</span>
- {:else}
- <span class="rounded-full bg-red-100 px-2.5 py-0.5 text-xs font-medium text-red-700">Failed</span>
- {/if}
- <span class="text-sm font-medium text-slate-700">{displayedContent.amount} {displayedContent.token}</span>
- <span class="text-xs text-slate-400">on {displayedContent.network}</span>
- </div>
-
- <!-- Addresses -->
- <div class="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs text-slate-600 font-mono">
- <span class="text-slate-400 font-sans">From</span>
- <span>{displayedContent.from?.slice(0,6)}…{displayedContent.from?.slice(-4)}</span>
- <span class="text-slate-400 font-sans">To</span>
- <span>{displayedContent.to?.slice(0,6)}…{displayedContent.to?.slice(-4)}</span>
- </div>
-
- <!-- Tx hash + explorer link -->
- <div class="flex items-center gap-2 text-xs font-mono text-slate-500">
- <span>{displayedContent.txHash?.slice(0,12)}…{displayedContent.txHash?.slice(-6)}</span>
- <a
- href={displayedContent.explorerUrl}
- target="_blank"
- rel="noopener noreferrer"
- class="ml-auto whitespace-nowrap rounded border border-slate-200 px-2 py-0.5 text-[10px] font-sans text-slate-600 hover:bg-slate-50 transition-colors"
- >
- View on Explorer ↗
- </a>
- </div>
- </div>
-{/if}
-```
-
-### 3. `displayedContent` assignment
-The existing reactive block already sets `displayedContent = toolresponse.content.content`. For `tx_result`, the full object IS the content — make sure the assignment in the block uses `displayedContent = toolresponse.content.content` which should already be the parsed object if the tool returns it correctly.
-
-If `toolresponse.content` is the raw object (i.e., `{ contentType: 'application/tx-result', content: { status, txHash, ... } }`), then `displayedContent = toolresponse.content.content` is already correct.
-
-## Verification
-- No existing display types (image, webpage, markdown, choice) should be affected.
-- A tool response with `contentType: 'application/tx-result'` renders the card, not raw JSON.
-- The "View code / View component" toggle button still works for this display type.
diff --git a/tasks/wallet-transactions/04-solana-tx-api.md b/tasks/wallet-transactions/04-solana-tx-api.md
deleted file mode 100644
index b34b63f99..000000000
--- a/tasks/wallet-transactions/04-solana-tx-api.md
+++ /dev/null
@@ -1,130 +0,0 @@
-# Task 04 — Backend: Solana Transaction Builder API
-
-## Goal
-Create a single API file `api/tx/solana/[action].js` with two endpoints:
-- `POST /api/tx/solana/build-transfer` — builds a serialized Solana transaction for SOL or SPL token transfer
-- `POST /api/tx/solana/build-swap` — fetches a swap transaction from Jupiter v6 for any token pair
-
-The frontend tool body will call these endpoints, receive a base64-encoded serialized transaction, have the user sign it via `window.solana`, then broadcast it.
-
-## Context
-- Existing API files (e.g., `api/payments/solana/[action].js`) use helpers from `api/_lib/`:
- - `cors`, `json`, `method`, `readJson`, `wrap`, `error` from `api/_lib/http.js`
- - `getSessionUser` from `api/_lib/auth.js`
- - `parse` + `z` (zod) from `api/_lib/validate.js`
- - `limits`, `clientIp` from `api/_lib/rate-limit.js`
-- Solana RPC env vars: `SOLANA_RPC_URL` (mainnet), `SOLANA_RPC_URL_DEVNET`
-- Available npm packages (already in package.json or resolvable): `@solana/web3.js`, `@solana/spl-token`
-
-## `api/tx/solana/[action].js`
-
-### Imports
-```js
-import { z } from 'zod';
-import {
- Connection, PublicKey, Transaction, SystemProgram, LAMPORTS_PER_SOL,
- sendAndConfirmTransaction
-} from '@solana/web3.js';
-import {
- getOrCreateAssociatedTokenAccount, createTransferInstruction,
- getMint, getAssociatedTokenAddress
-} from '@solana/spl-token';
-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
-import { getSessionUser } from '../../_lib/auth.js';
-import { limits, clientIp } from '../../_lib/rate-limit.js';
-import { parse } from '../../_lib/validate.js';
-```
-
-### `handleBuildTransfer`
-
-Schema:
-```js
-const transferSchema = z.object({
- sender: z.string(), // base58 sender public key
- recipient: z.string(), // base58 recipient public key
- amount: z.number().positive(), // human-readable (e.g. 1.5 SOL or 10 USDC)
- token: z.string().default('SOL'), // 'SOL' or SPL mint address
- memo: z.string().optional(),
- network: z.enum(['mainnet', 'devnet']).default('mainnet'),
-});
-```
-
-Logic:
-1. Validate auth: require `getSessionUser` (return 401 if not signed in).
-2. Build `Connection` from RPC URL based on network.
-3. If `token === 'SOL'`:
- - `SystemProgram.transfer({ fromPubkey, toPubkey, lamports: amount * LAMPORTS_PER_SOL })`
-4. If token is an SPL mint address:
- - Get sender ATA: `getAssociatedTokenAddress(mint, senderPubkey)`
- - Get recipient ATA: `getAssociatedTokenAddress(mint, recipientPubkey)`
- - Get mint decimals via `getMint(connection, mint)`
- - Build `createTransferInstruction(senderATA, recipientATA, senderPubkey, amountInSmallestUnit)`
- - Note: the transaction includes creating the recipient ATA if it doesn't exist (add `createAssociatedTokenAccountInstruction` if needed, checking `connection.getAccountInfo(recipientATA)`)
-5. Fetch recent blockhash: `connection.getLatestBlockhash()`
-6. Assemble `Transaction`, set `feePayer = senderPubkey`, set `recentBlockhash`
-7. If memo is provided, add a memo instruction using the SPL Memo program: `new TransactionInstruction({ keys: [], programId: new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'), data: Buffer.from(memo, 'utf-8') })`
-8. Serialize: `tx.serialize({ requireAllSignatures: false })` → base64
-9. Return:
-```js
-json(res, 200, {
- transaction: base64EncodedTx,
- network,
- blockhash: latestBlockhash.blockhash,
- lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
-});
-```
-
-### `handleBuildSwap`
-
-Schema:
-```js
-const swapSchema = z.object({
- sender: z.string(), // base58 wallet pubkey
- inputMint: z.string(), // token mint to sell
- outputMint: z.string(), // token mint to buy
- amount: z.number().positive(), // human-readable input amount
- slippageBps: z.number().int().min(1).max(5000).default(50),
- network: z.enum(['mainnet']).default('mainnet'), // Jupiter only supports mainnet
-});
-```
-
-Logic:
-1. Require auth.
-2. Get mint decimals for `inputMint` via RPC to compute `amountInSmallestUnit`.
-3. Fetch Jupiter v6 quote:
- ```
- GET https://quote-api.jup.ag/v6/quote?inputMint={inputMint}&outputMint={outputMint}&amount={amountInSmallestUnit}&slippageBps={slippageBps}
- ```
-4. If quote fails or no routes, return 422 with `{ error: 'no_route', message: 'No swap route found' }`.
-5. Fetch swap transaction from Jupiter:
- ```
- POST https://quote-api.jup.ag/v6/swap
- Body: { quoteResponse: <quote>, userPublicKey: sender, wrapAndUnwrapSol: true }
- ```
-6. Return:
-```js
-json(res, 200, {
- transaction: swapResponse.swapTransaction, // already base64
- network: 'mainnet',
- inputAmount: amount,
- outputAmount: quoteResponse.outAmount / 10**outputDecimals,
- outputMint,
- priceImpactPct: quoteResponse.priceImpactPct,
-});
-```
-
-### Router
-```js
-export default wrap(async (req, res) => {
- const action = req.url.split('/').pop().split('?')[0];
- if (action === 'build-transfer') return handleBuildTransfer(req, res);
- if (action === 'build-swap') return handleBuildSwap(req, res);
- return error(res, 404, 'not_found', 'unknown action');
-});
-```
-
-## Verification
-- `POST /api/tx/solana/build-transfer` with `{ sender, recipient, amount: 0.001, token: 'SOL', network: 'devnet' }` returns `{ transaction: '<base64>', blockhash, lastValidBlockHeight }`.
-- `POST /api/tx/solana/build-swap` with a valid Jupiter mainnet pair returns `{ transaction, outputAmount, priceImpactPct }`.
-- Unauthenticated requests return 401.
-- Invalid body returns 400/422.
diff --git a/tasks/wallet-transactions/05-solana-wallet-tools.md b/tasks/wallet-transactions/05-solana-wallet-tools.md
deleted file mode 100644
index 52c73552d..000000000
--- a/tasks/wallet-transactions/05-solana-wallet-tools.md
+++ /dev/null
@@ -1,214 +0,0 @@
-# Task 05 — Frontend: Solana Wallet Tools
-
-## Goal
-Add two new tools to `chat/src/tools.js` — `solana_transfer` and `solana_swap` — that the LLM can invoke to execute Solana transactions from within chat. Each tool:
-1. Calls the backend API (built in Task 04) to get a serialized transaction.
-2. Calls `window.requestWalletApproval(details)` (set up in Task 02) to pause for user confirmation.
-3. Signs the transaction with `window.solana`.
-4. Broadcasts via the Solana RPC.
-5. Returns a `tx_result` content object (rendered by Task 03).
-
-## Context
-- Tool bodies are JavaScript strings stored in `clientDefinition.body`. They are eval'd in the browser context. They can use `fetch`, `window.*`, and `async/await`.
-- `window.__wallet` holds `{ type, address }` (set up in Task 01).
-- `window.requestWalletApproval(details)` returns a Promise that resolves on user approval, rejects on cancel (Task 02).
-- `window.solana` is the Phantom/Solana wallet adapter.
-- Tool body receives its arguments as local variables matching the `arguments` array names.
-- Add these tools to the existing `pumpToolSchema` array at the bottom of that array (or create a new `walletToolSchema` — see Task 07).
-
-## Common Explorer URL helper (inline in each body)
-
-```js
-const solscanBase = network === 'devnet'
- ? 'https://solscan.io/tx/'
- : 'https://solscan.io/tx/';
-```
-Both mainnet and devnet use solscan; devnet links append `?cluster=devnet`.
-
----
-
-## Tool 1: `solana_transfer`
-
-### `clientDefinition`
-```js
-{
- name: 'solana_transfer',
- description: 'Send SOL or a Solana SPL token (e.g. USDC) to a recipient address. Requires a connected Solana wallet.',
- arguments: [
- { name: 'recipient', type: 'string', description: 'Base58 recipient wallet address' },
- { name: 'amount', type: 'number', description: 'Amount to send in human-readable units (e.g. 1.5 for 1.5 SOL)' },
- { name: 'token', type: 'string', description: 'Token to send: "SOL" or an SPL mint address (e.g. USDC mint). Default: "SOL"' },
- { name: 'memo', type: 'string', description: 'Optional memo string to attach' },
- { name: 'network', type: 'string', description: '"mainnet" or "devnet". Default: "mainnet"' },
- ],
- async body({ recipient, amount, token = 'SOL', memo, network = 'mainnet' }) {
- const wallet = window.__wallet;
- if (!wallet || wallet.type !== 'solana') throw new Error('No Solana wallet connected. Please connect a Solana wallet first.');
-
- // 1. Build transaction on backend
- const buildRes = await fetch('/api/tx/solana/build-transfer', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- credentials: 'include',
- body: JSON.stringify({ sender: wallet.address, recipient, amount, token, memo, network }),
- });
- if (!buildRes.ok) {
- const err = await buildRes.json().catch(() => ({}));
- throw new Error(err.message || 'Failed to build transaction');
- }
- const { transaction: txBase64 } = await buildRes.json();
-
- // 2. Request user approval
- await window.requestWalletApproval({
- network: network === 'devnet' ? 'Solana Devnet' : 'Solana',
- from: wallet.address,
- to: recipient,
- amount: String(amount),
- token,
- memo,
- });
-
- // 3. Deserialize, sign, and send
- const txBytes = Uint8Array.from(atob(txBase64), c => c.charCodeAt(0));
- // Use wallet.signAndSendTransaction if available (Phantom), else signTransaction + manual broadcast
- let signature;
- if (window.solana.signAndSendTransaction) {
- const { Transaction } = await import('https://esm.sh/@solana/web3.js@1');
- const tx = Transaction.from(txBytes);
- const result = await window.solana.signAndSendTransaction(tx);
- signature = result.signature;
- } else {
- throw new Error('Wallet does not support signAndSendTransaction');
- }
-
- const explorerUrl = `https://solscan.io/tx/${signature}${network === 'devnet' ? '?cluster=devnet' : ''}`;
-
- return {
- contentType: 'application/tx-result',
- content: {
- status: 'success',
- txHash: signature,
- network: network === 'devnet' ? 'Solana Devnet' : 'Solana',
- from: wallet.address,
- to: recipient,
- amount: String(amount),
- token,
- explorerUrl,
- },
- };
- }
-}
-```
-
-### `function` schema (OpenAI-compatible)
-```js
-{
- name: 'solana_transfer',
- description: 'Send SOL or SPL tokens on Solana. Requires a connected Solana wallet.',
- parameters: {
- type: 'object',
- properties: {
- recipient: { type: 'string', description: 'Base58 recipient wallet address' },
- amount: { type: 'number', description: 'Amount in human-readable units' },
- token: { type: 'string', description: '"SOL" or SPL mint address. Default: "SOL"' },
- memo: { type: 'string', description: 'Optional memo' },
- network: { type: 'string', enum: ['mainnet', 'devnet'], description: 'Default: mainnet' },
- },
- required: ['recipient', 'amount'],
- },
-}
-```
-
----
-
-## Tool 2: `solana_swap`
-
-### `clientDefinition`
-```js
-{
- name: 'solana_swap',
- description: 'Swap tokens on Solana via Jupiter aggregator. Finds the best route automatically. Requires a connected Solana wallet.',
- arguments: [
- { name: 'inputMint', type: 'string', description: 'Mint address of the token to sell (e.g. USDC: EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v)' },
- { name: 'outputMint', type: 'string', description: 'Mint address of the token to buy (e.g. SOL: So11111111111111111111111111111111111111112)' },
- { name: 'amount', type: 'number', description: 'Amount of input token to sell in human-readable units' },
- { name: 'slippageBps', type: 'number', description: 'Max slippage in basis points (100 = 1%). Default: 50' },
- ],
- async body({ inputMint, outputMint, amount, slippageBps = 50 }) {
- const wallet = window.__wallet;
- if (!wallet || wallet.type !== 'solana') throw new Error('No Solana wallet connected.');
-
- // 1. Build swap transaction
- const buildRes = await fetch('/api/tx/solana/build-swap', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- credentials: 'include',
- body: JSON.stringify({ sender: wallet.address, inputMint, outputMint, amount, slippageBps }),
- });
- if (!buildRes.ok) {
- const err = await buildRes.json().catch(() => ({}));
- throw new Error(err.message || 'Failed to get swap route');
- }
- const { transaction: txBase64, outputAmount, priceImpactPct } = await buildRes.json();
-
- // 2. Request approval
- await window.requestWalletApproval({
- network: 'Solana',
- from: wallet.address,
- to: 'Jupiter (DEX aggregator)',
- amount: String(amount),
- token: `${inputMint.slice(0,6)}… → ${outputMint.slice(0,6)}…`,
- memo: `~${outputAmount} out, ${priceImpactPct}% price impact`,
- });
-
- // 3. Sign and send
- const txBytes = Uint8Array.from(atob(txBase64), c => c.charCodeAt(0));
- const { Transaction } = await import('https://esm.sh/@solana/web3.js@1');
- const tx = Transaction.from(txBytes);
- const result = await window.solana.signAndSendTransaction(tx);
- const signature = result.signature;
-
- return {
- contentType: 'application/tx-result',
- content: {
- status: 'success',
- txHash: signature,
- network: 'Solana',
- from: wallet.address,
- to: outputMint,
- amount: String(outputAmount),
- token: outputMint.slice(0, 8) + '…',
- explorerUrl: `https://solscan.io/tx/${signature}`,
- },
- };
- }
-}
-```
-
-### `function` schema
-```js
-{
- name: 'solana_swap',
- description: 'Swap tokens on Solana via Jupiter. Best-route aggregation.',
- parameters: {
- type: 'object',
- properties: {
- inputMint: { type: 'string', description: 'Mint address of token to sell' },
- outputMint: { type: 'string', description: 'Mint address of token to buy' },
- amount: { type: 'number', description: 'Amount of input token in human-readable units' },
- slippageBps: { type: 'number', description: 'Max slippage in bps. Default: 50' },
- },
- required: ['inputMint', 'outputMint', 'amount'],
- },
-}
-```
-
----
-
-## Where to Add in `tools.js`
-Add both tools to the `pumpToolSchema` array. Each entry needs both `clientDefinition` and `function` keys, matching the pattern of existing tools in that array.
-
-## Verification
-- The LLM can see both tools when `pumpToolSchema` tools are active.
-- Calling `solana_transfer` from chat (with a connected Phantom wallet on devnet) shows the approval modal, then on approve attempts to sign and submit the transaction.
-- If no wallet is connected, the tool throws a clear error message that the LLM relays to the user.
diff --git a/tasks/wallet-transactions/06-evm-wallet-tools.md b/tasks/wallet-transactions/06-evm-wallet-tools.md
deleted file mode 100644
index a759220fa..000000000
--- a/tasks/wallet-transactions/06-evm-wallet-tools.md
+++ /dev/null
@@ -1,234 +0,0 @@
-# Task 06 — Frontend: EVM Wallet Tools
-
-## Goal
-Add two tools — `evm_transfer` and `evm_swap` — to `chat/src/tools.js` that execute EVM transactions from chat. Unlike Solana, EVM wallets (MetaMask) handle transaction building, signing, and broadcasting natively via `window.ethereum`, so no backend endpoint is needed for transfer. Swap uses the 1inch Fusion+ API for calldata.
-
-## Context
-- `window.__wallet` holds `{ type: 'evm', address, chainId }` after EVM sign-in (Task 01).
-- `window.ethereum` is the MetaMask provider. Use `eth_sendTransaction` RPC call to send.
-- `window.requestWalletApproval(details)` pauses for user confirmation (Task 02).
-- ERC20 ABI for transfer: `transfer(address to, uint256 amount)` → selector `0xa9059cbb`
-- MetaMask will show its own native confirmation after our approval modal — that's expected and fine.
-- For swaps, use the 1inch v5 API (no auth key needed for public quotes): `https://api.1inch.dev/swap/v5.2/{chainId}/swap`
-
-## Tool 1: `evm_transfer`
-
-### `clientDefinition`
-```js
-{
- name: 'evm_transfer',
- description: 'Send ETH or an ERC20 token to a recipient address on any EVM chain. Requires a connected EVM wallet (MetaMask or compatible).',
- arguments: [
- { name: 'recipient', type: 'string', description: '0x recipient address' },
- { name: 'amount', type: 'string', description: 'Amount in human-readable units (e.g. "0.01" for 0.01 ETH)' },
- { name: 'token', type: 'string', description: '"ETH" for native token, or an ERC20 contract address (0x...). Default: "ETH"' },
- { name: 'decimals', type: 'number', description: 'Token decimals (required for ERC20, ignored for ETH). Default: 18' },
- ],
- async body({ recipient, amount, token = 'ETH', decimals = 18 }) {
- const wallet = window.__wallet;
- if (!wallet || wallet.type !== 'evm') throw new Error('No EVM wallet connected. Please connect MetaMask or a compatible wallet.');
-
- // Chain name lookup
- const chainNames = { 1: 'Ethereum', 8453: 'Base', 10: 'Optimism', 42161: 'Arbitrum', 137: 'Polygon' };
- const networkName = chainNames[wallet.chainId] || `Chain ${wallet.chainId}`;
-
- // 1. Request approval
- await window.requestWalletApproval({
- network: networkName,
- from: wallet.address,
- to: recipient,
- amount,
- token: token === 'ETH' ? 'ETH' : `${token.slice(0, 8)}…`,
- });
-
- // 2. Build and send transaction
- let txHash;
- if (token === 'ETH') {
- // Native ETH transfer
- const valueHex = '0x' + BigInt(Math.round(parseFloat(amount) * 1e18)).toString(16);
- txHash = await window.ethereum.request({
- method: 'eth_sendTransaction',
- params: [{ from: wallet.address, to: recipient, value: valueHex }],
- });
- } else {
- // ERC20 transfer
- const amountBigInt = BigInt(Math.round(parseFloat(amount) * 10 ** decimals));
- // Encode transfer(address, uint256) calldata
- const selector = '0xa9059cbb';
- const paddedTo = recipient.slice(2).padStart(64, '0');
- const paddedAmount = amountBigInt.toString(16).padStart(64, '0');
- const data = selector + paddedTo + paddedAmount;
- txHash = await window.ethereum.request({
- method: 'eth_sendTransaction',
- params: [{ from: wallet.address, to: token, data }],
- });
- }
-
- // 3. Explorer URL
- const explorerBases = { 1: 'https://etherscan.io/tx/', 8453: 'https://basescan.org/tx/', 10: 'https://optimistic.etherscan.io/tx/', 42161: 'https://arbiscan.io/tx/', 137: 'https://polygonscan.com/tx/' };
- const explorerUrl = (explorerBases[wallet.chainId] || 'https://etherscan.io/tx/') + txHash;
-
- return {
- contentType: 'application/tx-result',
- content: {
- status: 'pending', // EVM tx is pending until mined; wallet confirmation happens outside this tool
- txHash,
- network: networkName,
- chainId: wallet.chainId,
- from: wallet.address,
- to: recipient,
- amount,
- token: token === 'ETH' ? 'ETH' : token.slice(0, 10) + '…',
- explorerUrl,
- },
- };
- }
-}
-```
-
-### `function` schema
-```js
-{
- name: 'evm_transfer',
- description: 'Send ETH or ERC20 tokens on any EVM chain (Ethereum, Base, Optimism, Arbitrum, Polygon).',
- parameters: {
- type: 'object',
- properties: {
- recipient: { type: 'string', description: '0x recipient address' },
- amount: { type: 'string', description: 'Amount in human-readable units' },
- token: { type: 'string', description: '"ETH" or ERC20 contract address. Default: "ETH"' },
- decimals: { type: 'number', description: 'ERC20 decimals. Default: 18' },
- },
- required: ['recipient', 'amount'],
- },
-}
-```
-
----
-
-## Tool 2: `evm_swap`
-
-### `clientDefinition`
-```js
-{
- name: 'evm_swap',
- description: 'Swap tokens on EVM chains using 1inch aggregator. Finds best DEX route. Requires a connected EVM wallet.',
- arguments: [
- { name: 'fromToken', type: 'string', description: 'Token contract address to sell (use "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE" for native ETH)' },
- { name: 'toToken', type: 'string', description: 'Token contract address to buy' },
- { name: 'amount', type: 'string', description: 'Amount of fromToken in human-readable units' },
- { name: 'decimals', type: 'number', description: 'Decimals of fromToken. Default: 18' },
- { name: 'slippage', type: 'number', description: 'Max slippage percentage (e.g. 1 for 1%). Default: 1' },
- ],
- async body({ fromToken, toToken, amount, decimals = 18, slippage = 1 }) {
- const wallet = window.__wallet;
- if (!wallet || wallet.type !== 'evm') throw new Error('No EVM wallet connected.');
-
- const chainNames = { 1: 'Ethereum', 8453: 'Base', 10: 'Optimism', 42161: 'Arbitrum', 137: 'Polygon' };
- const networkName = chainNames[wallet.chainId] || `Chain ${wallet.chainId}`;
- const amountWei = BigInt(Math.round(parseFloat(amount) * 10 ** decimals)).toString();
-
- // 1. Get swap calldata from 1inch
- const quoteUrl = `https://api.1inch.dev/swap/v5.2/${wallet.chainId}/swap?src=${fromToken}&dst=${toToken}&amount=${amountWei}&from=${wallet.address}&slippage=${slippage}&disableEstimate=true`;
- const quoteRes = await fetch(quoteUrl, {
- headers: { 'Accept': 'application/json' },
- });
- if (!quoteRes.ok) {
- const err = await quoteRes.json().catch(() => ({}));
- throw new Error(err.description || 'Failed to get swap quote from 1inch');
- }
- const quote = await quoteRes.json();
-
- const toAmountHuman = (Number(quote.toAmount) / 10 ** 18).toFixed(6); // approximate; real decimals of toToken unknown here
-
- // 2. Request approval
- await window.requestWalletApproval({
- network: networkName,
- from: wallet.address,
- to: `1inch Router`,
- amount,
- token: `${fromToken.slice(0,8)}… → ${toToken.slice(0,8)}…`,
- memo: `~${toAmountHuman} out`,
- });
-
- // 3. Check allowance and approve if needed (ERC20 only)
- const ETH_ADDRESS = '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE';
- if (fromToken.toLowerCase() !== ETH_ADDRESS.toLowerCase()) {
- // Check current allowance
- const allowanceSelector = '0xdd62ed3e';
- const paddedOwner = wallet.address.slice(2).padStart(64, '0');
- const paddedSpender = quote.tx.to.slice(2).padStart(64, '0');
- const allowanceData = allowanceSelector + paddedOwner + paddedSpender;
- const allowanceHex = await window.ethereum.request({
- method: 'eth_call',
- params: [{ to: fromToken, data: allowanceData }, 'latest'],
- });
- const allowance = BigInt(allowanceHex || '0x0');
- const needed = BigInt(amountWei);
- if (allowance < needed) {
- // Approve max
- const approveSelector = '0x095ea7b3';
- const maxUint256 = 'f'.repeat(64);
- const approveData = approveSelector + paddedSpender + maxUint256;
- await window.ethereum.request({
- method: 'eth_sendTransaction',
- params: [{ from: wallet.address, to: fromToken, data: approveData }],
- });
- }
- }
-
- // 4. Send swap transaction
- const txHash = await window.ethereum.request({
- method: 'eth_sendTransaction',
- params: [{ from: wallet.address, to: quote.tx.to, data: quote.tx.data, value: quote.tx.value || '0x0' }],
- });
-
- const explorerBases = { 1: 'https://etherscan.io/tx/', 8453: 'https://basescan.org/tx/', 10: 'https://optimistic.etherscan.io/tx/', 42161: 'https://arbiscan.io/tx/', 137: 'https://polygonscan.com/tx/' };
- const explorerUrl = (explorerBases[wallet.chainId] || 'https://etherscan.io/tx/') + txHash;
-
- return {
- contentType: 'application/tx-result',
- content: {
- status: 'pending',
- txHash,
- network: networkName,
- chainId: wallet.chainId,
- from: wallet.address,
- to: toToken,
- amount: `~${toAmountHuman}`,
- token: toToken.slice(0, 10) + '…',
- explorerUrl,
- },
- };
- }
-}
-```
-
-### `function` schema
-```js
-{
- name: 'evm_swap',
- description: 'Swap ERC20 tokens or ETH on EVM chains via 1inch DEX aggregator.',
- parameters: {
- type: 'object',
- properties: {
- fromToken: { type: 'string', description: 'Token to sell (address or 0xEeee... for ETH)' },
- toToken: { type: 'string', description: 'Token to buy (address)' },
- amount: { type: 'string', description: 'Amount of fromToken in human-readable units' },
- decimals: { type: 'number', description: 'fromToken decimals. Default: 18' },
- slippage: { type: 'number', description: 'Max slippage %. Default: 1' },
- },
- required: ['fromToken', 'toToken', 'amount'],
- },
-}
-```
-
----
-
-## Where to Add
-Add both tools to `pumpToolSchema` in `tools.js` (or to a new `walletToolSchema` if Task 07 creates one).
-
-## Verification
-- With MetaMask connected on a testnet, calling `evm_transfer` from chat opens the approval modal, then MetaMask's own confirmation dialog.
-- The tool returns a `tx_result` content object with `status: 'pending'` and a correct explorer link.
-- If no EVM wallet is connected, the tool returns a clear error.
diff --git a/tasks/wallet-transactions/07-wallet-tools-pack.md b/tasks/wallet-transactions/07-wallet-tools-pack.md
deleted file mode 100644
index ae8ce6af9..000000000
--- a/tasks/wallet-transactions/07-wallet-tools-pack.md
+++ /dev/null
@@ -1,65 +0,0 @@
-# Task 07 — Wallet Tools Pack Registration
-
-## Goal
-Bundle the four wallet transaction tools (from Tasks 05 and 06) into a named `walletToolSchema` export and register it as a curated tool pack so users can enable it from the tool dropdown like any other pack.
-
-## Context
-- `chat/src/tools.js` exports: `curatedToolPacks`, `defaultToolSchema`, `agentToolSchema`, `pumpToolSchema`
-- `curatedToolPacks` is an array of `{ name, description, tools }` objects used to populate the tool-pack picker UI
-- `chat/src/App.svelte` imports `{ defaultToolSchema, agentToolSchema, pumpToolSchema, curatedToolPacks }` from `./tools.js`
-- After this task, `walletToolSchema` should be importable from `tools.js` and appear in the curated tool packs list
-
-## Changes to `chat/src/tools.js`
-
-### 1. Extract `walletToolSchema`
-Move the four wallet tools added in Tasks 05 and 06 out of `pumpToolSchema` (or from wherever they were added) into their own named export:
-
-```js
-export const walletToolSchema = [
- {
- clientDefinition: { /* solana_transfer clientDefinition */ },
- function: { /* solana_transfer function schema */ },
- },
- {
- clientDefinition: { /* solana_swap clientDefinition */ },
- function: { /* solana_swap function schema */ },
- },
- {
- clientDefinition: { /* evm_transfer clientDefinition */ },
- function: { /* evm_transfer function schema */ },
- },
- {
- clientDefinition: { /* evm_swap clientDefinition */ },
- function: { /* evm_swap function schema */ },
- },
-];
-```
-
-### 2. Add to `curatedToolPacks`
-Append a new entry to the `curatedToolPacks` array:
-
-```js
-{
- name: 'Wallet Transactions',
- description: 'Send and swap tokens on Solana and EVM chains directly from chat. Supports SOL, SPL tokens, ETH, ERC20, and DEX swaps via Jupiter and 1inch.',
- tools: walletToolSchema,
-},
-```
-
-Place it after the existing packs (after the pump.fun / crypto pack if one exists).
-
-### 3. Update `App.svelte` import
-In `chat/src/App.svelte`, update the import line:
-
-```js
-import { defaultToolSchema, agentToolSchema, pumpToolSchema, walletToolSchema, curatedToolPacks } from './tools.js';
-```
-
-No other changes to App.svelte are needed — the curated tool packs are already consumed by the ToolPackModal component via `curatedToolPacks`.
-
-## Verification
-- Open the tool dropdown / tool pack modal in the chat UI.
-- A "Wallet Transactions" pack appears in the list with the correct description.
-- Enabling the pack adds all four tools (`solana_transfer`, `solana_swap`, `evm_transfer`, `evm_swap`) to the active tool set.
-- The LLM can see all four tool definitions when the pack is enabled.
-- No other tool packs or existing functionality is affected.
diff --git a/tasks/wow-sprint/01-bug-and-lazy-code-audit.md b/tasks/wow-sprint/01-bug-and-lazy-code-audit.md
deleted file mode 100644
index a52eedb56..000000000
--- a/tasks/wow-sprint/01-bug-and-lazy-code-audit.md
+++ /dev/null
@@ -1,38 +0,0 @@
-# Task: Codebase bug & lazy-code audit (diagnosis only)
-
-You are a senior engineer doing a cold-eyed audit of the three.ws codebase. Your
-job is **diagnosis, not repair** — produce a prioritized, actionable report. Do
-not change application code.
-
-## Scope
-Focus on the live frontend and API surface:
-- `src/**/*.js` (the app modules — `viewer.js`, `home-v4-hero.js`, `agent-home.js`, `pump/**`, `wallet*.js`, etc.)
-- `api/**/*.js` (Vercel functions)
-- `pages/**/*.html` (entry points wired in `vite.config.js`)
-
-Skip `node_modules`, `dist`, `dist-lib`, `vendor`, and third-party SDK folders.
-
-## What to hunt for
-1. **Real bugs** — logic errors, race conditions, unhandled promise rejections, off-by-one, wrong variable, missing `await`, broken conditionals, incorrect API contracts between frontend and `api/`.
-2. **Lazy code** — mocks, fake/sample data arrays shipped to prod, hardcoded values that should be dynamic, `setTimeout` fake-loading, stub functions, `throw new Error('not implemented')`, empty `catch {}`, commented-out code, `TODO`/`FIXME`/`// implement later`.
-3. **Broken boundaries** — network calls with no error handling at the boundary, user input not validated, missing loading/empty/error states.
-4. **Dead code** — run `npx knip` (config at `knip.config.js`) and fold its findings in.
-
-## Method
-- Grep for smells: `grep -rn "TODO\|FIXME\|not implemented\|sampleData\|mockData\|fake\|placeholder\|setTimeout(" src api pages --include=*.js --include=*.html`.
-- Read the highest-traffic modules in full: `src/home-v4-hero.js`, `src/agent-home.js`, `src/wallet.js`, `src/pump/dashboard.js`, `api/three-token/[action].js`, `api/pump/dashboard.js`.
-- Cross-check the existing `ISSUES.md` — note which listed issues are still unfixed.
-
-## Output
-Write `tasks/wow-sprint/REPORT-01-audit.md` with a table:
-
-| # | Severity (P0–P3) | File:line | Category | What's wrong | Suggested fix | Effort |
-
-Sort by severity, then by user impact. P0 = users hit it now. End with a
-"Top 10 fix-first" shortlist and a one-paragraph health summary.
-
-## Definition of done
-- Report file written, every finding has a real `file:line`.
-- No application code changed.
-- knip output incorporated.
-- You'd be comfortable handing this report to the team as the sprint backlog.