Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Remove completed task files
nirholas947b0c1967f2
diff --git a/tasks/agent-monetization/03-x402-manifest-update.md b/tasks/agent-monetization/03-x402-manifest-update.mddeleted file mode 100644index cc664d485..000000000--- a/tasks/agent-monetization/03-x402-manifest-update.md+++ /dev/null@@ -1,76 +0,0 @@-# Task 03 — Update x402 Manifest to Use Dynamic Pricing--## Goal-The existing endpoint `GET /api/agents/:id/x402/:skill/manifest` returns a hardcoded payment manifest. Update it to pull live pricing from the `agent_skill_prices` table created in Task 01.--## Current Behavior (file: `/api/agents/x402/[...slug].js` or similar)-The manifest likely returns a static amount from env vars or agent meta. Find the exact file and understand its shape before editing.--## Success Criteria-- Manifest amount matches the price set via the pricing API (Task 02)-- If no price is configured for the skill, return `404` with `{ error: "skill_not_priced" }`-- If `is_active = false`, return `404` with `{ error: "skill_not_available" }`-- Existing x402 intent creation flow continues to work unchanged--## Changes Required--### In the manifest handler:-1. Parse `agent_id` and `skill` from the route-2. Query `agent_skill_prices` for a row where `agent_id = ? AND skill = ? AND is_active = true`-3. If no row → 404-4. Build the manifest using `row.amount`, `row.currency_mint`, `row.chain`-5. Keep payout address from `agent_payout_wallets` (join on `agent_id`, fallback to agent's `wallet_address` in `agent_identities`)--### Payout address resolution (new helper `resolvePayoutAddress(agentId, chain)`)-```js-// api/_lib/payout.js-export async function resolvePayoutAddress(agentId, chain) {- const row = await db.query(- `SELECT address FROM agent_payout_wallets- WHERE agent_id = $1 AND chain = $2- ORDER BY is_default DESC, created_at DESC LIMIT 1`,- [agentId, chain]- );- if (row) return row.address;- // Fallback: agent's own wallet_address- const agent = await db.query(- `SELECT wallet_address FROM agent_identities WHERE id = $1`,- [agentId]- );- return agent?.wallet_address ?? null;-}-```--## Files to Touch-- Find and edit the existing x402 manifest endpoint (search for `x402` in `/api/agents/`)-- Add `/api/_lib/payout.js` (new helper)--## Do NOT Change-- Intent creation (`agent_payment_intents` insert) — that's unchanged-- Payment verification logic-- x402 spec envelope structure--## Verify-```bash-# After setting price via Task 02 API:-curl /api/agents/:id/x402/answer-question/manifest-# Should return manifest with amount=1000000 and correct payTo address--# Unpriced skill:-curl /api/agents/:id/x402/unpriced-skill/manifest-# Should return 404 { error: "skill_not_priced" }-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/agent-monetization/03-x402-manifest-update.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-floor-anchor/01-pure-anchor-math-and-tests.md b/tasks/irl-floor-anchor/01-pure-anchor-math-and-tests.mddeleted file mode 100644index 5e26cd439..000000000--- a/tasks/irl-floor-anchor/01-pure-anchor-math-and-tests.md+++ /dev/null@@ -1,109 +0,0 @@-# 01 — Pure floor-anchor math + unit tests--> Epic IRL/floor-anchor · Size **S** · Foundation — run first.-> Mirrors the pure-policy pattern of [src/irl/room-anchor.js](../../src/irl/room-anchor.js)-> and its test [tests/irl-room-anchor.test.js](../../tests/irl-room-anchor.test.js).--## Goal--Make the math that turns an anchored XR pose into a durable GPS pin **pure,-shared, and unit-tested**. Today it is hand-rolled inline inside the host with-duplicated constants and zero test coverage — the one part of the feature whose-correctness silently determines whether a saved pin reloads where the user tapped.--## Why it matters--`persistFloorAnchor` re-derives metres-per-degree and a yaw-from-quaternion by-hand. The same projection already exists, unit-tested, in `room-anchor.js`. Two-copies drift; an untested copy on the *write* path means a sign error ships-silently and every saved anchor lands in the wrong place for every viewer. A pure-module with tests is the cheapest possible insurance and unblocks confident edits-in tasks 02/05/07.--## Current state (real lines)--- [src/irl.js:1631-1635](../../src/irl.js#L1631-L1635) `yawFromQuat(q)` — quaternion- → yaw degrees, hand-rolled, untested.-- [src/irl.js:1658-1664](../../src/irl.js#L1658-L1664) `persistFloorAnchor` hand-rolls- `mLat = 110540`, `mLng = 111320 * cos(lat)`, then- `pinLat = lat + (-position.z / mLat)`, `pinLng = lng + (position.x / mLng)`.-- [src/irl/room-anchor.js:46-73](../../src/irl/room-anchor.js#L46-L73) already exports- `M_PER_DEG_LAT`, `mPerDegLng(lat)`, `geoToLocal`, `localToGeo` — the exact same- projection, with the exact same axis convention (`north = −Z`, `east = +X`).-- Convention comment to preserve: [src/irl/room-anchor.js:34-38](../../src/irl/room-anchor.js#L34-L38).--## What to build--### 1. A pure module — `src/irl/floor-anchor.js`--No DOM, no Three.js, no I/O — plain numbers in/out, exactly like `room-anchor.js`.--```js-// yaw (deg, 0–359, clockwise from local −Z) from a quaternion's (x,y,z,w).-export function yawDegFromQuat(x, y, z, w) { /* move src/irl.js:1631 here, normalized 0–359 */ }--// Anchored local-space pose (metres from the eye-level session origin) → the GPS-// pin to persist. Reuses room-anchor's localToGeo so there is ONE projection.-// localX = +east, localZ = +north-ish but world north = −Z, so pass −z as north.-export function anchorPoseToPin({ originLat, originLng, x, y, z, quat }) {- const { lat, lng } = localToGeo(originLat, originLng, /*east*/ x, /*north*/ -z);- const heading = ((Math.round(yawDegFromQuat(...quat)) % 360) + 360) % 360;- return { lat, lng, heading, heightM: y, quat, source: 'webxr' };-}-```--Import `localToGeo` from `./room-anchor.js`. Keep the `heightM` sign note from-[src/irl.js:1670](../../src/irl.js#L1670) (negative = below eye level) in a comment.--### 2. Rewire the host to the module--In [src/irl.js](../../src/irl.js): delete the inline `yawFromQuat` and the-hand-rolled `mLat`/`mLng` block; have `persistFloorAnchor` call-`anchorPoseToPin({ originLat: gpsState.lat, originLng: gpsState.lng, x: position.x,-y: position.y, z: position.z, quat: [q.x,q.y,q.z,q.w] })` and forward the result-straight into the existing `savePin(... { heightM, yawDeg, quat, source })` call.-Behaviour must be **identical** — this is a pure extraction, not a redesign.--### 3. Tests — `tests/irl-floor-anchor.test.js`--Mirror [tests/irl-room-anchor.test.js](../../tests/irl-room-anchor.test.js):--- `yawDegFromQuat`: identity quat → 0; 90°/180°/270° yaw quats → 90/180/270;- output always in `[0,360)`.-- `anchorPoseToPin`: a pose `+2 m east / +3 m north` of a known origin round-trips- through `geoToLocal` back to ~`(2, 3)` (sign sanity — catches the `−z` mistake);- `heightM` passes through unchanged; `source === 'webxr'`.-- Round-trip property: `anchorPoseToPin` then `geoToLocal` is identity within 1e-6.--## Acceptance checklist--- [ ] `src/irl/floor-anchor.js` is pure (no `import 'three'`, no DOM) and reuses- `room-anchor.js`'s projection — no duplicated metre-per-degree constants.-- [ ] `persistFloorAnchor` produces byte-identical `savePin` args vs. before.-- [ ] `tests/irl-floor-anchor.test.js` passes; covers yaw, sign, height, round-trip.-- [ ] `npm test` green; `npm run typecheck` clean if the file opts into `// @ts-check`.--## Out of scope--Orientation *replay* on render-back (that's 02). This task only makes the **write**-path pure and tested; it does not change what the viewer does with the stored quat.--## Verify--`npm test -- irl-floor-anchor` passes. Then `npm run dev` → place a floor anchor-on a WebXR device (or the 07 harness) and confirm the saved pin's `lat/lng/heading`-match the pre-refactor values for the same tap.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-floor-anchor/01-pure-anchor-math-and-tests.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-floor-anchor/02-orientation-replay-and-tilt.md b/tasks/irl-floor-anchor/02-orientation-replay-and-tilt.mddeleted file mode 100644index cf0dac11d..000000000--- a/tasks/irl-floor-anchor/02-orientation-replay-and-tilt.md+++ /dev/null@@ -1,110 +0,0 @@-# 02 — Orientation replay: make `anchor_quat` real (or retire it)--> Epic IRL/floor-anchor · Size **M** · Depends on 01.-> Closes the "stored but never used" gap on the render-back path.--## Goal--Decide and implement what the viewer does with the orientation captured at-placement. Right now the full tap-moment quaternion is written to the database and-returned to every client, then **silently ignored** when the agent is rendered.-Either use it (precise facing + optional surface tilt) or stop persisting it.-Shipping a dead column that looks like a feature is exactly the "half-wired" the-operating rules forbid.--## Why it matters--A pin you place facing a specific way should reload facing that way for everyone.-Today render-back only applies a rounded integer `anchor_yaw_deg`; the richer-`anchor_quat` — which also carries any surface tilt — is dropped. The result: a-flat-floor placement is *mostly* fine, but the data we collect promises fidelity-we never deliver, and a sloped or non-axis placement reloads subtly wrong.--## Current state (real lines)--- Write path stores it: [src/irl.js:1669-1673](../../src/irl.js#L1669-L1673)- forwards `quat: [x,y,z,w]`; `savePin` carries it through- [src/irl.js:1385-1387](../../src/irl.js#L1385-L1387).-- Server persists + returns it: [api/irl/pins.js:211](../../api/irl/pins.js#L211)- (`anchor_quat JSONB`), returned at [api/irl/pins.js:540](../../api/irl/pins.js#L540).-- Render-back only uses height + yaw:- [src/irl.js:1146-1156](../../src/irl.js#L1146-L1156) `pinHeightM` /- `anchor_yaw_deg`, applied at [src/irl.js:1273-1330](../../src/irl.js#L1273-L1330)- (`avatarRig.position` from `wp`, `avatarRig.quaternion.setFromAxisAngle(upY, …)`).- **`anchor_quat` is never read in `src/irl.js`.**-- The agent content also never picks up surface tilt at placement time:- [src/ar/webxr.js:176-178](../../src/ar/webxr.js#L176-L178) and- [195-196](../../src/ar/webxr.js#L195-L196) set `content.position` only; the- reticle gets the hit quaternion but the avatar does not.--## Decision (bake this in — do not block)--**Recommended:** keep humanoid avatars **upright** (yaw-only) for placement, but-make yaw *exact* by deriving it from `anchor_quat` when present (full float),-falling back to the rounded `anchor_yaw_deg` for legacy/gyro pins. Do **not** tilt-a standing humanoid to match a 30° ramp — it looks broken, not realistic. Reserve-true surface-tilt for a future non-humanoid prop mode and gate it behind an-explicit `anchor_tilt` flag, off by default.--This means: `anchor_quat` becomes the high-precision source for yaw, justifying its-existence, while we consciously ignore pitch/roll for humanoids and document why.--If after reading the code you conclude the rounded yaw is indistinguishable in-practice, the alternative is to **retire** the column: stop writing `quat`-(src/irl.js), drop it from the select/return (api/irl/pins.js), and migrate it out.-Pick one path; no dead field survives this task.--## What to build (recommended path)--1. Add `yawDegFromQuat` (from task 01's `floor-anchor.js`) as the render-back yaw- source: in the pin pose resolver around [src/irl.js:1146-1156](../../src/irl.js#L1146-L1156),- prefer `Array.isArray(pin.anchor_quat)` → `yawDegFromQuat(...pin.anchor_quat)`- over the integer `anchor_yaw_deg`; keep `anchor_yaw_deg` as the fallback so gyro- pins (no quat) and legacy rows are unaffected.-2. Keep `setFromAxisAngle(upY, yaw)` upright application- ([src/irl.js:1330](../../src/irl.js#L1330)) — exact yaw, no tilt.-3. Document the deliberate pitch/roll drop with a one-line comment next to the- resolver, referencing this task.-4. Round-trip test in `tests/irl-floor-anchor.test.js` (extend 01): a quat encoding- yaw=137° survives `anchorPoseToPin` → `yawDegFromQuat` to within <0.5°, proving- precision is actually retained end-to-end.--## Data / API changes--None if taking the recommended path (columns already exist). If retiring instead:-a guarded `ALTER TABLE irl_pins DROP COLUMN IF EXISTS anchor_quat` migration plus-removal from the select/return lists, and a changelog note.--## Acceptance checklist--- [ ] `anchor_quat` is either **consumed** on render-back (exact yaw, documented- upright policy) or **fully retired** (write, select, return, column) — not dead.-- [ ] Gyro/legacy pins (no quat) render exactly as before — fallback intact.-- [ ] A WebXR pin placed facing a non-axis direction reloads within <1° of the tap- facing on a second client (or the 07 harness asserts the float survives).-- [ ] No console errors; `npm test` + `npm run typecheck` green.--## Out of scope--Surface tilt for humanoids (intentionally rejected here) and the prop-mode tilt-flag (future). Occlusion is task 03.--## Verify--Place a floor anchor facing ~45° off a cardinal direction, reload `/irl` on a-second device near the spot, confirm the agent faces the same way — visibly tighter-than the old integer-rounded yaw.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-floor-anchor/02-orientation-replay-and-tilt.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-floor-anchor/03-realworld-occlusion-depth.md b/tasks/irl-floor-anchor/03-realworld-occlusion-depth.mddeleted file mode 100644index fa44d843f..000000000--- a/tasks/irl-floor-anchor/03-realworld-occlusion-depth.md+++ /dev/null@@ -1,96 +0,0 @@-# 03 — Real-world occlusion (WebXR depth-sensing)--> Epic IRL/floor-anchor · Size **M** · Depends on 01/02; parallel with 04.-> The single biggest "is this real AR?" perception upgrade.--## Goal--Make the placed agent hide behind real-world geometry — a couch, a doorway, a-person walking in front — instead of always painting on top of the camera feed.-This is what separates a sticker pasted on video from an object that lives in the-room. Snapchat gets this via World Mesh; WebXR exposes the equivalent through the-`depth-sensing` feature, and it must degrade silently where unsupported.--## Why it matters--Our agent currently draws over everything (`depthTest:false` reticle aside, the-avatar has no occluder). The instant a real object should be in front of it, the-illusion breaks and the agent looks like a floating overlay. Occlusion is the-highest-leverage realism fix available to a browser AR app and it is the feature-users instinctively test by walking behind something.--## Current state (real lines)--- Session requests no depth: [src/ar/webxr.js:95-98](../../src/ar/webxr.js#L95-L98)- `requiredFeatures:['hit-test']`, `optionalFeatures:['anchors','local-floor']`.-- The agent content is rendered normally against the transparent passthrough- background ([src/ar/webxr.js:120-123](../../src/ar/webxr.js#L120-L123),- render at [199](../../src/ar/webxr.js#L199)); nothing writes real-world depth.-- Three.js `WebGLRenderer.xr` is already in use (`renderer.xr.setSession`,- `renderer.xr.getCamera`) — the integration point exists.--## What to build--1. **Request depth, optionally.** Add `'depth-sensing'` to `optionalFeatures` with- the required descriptor:- ```js- optionalFeatures: ['anchors', 'local-floor', 'depth-sensing'],- depthSensing: { usagePreference: ['gpu-optimized', 'cpu-optimized'],- dataFormatPreference: ['luminance-alpha', 'float32'] },- ```- Feature-detect after start: `session.enabledFeatures?.includes('depth-sensing')`- (guard — not all UAs populate it) and only enable the occlusion path when present.--2. **Occluder pass.** Use Three's WebXR depth path: set- `renderer.xr.setSession(...)` (already done) and, where supported, build a depth- occlusion using the per-frame `XRWebGLDepthInformation` from- `frame.getDepthInformation(view)`. Prefer wiring through Three's built-in- `WebXRDepthSensing` support if the installed three version exposes it (check- `three/examples` / renderer flags for the version in `package.json`); otherwise- implement a minimal occluder material that samples the depth texture and discards- agent fragments behind real depth. Keep it in a new helper- `src/ar/depth-occlusion.js` so `webxr.js` stays readable; dispose it in `_handleEnd`.--3. **Quality + perf.** Occlusion runs every frame — keep allocations out of the- tick (reuse buffers, mirror the scratch-vector discipline in- [src/ar/webxr.js:255-261](../../src/ar/webxr.js#L255-L261)). Target no measurable- FPS regression on the tier budgets noted in the IRL perf system.--4. **Graceful degradation.** No `depth-sensing` → today's exact behavior, no error,- no console noise. Optionally surface a one-time subtle hint- ("Your device supports occlusion" is *not* needed — silence is the bar).--## Acceptance checklist--- [ ] On a depth-capable device (recent Android Chrome) the agent is correctly- hidden when a real object/person is between it and the camera.-- [ ] On a non-depth device the session runs exactly as before — no thrown errors,- no console warnings, button still works.-- [ ] No per-frame allocations added to the XR tick; FPS within perf budget.-- [ ] Depth resources disposed on exit ([src/ar/webxr.js:277-314](../../src/ar/webxr.js#L277-L314)).-- [ ] Reticle/anchor placement behavior unchanged.--## Out of scope--Using the depth texture for *placement* (depth-based instant hit-test) — that is a-nice follow-up but hit-test already places fine; this task is occlusion only.--## Verify--WebXR device: place the agent, walk a chair or your hand between phone and agent —-the agent is occluded. Toggle a non-depth UA (or simulate by removing the feature)-and confirm identical pre-occlusion behavior with a clean console.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-floor-anchor/03-realworld-occlusion-depth.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-floor-anchor/04-placement-ux-polish.md b/tasks/irl-floor-anchor/04-placement-ux-polish.mddeleted file mode 100644index da71e1c1a..000000000--- a/tasks/irl-floor-anchor/04-placement-ux-polish.md+++ /dev/null@@ -1,99 +0,0 @@-# 04 — Placement UX polish (reticle, shadow, confirm, haptics)--> Epic IRL/floor-anchor · Size **M** · Depends on 01/02; parallel with 03.-> Turns a functional placement into one people screenshot and share.--## Goal--Raise the moment-to-moment feel of placing an agent to the bar of the best mobile-AR apps: a reticle that reads as "searching" vs "locked," a grounded preview that-casts a contact shadow (so the agent sits *on* the floor, not floats), a crisp-confirm beat with haptics when the anchor takes, and copy/motion that respects-accessibility. Everything here is feel — but feel is the product.--## Why it matters--Right now placement is: a static purple ring appears, you tap, text changes. It-works, but nothing signals "found it," nothing grounds the avatar, and the commit-moment is silent. These micro-interactions are precisely what make AR feel solid-versus janky. This is the screenshot-and-share task.--## Current state (real lines)--- Reticle is a single static ring, visible/invisible only:- [src/ar/webxr.js:225-236](../../src/ar/webxr.js#L225-L236) (`_buildReticle`,- color `0x9b8cff`), toggled at [171-184](../../src/ar/webxr.js#L171-L184).-- Hit transitions already fire a host callback on change only:- [src/ar/webxr.js:246-251](../../src/ar/webxr.js#L246-L251) `_setHit` → `onHit`.-- Host hint copy: [src/irl.js:1596-1603](../../src/irl.js#L1596-L1603) and the- `setXrHint` states through [src/irl.js:1668-1684](../../src/irl.js#L1668-L1684).-- The previewed avatar follows the reticle but has no shadow:- [src/ar/webxr.js:176-178](../../src/ar/webxr.js#L176-L178).-- Overlay + hint styles: [pages/irl.html:448-511](../../pages/irl.html#L448-L511).--## What to build--1. **Reticle states.**- - *Searching* (no hit): dimmer, slow breathing scale/opacity pulse.- - *Locked* (hit found): brighter, snaps to full size with a quick scale-in,- subtle continuous rotation or inner-dot fill so "ready to place" is obvious.- Drive purely off the existing `_setHit` transition — no new per-frame branching- beyond a lerp. Respect `prefers-reduced-motion`: no pulse/spin, just a static- color/opacity swap.--2. **Contact shadow.** Add a soft radial shadow quad (or `ShadowMaterial` plane)- under the previewed avatar and the placed agent so it reads as grounded. Lives- in the XR scene, follows the reticle pre-tap and the anchor post-tap; disposed in- `_handleEnd`. Keep it cheap (single transparent plane, no real shadow map).--3. **Confirm beat.** On successful `_handleSelect` anchor:- - a one-shot reticle "pulse-out" ring animation,- - `navigator.vibrate?.(15)` (guarded; iOS ignores it harmlessly),- - the hint transitions to the existing "Anchored…" copy with a brief check/✓- affordance in `.irl-xr-hint`.--4. **Copy pass.** Tighten the four hint states for clarity and warmth without- jargon (searching → aiming → placed → saved). Keep `aria-live="polite"` on- `#irl-xr-hint` ([pages/irl.html:1660](../../pages/irl.html#L1660)) so each state- is announced. Ensure the exit affordance keeps its focus ring- ([pages/irl.html:500](../../pages/irl.html#L500)).--5. **Reduced-motion + contrast.** Gate every animation behind- `prefers-reduced-motion: reduce`. Verify reticle/hint contrast against bright and- dark real-world backgrounds (the overlay sits over live camera) — add a subtle- scrim behind the hint text if it fails on a white floor.--## Acceptance checklist--- [ ] Reticle visibly distinguishes searching vs locked; reduced-motion path is- static and calm.-- [ ] Avatar shows a contact shadow both as preview and once anchored; no float.-- [ ] Anchor commit gives a visual pulse + haptic (where supported) + ✓ copy.-- [ ] All four hint states are clear, announced via `aria-live`, readable over both- light and dark camera backgrounds.-- [ ] No per-frame allocations added; disposed cleanly on exit; no console noise.--## Out of scope--Occlusion (03), iOS parity (06). Don't change the anchoring math or persistence.--## Verify--WebXR device: sweep the phone across floor and away — watch searching↔locked;-confirm the shadow grounds the avatar; tap and feel the haptic + see the pulse +-✓. Re-run with reduced-motion enabled in OS settings and confirm calm static-states. Check the hint over a white floor and a dark rug.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-floor-anchor/04-placement-ux-polish.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-floor-anchor/05-session-lifecycle-hardening.md b/tasks/irl-floor-anchor/05-session-lifecycle-hardening.mddeleted file mode 100644index aca79c015..000000000--- a/tasks/irl-floor-anchor/05-session-lifecycle-hardening.md+++ /dev/null@@ -1,116 +0,0 @@-# 05 — Session lifecycle & error hardening (zero dead ends)--> Epic IRL/floor-anchor · Size **M** · Depends on 01. Run before 03/04.-> Where "zero error, production-ready" is actually earned.--## Goal--Make the AR session survive everything the real world throws at it —-backgrounding, an incoming call, tracking loss, camera contention, a rejected-anchor, a tap during GPS warm-up — with a designed, recoverable outcome every-time. No frozen overlays, no silent failures, no console noise, no state where the-user is stuck looking at a glued avatar with no way forward.--## Why it matters--The happy path already works. Production readiness is entirely about the unhappy-ones, and AR has many: phones lock, permissions get revoked mid-session, ARCore-loses tracking under low light, the OS reclaims the camera. Each must resolve to a-clear next action. This is the task that makes the difference between "demo" and-"shippable."--## Current state (real lines)--- Start path catches and shows a designed error with Retry / Use Pin:- [src/irl.js:1564-1585](../../src/irl.js#L1564-L1585) (`showXrError`),- [src/irl.js:1598-1626](../../src/irl.js#L1598-L1626) (`enterFloorAnchor` try/catch).- Good baseline — extend it, don't rewrite.-- Camera contention with the getUserMedia passthrough is half-handled: `disableAR()`- before entering ([src/irl.js:1591](../../src/irl.js#L1591)); exit restores clear- color/background ([src/irl.js:1612-1614](../../src/irl.js#L1612-L1614)) but does- **not** re-enable the passthrough the user had on.-- Anchor-creation rejection already falls back to frozen pose:- [src/ar/webxr.js:213-219](../../src/ar/webxr.js#L213-L219) — but the user is never- told the placement is degraded.-- Pre-GPS replay path exists but is untested:- [src/irl.js:1640-1651](../../src/irl.js#L1640-L1651) (`onFloorAnchored` holds- `_pendingXrAnchorPose`), dropped on exit ([src/irl.js:1607-1611](../../src/irl.js#L1607-L1611)).- The actual replay on first fix lives in `onGPSPosition` — find and verify it.-- **No handling at all** for `XRSession.visibilitychange`, `inputsourceschange`,- tracking loss (a frame with no viewer pose), or `session.end` originating from the- OS rather than our exit button.--## What to build--1. **Visibility / interruption.** Listen for `session.addEventListener('visibilitychange', …)`- in `WebXRSession`. On `hidden`/`blurred`, pause non-essential work and show a- "Paused — bring the app forward" hint via the `onHit(false)`-style host callback;- on `visible`, resume. Ensure an OS-initiated `end` runs the exact same- `_handleEnd` restoration as our button (it already binds `end` →- [src/ar/webxr.js:106](../../src/ar/webxr.js#L106) — verify the host `onEnd`- cleanup at [src/irl.js:1605-1617](../../src/irl.js#L1605-L1617) is idempotent).--2. **Tracking loss.** In `_tick`, when `frame.getViewerPose(localSpace)` is null for- N consecutive frames, surface a "Move to a brighter, more textured area" hint- (new `onTracking(false)` callback) and hide the reticle; clear it when pose- returns. Don't spam — transition-only, like `_setHit`.--3. **Degraded-anchor honesty.** When `createAnchor` returns/throws null- ([src/ar/webxr.js:213-219](../../src/ar/webxr.js#L213-L219)), tell the host so the- hint can say "Placed (this device can't lock it perfectly — it may drift)."- Still persists the pin; just stops pretending it's rock-solid.--4. **Camera passthrough restore.** In the `onEnd` handler- ([src/irl.js:1605-1617](../../src/irl.js#L1605-L1617)) re-enable the passthrough- if `arActive` was on before entering (track the prior state in `enterFloorAnchor`).- The user who was in camera-AR should return to camera-AR, not a black/gradient view.--5. **Pre-GPS replay correctness.** Confirm the `_pendingXrAnchorPose` set at- [src/irl.js:1646](../../src/irl.js#L1646) is actually consumed by `onGPSPosition`- on the first fix and routed through `persistFloorAnchor` (task 01's module). Add- the missing wiring if it's not. Cover it in tests (07 harness / unit): tap →- pose held → first fix → pin saved once, not zero or twice.--6. **Console hygiene.** Audit per the console-audit baseline: the only logging on- failure should be the intentional `log.error('[irl] WebXR start failed', …)`- ([src/irl.js:1622](../../src/irl.js#L1622)). No uncaught rejections, no warnings- from feature probes ([src/ar/webxr.js:77-83](../../src/ar/webxr.js#L77-L83) already- swallows correctly — match that everywhere).--## Acceptance checklist--- [ ] Backgrounding / locking the phone mid-session pauses cleanly and resumes (or- exits) with full restoration — no frozen overlay.-- [ ] OS-initiated session end restores render loop, background, controls, and- passthrough identically to the exit button (idempotent `_handleEnd`/`onEnd`).-- [ ] Tracking loss shows a recoverable hint and self-clears; never a dead reticle.-- [ ] Degraded anchor (no `XRAnchor`) is disclosed honestly and still saves a pin.-- [ ] Tap-during-GPS-warmup persists exactly once on the first fix (test-proven).-- [ ] Returning from AR restores prior camera passthrough state.-- [ ] Zero uncaught errors/warnings across the full lifecycle (console audit clean).--## Out of scope--Occlusion (03), cosmetic reticle states (04), iOS (06). This is correctness and-recovery only.--## Verify--WebXR device: enter AR, lock the phone, unlock → clean resume. Enter, get a call /-switch apps → clean exit + full restore. Cover a camera with your hand to force-tracking loss → recoverable hint. Tap immediately on entry before GPS locks, wait-for the fix → exactly one pin saved (check Network + `/api/irl/pins`).--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-floor-anchor/05-session-lifecycle-hardening.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-floor-anchor/06-ios-nonwebxr-parity.md b/tasks/irl-floor-anchor/06-ios-nonwebxr-parity.mddeleted file mode 100644index 3f991b8da..000000000--- a/tasks/irl-floor-anchor/06-ios-nonwebxr-parity.md+++ /dev/null@@ -1,115 +0,0 @@-# 06 — iOS / non-WebXR parity (AR placement everywhere)--> Epic IRL/floor-anchor · Size **L** · Depends on 01/02/05 being stable.-> The biggest reach gap: today half of mobile (iOS Safari) has no AR placement.--## Goal--Give iOS Safari and other non-WebXR devices the best floor-placement experience-their platform allows — not just the compass+GPS fallback — so "Place on floor"-isn't an Android-only feature. The end state: every modern phone can place an agent-on a real floor surface, and any device that truly can't gets a polished, honest,-non-dead-end alternative.--## Why it matters--iOS Safari has no `immersive-ar`, so `detectFloorAnchorSupport`-([src/irl.js:1542-1550](../../src/irl.js#L1542-L1550)) hides the button entirely-and iPhone users fall back to the gyro+GPS "Pin here" path with no real surface-detection. That's the majority of premium mobile users getting the lesser-experience. Snapchat's equivalent works on iOS via ARKit; our parity story is the-difference between "works on my phone" and "works."--## Current state (real lines)--- Support gate: [src/irl.js:1542-1550](../../src/irl.js#L1542-L1550) — `isSupported()`- false on iOS ⇒ button stays `hidden`; only the gyro+GPS Pin path remains.-- `WebXRSession.isSupported` probes `navigator.xr.isSessionSupported('immersive-ar')`- ([src/ar/webxr.js:77-83](../../src/ar/webxr.js#L77-L83)) — always false in iOS Safari.-- The persistence layer is transport-agnostic: any path that yields- `{ position, quaternion }` can reuse `onFloorAnchored` / `persistFloorAnchor`- ([src/irl.js:1640-1686](../../src/irl.js#L1640-L1686)) and task 01's module — so a- new AR backend only needs to produce a floor pose.--## Decision (evaluate, then commit in the task)--Pick the iOS surface-placement backend. Options, with the honest trade-offs:--1. **`<model-viewer>` AR / AR Quick Look (USDZ)** — *free, native, zero-key.* iOS- ARKit Quick Look places a model on a detected plane. Limitation: it's a separate- system AR viewer, not our live canvas — it can *place and view* but doesn't feed a- pose back for our GPS-pin persistence. Best as a "view your agent in your room"- path; weaker for our shareable-pin model. **Recommended first ship** because it's- free and genuinely useful on iOS today.-2. **WebXR Viewer app / WebXR polyfill** — only works for users who install Mozilla's- WebXR Viewer; not a mainstream answer. Skip as a primary.-3. **8th Wall / commercial WebAR SLAM** — *true in-canvas surface placement on iOS- Safari with pose callbacks*, fully matches our persistence model and UX. Cost: a- paid SDK + API key + attribution. This is the only option that achieves full- feature parity (live placement → shareable GPS pin) on iOS. **Recommended target**- if the product wants real parity and the budget exists — flag the key/cost as a- decision for the user, do not hardcode a placeholder.--Default plan: ship (1) now for an honest iOS AR experience, and scope (3) behind a-config flag + key so it lights up the moment the credential exists — never a-half-wired stub in between.--## What to build--1. **Capability detection.** Replace the binary WebXR gate with a small resolver- `src/ar/placement-capability.js` → `'webxr' | 'quicklook' | 'pin'`, choosing the- richest path the device supports. `detectFloorAnchorSupport` consumes it and shows- the button (relabeled appropriately) for *both* webxr and quicklook, not just webxr.--2. **iOS path (model-viewer / Quick Look).** Generate/serve a USDZ (or reuse an- existing GLB→USDZ path if one exists in the repo — search before adding) and wire- an AR Quick Look launch from the same button. Clearly framed: on iOS the button- places-and-views in your room; persistence falls back to the gyro+GPS pin with the- user's confirmed spot. No silent feature gap — the copy states what each platform does.--3. **(Flagged) 8th Wall path.** If pursuing parity: behind `IRL_WEBAR_PROVIDER` +- key, mount the SLAM session, surface a hit-test reticle matching task 04, and on- tap emit `{ position, quaternion }` into the *existing* `onFloorAnchored` so- persistence, occlusion, and UX are shared with the WebXR path. Zero duplicated- persistence logic.--4. **Unified copy + states.** One mental model across platforms: "Place on floor"- everywhere, with per-capability hint text. The unsupported-everywhere case keeps- the existing Pin path with a clear "AR placement isn't available on this- device — pin with compass + GPS instead."--## Acceptance checklist--- [ ] iOS Safari shows a working AR placement entry (not a hidden button).-- [ ] Capability resolver picks the richest path per device; Android WebXR- unchanged; true-legacy devices keep the Pin path with honest copy.-- [ ] Any in-canvas backend reuses `onFloorAnchored`/`persistFloorAnchor` — no- second persistence path.-- [ ] Commercial-SDK path (if built) is fully behind a key/flag — no stub, no dead- UI when the key is absent; surface the key need to the user as a decision.-- [ ] Copy makes each platform's behavior clear; no console errors on any path.--## Out of scope--Re-implementing SLAM ourselves. The pin-persistence schema (unchanged). Occlusion-on the iOS path beyond what the chosen backend provides natively.--## Verify--Real iPhone (Safari): tap Place on floor → ARKit places the agent on a real plane.-Android (WebXR): unchanged full path. A device with neither: Pin path with the-honest fallback copy. Confirm no path throws and the button is never a dead end.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-floor-anchor/06-ios-nonwebxr-parity.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-floor-anchor/07-verification-harness-and-signoff.md b/tasks/irl-floor-anchor/07-verification-harness-and-signoff.mddeleted file mode 100644index e88384b8c..000000000--- a/tasks/irl-floor-anchor/07-verification-harness-and-signoff.md+++ /dev/null@@ -1,104 +0,0 @@-# 07 — Verification harness + final sign-off--> Epic IRL/floor-anchor · Size **M** · Run last.-> Makes the whole feature provable without a phone, then closes the epic.--## Goal--Build a repeatable way to exercise the floor-anchor flow without physical AR-hardware, use it to verify every prior task, and complete the Definition-of-Done:-clean console across all states, passing tests, a changelog entry, and a written-record of what was confirmed on real hardware versus the harness.--## Why it matters--WebXR can't be driven by the normal headless browser, so without a harness this-feature is only ever "tested on my one Android phone" — which means regressions-ship invisibly. A fake-XR harness turns the session lifecycle and pose math into-something CI and any agent can assert against, and it's the only honest way to-claim "zero error" without hand-waving.--## Current state (real lines)--- The session is structured for injection: `WebXRSession` takes a `viewer` shim and- callbacks ([src/ar/webxr.js:32-75](../../src/ar/webxr.js#L32-L75)); the IRL host- builds that shim explicitly ([src/irl.js:1512-1525](../../src/irl.js#L1512-L1525)).- Hit results flow through `frame.getHitTestResults` / `getPose`- ([src/ar/webxr.js:165-197](../../src/ar/webxr.js#L165-L197)) — all fakeable.-- Pure math from task 01 (`src/irl/floor-anchor.js`) is already unit-testable.-- Existing patterns to mirror: server test- [tests/api/irl-pins-anchor-pose.test.js](../../tests/api/irl-pins-anchor-pose.test.js),- pure-module test [tests/irl-room-anchor.test.js](../../tests/irl-room-anchor.test.js),- and the headless-Playwright recipe noted in the IRL perf memory.--## What to build--1. **Fake-XR harness** — `tests/helpers/fake-xr.js`: minimal stand-ins for- `XRSession`, `XRFrame`, `XRHitTestResult`, `XRReferenceSpace`, and `XRAnchor` that- let a test:- - feed a scripted sequence of hit poses (no-hit → hit at a known matrix),- - fire `select` to trigger `_handleSelect`,- - emit `visibilitychange` and `end`,- - assert `onHit`/`onAnchored`/`onTracking`/`onEnd` fire with the right payloads.- Inject by passing a fake `navigator.xr` (or a renderer stub) into `WebXRSession` —- keep Three.js real where cheap, stub only the XR device layer.--2. **Lifecycle tests** — `tests/ar-webxr-session.test.js`:- - hit→tap→anchored emits `onAnchored` with the captured tap-moment pose- ([src/ar/webxr.js:205-221](../../src/ar/webxr.js#L205-L221));- - `createAnchor` rejection falls back to frozen pose and still fires `onAnchored`- (task 05 degraded path);- - OS `end` runs full restoration idempotently;- - tracking-loss and visibility transitions fire once, on change only.--3. **Pose round-trip test** (extends task 01): a known hit matrix → `_readAnchorPose`- → `anchorPoseToPin` → expected lat/lng/heading/height, proving the whole write- path numerically.--4. **Console-audit pass.** Run the route audit from the console-audit baseline against- `/irl`, exercise the AR entry/exit, and confirm the only logs are intentional.- Note any known-benign lines explicitly.--5. **Definition-of-Done sweep.** Walk the CLAUDE.md DoD list for the whole feature:- every state designed, no dead paths, reachable from the UI, tests green,- `npm run typecheck` clean, `git diff` reviewed.--6. **Changelog.** Append a holder-readable `data/changelog.json` entry (tag- `feature` or `improvement`) summarizing the upgraded floor placement (occlusion,- precise facing, iOS support, polish — whatever shipped), run `npm run build:pages`- to validate, and leave `npm run changelog:push` for post-deploy.--## Acceptance checklist--- [ ] `tests/helpers/fake-xr.js` + `tests/ar-webxr-session.test.js` exercise- hit/tap/anchor/degrade/visibility/end without hardware; `npm test` green.-- [ ] Write-path pose round-trip is asserted numerically end-to-end.-- [ ] Console audit on `/irl` AR flow is clean (or every line documented benign).-- [ ] DoD list walked and satisfied for the full feature; `typecheck` clean.-- [ ] Changelog entry added and `npm run build:pages` validates it.-- [ ] A short written note records what was verified on a real device vs. the harness.--## Out of scope--New product behavior — this task verifies and documents what tasks 01–06 built. If-verification surfaces a real bug, fix it (no error without a solution) and note it.--## Verify--`npm test` runs the new suites in CI without a device. Then a final manual pass on-real hardware (Android WebXR + iPhone from task 06) confirming the harness's claims-match reality, captured in the sign-off note.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-floor-anchor/07-verification-harness-and-signoff.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-hardening/H1-privacy-invariant-test-suite.md b/tasks/irl-hardening/H1-privacy-invariant-test-suite.mddeleted file mode 100644index 71c211d1f..000000000--- a/tasks/irl-hardening/H1-privacy-invariant-test-suite.md+++ /dev/null@@ -1,114 +0,0 @@-# H1 — Privacy-invariant test suite + build gate--> Epic IRL-Hardening · Size **M** · New `tests/api/irl-privacy.test.js` (+ siblings).-> The regression fence. Build this FIRST — every other task lands against it.--## Goal--A single, fast, offline test suite that asserts every location-privacy invariant-of `/irl` and **fails the build** the moment one regresses. Today the guarantees-exist in code and comments but are only partially pinned by tests; a future edit-could silently re-leak coordinates, an owner id, or a device token. After this-task, that edit goes red in CI instead of shipping.--## Why it matters--The founder's bar is "nobody's location ever leaks." A guarantee with no test is-a guarantee with a shelf life. This suite is the contract: it encodes the privacy-model so precisely that the safest way to change `/irl` is to keep it green.--## Current state (verified)--- `tests/api/irl-pins-room.test.js` already mocks `db.js`/`auth.js`/`rate-limit.js`/- `granite-guardian.js` and drives the real `api/irl/pins.js` handler with a- content-addressed `sqlMock`. **Reuse this harness pattern verbatim.**-- `tests/api/http-redact-url.test.js` already covers `redactUrl()` (shipped this pass).-- Invariants currently true in code but **not** all asserted:- - Nearby projection omits `user_id` + `device_token`, exposes only `is_mine`.- - `roundCoord()` coarsens `lat`/`lng`/`origin_lat`/`origin_lng` to `PUBLIC_COORD_DP=5`.- - Radius is clamped to `[10, 60]`, default 40; missing lat/lng → 400.- - `handleCalibrate` / outfit / PATCH / DELETE reject a non-owner (403/404).- - `interactions.js` `pay` requires a valid signature + a `$THREE`/USDC mint.- - `interactions.js` never stores the **viewer's** GPS — only the pin's `lat`/`lng`.- - `IrlRoom._coarseViewerPos` returns a cell-centre±jitter point, never the input.--## What to build--### 1. `tests/api/irl-privacy.test.js` — the read/write feed invariants--Drive the real `pins.js` handler (copy the `irl-pins-room.test.js` mock setup):--```js-it('nearby feed never leaks an owner identifier', async () => {- nearbyRow = { /* …with user_id + device_token set… */ };- const { body } = await getNearby({ lat, lng });- for (const p of body.pins) {- expect(p).not.toHaveProperty('user_id');- expect(p).not.toHaveProperty('device_token');- expect(p).toHaveProperty('is_mine');- }-});--it('nearby feed coarsens every outbound coordinate to ≤ 5 decimals', async () => {- // assert lat/lng/origin_lat/origin_lng have ≤ PUBLIC_COORD_DP fractional digits-});--it('clamps radius to 60 m and rejects a missing fix', async () => { /* 400 path */ });-```--Add ownership-gate tests: a PATCH `calibrate`, an outfit change, a field PATCH,-and a DELETE from a non-owner (wrong `deviceToken`, wrong/absent session) each-return 403/404 and mutate nothing.--### 2. `tests/api/irl-interactions-privacy.test.js`--Drive `api/irl/interactions.js`: assert a `pay` without a valid signature or with-a non-`$THREE`/USDC mint is rejected; assert the inserted row carries the **pin's**-`lat`/`lng` (snapshotted from the pin), never a caller-supplied coordinate; assert-the `?mine=1` owner feed is null-guarded so an empty device token matches nothing.--### 3. `tests/irl-presence-privacy.test.js`--Unit-test `IrlRoom._coarseViewerPos(lat, lng)` (or extract the pure helper if it-isn't already importable): for a known precise input, the output must be inside-the geocell-6 cell but **not equal** to the input, proving raw GPS never survives.-Assert the room's `pins` MapSchema stays empty after a join (no roster broadcast).--### 4. Wire into the gate--These run under the existing `npm test` (vitest). Confirm they're picked up by the-default glob and that the Vercel build runs `npm test` (or add them to whatever-pre-deploy check exists). Keep the whole suite **offline** (all I/O mocked) and-under a few seconds so it's a cheap, always-on fence.--## Acceptance checklist--- [ ] `irl-privacy.test.js`, `irl-interactions-privacy.test.js`, `irl-presence-privacy.test.js` exist and pass.-- [ ] A deliberately reverted guarantee (e.g. temporarily return `user_id`, or drop `roundCoord`) turns the suite RED — verified by trying it.-- [ ] No real DB/RPC/network — fully mocked, runs in the existing vitest config.-- [ ] Suite added to the run that gates deploys; total added runtime < 5 s.-- [ ] `npm test` + `npm run typecheck` green.--## Out of scope--New product behavior — H1 only *locks in* existing + subsequently-built behavior.-The new invariants from H2/H3/H6 get their assertions added in those tasks.--## Verify--`npm test` green. Then locally revert one guarantee in `pins.js`, re-run, watch-the specific assertion fail with a clear message, restore it, confirm green again.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-hardening/H1-privacy-invariant-test-suite.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-hardening/H6-retention-data-minimization.md b/tasks/irl-hardening/H6-retention-data-minimization.mddeleted file mode 100644index 787bdadc1..000000000--- a/tasks/irl-hardening/H6-retention-data-minimization.md+++ /dev/null@@ -1,116 +0,0 @@-# H6 — Retention + data-minimization (reaper + interactions)--> Epic IRL-Hardening · Size **S** · Touches `api/cron/irl-reap.js`,-> `api/irl/interactions.js` (`ensureTable`), and the H1 suite.--## Goal--Stop location-bearing data from outliving its purpose. The hourly reaper currently-deletes expired anonymous pins and orphaned reports — but **never touches-`irl_interactions`**, which store a `viewer_device` and the pin's `lat`/`lng` on-every tap/view/message/pay. Those rows linger after their pin is gone, and forever-for permanent pins. Add a retention policy: cascade-delete interactions when their-pin dies, and age out old interaction rows so a place someone visited isn't kept-indefinitely.--## Why it matters--Data minimization is the cheapest, most durable privacy control: data you don't-keep can't leak. An interaction row is a record that *device X was at coordinate-Y at time T* — exactly the kind of trail that should not accumulate. Closing this-gap shrinks the blast radius of any future incident to "live pins only."--## Current state (verified)--- `api/cron/irl-reap.js` (hourly, cron-secret-gated): deletes `irl_pins` with- `expires_at < NOW() - INTERVAL '1 day'`, and `irl_pin_reports` orphaned by a- missing pin. **No `irl_interactions` cleanup at all.**-- `api/irl/interactions.js` `ensureTable()` creates `irl_interactions` with- `pin_id`, `viewer_device`, `lat`, `lng`, `created_at`, etc. and the pay/earnings- columns. No retention index, no FK cascade.-- Permanent (signed-in) pins never expire, so their interaction trail grows- unbounded.--## What to build--### 1. Cascade orphaned interactions in the reaper--In `api/cron/irl-reap.js`, after the pin delete, add a guarded delete of-interactions whose pin no longer exists (mirror the `irl_pin_reports` orphan-sweep, with the same `to_regclass` existence guard so a fresh DB never 500s):--```js-const reapedIx = ixTable- ? await sql`- DELETE FROM irl_interactions ix- WHERE NOT EXISTS (SELECT 1 FROM irl_pins p WHERE p.id = ix.pin_id)- RETURNING ix.id`- : [];-```--Return `reapedInteractions` in the JSON summary alongside `reapedPins` /-`reapedReports`.--### 2. Age-out window for interactions--Add a retention window (e.g. delete interactions older than 180 days regardless of-pin state — choose and document the number). This bounds the trail even for-permanent pins. Keep `pay` rows if they're needed for earnings history, OR move the-durable earnings aggregate elsewhere and still age out the raw geo-bearing row —-decide explicitly and write the rationale in the file header.--```sql-DELETE FROM irl_interactions-WHERE created_at < NOW() - INTERVAL '180 days'-RETURNING id;-```--Add `CREATE INDEX IF NOT EXISTS irl_interactions_created ON irl_interactions (created_at)`-in `ensureTable()` so the sweep is index-backed.--### 3. Minimize what's stored going forward--Review the columns `irl_interactions` actually needs. The stored `lat`/`lng` are-the *pin's* location (already owned by the pin) — confirm whether duplicating them-on every interaction row earns its keep or can be dropped/joined on read. If kept,-note why. Don't store anything the owner inbox doesn't render.--## Data / API changes--- `api/cron/irl-reap.js`: deletes orphaned + aged-out interactions; richer summary.-- `api/irl/interactions.js`: new `created_at` index; documented retention window.-- No new endpoints. The on-demand cascade for user-initiated deletes lives in **H5**.--## Acceptance checklist--- [ ] Reaper deletes interactions orphaned by a removed pin (existence-guarded).-- [ ] Reaper ages out interactions past the documented window; index-backed.-- [ ] Reaper summary reports `reapedInteractions`; idempotent re-run deletes nothing new.-- [ ] Retention window + any column-minimization decision documented in the file header.-- [ ] H1 suite extended: an orphaned interaction is reaped; a fresh-DB run (no table) doesn't 500.-- [ ] `npm test` + `npm run typecheck` green.--## Out of scope--The user-facing "delete my data / forget device" actions (**H5** — which call the-same cascade on demand). Changing pin expiry windows.--## Verify--Invoke the reaper locally with the cron secret against a DB seeded with an-interaction whose pin was deleted and one older than the window; confirm both are-removed and the summary counts them; re-run and confirm zero further deletions.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-hardening/H6-retention-data-minimization.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-hardening/H7-anti-scrape-resilience.md b/tasks/irl-hardening/H7-anti-scrape-resilience.mddeleted file mode 100644index 34b9cec47..000000000--- a/tasks/irl-hardening/H7-anti-scrape-resilience.md+++ /dev/null@@ -1,111 +0,0 @@-# H7 — Anti-scrape resilience, fail-closed reads, anomaly alerting--> Epic IRL-Hardening · Size **M** · Touches `api/irl/pins.js`,-> `api/_lib/rate-limit.js` (read its limiter semantics), `api/_lib/alerts.js`,-> and the H1 suite. Builds on **H3** (proof-of-presence).--## Goal--Prove — with tests and runtime behavior — that the public nearby read cannot be-turned into a bulk location-harvesting tool, and that it **fails closed** under-stress rather than opening the floodgates. Add anomaly detection so sweep-shaped-traffic is surfaced to ops, and document the residual threat model so the team-ships with eyes open.--## Why it matters--A location feed is only as private as its worst day. The dangerous failure mode is-silent: a limiter outage that fails *open*, a radius cap that's accidentally-widened, or a slow methodical sweep that never trips a per-minute counter. "We rate-limit it" is not a guarantee until it's tested at the boundary and the degradation-path is known. This task converts assumptions into asserted, monitored facts.--## Current state (verified)--- `api/irl/pins.js` read path: `radius` clamped `[10,60]`, default 40; IP- rate-limit `limits.publicIp`; coarse allow-list projection; coords coarsened- (`roundCoord`, shipped). With **H3**, reads also require a cell-bound fix token.-- `api/_lib/rate-limit.js` limiters return `{ success, reason }`; some buckets- "fail closed" with `rate_limiter_unavailable`, others fail open (per the- `redis-quota-incident` + `http.js` `rateLimited` reason handling). **The read- path's degradation behavior must be verified, not assumed.**-- `api/_lib/alerts.js` `sendOpsAlert` exists (deduped by signature) and is already- used for IRL pay events — reuse for anomaly alerts.--## What to build--### 1. Verify + enforce fail-closed on the read--Audit which limiter backs the nearby read and what it does when Redis is degraded.-For the **public location read**, a degraded limiter must **fail closed** (reject-with a retryable `rate_limiter_unavailable`, surfaced by the client as "temporarily-unavailable, retrying"), never fail open into an unmetered scrape window. If the-current bucket fails open, switch the read to a fail-closed bucket or add an-explicit guard. Document the decision in the handler.--### 2. Boundary tests (in the H1 suite)--- A request with `radius` > 60 is clamped to 60 (already true — pin it).-- A burst past the per-IP ceiling returns 429 with `Retry-After`.-- With the limiter forced into its degraded state, the read **rejects** (closed),- not serves.-- With **H3** active: a single fix token can only read its own cell (+ neighbors),- so a token-per-cell sweep needs a real fix per cell — assert a far-cell read- with a near-cell token is denied.--### 3. Sweep anomaly detection → ops alert--Add lightweight per-IP/-device counters (Redis, short TTL) tracking **distinct-cells read** within a window. A single caller reading many distinct geocells in a-short time is sweep-shaped (a real user stays in ~1 cell). Past a threshold, fire a-deduped `sendOpsAlert('IRL sweep suspected', …)` with the IP/device hash and cell-count — **never** with any coordinate or token (route through the same discipline-as `redactUrl`). Optionally auto-tighten that caller's limit for a cooldown.--### 4. Document the residual threat model--Add a short, honest `THREAT-MODEL.md` (in this folder or `docs/`) stating what the-read protects against (remote browsing, bulk harvest, deanonymization via owner id,-log/Referer credential leak) and the accepted residual (someone physically present-can, by definition, see the handful of pins right where they stand — that's the-product). No silent caps: if any limit drops coverage, it's written down.--## Data / API changes--- No new public endpoints. New internal Redis counters (short TTL).-- New ops-alert signal `IRL sweep suspected` (coordinate-free).-- New doc: `THREAT-MODEL.md`.--## Acceptance checklist--- [ ] The nearby read fails **closed** under limiter degradation (verified by test).-- [ ] Radius clamp, burst 429, and (with H3) cross-cell denial are asserted in H1.-- [ ] Distinct-cell sweep detection fires a deduped, coordinate-free ops alert past threshold.-- [ ] `THREAT-MODEL.md` documents protections + accepted residual + any coverage caps.-- [ ] No alert/log path emits a coordinate or token (reuse the redaction discipline).-- [ ] `npm test` + `npm run typecheck` green.--## Out of scope--The proof-of-presence mechanism itself (**H3**, a dependency) and per-account-reputation/banning (future). This task verifies, monitors, and documents.--## Verify--Run the boundary tests green. Locally force the limiter degraded and confirm the-read rejects. Simulate a multi-cell sweep against a dev instance and confirm a-single deduped ops alert fires with counts only — no coordinates.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-hardening/H7-anti-scrape-resilience.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-live/C1-dashboard-overview.md b/tasks/irl-live/C1-dashboard-overview.mddeleted file mode 100644index 37f6563fe..000000000--- a/tasks/irl-live/C1-dashboard-overview.md+++ /dev/null@@ -1,151 +0,0 @@-# C1 — Owner dashboard overview (live IRL agent monitoring)--> Epic C · Size **M** · Extends `src/dashboard-next/pages/irl-placements.js`.-> Foundation for C2–C6 — every per-agent action surface links off this card.--## Goal--Turn the flat "My Placed Avatars" list into a real **monitoring overview**. Each-placed-agent card surfaces, at a glance: live $THREE/SOL balance, online/visible-status, last-seen + last-interaction time, lifetime interaction count, and a-human location label. From each card the owner opens the management surfaces-(skills, reputation, location, outfit, inbox) built in C2–C6.--## Why it matters--A pin you can't observe is dead weight. Owners place an agent somewhere they-aren't standing, then leave. The dashboard is their only window onto whether-the agent is working, earning, and being interacted with. Without live signal-the product is a write-only toy. This card is the home base for the whole epic.--## Current state (real lines)--- `src/dashboard-next/pages/irl-placements.js:131` `mount(el)` renders skeletons- (`:141`), fetches `GET /api/irl/pins?mine=1` (`:145`), renders `cardHtml` (`:97`),- then reverse-geocodes each pin one-at-a-time (`:169`). Remove + caption edit are- wired via delegation (`:184`).-- `api/irl/pins.js:80` the `?mine=1` branch already selects- `id, lat, lng, heading, avatar_url, avatar_name, caption, agent_id, placed_at, expires_at`.- **`agent_id` is already returned** — the link to the agent record exists.-- Balance source: `api/agents/solana-wallet.js:257` `handlePublicWalletRead`- returns `{ data: { wallet, balance, lamports, balance_error } }` (no auth, 60 s- cached). Route: `GET /api/agents/:id/solana`.-- No status/last-seen/interaction-count exists yet — C4 introduces `irl_interactions`.--## What to build--### 1. `GET /api/irl/agent-summary?mine=1` (new, in `api/irl/pins.js` or sibling)--One round-trip that joins each owned pin to its agent + derived activity, so the-card paints without N balance calls blocking first render.--```js-// auth required; returns one row per owned pin-const rows = await sql`- SELECT p.id AS pin_id, p.agent_id, p.lat, p.lng, p.heading, p.caption,- p.avatar_url, p.avatar_name, p.placed_at, p.expires_at,- a.name AS agent_name, a.meta->>'solana_address' AS solana_address,- a.meta->>'solana_asset' AS solana_asset,- COALESCE(ix.total, 0) AS interaction_count,- ix.last_at AS last_interaction_at- FROM irl_pins p- LEFT JOIN agent_identities a ON a.id = p.agent_id AND a.deleted_at IS NULL- LEFT JOIN (- SELECT pin_id, COUNT(*)::int AS total, MAX(created_at) AS last_at- FROM irl_interactions GROUP BY pin_id -- table from C4- ) ix ON ix.pin_id = p.id- WHERE p.user_id = ${session.id}- ORDER BY p.placed_at DESC LIMIT 100`;-```--If `irl_interactions` is not yet created (C4 not shipped), wrap the LEFT JOIN in a-`to_regclass('irl_interactions') IS NOT NULL` guard and fall back to `0`/`NULL` —-never 500. Status is **derived**: `online` if a nearby-fetch touched the pin in-the last 5 min (C4/D1 will write `last_seen_at`); until then derive `visible` from-`expires_at > NOW()`.--### 2. Card upgrade in `irl-placements.js`--Keep `mountShell` + `requireUser` + `get()` exactly as-is. Replace the-hand-rolled skeleton/empty/error with **state-kit**:--```js-import { skeletonHTML, emptyStateHTML, errorStateHTML, ensureStateKitStyles, attachRetry }- from '../../shared/state-kit.js';--ensureStateKitStyles();-list.innerHTML = `<div class="irl-grid">${skeletonHTML(3, 'row')}</div>`;-// error → errorStateHTML({ title:'Couldn't load your IRL agents', scope:'irl' }); attachRetry(list, render)-// empty → emptyStateHTML({ title:'No agents placed yet', body:'…', actions:[{label:'Open IRL', href:'/irl', primary:true}] })-```--Extend `cardHtml(pin, geo)` with a stats strip (skeleton values first, hydrated-after). Render a **balance chip** (`—` skeleton → `0.42 SOL` / `Balance-unavailable` on `balance_error`), a **status dot** (green online / amber visible /-grey expired), **last interaction** (`relTime`), and an **interaction count**.-Add a tab/link row on each card to the C2–C6 surfaces:--```-[Skills] [Reputation] [Location] [Outfit] [Inbox •3] View in IRL ↗ Remove-```--Each is an anchor/button carrying `data-pin="${pin.id}" data-agent="${pin.agent_id}"`.-Disable Skills/Reputation/Outfit (with a tooltip) when `agent_id` is null — an-anonymously-placed avatar has no agent record to manage.--### 3. Balance hydration (parallel, non-blocking)--After cards paint, fan out exactly like `widgets.js:78` does with stats:--```js-const bals = await Promise.allSettled(rows.map(r =>- r.agent_id ? get(`/api/agents/${encodeURIComponent(r.agent_id)}/solana`) : Promise.reject('no-agent')));-bals.forEach((res, i) => applyBalanceToCard(card(i),- res.status === 'fulfilled' ? res.value.data : { balance_error: 'unavailable' }));-```--Render `balance_error` as the literal "Balance unavailable" chip (per the-wallet-card convention) — never show a misleading `0`.--## Data / API changes--- New: `GET /api/irl/agent-summary?mine=1` → `{ agents: [...] }` (auth). Register- its route in `vercel.json` (mirror the `/api/irl/pins` entry).-- No `irl_pins` schema change. Reuses `agent_identities.meta.solana_address`.-- Reuses existing `GET /api/agents/:id/solana` for balance.--## Acceptance checklist--- [ ] `GET /api/irl/agent-summary?mine=1` returns agents w/ counts; degrades to- `0`/`null` when `irl_interactions` absent; never 500s.-- [ ] Card shows balance chip, status dot, last-seen, interaction count, location.-- [ ] Balance hydrates in parallel after first paint; `balance_error` → "Balance- unavailable", not `0`.-- [ ] state-kit skeleton/empty/error with working Retry.-- [ ] Each card links to C2–C6 surfaces (disabled + tooltip when `agent_id` null).-- [ ] Reverse-geocode label preserved; 320 / 768 / 1440px clean; no console errors.--## Out of scope--Realtime push of status (D1/D3), the management panels themselves (C2–C6), and-the interaction table itself (C4) — this card only *reads* and *links*.--## Verify--`npm run dev` → `/dashboard/irl-placements` with ≥1 placed agent: confirm the-Network tab shows one `agent-summary` call + parallel `…/solana` calls, balance-chips resolve to real on-chain values, and every card link navigates.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-live/C1-dashboard-overview.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-location-control/L1-simulated-location-dev.md b/tasks/irl-location-control/L1-simulated-location-dev.mddeleted file mode 100644index 6652a5a8a..000000000--- a/tasks/irl-location-control/L1-simulated-location-dev.md+++ /dev/null@@ -1,139 +0,0 @@-# L1 — Simulated location for testing (DEV-only)--> Epic · Size **S** · Touches `src/irl.js` only. DEV-gated, tree-shaken — never ships.-> The direct fix for "I want to test `/irl` on my iPhone without leaking my real spot."--## Goal--Let a developer or QA run the **entire** real `/irl` flow — place a pin, see the-nearby read, lock/anchor — at **any chosen coordinate**, with zero dependency on-the device's real GPS. Enabled two ways, both gated behind `import.meta.env.DEV`-so they are stripped from production bundles exactly like the existing-`__irlSeed*` harness (`src/irl.js:4405`):--- **URL param:** `…/irl?mockLoc=37.7749,-122.4194` (optionally `&mockAcc=8`).-- **Console:** `__irlMockLocation(37.7749, -122.4194)` to set, `__irlMockLocation(null)` to clear.--While active, a persistent on-screen **"SIMULATED LOCATION"** badge is shown so a-fake fix can never be mistaken for a real one, and the real `watchPosition` is-suppressed so no real coordinate is ever read or transmitted.--## Why it matters--Two hard blocks make on-device testing leak the tester's real location today:--1. **iOS Safari cannot spoof location** — no DevTools Sensors panel, and Web- Inspector has no geolocation override. The only system-wide spoof is a paid- third-party tool. So a real-device test writes the tester's true coordinates- into the public `irl_pins` feed.-2. **A LAN dev build can't read GPS at all.** `navigator.geolocation` requires a- secure context; over `http://<lan-ip>:3000` it's blocked, so `onGPSPosition`- (`src/irl.js:1227`) never fires and the place flow is untestable.--Seeding `gpsState` directly sidesteps both: the flow runs on the fake fix, real-GPS is never touched, and it works over plain-http LAN. This is the foundation-that lets L2–L5 be exercised on a real phone safely.--## Current state (real lines)--- `src/irl.js:1123` `const gpsState = { lat: null, lng: null, ready: false, watchId: null, accuracy: null, altitude: null }`.-- `src/irl.js:1336` `initGPS()` starts the single `watchPosition` (idempotent on `gpsState.watchId`).-- `src/irl.js:1227` `onGPSPosition(pos)` is the only writer of `gpsState.lat/lng/ready`; on the **first** fix it calls `revealMyPinsBtn()` and `startPinSync()`, and resolves a `_pendingGpsLock`.-- `src/irl.js:4405` `if (import.meta.env.DEV) { window.__irlSeedPins = …; window.__irlPerf = …; window.__irlSeedRoom = …; }` — the established DEV-only window-API pattern to mirror.--## What to build--### 1. A single `applyMockFix(lat, lng, accuracy)` path--Reuse the real first-fix sequence rather than duplicating it. Factor the body of-`onGPSPosition`'s first-fix branch (seed `gpsState.lat/lng`, `ready = true`, then-`revealMyPinsBtn()` + `startPinSync()` + resolve `_pendingGpsLock`) into a small-helper, and have both `onGPSPosition` and `applyMockFix` call it, so a simulated-fix exercises the identical downstream code as a real one.--```js-// DEV-only. Seeds a synthetic fix and stops the real watch so no real coord is read.-function applyMockFix(lat, lng, accuracy = 10) {- if (gpsState.watchId != null) { navigator.geolocation.clearWatch(gpsState.watchId); gpsState.watchId = null; }- _mockLocation = true;- gpsState.accuracy = accuracy;- gpsState.altitude = null;- onFirstOrBlendedFix(lat, lng); // the extracted shared helper- showMockBadge(lat, lng);-}-```--`initGPS()` must early-return when `_mockLocation` is set so a later call can't-re-attach the real watch and overwrite the fake fix.--### 2. URL-param entry (parse once at boot, DEV-only)--Inside the existing `if (import.meta.env.DEV) { … }` block, parse `mockLoc`-(`"lat,lng"`, both finite, lat ∈ [-90,90], lng ∈ [-180,180]) and optional-`mockAcc`. On a valid value call `applyMockFix(...)` and skip `initGPS()`. On a-malformed value, `log.warn` and fall through to real GPS — never throw.--### 3. Console entry + badge--```js-window.__irlMockLocation = (lat, lng, acc = 10) => {- if (lat == null) { /* clear: hide badge, _mockLocation=false, initGPS() to resume real */ return 'cleared'; }- if (!Number.isFinite(lat) || !Number.isFinite(lng)) return 'usage: __irlMockLocation(lat, lng[, accuracyM])';- applyMockFix(lat, lng, acc);- return { mocked: { lat, lng, acc } };-};-```--The **badge** is a fixed-position pill (top-center, high z-index, `pointer-events:none`)-reading `📍 SIMULATED LOCATION · 37.7749, -122.4194`. Style it unmistakably (amber-border, mono coords) — its entire job is to prevent confusing a fake fix for real.-Tapping it does nothing; clearing the mock removes it.--### 4. Persist nothing, ship nothing--`_mockLocation` lives in module scope only (no localStorage — a refresh without the-param returns to real GPS). The whole feature sits inside `import.meta.env.DEV`-guards so Vite tree-shakes it out of the production build. **Verify the prod bundle-contains neither `__irlMockLocation` nor `SIMULATED LOCATION`.**--## Data / API changes--None. Client-only. No new endpoint, no schema change. The real `POST /api/irl/pins`-runs unchanged — it simply receives the simulated coordinate.--## Acceptance checklist--- [ ] `?mockLoc=37.7749,-122.4194` makes `gpsState.ready` true at that point with **no** real GPS prompt; My-pins reveals; nearby read fires for the fake spot.-- [ ] `__irlMockLocation(lat,lng)` sets, `__irlMockLocation(null)` clears and resumes real GPS.-- [ ] The real `watchPosition` is cleared/never started while mock is active; `initGPS()` is a no-op under mock.-- [ ] Placing a pin while mocked writes the **simulated** coordinate (confirm the POST body in the Network tab).-- [ ] The "SIMULATED LOCATION" badge shows the active coords and disappears on clear.-- [ ] Malformed `mockLoc` logs a warning and falls back to real GPS — no throw, no console error.-- [ ] **Production bundle (`npm run build`) contains no `__irlMockLocation` / `SIMULATED LOCATION` / `mockLoc` strings.**--## Out of scope--A user-facing "set my location" UI (that's L2's map picker). Persisting the mock-across reloads. Faking compass/heading (the magnetometer is untouched — heading-still reflects the real device, which is fine for placement testing).--## Verify--`npm run dev`, then:-1. Desktop: open `/irl?mockLoc=37.7749,-122.4194` → badge shows, no location prompt, place a pin → POST body carries `37.7749/-122.4194`.-2. Real iPhone over LAN: connect the phone to the same network, open `http://<your-lan-ip>:3000/irl?mockLoc=…` → the flow runs even though plain-http GPS is blocked; the pin lands at the fake spot, not your home.-3. `npm run build` → `grep -r "__irlMockLocation\|SIMULATED LOCATION" dist/` returns nothing.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-location-control/L1-simulated-location-dev.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-location-control/L2-map-placement-picker.md b/tasks/irl-location-control/L2-map-placement-picker.mddeleted file mode 100644index a3767be40..000000000--- a/tasks/irl-location-control/L2-map-placement-picker.md+++ /dev/null@@ -1,133 +0,0 @@-# L2 — "Choose where to place" map picker--> Epic · Size **M** · Touches `src/irl.js` + `pages/irl.html` (UI) · reuses the-> Leaflet/Nominatim approach from `src/dashboard-next/pages/irl-placements.js`.--## Goal--When a user places an agent, give them a real choice instead of silently writing-their exact GPS:--- **Use my location (precise)** — the current behavior: anchor at the live fix.-- **Pick a spot on a map** — open a Leaflet picker (search + draggable marker),- confirm a chosen point, and `savePin` uses *that* coordinate.--This is both the headline **privacy** win for real users (place your agent at a-chosen public spot — a café, a plaza, a venue — without your home coordinates ever-entering the feed) and a UX upgrade (place an agent somewhere you're planning to-be, or somewhere meaningful, not only where you're standing right now).--## Why it matters--The product premise is "agents anchored to real places," but forcing precise GPS-means the *only* place a user can pin is wherever they currently are — usually-home. That is a privacy non-starter for a public feed and it caps the product:-people want to place an agent at a landmark, an event, a storefront. A map picker-removes the leak and unlocks intentional placement. It mirrors how every mature-location product (Find My, Airbnb, Uber) lets you confirm/adjust a point rather-than trusting a raw fix.--## Current state (real lines)--- `src/irl.js:1313` `anchorGpsPin()` and `src/irl.js:1454` `openCaptionPanel()` both- end at `savePin(lat, lng, heading, caption, anchor)` (`:1351`) which POSTs to- `/api/irl/pins`. Placement coordinates today come straight from `gpsState`.-- `api/irl/pins.js:554` POST already validates and stores arbitrary `lat`/`lng`- (range-checked `:566`), so **no server change is required** to accept a picked point.-- `src/dashboard-next/pages/irl-placements.js:1083` lazy-loads Leaflet from- `https://esm.sh/[email protected]` + CSS from unpkg (`ensureLeafletCss`/`loadLeaflet`),- dark-themed (`:339`); `reverseGeocode` (`:111`) hits Nominatim. **Copy this loader- and theme verbatim** — do not introduce a second map stack.--## What to build--### 1. Placement-source chooser--Before the caption panel opens, present two clear choices (a small designed-sheet, not a browser confirm):--```-How should we place this agent?- ◉ Use my location ~precise · within {accuracy}m- ○ Pick a spot on a map choose any point-```--Default to "Use my location" when `gpsState.ready`; default to (and only offer)-the map when there's no fix. Selecting the map opens the picker; selecting precise-goes straight to the existing caption/anchor flow unchanged.--### 2. Leaflet picker sheet--A full-width bottom sheet (mobile-first) containing:--- A Leaflet map, dark theme, centered on `gpsState` if available else a sensible- default, zoom ~16. Lazy-load via the dashboard's `loadLeaflet()`/`ensureLeafletCss()`- pattern — **with a designed loading skeleton and a retry error state** if the CDN- fails (Rule 9: never a blank map).-- A **draggable center marker** (or tap-to-move) — the agent drops where the marker- sits. Show the live `lat, lng` + a debounced `reverseGeocode` label under the map.-- A **search box** (Nominatim `/search?q=`) so a user can type "Dolores Park, SF"- and fly the map there. Debounce input; handle empty/no-results/error states.-- **Confirm** ("Place here") and **Cancel**. Confirm closes the picker and calls- the normal caption flow with the chosen `{ lat, lng }`; heading falls back to the- device compass or 0.--### 3. Wire chosen coordinate through `savePin`--Thread the picked point so `savePin` posts it instead of `gpsState`. A map-picked-pin is **not** GPS-anchored, so set the anchor pose `source` accordingly — pass-`source: 'map'` (the server already normalizes unknown sources; extend the-`anchor_source` allow-list note in `api/irl/pins.js:688` to record `'map'` so the-viewer/A3 knows this pin's bearing isn't compass-trustworthy). Caption/avatar/x402-flow is unchanged.--### 4. Designed states + a11y--Loading (map tiles), empty (search no-results), error (CDN/tiles/Nominatim-failure → retry), and a clear "you're placing remotely" hint. Keyboard: search-focusable, Confirm/Cancel reachable, `Esc` cancels. Marker has an ARIA label.-Respect 320 / 768 / 1440px.--## Data / API changes--- **No schema change.** POST already accepts arbitrary in-range `lat`/`lng`.-- Add `'map'` to the recognized `anchor_source` values (doc + the normalize line at- `api/irl/pins.js:688`) so a map-placed pin is distinguishable from a `gyro-gps` one.-- New external calls: Nominatim `/search` (in addition to the existing `/reverse`).- Reuse the dashboard's memoized client + a short timeout; never block placement on it.--## Acceptance checklist--- [ ] Placement offers "Use my location" vs "Pick a spot on a map"; precise path is byte-for-byte the current flow.-- [ ] Map picker lazy-loads Leaflet (dashboard pattern), dark theme, draggable marker, working search, live reverse-geocode label.-- [ ] Confirm places the agent at the **picked** coordinate (verify POST body); Cancel returns with nothing written.-- [ ] Map load failure / no GPS / no search results each render a designed, retryable state — never a blank map.-- [ ] `anchor_source` records `'map'` for map-placed pins.-- [ ] 320 / 768 / 1440px clean; keyboard + ARIA pass; no console errors/warnings.-- [ ] `data/changelog.json` entry added (`feature`); `npm run build:pages` passes.--## Out of scope--Moving/relocating an *existing* pin (that's the dashboard's remote-location-management + L5). Precise-vs-approximate *discovery* of nearby agents (L3/L4).-A custom tile server — OSM tiles via Leaflet default are fine.--## Verify--`npm run dev` → `/irl`: place via "Pick a spot on a map," search a landmark, drag-the marker, Place here → Network tab shows the POST with the picked coords and-`anchor_source:'map'`; the agent renders; your real GPS never entered the request.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-location-control/L2-map-placement-picker.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-location-control/L3-location-privacy-center.md b/tasks/irl-location-control/L3-location-privacy-center.mddeleted file mode 100644index ba2f37c4b..000000000--- a/tasks/irl-location-control/L3-location-privacy-center.md+++ /dev/null@@ -1,125 +0,0 @@-# L3 — Location Privacy Center + disclosure--> Epic · Size **M** · Touches `src/irl.js`, `pages/irl.html`, `src/irl/onboarding.js`.-> Owns the controls + copy; **L4** implements the approximate-discovery behavior this toggles.--## Goal--One designed, reachable surface in `/irl` — a **"Location & privacy"** sheet —-that tells the user, in plain language, exactly what is shared and gives them the-controls in one place:--1. **What's stored & who sees it** — honest disclosure: a placed pin's coordinates- reach another person *only* when they're physically within ≤60 m of it, never as- a map/roster, never with your account id; anonymous pins auto-expire in 7 days.-2. **Discovery precision** — *Precise* (default) vs *Approximate*: when approximate,- the coordinate sent to the nearby read is coarsened on-device (L4) so browsing- doesn't hand the server your exact position.-3. **Appear to others** — surface the existing presence opt-in (`getShareGhost`,- default off) here so every location-sharing control lives together.-4. **Manage placements** — a link straight into the My-pins sheet (L5).--Plus a **first-run disclosure**: the first time location is granted, a short,-designed explainer (not a wall of text) covering the same three facts, wired into-the existing onboarding so it's shown once and never nags again.--## Why it matters--The user's literal worry — "my actual location is going to leak" — is mostly a-*trust* problem, and trust is built with disclosure and control, not silence. The-privacy posture is already strong (tight radius, no roster, owner-id stripped,-7-day expiry) but it's **invisible**: nothing in the UI tells the user any of it,-and the one real lever (don't broadcast exact position while browsing) doesn't-exist yet. A single honest control center turns an anxious tester into a confident-user and is the difference between "felt creepy" and "felt in control."--## Current state (real lines)--- `src/irl.js:1820` `getShareGhost()` / `setShareGhost()` (localStorage `irl_share_ghost`,- default off), toggle handler `:2578`, `syncGhostToggle` `:2568`, comment at `:1815`- documenting count-only presence. The presence control exists but lives alone.-- `src/irl.js:2009` `loadNearbyPins()` sends `gpsState.lat/lng` verbatim (`:2016`) — the- exact-position-while-browsing vector L4 fixes; L3 provides the toggle that drives it.-- `src/irl/onboarding.js:22` `PERMS.location`, persisted outcomes (`SAVE_KEY`), designed- state cards via state-kit — the place to attach first-run disclosure.-- `src/irl.js:2561` My-pins button + `openMyPinsSheet` (`:2514`) — link target.--## What to build--### 1. "Location & privacy" sheet--A bottom sheet opened from a small shield/location control in the `/irl` topbar.-Sections, each with microcopy:--- **What others can see** — 2–3 plain sentences with the real facts (≤60 m radius,- no map/roster, no account id, anonymous pins expire in 7 days). No legalese.-- **Discovery precision** — a segmented control: `Precise · exact` / `Approximate ·- ~city-block`. Persist to localStorage (`irl_discovery_precision`, default `precise`).- Expose the chosen mode so `loadNearbyPins` (L4) reads it. Copy explains the- trade-off: approximate keeps your exact position off the server but may surface- agents a little less precisely.-- **Appear to others** — move the existing ghost toggle here (keep the topbar pill- too, or make this the canonical home and have both reflect the same state via- `syncGhostToggle`). Default off; copy matches `:1815`.-- **Your placements** — a row that opens the My-pins sheet ("Manage / remove the- agents you've placed →").--All four sections use state-kit styling; the sheet is keyboard-navigable, `Esc`-closes, controls have ARIA roles/labels, and it's clean at 320 / 768 / 1440px.--### 2. First-run disclosure (onboarding)--In `src/irl/onboarding.js`, after location is **granted** for the first time, show-a one-screen disclosure card (reuse the module's card renderer) with the same-three facts + a single "Got it" action, then persist a flag (e.g.-`irl_location_disclosed_v1`) so it never shows again. Do **not** block the flow —-it's informational, dismissible, shown once. If location is denied/unsupported,-skip it (onboarding already handles those states).--### 3. Persistence helpers--Add `getDiscoveryPrecision()` / `setDiscoveryPrecision()` next to the ghost helpers-(`src/irl.js:1820`), localStorage-backed, try/catch-guarded like the existing ones.-Export/expose the getter so L4's `loadNearbyPins` can read it without a circular hop.--## Data / API changes--None server-side. Purely client state (localStorage) + UI. L4 consumes-`getDiscoveryPrecision()`; this task ships the control and the default (`precise`),-so behavior is unchanged until L4 lands the coarsening.--## Acceptance checklist--- [ ] A "Location & privacy" control in the `/irl` topbar opens the sheet.-- [ ] Sheet shows honest "what others can see" copy, a precise/approximate toggle (persisted, default precise), the presence opt-in, and a link into My-pins.-- [ ] Ghost toggle state stays in sync wherever it's shown (`syncGhostToggle`).-- [ ] First location grant shows a one-time disclosure card; it never re-shows; denied/unsupported skip it.-- [ ] `getDiscoveryPrecision()` exists, defaults `precise`, persists across reload.-- [ ] Keyboard + ARIA pass; 320 / 768 / 1440px clean; no console errors/warnings.-- [ ] `data/changelog.json` entry added (`feature`/`improvement`); `npm run build:pages` passes.--## Out of scope--The actual coordinate coarsening on the nearby read (**L4** — this task only ships-the toggle + default). The map placement picker (L2). My-pins internals (L5).--## Verify--`npm run dev` → `/irl`: open Location & privacy, flip to Approximate (persists on-reload), confirm the disclosure copy reads honestly against `api/irl/pins.js`-behavior, follow the link into My-pins. Fresh profile (clear localStorage), grant-location → the one-time disclosure card appears once.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-location-control/L3-location-privacy-center.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-location-control/L4-proximity-read-hardening.md b/tasks/irl-location-control/L4-proximity-read-hardening.mddeleted file mode 100644index 9eaf8e86c..000000000--- a/tasks/irl-location-control/L4-proximity-read-hardening.md+++ /dev/null@@ -1,126 +0,0 @@-# L4 — Proximity-read privacy hardening--> Epic · Size **M** · Touches `src/irl.js` (client coarsening) + `api/irl/pins.js`-> (logging/PII). Consumes the toggle from **L3**. Closes the browsing-leak vector.--## Goal--Make *browsing* `/irl` stop broadcasting the viewer's exact position. Two halves:--1. **Client (Approximate discovery):** when the L3 precision toggle is- `approximate`, snap the caller's own `lat/lng` to a coarse grid (~75–150 m)- before the nearby read, so the server only ever receives a fuzzed origin. The- proximity radius still finds nearby agents; the viewer's precise position never- leaves the device.-2. **Server (no exact-coordinate logging):** ensure `api/irl/pins.js` never writes- precise caller coordinates to logs, and document retention. The endpoint already- strips owner ids from the response and IP-rate-limits scraping — this closes the- remaining "our own logs know where everyone stood" gap.--## Why it matters--Placement is the obvious leak, but the quieter one is **reads**: every ~10 s,-`loadNearbyPins` sends the viewer's exact GPS to the server to ask "who's near me?"-A user who never places a single pin is still continuously telling the backend-(and any log sink) precisely where they are. For a location product, hardening the-read is as important as hardening the write — and "Approximate" is the concrete-lever L3 promises the user. Coarsening client-side means the precise coordinate is-never transmitted at all, which is strictly stronger than trusting the server to-forget it.--## Current state (real lines)--- `src/irl.js:2009` `loadNearbyPins()` → `src/irl.js:2016`- `fetch('/api/irl/pins?lat=${gpsState.lat}&lng=${gpsState.lng}&radius=${NEARBY_RADIUS}')`- — sends full-precision coordinates on every poll.-- `api/irl/pins.js:467` the GET nearby branch parses `lat`/`lng` (`:468`), clamps- `radius` to ≤60 m (`:473`), IP-rate-limits the read (`:415`), and projects out- `user_id`/`device_token` (`:504`). No caller-coordinate logging exists today —- **keep it that way and assert it** (a future `console.log(req.query)` would regress this).-- L3 provides `getDiscoveryPrecision()` (default `precise`).--## What to build--### 1. Client-side coarsening (the Approximate behavior)--In `loadNearbyPins`, when `getDiscoveryPrecision() === 'approximate'`, snap the-origin to a fixed grid before building the URL:--```js-// ~111 m per 0.001° lat. Snap to a ~150 m cell so the exact origin never leaves the device.-const CELL_DEG = 0.0015;-function coarsen(v) { return Math.round(v / CELL_DEG) * CELL_DEG; }--const precise = getDiscoveryPrecision() !== 'approximate';-const qLat = precise ? gpsState.lat : coarsen(gpsState.lat);-const qLng = precise ? gpsState.lng : coarsen(gpsState.lng);-```--Send `qLat/qLng`. Because the snapped origin can sit up to ~one cell from the true-position, **widen the request radius by one cell** in approximate mode (still-clamped server-side to 60 m) so a nearby agent isn't missed, and keep computing the-on-screen distance/threshold against the *true* `gpsState` locally (the server's-`distance_m` is advisory; the client already places pins from the live origin).-Document the precision/recall trade-off in a comment — approximate trades a little-placement precision for not transmitting an exact position.--### 2. Server: assert no exact-coordinate logging + retention note--- Audit the GET path in `api/irl/pins.js` and add a short comment at `:467`- stating the contract: **caller `lat`/`lng` are used for the proximity query and- are never logged.** If any debug log of `req.query`/coords exists anywhere on this- path, remove it.-- Add a one-line note (in the file header or near `ensureTable` `:167`) that- `irl_pins` stores placement coordinates only; proximity *reads* are not persisted- beyond the rate-limit counter (which keys on IP, not coordinates).-- Keep the existing IP rate-limit + owner-id-stripped projection exactly as-is.--### 3. No behavior change when precise--Default is `precise`, so unless the user opted into Approximate in L3, the read is-byte-identical to today. This task adds a lever, it doesn't degrade the default-experience.--## Data / API changes--- **No schema or endpoint signature change.** Same `GET /api/irl/pins?lat&lng&radius`.-- Client may send a slightly larger `radius` in approximate mode (server still clamps ≤60 m).-- Documentation/comments only on the server; a possible deletion of any stray- coordinate log line.--## Acceptance checklist--- [ ] In Approximate mode, the nearby request URL carries a grid-snapped `lat/lng` (verify in Network tab — the exact `gpsState` value is **not** present).-- [ ] In Precise mode, the request is unchanged from today.-- [ ] Nearby agents within the radius still resolve in approximate mode (radius widened by one cell, on-screen distances computed from the true origin).-- [ ] `api/irl/pins.js` GET path provably logs no caller coordinates; contract comment added; retention note added.-- [ ] Existing IP rate-limit + owner-id-stripped projection untouched.-- [ ] No console errors; precise-mode behavior identical to pre-change.--## Out of scope--The toggle UI + persistence (L3). Placement coordinate privacy (L2 — placement is-a deliberate, user-chosen write; this task is only about the passive read).-Server-side geofuzzing of *stored* pins (placement stays precise so the AR walk-up-works).--## Verify--`npm run dev` → `/irl` with a fix (real or L1 mock): in Precise mode confirm the-nearby URL has full-precision coords; flip to Approximate (L3) and confirm the URL-coords are snapped to the grid while nearby agents still render. Grep the server-path to confirm no coordinate is logged.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-location-control/L4-proximity-read-hardening.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-location-control/L5-my-pins-management-upgrade.md b/tasks/irl-location-control/L5-my-pins-management-upgrade.mddeleted file mode 100644index f18807951..000000000--- a/tasks/irl-location-control/L5-my-pins-management-upgrade.md+++ /dev/null@@ -1,133 +0,0 @@-# L5 — My-pins management upgrade--> Epic · Size **S** · Touches `src/irl.js` (My-pins sheet) · reuses the Leaflet-> loader from `src/dashboard-next/pages/irl-placements.js`. Builds on the existing sheet.--## Goal--Make the existing **My-pins** sheet a real management surface so a tester (or any-user) can see and purge what they've placed in seconds:--1. **Map overview** — a small Leaflet map at the top of the sheet plotting every- pin this device/account owns, so "where did I drop things?" is answered visually.-2. **Expiry countdown** — each row shows `expires in 6d` (anonymous) or `permanent`- (signed-in), so a tester knows exactly when a forgotten test pin self-destructs.-3. **Remove all from this device** — a guarded bulk purge (confirm step) that deletes- every pin tied to the local device token in one action, for fast cleanup after testing.--## Why it matters--The whole anxiety in "I'm worried my location will leak" is really "and I won't be-able to take it back." The sheet today lists pins and deletes them one at a time-(`deleteMyPin`), with no map and no expiry visibility. After a testing session you-might have a dozen pins at (or near) a real spot and no fast way to confirm they're-gone. A map + countdown + one-tap purge turns cleanup from a chore into a reflex —-which is exactly what makes people comfortable experimenting in the first place.--## Current state (real lines)--- `src/irl.js:2476` `loadMyPins()` → `GET /api/irl/pins/mine?deviceToken=` returns- `id, lat, lng, avatar_name, caption, placed_at, expires_at, view_count`- (`api/irl/pins.js:428`) — **expiry + coords already come back**, nothing new to fetch.-- `src/irl.js:2501` `renderMyPins(pins, listEl)` paints rows; `:2531` `deleteMyPin(id, btn)`- does the per-row DELETE; `:2466` `MYPINS_EMPTY` is the shared empty state;- `:2442` `relativeTime()` already formats `placed_at` (mirror it for `expires_at`).-- `src/irl.js:2514` `openMyPinsSheet()` uses `loadInto` (skeleton/empty/error/retry).-- `api/irl/pins.js:847` DELETE removes one pin by `id` + owner (`device_token`/`user_id`);- there is **no** bulk-delete endpoint yet.-- Leaflet loader to reuse: `src/dashboard-next/pages/irl-placements.js:1083`.--## What to build--### 1. Map overview in the sheet--Above the list, render a Leaflet map (lazy-loaded via the dashboard's-`loadLeaflet()`/`ensureLeafletCss()`, dark theme) with a marker per owned pin,-auto-`fitBounds` to them. Empty → hide the map and show `MYPINS_EMPTY`. Map CDN-failure → degrade gracefully to the list alone (the list is the source of truth;-the map is an enhancement, never a hard dependency — Rule 9). Tapping a marker-highlights/scrolls to its row.--### 2. Expiry countdown per row--Extend `renderMyPins` so each row's meta line shows expiry. Add a small-`relativeExpiry(expires_at)` next to `relativeTime`:--- `expires_at` null → `permanent` (signed-in pins).-- future → `expires in 6d` / `expires in 5h` / `expires in 12m`.-- past (shouldn't surface — the feed filters expired) → `expired`.--Use the existing `.irl-pin-meta` styling; keep `_pinMetaLine` (`:2454`) as the-composer so distance + age + expiry read as one line.--### 3. "Remove all from this device" bulk purge--A footer button in the sheet (only shown when ≥1 pin and a `_deviceToken` exists).-On tap → a **confirm** step (designed, not `window.confirm`): "Remove all N agents-you placed from this device? This can't be undone." On confirm, delete them all and-re-render to the empty state.--Implement the delete with a new bulk branch on the existing endpoint to avoid N-round-trips:--```-DELETE /api/irl/pins?all=1&deviceToken=<token>-```--In `api/irl/pins.js` DELETE (`:847`): when `req.query.all` is truthy and a-`deviceToken` is present, delete **every** row matching that exact device token-(`device_token = ${deviceToken}` — same strict, null-guarded ownership as the-single delete; never a NULL/empty-token match), returning the deleted count. Keep-the single-`id` path unchanged. Auth users without a device token are out of scope-here (they manage permanent pins from the dashboard) — gate the button on-`_deviceToken`.--### 4. Designed states + a11y--Loading (skeleton rows + map skeleton), empty (`MYPINS_EMPTY`), error (retry),-purge confirm (focus-trapped, `Esc` cancels), and disabled/spinner states on the-buttons during deletion. 320 / 768 / 1440px clean. Buttons have ARIA labels;-destructive purge is clearly styled.--## Data / API changes--- New DELETE branch: `DELETE /api/irl/pins?all=1&deviceToken=` → `{ ok: true, deleted: N }`.- Strict device-token ownership, null-guarded exactly like `api/irl/pins.js:869`.-- No schema change. `loadMyPins` already returns `lat/lng/expires_at` — no new read.--## Acceptance checklist--- [ ] My-pins sheet shows a Leaflet map of owned pins (fitBounds); CDN failure degrades to the list, never a blank/broken sheet.-- [ ] Each row shows expiry: `permanent` / `expires in 6d` etc., composed into the existing meta line.-- [ ] Marker tap highlights/scrolls to the matching row.-- [ ] "Remove all from this device" appears only with ≥1 pin + a device token, runs a designed confirm, deletes all in one request, lands on the empty state.-- [ ] Bulk DELETE matches **only** the caller's device token (a NULL/empty token deletes nothing); single-`id` delete unchanged.-- [ ] Skeleton/empty/error/confirm states designed; keyboard + ARIA pass; no console errors.-- [ ] `data/changelog.json` entry added (`improvement`); `npm run build:pages` passes.--## Out of scope--Editing a pin's location/caption from the sheet (dashboard remote management owns-relocation). Bulk delete for signed-in/permanent pins (dashboard scope). Map-placement of *new* pins (L2).--## Verify--`npm run dev` → `/irl` (use L1 mock to place a few test pins safely) → open My-pins: map plots them, rows show countdowns, "Remove all" → confirm → Network tab-shows one `DELETE …?all=1` returning the count, sheet shows the empty state, and a-reload confirms they're gone from the nearby feed.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-location-control/L5-my-pins-management-upgrade.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-privacy/03-proximity-arrival-cue.md b/tasks/irl-privacy/03-proximity-arrival-cue.mddeleted file mode 100644index 944a8bfcd..000000000--- a/tasks/irl-privacy/03-proximity-arrival-cue.md+++ /dev/null@@ -1,90 +0,0 @@-# 03 — Proximity-arrival cue + non-map directional hint--> Size **M** · `src/irl.js` (`loadNearbyPins`/`refreshKnownPin`, spawn path,-> `onGPSPosition`, compass heading), a small pure module `src/irl/proximity-cue.js`,-> `src/irl.css`. The delight that makes serendipity actually work.--## Goal--Make the moment an agent enters your ~40 m bubble **felt**: a subtle haptic + soft-chime + a brief on-screen "an agent is near — look around," plus a gentle,-**non-map** directional nudge (an edge glow pointing toward the agent's bearing)-so the user knows which way to turn their camera. Discovery without a radar only-works if arrival is sensed.--## Why it matters--We removed the list and the radar on purpose. The cost: a user can be standing 15 m-from an agent, facing the wrong way, and never know. A single ambient "something is-here, turn around" cue — the way a notification buzz makes you look at your phone —-is what converts "empty screen" into "oh!". This is the difference between a privacy-feature that feels dead and one that feels magical. Crucially, the hint points a-*direction*, never reveals a list/coordinates — it's the in-world equivalent of-hearing a sound nearby.--## Current state (real lines)--- New pins enter via `loadNearbyPins()` → `spawnNearbyPin(entry)`. Known pins go- through `refreshKnownPin`. There is **no** signal fired on first arrival today.-- The viewer's compass bearing is available (`currentHeadingDeg()`,- `lastCompassHeading`); a pin's world position comes from `pinWorldPos(pin)` →- `{x,y,z}` in metres relative to the viewer, so its **screen-relative bearing** is- derivable (`atan2(x, -z)`) without exposing any coordinate.--## What to build--1. **`src/irl/proximity-cue.js`** — pure, unit-testable: given the set of currently- in-range pin ids and the previously-seen set, return the newly-arrived ids- (debounced so GPS-edge churn — see task 04 — doesn't double-fire). No DOM.-2. **Arrival cue** fired from `loadNearbyPins` when `proximity-cue` reports a new- arrival:- - `navigator.vibrate?.(...)` (guarded; many browsers/iOS ignore it — never assume).- - A short, quiet chime via WebAudio (preloaded, user-gesture-unlocked on the- same tap that started the camera). Respect a **mute toggle** (persist in- `localStorage`) and the OS reduced-motion/`prefers-reduced-motion` for the visual.- - A transient banner: *"An agent is near — look around."* aria-live polite.-3. **Directional nudge** — a soft glow/arrow at the screen edge toward the agent's- current screen-relative bearing (recomputed as the user rotates, from compass +- `pinWorldPos`). Fades once the agent is on-screen/in view frustum. **Never** a- minimap, never a distance readout that could be triangulated — just "that way."- When multiple agents are in range, nudge toward the nearest only.-4. Cap frequency: at most one chime/haptic per arrival, and a short global cooldown- so a busy spot isn't a slot machine.--## Acceptance checklist--- [ ] `proximity-cue.js` is pure + unit-tested (new arrivals, debounce, no re-fire- on a pin that merely refreshed).-- [ ] Arrival fires haptic (where supported) + optional chime + aria-live banner,- exactly once per arrival, with a cooldown.-- [ ] Mute toggle persisted; `prefers-reduced-motion` disables the animated glow.-- [ ] Directional nudge points toward the nearest in-range agent and updates as the- device rotates; disappears when the agent is in view. No map, no coordinates.-- [ ] WebAudio unlocked on the existing camera-start gesture; no autoplay warning.-- [ ] No console errors; clean at 320/768/1440; holder changelog entry + `build:pages`.--## Out of scope--Membership churn / hysteresis at the radius edge (task 04 — this task consumes its-debounced arrival signal). The empty-state explainer (task 02).--## Verify--`npm run dev` → /irl, seed a pin just inside range behind the camera-(`__irlSeedPins`): confirm the haptic/chime/banner fire once and the edge glow-points toward it; rotate to face it and confirm the glow fades. Toggle mute and-reduced-motion and re-confirm.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-privacy/03-proximity-arrival-cue.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-privacy/08-trust-surface-docs-changelog.md b/tasks/irl-privacy/08-trust-surface-docs-changelog.mddeleted file mode 100644index 1969b5290..000000000--- a/tasks/irl-privacy/08-trust-surface-docs-changelog.md+++ /dev/null@@ -1,91 +0,0 @@-# 08 — User-facing "how location works" trust surface + docs + changelog--> Size **S–M** · A small in-app explainer + a help/docs page, doc cleanup of any-> stale "realtime pin sync" references, and finalizing the changelog. Closes the epic.--## Goal--Tell users — plainly and proudly — how location works on /irl: agents are private by-location, discovered only in person, never listed. For a safety feature, the-*explanation* is part of the product: it's what converts "creepy AR thing that wants-my camera and GPS" into "oh, this is actually thoughtful about privacy." Then scrub-the docs of the old model and finalize the changelog.--## Why it matters--Trust is UX. The single biggest objection to a location-based AR app is "who can see-where I put this / where I am?" A clear, honest answer — surfaced at the right moment-and on a linkable page — is a feature, not boilerplate. And any doc still describing-the removed realtime pin-sync ("agents update live across the neighborhood") is now a-lie that erodes that trust.--## Current state--- The first-run explainer (task 02) carries a one-line privacy reassurance; this task- gives it a "Learn more" → a real page.-- `data/changelog.json` has the entry "IRL world: placed agents are private by- location — discovered only in person" (already rewritten to the final model).- `public/changelog.{json,xml}` + `CHANGELOG.md` regenerate via `npm run build:pages`.-- Search the repo/docs for stale language: any mention that IRL pins sync "live" /- "in realtime" across viewers, a "nearby list/feed," a "map of agents," or the old- bbox/window/`/internal/irl-publish` flow — in `docs/`, `pages/`, blog posts, SDK- docs, and code comments. Public copy must stay literal + professional- ([memory: public-copy-tone]).--## What to build--1. **In-app "How location works"** — reachable from the first-run explainer's "?" and- from a small link in the /irl onboarding/settings. Short, plain, honest:- - Agents are placed at real spots; you find them only by being near them in person.- - There is **no list or map** of where agents are — not for other users, and not a- public directory. (Your own placements are visible only to you, in your dashboard.)- - What others *can* see when you're around: an anonymous "someone is viewing- nearby" presence count and, if you opt in, a coarse ghost — never your exact GPS.- - Camera/motion/location are used on-device to render the scene; link the privacy- policy.-2. **Docs cleanup** — update or remove every stale reference found above so docs- describe the proximity-only model. If a docs page described D1 realtime pin sync,- rewrite it to "presence + reactions are realtime; pins are discovered by proximity."-3. **Changelog finalize** — confirm the existing entry reads cleanly for holders, run- `npm run build:pages` (it validates + regenerates), and after deploy run- `npm run changelog:push --dry-run` to preview the holder Telegram post (skip the- real push unless asked; creds may be absent locally).-4. Remove the now-obsolete `smoke:irl-d1` script + `scripts/irl-d1-smoke.mjs` if still- present (the D1 realtime pin-sync it smoke-tested no longer exists).--## Acceptance checklist--- [ ] "How location works" surface exists, reachable in-app, plain + accurate, links- the privacy policy; copy is literal/professional (no sci-fi metaphors).-- [ ] Zero stale references to realtime pin sync / nearby list / map / bbox / publish- webhook remain in `docs/`, `pages/`, blog, SDK docs, or code comments.-- [ ] `data/changelog.json` entry final; `npm run build:pages` passes + regenerates- `CHANGELOG.md` + `public/changelog.{json,xml}`.-- [ ] `changelog:push --dry-run` previews cleanly (no real push without ask).-- [ ] Obsolete `smoke:irl-d1` script + file removed.-- [ ] Clean at 320/768/1440; no console errors.--## Out of scope--The first-run explainer component itself (task 02 builds it; this adds its linked-"Learn more" page + the privacy copy).--## Verify--`npm run dev` → open the "How location works" page from /irl; `grep -ri` the repo for-the stale terms and confirm none remain in user-facing docs; `npm run build:pages`-green.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-privacy/08-trust-surface-docs-changelog.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-production/11-api-error-boundaries.md b/tasks/irl-production/11-api-error-boundaries.mddeleted file mode 100644index f40913c88..000000000--- a/tasks/irl-production/11-api-error-boundaries.md+++ /dev/null@@ -1,66 +0,0 @@-# Task 11 — API error boundaries: zero 500s, graceful degradation--**Phase:** 3 (backend) · **Effort:** M · **Files:** `api/irl/*.js`--## Why-Every endpoint boundary must handle malformed input, missing rows, missing tables,-and unserializable payloads without throwing a 500 or leaking a stack trace. A-production API returns a clean status and a useful body on every path.--## Read first (verify before fixing — confirm each line still matches)-- `api/irl/pins.js` — `handleCalibrate` null-row (~346); nearby `radius` parse (~489)-- `api/irl/interactions.js` — fire-and-forget view_count `.catch(()=>{})` (~251);- `JSON.stringify(payload)::jsonb` insert (~242); pay de-dupe (~216-221)-- `api/irl/interactions-stream.js` — `conn.send(...)` error swallow (~163)-- `api/irl/agent-card.js` — `fetchReputation` null/missing-table path (~86-110, ~149)-- `api/irl/agent-summary.js` — interaction_count / last_interaction_at + LEFT JOIN nulls (~48-78)--## Scope — confirm, then fix--1. **Null-row after mutation.** `handleCalibrate` (and any UPDATE…RETURNING path that- can match zero rows) must return `404` when no row comes back, not `{ pin: null }`.--2. **JSON safety.** Wrap the interactions `JSON.stringify(payload)` insert so a- circular/unserializable payload returns `400`, never an uncaught 500. Validate- `clampPayload` output is always serializable.--3. **Graceful schema degrade.** Where a table may not exist yet (reputation,- `irl_interactions`), the query must `.catch` into a safe default- (`available:false` / `0` / `null`) so a fresh or mid-migration DB never 500s.- Guard the downstream code against undefined rows (e.g. agent-card `buildCard`).--4. **Input validation at the boundary.** `radius` (reject non-finite), pin `id`- format, and required body fields validated up front with a `400` + clear message.--5. **SSE send failures surface, not vanish.** `conn.send` failures must be logged- (task 14 covers the logging contract) and the dead connection cleaned up, not- silently dropped.--## Implementation guidance-- Keep the existing `json(res, status, body)` helper and response shapes.-- Internal code may trust itself; harden only the boundaries (network, DB, user input).-- Add/extend tests under `tests/api/irl-*.test.js` for each new failure path (malformed- input → 400, missing row → 404, missing table → safe default). These tests run in- Node and ARE verifiable here.-- **Do not edit `data/changelog.json`** — return your proposed changelog line in your- summary; the orchestrator consolidates it.--## Definition of done-- [ ] No endpoint can 500 on malformed input, missing row, or missing table — covered- by new/extended `tests/api/irl-*.test.js`.-- [ ] No stack trace or internal detail in any client response (coordinate with task 13).-- [ ] `npm test` green.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-production/11-api-error-boundaries.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-xr/README.md b/tasks/irl-xr/README.mddeleted file mode 100644index 846f51a42..000000000--- a/tasks/irl-xr/README.md+++ /dev/null@@ -1,23 +0,0 @@-# IRL + XR Task Queue--Tasks from the IRL/XR session — run each in a fresh Claude Code chat.--| # | File | Summary | Effort |-|---|------|---------|--------|-| 01 | [01-xr-avatar-lock.md](01-xr-avatar-lock.md) | Add pin/lock toggle to /xr (orbit lock instead of movement lock) | Small |-| 02 | [02-avatar-picker-thumbnail-3d.md](02-avatar-picker-thumbnail-3d.md) | Render live 3D GLB thumbnails in the avatar picker when no image exists | Medium |-| 03 | [03-irl-xr-deeplink.md](03-irl-xr-deeplink.md) | "Walk IRL" + "View in XR" buttons on avatar detail page | Small |-| 04 | [04-irl-scene-persistence.md](04-irl-scene-persistence.md) | Save/restore chosen avatar, lock state, and placed objects to localStorage | Small |-| 05 | [05-irl-xr-screenshot.md](05-irl-xr-screenshot.md) | Screenshot + share: composites 3D canvas + camera feed, native share sheet | Medium |--## What's already done (this session)--- `/xr` loading overlay stuck fix (`#xr-loading[hidden] { display: none }`)-- Avatar picker bottom sheet (`src/avatar-picker.js`) — shared by IRL + XR-- `/irl` avatar picker wired (Avatar pill button → hot-swap GLB in-scene)-- `/xr` avatar picker wired (Change button → hot-swap GLB in-scene)-- `/irl` avatar lock (Lock pill → freezes movement, unfreezes camera orbit in AR mode)--## Run order--01 → 03 → 04 → 05 → 02 (02 is the most complex; save for last)diff --git a/tasks/launchpad/07-tokenized-agents-skill-gate.md b/tasks/launchpad/07-tokenized-agents-skill-gate.mddeleted file mode 100644index b371c1866..000000000--- a/tasks/launchpad/07-tokenized-agents-skill-gate.md+++ /dev/null@@ -1,110 +0,0 @@-# 07 — Tokenized agents: wire $THREE holder gate into skill execution--## Problem--[pump-fun-skills/tokenized-agents/](../../pump-fun-skills/tokenized-agents/) documents the "Tokenized Agent Payments" skill: agents accept USDC or SOL payments on-chain and verify invoices. The payment infrastructure (prep + confirm) works. What does not exist is the **holder gate**: an agent can be configured to require that the calling wallet holds a minimum amount of $THREE tokens to access the agent's skills at all — the equivalent of a token-gated service.--This is a core part of the three.ws value proposition: $THREE utility beyond speculation. Without this, there is no reason for users to hold $THREE to interact with agents.--**$THREE contract address**: `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`--## Target files--**New API endpoint** (create):-- `api/pump/check-three-balance.js` — returns whether a wallet meets a $THREE threshold--**Modified files**:-- [api/pump/[action].js](../../api/pump/[action].js) — add `check-three-balance` case to the dispatcher-- [api/agents/](../../api/agents/) — identify the agent skill execution handler (find `handleSkillCall` or similar) and add gate check before skill invocation-- [pump-fun-skills/tokenized-agents/SKILL.md](../../pump-fun-skills/tokenized-agents/SKILL.md) — document the gate config--## How the gate works--### Agent configuration--An agent opts into the gate by setting in their `meta` JSON (stored in `agents.meta`):-```json-{- "three_gate": {- "enabled": true,- "min_balance": 1000- }-}-```-`min_balance` is the minimum $THREE tokens (raw, no decimals — $THREE has 6 decimals, so 1000 raw = 0.001 $THREE). This is intentionally low to make gate-testing easy. Real agents might set 10_000_000 (= 10 $THREE).--### Balance check endpoint--```-GET /api/pump/check-three-balance?wallet=<base58>&min=<raw_amount>-```--Response:-```json-{- "wallet": "…",- "balance": 12345678,- "min": 1000,- "eligible": true-}-```--Implementation in `api/pump/check-three-balance.js`:-1. Import `Connection` from `@solana/web3.js` using the `SOLANA_RPC_URL` env var (already used throughout `api/_lib/`).-2. Fetch all token accounts for the wallet via `connection.getParsedTokenAccountsByOwner(pubkey, { mint: THREE_CA_PUBKEY })`.-3. Sum `tokenAmount.amount` across all matching accounts.-4. Compare to `min`. Return the result JSON.-5. Cache the response in Upstash Redis for 30 seconds (same pattern as `/api/pump/coin` — see [api/_lib/redis.js](../../api/_lib/redis.js)). The cache key is `three-gate:<wallet>:<min>`.-6. Return 400 if `wallet` is not a valid base58 public key (use `PublicKey` constructor in a try-catch).-7. Return 200 in all other cases (including balance = 0, eligible = false).--### Gate enforcement in skill execution--Find the API handler that processes agent skill calls (search for `skill` or `handleSkill` in `api/agents/`). Before executing the skill:--1. Check if `agent.meta?.three_gate?.enabled` is `true`.-2. If yes, extract the caller's wallet from the request (it should already be present as part of the payment/auth flow — find where `caller_wallet` or `payer` is validated in existing handlers).-3. Call the balance check (`fetch('/api/pump/check-three-balance?wallet=<wallet>&min=<min_balance>')` internally, or call the database directly).-4. If `eligible: false`, return HTTP 402 with body:-```json-{- "error": "insufficient_three_balance",- "message": "This agent requires a minimum $THREE balance. Acquire $THREE to use this skill.",- "required": 10000000,- "held": 5000,- "buy_url": "https://pump.fun/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump"-}-```-5. If `eligible: true`, proceed with skill execution as normal.--### Agent settings UI--In [pages/agent-edit.html](../../pages/agent-edit.html) or [pages/agent-home.html](../../pages/agent-home.html) (whichever contains the agent settings panel), add a "$THREE Gate" toggle:-- A checkbox "Require $THREE to use this agent's skills"-- A number input "Minimum $THREE balance" (shown when checked, default 10_000_000 = 10 $THREE)-- Save writes to `agent.meta.three_gate` via `PATCH /api/agents/<id>` (already exists)--## Definition of done--- Create an agent, enable the $THREE gate with min=10_000_000.-- Send a skill call from a wallet with 0 $THREE → receive 402 with `insufficient_three_balance` error and `buy_url`.-- Send the same skill call from a wallet with ≥ 10_000_000 $THREE (test with a real mainnet wallet that holds $THREE, or stub the balance check in test) → skill executes normally.-- `GET /api/pump/check-three-balance?wallet=<valid>&min=1000` returns correct `balance` and `eligible` fields.-- `GET /api/pump/check-three-balance?wallet=invalid` returns 400.-- The agent settings panel shows the gate toggle and min-balance field. Saving persists.-- `npm test` green.-- Completionist subagent run on changed files.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/launchpad/07-tokenized-agents-skill-gate.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/mcp-agent-selfsufficiency/README.md b/tasks/mcp-agent-selfsufficiency/README.mddeleted file mode 100644index 0c037039b..000000000--- a/tasks/mcp-agent-selfsufficiency/README.md+++ /dev/null@@ -1,160 +0,0 @@-# Initiative: make the agent self-sufficient over MCP--**Goal.** Today the three.ws platform exposes the **read/consume** half of every-capability over MCP, but the **create/write** half still requires the web app.-An AI agent connected through MCP (Claude, Cursor, watsonx Orchestrate) can-_observe and spend_, but it cannot bootstrap itself end-to-end. This initiative-closes that gap so an agent can give itself a **body, brain (memory), wallet,-on-chain identity, and an embed** — entirely through MCP, matching the public-IBM-partnership narrative: _"Every AI needs a body, a brain (LLM memory), a-wallet (jobs with x402), and every digital identity needs a network."_--Each task below is a **self-contained brief** meant to be run in its own fresh-chat. They are independent and can be done in any order, but the recommended-sequence (each unlocks the next in the agent lifecycle) is 01 → 02 → 03 → 04 → 05.--| # | Task | Pillar | New MCP tools |-| --- | ------------------------------------------------------------------ | ------------------ | --------------------------------------- |-| 01 | [Memory tools](01-memory-mcp-tools.md) | Brain (LLM memory) | `remember`, `recall`, `forget` |-| 02 | [Persist & render avatar](02-avatar-persist-and-render.md) | Body | `save_avatar`, `render_avatar_image` |-| 03 | [Register agent on-chain](03-register-agent-onchain.md) | Network / identity | `register_agent`, `identity_check` |-| 04 | [Embed code tool](04-embed-code-tool.md) | Embed | `get_embed_code` |-| 05 | [Provision & monetize wallet](05-wallet-provision-and-monetize.md) | Wallet | `provision_wallet`, `monetize_endpoint` |-------## Shared conventions (read before any task)--These apply to every task. Each task brief restates the critical bits, but this-is the canonical reference.--### Project rules (non-negotiable — see `/CLAUDE.md`)--- **No mocks, no fake data, no placeholders, no TODOs, no stubs.** Wire to the- real endpoints/DB/contracts that already exist. If a credential is missing,- surface a clean, designed "not configured" state — never fabricate output.-- **`$THREE` is the only coin.** Contract `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`.- Never reference any other token anywhere (code, tests, fixtures, docs).-- **Errors handled at boundaries** (network, user input); internal code trusts- itself. Every state designed (loading/empty/error/success).-- Match existing naming, file organization, and abstractions. Read before you- write. Delete dead code. Keep the repo root clean.--### The MCP tool authoring contract--A tool is a plain object in a `toolDefs` array exported from a file under-`api/_mcp*/tools/`:--```js-{- name: 'tool_name', // snake_case, unique within the server- title: 'Human title',- description: 'What it does + when to use it (LLMs read this to choose it).',- scope: 'namespace:action', // OPTIONAL — gate behind an OAuth scope (see below)- inputSchema: { // JSON Schema; additionalProperties:false- type: 'object',- properties: { /* ... */ },- required: [ /* ... */ ],- additionalProperties: false,- },- async handler(args, auth, req) {- // args — validated input (ajv compiled the schema at catalog load)- // auth — { userId, scope, apiKeyId, clientId, rateKey } (userId is the- // authenticated three.ws user id; null on the x402-payer path)- // req — the raw Node request (headers, etc.). Threaded by BOTH dispatchers.- // Return an MCP tool result:- return {- content: [{ type: 'text', text: '...human-readable...' }],- structuredContent: { /* machine-readable result */ },- // isError: true // on a handled failure- };- },-}-```--Wiring a new tool file into a server:--1. Create `api/_mcp<server>/tools/<name>.js` exporting `toolDefs`.-2. Import it in that server's `catalog.js` and add to the `allDefs` array.-3. The shared `catalog.js` strips `scope`/`handler` for `tools/list` and- ajv-compiles each `inputSchema` — a malformed schema throws at load, so the- assembly check below is a real test.-4. If the tool should appear in the server's `initialize` instructions, update- the `INSTRUCTIONS` string in that server's `dispatch.js`.--**Servers and their dispatchers** (both pass `(args, auth, req)` to handlers):--| Server | Endpoint | Dispatcher | tools dir | catalog |-| ------------ | ----------------- | ---------------------------- | ------------------- | ------------------------ |-| main | `/api/mcp` | `api/_mcp/dispatch.js` (own) | `api/_mcp/tools/` | `api/_mcp/catalog.js` |-| 3D Studio | `/api/mcp-3d` | shared `makeDispatcher` | `api/_mcp3d/tools/` | `api/_mcp3d/catalog.js` |-| agent wallet | `/api/mcp-agent` | shared `makeDispatcher` | `api/_mcpagent/` | `api/_mcpagent/...` |-| bazaar | `/api/mcp-bazaar` | shared `makeDispatcher` | `api/_mcpbazaar/` | — |-| IBM Granite | `/api/ibm-mcp` | shared (`_mcpibm`) | `api/_mcpibm/` | `api/_mcpibm/catalog.js` |--Each server has a registry manifest at the repo root: `server.json` (main),-`server-3d.json`, `server-agent.json`, `server-bazaar.json`, `server-ibm.json`.-Update the relevant manifest `description` if a task materially changes a-server's capability surface.--### Auth, ownership, and scopes--- `auth.userId` is the authenticated three.ws user. **Any write tool MUST verify- ownership** before mutating: an agent record lives in the `agent_identities`- table with a `user_id` column — confirm `agent_identities.user_id === auth.userId`- (the existing REST endpoints do exactly this; reuse their query/helper).-- Gate write tools behind a scope via the `scope:` field (e.g.- `memory:write`, `avatars:write`). Read tools that only return the caller's own- data use a read scope (e.g. `memory:read`). Look at `delete_avatar` in- `api/_mcp/tools/avatars.js` (`scope: 'avatars:delete'`) and `api/_mcp/auth.js` /- `api/_lib/auth.js` for how scopes are defined and checked, and register any- new scope in the OAuth scope list so it can actually be granted.-- The x402-payer path has `auth.userId === null`. Write tools that need an owner- must return a clear "sign in with three.ws OAuth to use this tool" error in- that case rather than throwing.--### Definition of Done (every task)--A task is complete only when ALL of these hold — state explicitly which you-verified:--- [ ] New tool file(s) created and wired into the server's `catalog.js`.-- [ ] `server-*.json` description and the server's `dispatch.js` `INSTRUCTIONS`- updated if the capability surface changed.-- [ ] **Real wiring** to the existing endpoint/DB/contract — no mock, no stub,- no fabricated data. Missing-credential path returns a designed error.-- [ ] Ownership + scope enforced on every write tool; x402-payer (`userId:null`)- handled.-- [ ] `node --check` passes on every changed `.js` file.-- [ ] **Catalog assembles** — the assembly command below ajv-compiles every- schema and proves the handlers resolve; it must list your new tool names.-- [ ] A vitest spec is added under `tests/api/` covering the new tools- (schema/validation + a happy path with the DB/HTTP layer mocked at the- module boundary, mirroring `tests/api/mcp-3d.test.js`) and passes.-- [ ] `npx prettier --write` then `--check` clean on all changed files.-- [ ] `git diff` self-reviewed; every changed line justified.--### Verification commands cheat-sheet--```bash-# Syntax-check a changed tool file:-node --check api/_mcp<server>/tools/<name>.js--# Catalog assembles (ajv-compiles every schema, resolves every handler):-node --input-type=module -e "import('./api/_mcp<server>/catalog.js').then(m=>{for(const t of m.TOOL_CATALOG)if(!t.name||!t.description||!t.inputSchema)throw new Error('bad entry '+t.name);console.log('tools:',m.TOOL_CATALOG.length,m.TOOL_CATALOG.map(t=>t.name).join(', '));})"--# Run your spec + formatting:-npx vitest run tests/api/<spec>.test.js-npx prettier --check <files>--# Inspect live locally:-npm run dev-npx @modelcontextprotocol/inspector http://localhost:5173/api/<endpoint>-```--### Note for whoever runs these--This repo is worked by a **concurrent agent fleet sharing one worktree on-`main`** — files and commits can shift mid-task. Stage explicit paths, re-check-`git status` before committing, and never `git pull`/`fetch` from the `threeD`-mirror (canonical remote is `threews`). Do not push without explicit approval.diff --git a/tasks/monetization-feature/06-backend-api-for-nft-collection.md b/tasks/monetization-feature/06-backend-api-for-nft-collection.mddeleted file mode 100644index 7763019c5..000000000--- a/tasks/monetization-feature/06-backend-api-for-nft-collection.md+++ /dev/null@@ -1,110 +0,0 @@-----status: completed------# Prompt 6: Backend - API for NFT Collection Creation--**Status:** Not Started--## Objective-Create an API endpoint for an authenticated agent creator to generate a new Metaplex Certified Collection on Solana, which will be used to group all the paid skills for a specific agent.--## Explanation-Before we can mint individual skill NFTs, they need to belong to a "collection." This allows marketplaces to group them and verifies their authenticity. This task involves creating an API that uses the Metaplex Umi library to create a new NFT collection on behalf of the agent's creator. The platform will be the update authority to manage the collection.--## Instructions-1. **Set up Metaplex Umi:**- - Install the necessary Metaplex and Solana libraries (`@metaplex-foundation/umi-bundle-defaults`, `@metaplex-foundation/mpl-token-metadata`, `@solana/web3.js`).- - Create a helper function to initialize Umi with your platform's keypair and connection to the Solana devnet.--2. **Create the API Endpoint:**- - Create a new API route, for example, `/api/agents/[id]/skill-collection`.- - Implement a `POST` handler that is protected, ensuring only the agent owner can create a collection.--3. **Implement the Collection Creation Logic:**- - The handler should first check if a collection already exists for this agent to prevent duplicates.- - Generate a new keypair for the collection NFT's mint account.- - Use the `createNft` function from `@metaplex-foundation/mpl-token-metadata`.- - The `createNft` call should specify:- - `name`: e.g., "Agent [Agent Name] Skills"- - `symbol`: e.g., "A1SKILL"- - `uri`: A URL to a JSON file containing the collection's metadata (e.g., agent's name, description, image).- - `sellerFeeBasisPoints`: Set to `0` for the collection NFT itself.- - `isCollection`: `true`.- - Store the collection's mint address in the `agents` table, associated with the agent `id`.--## Code Example (Vercel Serverless Function - `api/agents/[id]/skill-collection.js`)--```javascript-import { createNft } from '@metaplex-foundation/mpl-token-metadata';-import { generateSigner, percentAmount } from '@metaplex-foundation/umi';-import { initializeUmi } from '@lib/solana/umi'; // Your Umi setup helper-import { db } from '@lib/db';-import { withAuth } from '@lib/auth';--async function handler(req, res) {- if (req.method !== 'POST') {- return res.status(405).end();- }- const { id: agentId } = req.query;- const { userId } = req.auth;-- // 1. Verify ownership and check if collection already exists- const agent = await db.query('SELECT owner_id, skill_collection_mint FROM agents WHERE id = $1', [agentId]);- if (!agent.rows.length || agent.rows[0].owner_id !== userId) {- return res.status(403).json({ error: 'Forbidden' });- }- if (agent.rows[0].skill_collection_mint) {- return res.status(400).json({ error: 'Collection already exists' });- }-- try {- const umi = initializeUmi();- const collectionMint = generateSigner(umi);-- // TODO: Upload collection metadata to Arweave/IPFS- const collectionMetadataUri = 'https://...';-- await createNft(umi, {- mint: collectionMint,- name: `Agent ${agent.name} Skills`,- symbol: 'A1SKILL',- uri: collectionMetadataUri,- sellerFeeBasisPoints: percentAmount(0),- isCollection: true,- }).sendAndConfirm(umi);-- const collectionMintAddress = collectionMint.publicKey;-- // 3. Save the mint address to your database- await db.query('UPDATE agents SET skill_collection_mint = $1 WHERE id = $2', [collectionMintAddress, agentId]);-- return res.status(200).json({ collectionMint: collectionMintAddress });- } catch (error) {- console.error('Failed to create collection NFT:', error);- return res.status(500).json({ error: 'Failed to create collection' });- }-}--export default withAuth(handler);-```--## Definition of Done-- The `/api/agents/[id]/skill-collection` endpoint is created and functional.-- When called by the agent owner, a new Metaplex collection NFT is created on Solana devnet.-- The new collection's mint address is saved to the `agents` table.-- The endpoint correctly handles errors and prevents duplicate collection creation.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/monetization-feature/06-backend-api-for-nft-collection.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/monetization-feature/07-backend-api-for-nft-minting.md b/tasks/monetization-feature/07-backend-api-for-nft-minting.mddeleted file mode 100644index 36db8c2f6..000000000--- a/tasks/monetization-feature/07-backend-api-for-nft-minting.md+++ /dev/null@@ -1,121 +0,0 @@-----status: not-started------# Prompt 7: Backend - API for Skill NFT Minting--**Status:** Not Started--## Objective-Create an API endpoint that allows a user to purchase a skill and receive it as an NFT. This endpoint will be responsible for creating and processing the Solana transaction.--## Explanation-This is the core of the monetization feature. This API will take a user's public key and the desired skill, and in return, provide a transaction that, when signed by the user, will transfer the funds and mint the skill NFT to their wallet. We will use Solana Pay's Transaction Request standard for a seamless user experience.--## Instructions-1. **Create the API Endpoint:**- - Create a new API route, for example, `/api/skills/purchase`.- - Implement a `POST` handler that accepts `user_account`, `agent_id`, and `skill_name`.--2. **Implement the Transaction Logic:**- - Fetch the skill's price from the `agent_skill_prices` table.- - Fetch the agent creator's wallet address from the `users` table.- - Fetch the agent's `skill_collection_mint` from the `agents` table.- - Upload the skill's NFT metadata (as defined in Prompt 5) to Arweave or IPFS.- - Generate a new keypair for the skill NFT's mint account.- - Build a Solana transaction using `@solana/web3.js`. This transaction must include:- - A `SystemProgram.transfer` instruction to send the purchase amount from the `user_account` to the creator's wallet.- - The instructions to create and mint the new NFT, associating it with the agent's collection. Use the Metaplex Umi library for this.- - Serialize the transaction, but *do not* sign it.--3. **Return a Solana Pay-Compatible Response:**- - The API response should follow the Solana Pay Transaction Request standard.- - The `transaction` field should be the base64-encoded serialized transaction.- - Include a `message` like "Purchase Skill '[Skill Name]' for [Amount] USDC".--## Code Example (Vercel Serverless Function - `api/skills/purchase.js`)--```javascript-import { createNft } from '@metaplex-foundation/mpl-token-metadata';-import { generateSigner, some } from '@metaplex-foundation/umi';-import { Transaction, SystemProgram, PublicKey } from '@solana/web3.js';-import { initializeUmi } from '@lib/solana/umi';-import { db } from '@lib/db';--async function handler(req, res) {- if (req.method !== 'POST') {- return res.status(405).end();- }- const { user_account, agent_id, skill_name } = req.body;-- try {- // 1. Fetch all required data- const priceInfo = await db.query('SELECT * FROM agent_skill_prices WHERE agent_id = $1 AND skill_name = $2', [agent_id, skill_name]);- const agent = await db.query('SELECT owner_id, skill_collection_mint FROM agents WHERE id = $1', [agent_id]);- const creator = await db.query('SELECT wallet_address FROM users WHERE id = $1', [agent.rows[0].owner_id]);-- if (!priceInfo.rows.length || !creator.rows.length || !agent.rows[0].skill_collection_mint) {- return res.status(404).json({ error: 'Skill or creator not found' });- }-- const umi = initializeUmi();- const skillMint = generateSigner(umi);-- // 2. TODO: Upload metadata to Arweave- const metadataUri = 'https://...';-- // 3. Build the mint instruction- const mintIx = createNft(umi, {- mint: skillMint,- name: skill_name,- uri: metadataUri,- sellerFeeBasisPoints: percentAmount(0),- collection: some({ key: new PublicKey(agent.rows[0].skill_collection_mint), verified: false }),- }).getInstructions();-- // 4. Build the full transaction- let transaction = new Transaction();- transaction.add(- SystemProgram.transfer({- fromPubkey: new PublicKey(user_account),- toPubkey: new PublicKey(creator.rows[0].wallet_address),- lamports: priceInfo.rows[0].amount,- })- );- // This is a simplification; you'd convert the Umi instructions to web3.js format- // transaction.add(...convertedMintIx);-- // 5. Return Solana Pay response- const serializedTransaction = transaction.serialize({ requireAllSignatures: false });-- return res.status(200).json({- transaction: serializedTransaction.toString('base64'),- message: `Purchase ${skill_name} for ${priceInfo.rows[0].amount / 1e6} USDC`,- });-- } catch (error) {- console.error('Failed to create purchase transaction:', error);- return res.status(500).json({ error: 'Failed to create transaction' });- }-}-```--## Definition of Done-- The `/api/skills/purchase` endpoint is created.-- The endpoint correctly fetches all necessary data.-- It generates a transaction with both the payment and minting instructions.-- The response is compatible with the Solana Pay Transaction Request standard.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/monetization-feature/07-backend-api-for-nft-minting.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/monetization-feature/07-creator-earnings-dashboard.md b/tasks/monetization-feature/07-creator-earnings-dashboard.mddeleted file mode 100644index 04b35d50b..000000000--- a/tasks/monetization-feature/07-creator-earnings-dashboard.md+++ /dev/null@@ -1,77 +0,0 @@-----status: not-started------# Prompt 7: Frontend - Creator Earnings Dashboard--## Objective-Create a dedicated page for creators to view their total earnings, pending payments, and a history of their sales.--## Explanation-To empower creators, they need a transparent view of their monetization performance. This dashboard will serve as their financial hub, providing key metrics and a detailed breakdown of every sale, which builds trust and encourages them to create more premium content.--## Instructions-1. **Create New Frontend Files:**- * Create a new HTML file: `earnings.html`.- * Create a new JavaScript module: `src/earnings.js`.- * Link the script in the HTML file: `<script type="module" src="/src/earnings.js"></script>`.--2. **Design the UI in `earnings.html`:**- * Add a main title, e.g., "Creator Earnings".- * Create summary boxes for "Total Revenue", "Pending Payout", and "Total Sales".- * Add a table element with a `<thead>` for the sales history. Columns should include: "Date", "Skill Name", "Agent Name", "Price", and "Status" (e.g., Pending, Paid).- * The table should have a `<tbody>` with a unique ID for dynamically inserting rows.--3. **Implement Frontend Logic in `src/earnings.js`:**- * On page load, make a GET request to a new `/api/users/earnings` endpoint.- * Process the JSON response.- * Populate the summary boxes with the aggregate data.- * Iterate through the sales history array. For each sale, create a `<tr>` element and insert it into the table body.- * Format dates and currency values for readability.--## HTML Structure Example (`earnings.html`)--```html-<main>- <h1>Creator Earnings</h1>- <div class="summary-cards">- <div class="card">- <h2>Total Revenue</h2>- <p id="total-revenue">$0.00</p>- </div>- <div class="card">- <h2>Pending Payout</h2>- <p id="pending-payout">$0.00</p>- </div>- </div>- <h2>Sales History</h2>- <table id="sales-table">- <thead>- <tr>- <th>Date</th>- <th>Skill</th>- <th>Price</th>- <th>Status</th>- </tr>- </thead>- <tbody id="sales-tbody">- <!-- Rows will be inserted here by JavaScript -->- </tbody>- </table>-</main>-<script type="module" src="/src/earnings.js"></script>-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/monetization-feature/07-creator-earnings-dashboard.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/monetization-feature/07-frontend-ui-creator-dashboard.md b/tasks/monetization-feature/07-frontend-ui-creator-dashboard.mddeleted file mode 100644index 0ef929a5c..000000000--- a/tasks/monetization-feature/07-frontend-ui-creator-dashboard.md+++ /dev/null@@ -1,73 +0,0 @@-----status: not-started-----# Prompt 7: Creator Dashboard UI--**Status:** Not Started--## Objective-Create a new "Creator Dashboard" page where users can see a list of the skills they have created.--## Explanation-To enable creators to manage their skills (e.g., set prices), they first need a dedicated space to view their creations. This task involves creating a new HTML page and the associated JavaScript to fetch and display the skills created by the currently logged-in user.--## Instructions-1. **Create a new HTML file: `public/creator-dashboard.html`.**-2. **Add basic HTML structure, including a header and a main content area with an empty container for the skill list, like `<div id="my-skills-list"></div>`.**-3. **Create a new JavaScript file: `src/creator-dashboard.js`.**-4. **In the script, add a function to fetch skills from a new API endpoint (e.g., `/api/users/me/skills`).**-5. **On page load, call this function and render the returned skills into the `#my-skills-list` container.**- - For each skill, display its name, description, and a placeholder for future actions (like a "Set Price" button).--## Code Example (Frontend - `src/creator-dashboard.js`)-```javascript-document.addEventListener('DOMContentLoaded', () => {- fetchMySkills();-});--async function fetchMySkills() {- try {- const response = await fetch('/api/users/me/skills'); // Assumes this API exists- if (!response.ok) throw new Error('Failed to fetch skills.');-- const skills = await response.json();- renderSkills(skills);- } catch (error) {- console.error(error);- document.getElementById('my-skills-list').innerHTML = `<p>Error loading your skills.</p>`;- }-}--function renderSkills(skills) {- const container = document.getElementById('my-skills-list');- if (!skills.length) {- container.innerHTML = `<p>You haven't created any skills yet.</p>`;- return;- }-- container.innerHTML = skills.map(skill => `- <div class="skill-card">- <h3>${skill.name}</h3>- <p>${skill.description}</p>- <div class="skill-actions">- <button data-skill-id="${skill.id}" class="set-price-btn">Set Price</button>- </div>- </div>- `).join('');-}-```-*Note: This requires a new backend endpoint `GET /api/users/me/skills` which should be created as part of this task.*--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/monetization-feature/07-frontend-ui-creator-dashboard.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/monetization-feature/08-creator-earnings-dashboard.md b/tasks/monetization-feature/08-creator-earnings-dashboard.mddeleted file mode 100644index 934f48301..000000000--- a/tasks/monetization-feature/08-creator-earnings-dashboard.md+++ /dev/null@@ -1,47 +0,0 @@-----status: not-started------# Prompt 8: Creator Earnings Dashboard--**Status:** Not Started--## Objective-Create a dashboard for creators to view their earnings from skill sales.--## Explanation-Creators need to be able to track how much they've earned. This requires a new page in the creator dashboard that shows total revenue, a list of recent sales, and other relevant analytics.--## Instructions-- [ ] **Create a new database table: `skill_sales`**. It should log every purchase:- - `id`: Primary key.- - `agent_id`: The agent whose skill was sold.- - `creator_id`: The user who owns the agent.- - `buyer_id`: The user who bought the skill.- - `skill_name`: The name of the skill.- - `amount`: The sale price.- - `currency_mint`: The currency of the sale.- - `signature`: The Solana transaction signature of the sale.- - `created_at`: Timestamp.-- [ ] **Log every sale.** After a successful purchase is confirmed on-chain, add an entry to this table.-- [ ] **Create a new API endpoint, e.g., `GET /api/dashboard/earnings`**.- - This endpoint should query the `skill_sales` table for the currently logged-in user.- - It should return aggregated data (total earnings per currency) and a list of recent transactions.-- [ ] **Create a new page in the dashboard (e.g., `dashboard/earnings.html`)**.- - This page should fetch data from the new API endpoint.- - **Display summary cards:** "Total Earnings (USDC)", "Total Earnings (SOL)", etc.- - **Display a table of recent sales:** Show the skill name, date, price, and buyer.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/monetization-feature/08-creator-earnings-dashboard.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/monetization-feature/08-frontend-ui-set-price-modal.md b/tasks/monetization-feature/08-frontend-ui-set-price-modal.mddeleted file mode 100644index 1fc9c6e0a..000000000--- a/tasks/monetization-feature/08-frontend-ui-set-price-modal.md+++ /dev/null@@ -1,65 +0,0 @@-----status: not-started-----# Prompt 8: Set Price Modal UI--**Status:** Not Started--## Objective-Design and implement a modal dialog on the Creator Dashboard for setting a skill's price.--## Explanation-Clicking the "Set Price" button next to a skill should open a modal where the creator can input a price and select a currency. This provides a clean and focused user experience for price management.--## Instructions-1. **Add a hidden modal structure to `public/creator-dashboard.html`.** It should be outside the main flow, ready to be displayed with JavaScript.-2. **The modal should contain:**- - A title, e.g., "Set Price for [Skill Name]".- - An input field for the `amount`.- - A dropdown (`<select>`) for the `currency_mint`. Pre-fill this with supported currencies (e.g., USDC, SOL).- - "Save" and "Cancel" buttons.-3. **In `src/creator-dashboard.js`, add an event listener to the `#my-skills-list` container.**-4. **Delegate the event to handle clicks on `.set-price-btn` buttons.**-5. **When a button is clicked:**- - Get the `skill_id` from the `data-skill-id` attribute.- - Populate the modal's title with the skill's name.- - Show the modal.--## HTML Example (in `creator-dashboard.html`)-```html-<div id="price-modal" class="modal" hidden>- <div class="modal-content">- <h2 id="modal-title">Set Price</h2>- <form id="price-form">- <input type="hidden" id="modal-skill-id" />- <div>- <label for="price-amount">Amount</label>- <input type="number" id="price-amount" step="0.01" min="0" required />- </div>- <div>- <label for="price-currency">Currency</label>- <select id="price-currency" required>- <option value="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6T">USDC</option>- <!-- Add other currencies like native SOL -->- </select>- </div>- <button type="submit">Save</button>- <button type="button" id="modal-cancel-btn">Cancel</button>- </form>- </div>-</div>-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/monetization-feature/08-frontend-ui-set-price-modal.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/monetization-feature/09-admin-payout-system.md b/tasks/monetization-feature/09-admin-payout-system.mddeleted file mode 100644index db3d56c22..000000000--- a/tasks/monetization-feature/09-admin-payout-system.md+++ /dev/null@@ -1,63 +0,0 @@-----status: not-started------# Prompt 9: Admin - Creator Payout System--## Objective-Build a secure internal admin interface to manage and process creator payouts efficiently.--## Explanation-As creators earn money, the platform needs a robust and trustworthy system for paying them. This internal tool will allow administrators to view pending payouts, mark them as paid, and record transaction details for accounting and dispute resolution. This is a critical operational component for a monetized platform.--## Instructions-1. **Create a New Admin Page:**- * In a dedicated admin section of your application, create a new page: `/admin/payouts.html`.- * Secure this page to ensure only authorized administrators can access it.--2. **Backend API for Payouts:**- * Create a new admin-only API endpoint: `/api/admin/payouts.js`.- * This endpoint will have two functions:- * `GET`: Fetches a list of all creators who have a pending payout balance greater than zero. It should include the creator's username, their pending balance, and their preferred payout method/address.- * `POST`: Marks a creator's pending payouts as `completed`. It should accept a `creator_id` and a `transaction_reference` (e.g., a bank transfer ID or a blockchain transaction hash).--3. **Frontend UI for Payouts:**- * The `/admin/payouts.html` page should:- * Fetch and display the list of pending payouts in a table.- * Each row should have a "Mark as Paid" button.- * Clicking the button should open a form/modal where the admin can enter the transaction reference.- * Submitting the form should call the `POST` method on the API endpoint.- * The UI should update to reflect the completed payout.--4. **Update Payout Status in the Database:**- * The `POST` request to the API should trigger a database update.- * It should update the `status` of all `pending` items in the `royalty_ledger` for that creator to `paid`.- * It should also record the payout transaction in a new `payouts` table for auditing purposes.--## `payouts` Table SQL Example--```sql-CREATE TABLE payouts (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- creator_user_id UUID NOT NULL REFERENCES users(id),- amount_usd NUMERIC(12, 2) NOT NULL,- payout_method VARCHAR(64),- transaction_reference TEXT,- processed_by_admin_id UUID NOT NULL REFERENCES users(id),- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()-);-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/monetization-feature/09-admin-payout-system.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/monetization-feature/09-backend-creator-payouts-table.md b/tasks/monetization-feature/09-backend-creator-payouts-table.mddeleted file mode 100644index 0937e4efa..000000000--- a/tasks/monetization-feature/09-backend-creator-payouts-table.md+++ /dev/null@@ -1,66 +0,0 @@-----status: not-started------# Prompt 9: Create Creator Payouts Table--**Status:** Not Started--## Objective-Create the necessary database tables to manage payouts for agent creators.--## Explanation-To complete the monetization loop, we need to track how much each agent creator has earned and when they get paid. This involves two tables: one to store creator wallet/payout information (`creator_payout_settings`) and another to log each payout transaction (`payouts`).--## Instructions-- [ ] **Update the Migration Script:** Add `CREATE TABLE` statements for two new tables in `scripts/migrate-db.mjs`.-- [ ] **`creator_payout_settings` Schema:**- - `user_id`: Foreign key to `users`. This is the agent creator.- - `payout_wallet_address`: The Solana address where they want to receive funds.- - `payout_currency_mint`: The currency they prefer for payouts.-- [ ] **`payouts` Schema:**- - `id`: Primary key.- - `user_id`: The user (creator) who was paid.- - `amount`: The total amount paid out.- - `currency_mint`: The currency of the payout.- - `transaction_signature`: The on-chain signature of the payout transaction.- - `created_at`: Timestamp of the payout.- - It should also include details on the earnings period this payout covers.-- [ ] **Execute and Verify** the migration.--## Code Example (SQL)--```sql-CREATE TABLE IF NOT EXISTS creator_payout_settings (- user_id UUID PRIMARY KEY NOT NULL REFERENCES users(id) ON DELETE CASCADE,- payout_wallet_address VARCHAR(255) NOT NULL,- payout_currency_mint VARCHAR(255) NOT NULL,- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()-);--CREATE TABLE IF NOT EXISTS payouts (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- user_id UUID NOT NULL REFERENCES users(id),- amount BIGINT NOT NULL,- currency_mint VARCHAR(255) NOT NULL,- -- Could be a Solana tx sig or a Stripe transfer ID, etc.- transaction_signature VARCHAR(255) UNIQUE,- earnings_start_date DATE NOT NULL,- earnings_end_date DATE NOT NULL,- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()-);-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/monetization-feature/09-backend-creator-payouts-table.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/monetization-feature/09-frontend-integrate-solana-pay.md b/tasks/monetization-feature/09-frontend-integrate-solana-pay.mddeleted file mode 100644index 2d2e34692..000000000--- a/tasks/monetization-feature/09-frontend-integrate-solana-pay.md+++ /dev/null@@ -1,98 +0,0 @@-----status: not-started------# Prompt 9: Frontend - Integrate Solana Pay QR Code--## Objective-Connect the purchase modal to the backend, generate a Solana Pay QR code, and display it to the user.--## Explanation-This prompt links our frontend UI to the backend payment logic. When a user clicks "Purchase", we will call the API created in the previous step, receive the Solana Pay URL, and render it as a QR code within the modal. This is the core of the user-facing payment experience.--## Instructions-1. **Add a QR Code Library:**- * Install a library to generate QR codes, such as `qrious`. You can add it via a script tag or install it via npm.--2. **Handle the Purchase Click:**- * In `src/marketplace.js`, add an event listener to the "Purchase" button in the modal (`purchase-modal-cta`).- * When clicked, it should:- * Show a loading state in the modal status area.- * Make a `POST` request to your `/api/payments/create-transaction` endpoint, sending the `skillId` and the user's connected wallet address.- * On success, receive the `solanaPayUrl` and `reference`.--3. **Render the QR Code:**- * Use the QR code library to generate a QR code from the `solanaPayUrl`.- * Display the QR code in the modal, replacing the "Purchase" button.- * Update the status text to "Scan with your Solana wallet to approve."--## Code Example (`src/marketplace.js`)--```javascript-// Add QR library to marketplace.html-// <script src="https://cdnjs.cloudflare.com/ajax/libs/qrious/4.0.2/qrious.min.js"></script>--async function handlePurchaseClick(event) {- const cta = event.target;- const { skillName, amount, mint } = cta.dataset;- const statusEl = $('purchase-modal-status');- const modalBody = $('purchase-modal').querySelector('.modal-body');-- statusEl.textContent = 'Generating transaction...';- cta.disabled = true;-- try {- const res = await fetch('/api/payments/create-transaction', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- skillId: getSkillIdByName(skillName), // You'll need a way to get the ID- buyerAddress: window.userWallet.publicKey.toBase58(), // Assuming wallet is connected- }),- });-- if (!res.ok) throw new Error('Failed to create transaction');-- const { solanaPayUrl, reference } = await res.json();-- // Hide description, price, etc. to make space for QR- modalBody.innerHTML = `- <div id="qr-code-container" style="text-align: center;"></div>- <div class="status-area">Scan with your Solana wallet to approve.</div>- `;-- // Render QR code- new QRious({- element: $('qr-code-container'),- value: solanaPayUrl,- size: 200,- background: 'white',- foreground: 'black',- });-- // Start polling for transaction confirmation- pollForTransaction(reference);-- } catch (error) {- statusEl.textContent = `Error: ${error.message}`;- cta.disabled = false;- }-}--// Attach listener-$('purchase-modal-cta').addEventListener('click', handlePurchaseClick);-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/monetization-feature/09-frontend-integrate-solana-pay.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/monetization-feature/09-frontend-js-set-price-api-call.md b/tasks/monetization-feature/09-frontend-js-set-price-api-call.mddeleted file mode 100644index c7571c36f..000000000--- a/tasks/monetization-feature/09-frontend-js-set-price-api-call.md+++ /dev/null@@ -1,76 +0,0 @@-----status: not-started-----# Prompt 9: Set Price API Call from Frontend--**Status:** Not Started--## Objective-Implement the frontend JavaScript logic to submit the new price from the modal to the backend API.--## Explanation-This task connects the UI created in the previous step to the backend API for setting prices. It involves handling the form submission, calling the API with the correct data, and providing feedback to the user based on the response.--## Instructions-- **In `src/creator-dashboard.js`, add a `submit` event listener to the `#price-form` in the modal.**-- **Inside the submit handler:**- 1. Prevent the default form submission.- 2. Retrieve the `skill_id`, `amount`, and `currency_mint` from the form inputs.- 3. **Important:** Convert the human-readable amount (e.g., 1.50 USDC) to the smallest unit required by the backend (e.g., 1,500,000 lamports). This might involve multiplying by `1e6` for USDC.- 4. Call the `POST /api/skills/:skill_id/price` endpoint using `fetch`.- 5. Include the data in the request body as JSON.- 6. Handle the response:- - On success, close the modal and show a confirmation message. Maybe update the UI to show the new price.- - On failure, display an error message to the user.--## Code Example (Frontend - `src/creator-dashboard.js`)-```javascript-document.getElementById('price-form').addEventListener('submit', async (event) => {- event.preventDefault();-- const skillId = document.getElementById('modal-skill-id').value;- const amountInput = document.getElementById('price-amount').value;- const currency = document.getElementById('price-currency').value;-- // Convert to smallest unit (e.g., lamports for USDC)- const amountInSmallestUnit = parseFloat(amountInput) * 1e6;-- try {- const response = await fetch(`/api/skills/${skillId}/price`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- amount: amountInSmallestUnit,- currency_mint: currency,- }),- });-- if (!response.ok) {- const error = await response.json();- throw new Error(error.error || 'Failed to set price.');- }-- // Success- alert('Price updated successfully!');- document.getElementById('price-modal').hidden = true;- fetchMySkills(); // Refresh the list to show new price-- } catch (error) {- alert(`Error: ${error.message}`);- }-});-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/monetization-feature/09-frontend-js-set-price-api-call.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/monetization-feature/09-platform-fee-system.md b/tasks/monetization-feature/09-platform-fee-system.mddeleted file mode 100644index 171e35042..000000000--- a/tasks/monetization-feature/09-platform-fee-system.md+++ /dev/null@@ -1,44 +0,0 @@-----status: not-started------# Prompt 9: Platform Fee System--**Status:** Not Started--## Objective-Implement a platform fee for every skill purchase.--## Explanation-To make the platform sustainable, we will take a small percentage of each skill sale as a platform fee. This requires modifying the purchase transaction to include a transfer to the platform's wallet.--## Instructions-- [ ] **Modify the skill purchase API (`/api/skills/purchase`)**.-- [ ] **When constructing the transaction, add a second `transfer` instruction.**- - The source will be the user's account.- - The destination will be the platform's fee wallet.- - The amount should be a percentage of the total price (e.g., 5%).-- [ ] **Adjust the creator's transfer amount.** The amount transferred to the creator should be the total price minus the platform fee.-- [ ] **The sum of the two transfers must equal the total amount** the user is paying.-- [ ] **Store the platform fee** in the `skill_sales` table for accounting purposes. Add a `platform_fee` column.--## Example-If a skill costs 1 USDC and the platform fee is 5%:-- The user pays 1 USDC.-- The creator receives 0.95 USDC.-- The platform receives 0.05 USDC.-The Solana transaction will contain two separate transfers to reflect this split. This is known as a "split transaction".--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/monetization-feature/09-platform-fee-system.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/monetization-feature/10-backend-payout-cron.md b/tasks/monetization-feature/10-backend-payout-cron.mddeleted file mode 100644index 81ddea28e..000000000--- a/tasks/monetization-feature/10-backend-payout-cron.md+++ /dev/null@@ -1,81 +0,0 @@-----status: not-started------# Prompt 10: Backend Payout Cron Job--**Status:** Not Started--## Objective-Create a scheduled job (cron job) that calculates creator earnings and initiates payouts.--## Explanation-This is a backend-only task. On a regular schedule (e.g., weekly or monthly), a script needs to run that:-1. Calculates the total revenue for each agent creator from `skill_purchases`.-2. Subtracts any platform fees.-3. Initiates a transfer to the creator's wallet stored in `creator_payout_settings`.-4. Records the transaction in the `payouts` table.--## Instructions-- [ ] **Create a new cron job file** within the Vercel infrastructure (e.g., `/api/cron/process-payouts.js`).-- [ ] **Configuration:**- - [ ] Configure `vercel.json` to schedule this job to run periodically (e.g., once a month).-- [ ] **Script Logic:**- - [ ] Find the date of the last payout for each user to determine the new earnings period.- - [ ] `SELECT` and `SUM` the `purchase_amount` from `skill_purchases`, grouped by the agent's `user_id`.- - [ ] For each user with earnings, calculate the final payout amount after fees.- - [ ] Fetch their payout wallet from `creator_payout_settings`.- - [ ] Use the Solana SDK to create and send a transaction for the payout amount.- - [ ] After the transaction is confirmed, `INSERT` a record into the `payouts` table.-- [ ] **Security:** This endpoint must be protected and only executable by Vercel's cron service, typically via a secret key.--## Code Example (Conceptual Vercel Cron Job)--```javascript-// In /api/cron/process-payouts.js-import { sql } from '../_lib/db.js';--export default async function handler(req, res) {- // 1. Authenticate the cron job request- // ...-- // 2. Determine earnings period (e.g., the last month)- const endDate = new Date();- const startDate = new Date();- startDate.setMonth(startDate.getMonth() - 1);-- // 3. Calculate earnings for all creators in this period- const { rows: earnings } = await sql`- SELECT i.user_id, SUM(p.purchase_amount) as total_earnings- FROM skill_purchases p- JOIN agent_identities i ON p.agent_id = i.id- WHERE p.created_at >= ${startDate} AND p.created_at < ${endDate}- GROUP BY i.user_id;- `;-- // 4. Process each payout- for (const userEarning of earnings) {- const platformFee = 0.10; // 10% fee- const payoutAmount = userEarning.total_earnings * (1 - platformFee);-- // Fetch wallet, create & send Solana tx, then record in payouts table- // ... (complex logic here) ...- }-- res.status(200).send('Payouts processed');-}-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/monetization-feature/10-backend-payout-cron.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/monetization-feature/10-referral-system-frontend.md b/tasks/monetization-feature/10-referral-system-frontend.mddeleted file mode 100644index a65467100..000000000--- a/tasks/monetization-feature/10-referral-system-frontend.md+++ /dev/null@@ -1,85 +0,0 @@-----status: not-started------# Prompt 10: Frontend - Display Referral System Info--## Objective-Integrate the user's referral code and performance statistics into their profile page.--## Explanation-To make the referral program successful, users must be able to easily find their unique referral code and track how many people they've referred. By displaying this information clearly on their profile page, we empower them to become advocates for the platform.--## Instructions-1. **Update the Profile Page HTML:**- * Open the `profile.html` file.- * Add a new section titled "Referral Program".- * Inside this section, add elements with unique IDs to display:- * The user's referral code.- * A "copy to clipboard" button next to the code.- * The number of users they have successfully referred.- * Their total referral earnings to date.--2. **Modify the Profile Page JavaScript:**- * Open `src/profile.js`.- * In the function that fetches profile data, also make a GET request to the `/api/users/referrals` endpoint you created previously.- * When the data is returned, populate the new elements in `profile.html` with the `referral_code`, `referred_users_count`, and `referral_earnings_total`.--3. **Implement the "Copy to Clipboard" Functionality:**- * Add a click event listener to the copy button.- * When clicked, use the `navigator.clipboard.writeText()` API to copy the referral code to the user's clipboard.- * Provide visual feedback to the user, e.g., by changing the button text to "Copied!" for a few seconds.--## HTML Example (`profile.html`)--```html-<section id="referral-section">- <h2>Referral Program</h2>- <p>Share your code to earn rewards!</p>- <div class="referral-code-wrapper">- <strong>Your Code:</strong>- <span id="referral-code"></span>- <button id="copy-referral-btn">Copy</button>- </div>- <div class="referral-stats">- <div>- <p>Users Referred</p>- <strong id="referred-users-count">0</strong>- </div>- <div>- <p>Total Earnings</p>- <strong id="referral-earnings-total">$0.00</strong>- </div>- </div>-</section>-```--## JavaScript Snippet (`src/profile.js`)--```javascript-// After fetching data from /api/users/referrals-const referralData = await response.json();--document.getElementById('referral-code').textContent = referralData.referral_code;-document.getElementById('referred-users-count').textContent = referralData.referred_users_count;-document.getElementById('referral-earnings-total').textContent = `$${referralData.referral_earnings_total.toFixed(2)}`;--document.getElementById('copy-referral-btn').addEventListener('click', () => {- navigator.clipboard.writeText(referralData.referral_code);- // ... provide visual feedback-});-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/monetization-feature/10-referral-system-frontend.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/monetization-feature/10-subscription-based-skills-db-schema.md b/tasks/monetization-feature/10-subscription-based-skills-db-schema.mddeleted file mode 100644index 240363139..000000000--- a/tasks/monetization-feature/10-subscription-based-skills-db-schema.md+++ /dev/null@@ -1,38 +0,0 @@-----status: not-started------# Prompt 10: Subscription-Based Skills (Part 1 - DB Schema)--**Status:** Not Started--## Objective-Update the database schema to support subscription-based pricing for skills (e.g., monthly access).--## Explanation-In addition to one-time purchases, we want to allow creators to sell skills as a recurring subscription. This requires changes to how we model pricing and access.--## Instructions-- [ ] **Modify the `agent_skill_prices` table.**- - Add a `pricing_type` column (e.g., `one_time` or `subscription`).- - Add a `renewal_period_days` column (e.g., 30 for monthly). This can be nullable if `pricing_type` is `one_time`.-- [ ] **Modify the `user_skill_access` table.**- - Ensure the `expires_at` column exists. When a user buys a subscription, this will be set to `now() + renewal_period_days`.-- [ ] **Update the creator dashboard UI.**- - When setting a price, allow creators to choose between "One-Time" and "Subscription".- - If "Subscription" is chosen, show an input for the renewal period.-- [ ] **Update the API for saving prices** to handle these new fields.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/monetization-feature/10-subscription-based-skills-db-schema.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/monetization-feature/11-confirm-payment-api.md b/tasks/monetization-feature/11-confirm-payment-api.mddeleted file mode 100644index 2c00b5911..000000000--- a/tasks/monetization-feature/11-confirm-payment-api.md+++ /dev/null@@ -1,109 +0,0 @@-# Prompt 11: Create Payment Confirmation API--## Objective-Create a backend API endpoint that verifies a Solana transaction signature, marks the corresponding payment intent as "paid," and records the revenue event.--## Explanation-After the frontend successfully sends a transaction, it has a transaction signature (`txid`). To prevent fraud and ensure the creator gets credit, the frontend must send this signature to our backend. The backend then acts as the source of truth, performing the critical step of verifying the transaction on the Solana blockchain itself. If the transaction is valid and matches the intent, we update our database to reflect the successful purchase.--## Instructions-1. **Create a New API File:**- * Create a file at `/api/payments/confirm.js`.--2. **Define the Endpoint Logic:**- * The endpoint accepts a `POST` request and must be authenticated.- * The request body should contain the `intent_id` and the `transaction_signature` (`txid`).--3. **Implement Verification Logic:**- * **Fetch the Intent:** Retrieve the `agent_payment_intents` record from your database using the `intent_id`. Verify that it exists and its status is `'pending'`.- * **Fetch the Transaction:** Use the Solana web3.js library (`@solana/web3.js`) on the backend to connect to the Solana cluster. Call `connection.getParsedTransaction(transaction_signature)`.- * **Validate the Transaction:** This is the most critical step.- * Check that the transaction is not null and has no errors (`transaction.meta.err === null`).- * Parse the transaction instructions to find the token transfer. Look at the `preTokenBalances` and `postTokenBalances` to verify the amount transferred.- * Confirm that the source account in the transaction matches the user who initiated the intent.- * Confirm that the destination account matches the recipient from the payment intent.- * Confirm that the amount transferred is equal to or greater than the amount in the intent.- * Confirm the token mint matches the currency from the intent.- * **Handle Failure:** If any validation step fails, return a 400-level error and do not update the database.--4. **Update the Database on Success:**- * If validation passes, update the `agent_payment_intents` record: set `status` to `'paid'`, and store the `transaction_signature` and `paid_at` timestamp.- * Insert a new record into the `agent_revenue_events` table to log the earnings for the creator. Calculate the net amount after taking a platform fee (if any).--5. **Add Vercel Routing:**- * In `vercel.json`, add a route for `/api/payments/confirm`.--## Code Example (Backend - `api/payments/confirm.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 { Connection, clusterApiUrl } from '@solana/web3.js';--const PLATFORM_FEE_BPS = 500; // 5% platform fee--export default wrap(async (req, res) => {- // ... boilerplate for CORS, method check, and auth ...- const user = await getSessionUser(req);- if (!user) return error(res, 401, 'unauthorized');-- const { intent_id, transaction_signature } = await readJson(req);- if (!intent_id || !transaction_signature) return error(res, 400, 'validation_error', 'intent_id and transaction_signature are required');-- // 1. Fetch our internal record of the intent- const [intent] = await sql`- SELECT * FROM agent_payment_intents WHERE id = ${intent_id} AND payer_user_id = ${user.id}- `;- if (!intent) return error(res, 404, 'not_found', 'Payment intent not found.');- if (intent.status !== 'pending') return error(res, 400, 'invalid_request', `Intent is already in status: ${intent.status}`);-- // 2. Fetch and validate the on-chain transaction- const connection = new Connection(clusterApiUrl('mainnet-beta')); // Or devnet- const tx = await connection.getParsedTransaction(transaction_signature, { maxSupportedTransactionVersion: 0 });-- if (!tx || tx.meta.err) {- return error(res, 400, 'transaction_failed', 'On-chain transaction failed or was not found.');- }-- // Basic validation (a robust implementation would parse instructions thoroughly)- // Here we will just check that the intent is updated- // A full implementation would be much more complex. We'll simplify for this prompt.-- // 3. Update database- await sql.transaction(async (tx) => {- await tx`- UPDATE agent_payment_intents- SET status = 'paid', transaction_signature = ${transaction_signature}, paid_at = now()- WHERE id = ${intent_id}- `;-- const gross_amount = BigInt(intent.amount);- const fee_amount = (gross_amount * BigInt(PLATFORM_FEE_BPS)) / 10000n;- const net_amount = gross_amount - fee_amount;-- await tx`- INSERT INTO agent_revenue_events- (agent_id, intent_id, skill, gross_amount, fee_amount, net_amount, currency_mint, chain)- VALUES- (${intent.agent_id}, ${intent.id}, ${intent.payload.skill}, ${gross_amount}, ${fee_amount}, ${net_amount}, ${intent.currency_mint}, 'solana')- `;- });-- return json(res, 200, { success: true, message: "Payment confirmed." });-});-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/monetization-feature/11-confirm-payment-api.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/monetization-feature/11-subscription-based-skills-access-logic.md b/tasks/monetization-feature/11-subscription-based-skills-access-logic.mddeleted file mode 100644index b8e59296e..000000000--- a/tasks/monetization-feature/11-subscription-based-skills-access-logic.md+++ /dev/null@@ -1,39 +0,0 @@-----status: not-started------# Prompt 11: Subscription-Based Skills (Part 2 - Access Logic)--**Status:** Not Started--## Objective-Update the skill access control logic to handle subscriptions.--## Explanation-Now that we can store subscription prices, we need to enforce access based on whether a user's subscription is active.--## Instructions-- [ ] **Modify the skill purchase logic.**- - When a user buys a subscription skill, in the `user_skill_access` table, set `expires_at` to the correct future date.-- [ ] **Modify the skill access control check (`/api/agent/invoke`).**- - When checking for access in the `user_skill_access` table:- - If the skill is a subscription, you must also check that `expires_at` is in the future.- - `WHERE user_id = ? AND skill_name = ? AND expires_at > NOW()`-- [ ] **Update the UI to show subscription status.**- - On the agent detail page, if a user owns a subscription, show "Subscribed" and the expiry date instead of a "Buy" button.- - If a subscription is expired, show a "Renew" button.-- [ ] **Implement the renewal logic.** The "Renew" button should trigger the same purchase flow, which will update the `expires_at` date.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/monetization-feature/11-subscription-based-skills-access-logic.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/monetization-feature/14-frontend-creator-earnings-dashboard.md b/tasks/monetization-feature/14-frontend-creator-earnings-dashboard.mddeleted file mode 100644index 3013941a7..000000000--- a/tasks/monetization-feature/14-frontend-creator-earnings-dashboard.md+++ /dev/null@@ -1,74 +0,0 @@-----status: not-started------# Prompt 14: Creator Earnings Dashboard--**Status:** Not Started--## Objective-Create a simple dashboard for agent creators to see their total earnings and a history of their payouts.--## Explanation-To provide transparency and build trust, creators need to see how much they've earned from their paid skills. This task involves creating a new UI component, possibly in the "Monetization" tab or on a separate page, that fetches and displays earnings and payout data from the backend.--## Instructions-- [ ] **Create Backend Endpoints:**- - [ ] You will need two new API endpoints:- - `GET /api/earnings/summary`: Should return the user's total all-time earnings and their current balance pending payout.- - `GET /api/earnings/payouts`: Should return a paginated list of the user's past payouts from the `payouts` table.-- [ ] **Build the Frontend UI:**- - [ ] In the agent editor's "Monetization" tab (or a new page), add a new section for "Earnings".- - [ ] Add display cards for "Total Revenue" and "Pending Payout".- - [ ] Add a table to display the payout history.-- [ ] **Fetch and Render Data:**- - [ ] On page load, call the new endpoints to get the data.- - [ ] Populate the UI with the fetched data. Format dates and amounts nicely.--## Code Example (Conceptual UI)--```html-<!-- In the Monetization tab -->-<div id="earnings-dashboard">- <h3>Your Earnings</h3>- <div class="stats-grid">- <div class="stat-card">- <h4>Total Revenue</h4>- <p id="total-revenue">$0.00</p>- </div>- <div class="stat-card">- <h4>Pending Payout</h4>- <p id="pending-payout">$0.00</p>- </div>- </div>-- <h4>Payout History</h4>- <table id="payouts-table">- <thead>- <tr>- <th>Date</th>- <th>Amount</th>- <th>Status</th>- <th>Transaction</th>- </tr>- </thead>- <tbody>- <!-- Rows will be populated by JavaScript -->- </tbody>- </table>-</div>-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/monetization-feature/14-frontend-creator-earnings-dashboard.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/monetization-feature/14-skill-bundles.md b/tasks/monetization-feature/14-skill-bundles.mddeleted file mode 100644index 98553f4de..000000000--- a/tasks/monetization-feature/14-skill-bundles.md+++ /dev/null@@ -1,40 +0,0 @@-----status: not-started------# Prompt 14: Skill Bundles--**Status:** Not Started--## Objective-Allow creators to sell multiple skills together as a discounted bundle.--## Explanation-Bundles can increase the average revenue per user. A creator could offer a "Pro Pack" of 3 skills at a lower price than buying them individually.--## Instructions-- [ ] **Create new database tables:**- - `skill_bundles`: to store bundle details (`id`, `agent_id`, `name`, `price`, `currency_mint`).- - `bundle_skills`: a join table linking bundles to skills (`bundle_id`, `skill_name`).-- [ ] **Update the creator dashboard.**- - Add a new section for creating and managing bundles.- - A creator should be able to create a bundle, give it a name, set a price, and select which of their existing skills to include.-- [ ] **Update the marketplace UI.**- - Display bundles on the agent detail page.- - A "Buy Bundle" button should trigger a purchase flow similar to a single skill.-- [ ] **Update the purchase and access logic.**- - When a bundle is purchased, grant access to *all* skills within that bundle in the `user_skill_access` table.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/monetization-feature/14-skill-bundles.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/monetization-feature/14-user-skills-database.md b/tasks/monetization-feature/14-user-skills-database.mddeleted file mode 100644index ba64b1baf..000000000--- a/tasks/monetization-feature/14-user-skills-database.md+++ /dev/null@@ -1,84 +0,0 @@-# Prompt 14: Database for User's Purchased Skills--## Objective-Create a new table in the PostgreSQL database to permanently store which users have unlocked which skills for which agents.--## Explanation-Frontend state is temporary. To ensure a user's purchases are remembered across sessions and devices, we need to store their unlocked skills in our database. A dedicated table is the right way to do this. This table will link a `user_id` to an `agent_id` and a `skill_name`, creating a permanent record of the entitlement.--## Instructions-1. **Create a New SQL Migration File:**- * In the `/api/_lib/migrations/` directory, create a new SQL file. A good name would be `2026-05-05-user-unlocked-skills.sql` (using a current or future date).--2. **Write the DDL (Data Definition Language):**- * Inside the new file, write the `CREATE TABLE` statement for a table named `user_unlocked_skills`.- * The table should include the following columns:- * `user_id`: `UUID`, a foreign key referencing `users(id)`.- * `agent_id`: `UUID`, a foreign key referencing `agent_identities(id)`.- * `skill_name`: `TEXT`, to store the name of the skill.- * `created_at`: `TIMESTAMPTZ`, with a default value of `now()`.- * `source`: `TEXT`, to note how the skill was acquired (e.g., 'purchase').- * `payment_intent_id`: `TEXT`, a foreign key referencing `agent_payment_intents(id)`.- * Define a `PRIMARY KEY` on (`user_id`, `agent_id`, `skill_name`) to prevent duplicate entries.- * Add indexes on `user_id` and `agent_id` for efficient lookups.- * Wrap the entire statement in a `BEGIN;` and `COMMIT;` block to make it transactional.--3. **Update the Payment Confirmation Logic:**- * In the backend API at `/api/payments/confirm.js`, modify the transaction block.- * After successfully creating the `agent_revenue_events` record, add a new `INSERT` statement to add a record to your new `user_unlocked_skills` table.- * You have all the necessary information available: `user.id`, `intent.agent_id`, `intent.payload.skill`, and the `intent_id`.--## Code Example (SQL Migration - `api/_lib/migrations/...-user-unlocked-skills.sql`)--```sql-BEGIN;--CREATE TABLE IF NOT EXISTS user_unlocked_skills (- user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,- agent_id UUID NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,- skill_name TEXT NOT NULL,- created_at TIMESTAMPTZ NOT NULL DEFAULT now(),- source TEXT NOT NULL DEFAULT 'purchase',- payment_intent_id TEXT REFERENCES agent_payment_intents(id) ON DELETE SET NULL,- PRIMARY KEY (user_id, agent_id, skill_name)-);--CREATE INDEX IF NOT EXISTS user_unlocked_skills_user_id_idx ON user_unlocked_skills (user_id);-CREATE INDEX IF NOT EXISTS user_unlocked_skills_agent_id_idx ON user_unlocked_skills (agent_id);--COMMIT;-```--## Code Example (Backend - `/api/payments/confirm.js`)--```javascript-// ... inside the sql.transaction block ...--await tx`- INSERT INTO agent_revenue_events- -- ... (as before)-`;--await tx`- INSERT INTO user_unlocked_skills- (user_id, agent_id, skill_name, payment_intent_id)- VALUES- (${user.id}, ${intent.agent_id}, ${intent.payload.skill}, ${intent.id})- ON CONFLICT (user_id, agent_id, skill_name) DO NOTHING-`;-```-After creating the migration file, remember to run your migration script to apply the changes to the database.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/monetization-feature/14-user-skills-database.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/monetization-feature/15-api-billing-and-subscriptions.md b/tasks/monetization-feature/15-api-billing-and-subscriptions.mddeleted file mode 100644index c6be12ddc..000000000--- a/tasks/monetization-feature/15-api-billing-and-subscriptions.md+++ /dev/null@@ -1,85 +0,0 @@-----status: not-started------# Prompt 15: Backend - API Billing and Subscriptions--## Objective-Integrate a payment provider like Stripe to manage recurring subscriptions for API access.--## Explanation-This task turns API usage into a revenue stream. It involves setting up subscription plans, creating a secure checkout process for users to subscribe, and using webhooks to keep your application's state in sync with the billing provider.--## Instructions-1. **Set Up Stripe Account and Products:**- * In your Stripe dashboard, create new products for your API plans (e.g., "Developer Plan", "Business Plan").- * Define the pricing for each plan (e.g., $49/month) and set usage limits (e.g., 100,000 API calls/month).--2. **Create a `subscriptions` Table:**- * In your database, create a table to track user subscriptions.- * Columns: `id`, `user_id`, `stripe_subscription_id` (unique), `stripe_customer_id`, `plan_name`, `status` (e.g., `active`, `canceled`, `past_due`), `current_period_end`.--3. **Implement Stripe Checkout Endpoint:**- * Create an API endpoint (e.g., `/api/billing/create-checkout-session`).- * This endpoint, using the Stripe Node.js library, will create a new Checkout Session for a specific plan.- * It should associate the session with a Stripe Customer ID (creating one if the user doesn't have one yet).- * Return the `sessionId` to the frontend, which will redirect the user to the Stripe-hosted checkout page.--4. **Implement Stripe Webhook Handler:**- * Create a webhook endpoint (e.g., `/api/billing/webhook`) to receive events from Stripe.- * **Crucially, verify the webhook signature** to ensure the request is from Stripe.- * Handle key events:- * `checkout.session.completed`: A user has successfully subscribed. Use the data from this event to create a new record in your `subscriptions` table.- * `invoice.payment_succeeded`: A recurring payment was successful. Update the `current_period_end` in your database.- * `customer.subscription.deleted`: The user has canceled. Update the subscription `status` in your database.--5. **Link Subscriptions to API Access:**- * In your API usage tracking middleware, before allowing an API call, check the user's subscription status in your database. If they have no active subscription or are over their usage limit, return a `403 Forbidden` or `429 Too Many Requests` error.--## Webhook Handler Snippet--```javascript-// POST /api/billing/webhook-const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);--// ... (inside the handler, after reading the raw body)-let event;-try {- event = stripe.webhooks.constructEvent(- rawBody,- req.headers['stripe-signature'],- process.env.STRIPE_WEBHOOK_SECRET- );-} catch (err) {- return res.status(400).send(`Webhook Error: ${err.message}`);-}--switch (event.type) {- case 'checkout.session.completed':- const session = event.data.object;- // ... create subscription in your DB- break;- case 'customer.subscription.updated':- case 'customer.subscription.deleted':- const subscription = event.data.object;- // ... update subscription status in your DB- break;- // ... other events-}--res.status(200).json({ received: true });-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/monetization-feature/15-api-billing-and-subscriptions.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/monetization-feature/15-user-skills-api.md b/tasks/monetization-feature/15-user-skills-api.mddeleted file mode 100644index 19396b871..000000000--- a/tasks/monetization-feature/15-user-skills-api.md+++ /dev/null@@ -1,95 +0,0 @@-# Prompt 15: API to Fetch User's Unlocked Skills--## Objective-Create a backend API endpoint that returns a list of all skills a user has unlocked for a specific agent.--## Explanation-Now that we are storing a user's skill purchases in the database, we need a way for the frontend to retrieve this information when a page loads. This will allow us to show the correct "Unlocked" state for skills even if the user refreshes the page or visits from a new device.--## Instructions-1. **Create a New API File:**- * Create a file at `/api/agents/[id]/unlocked-skills.js`. This nested route makes sense as the unlocked skills are specific to an agent for a given user.--2. **Define the Endpoint Logic:**- * The endpoint should handle `GET` requests.- * It must be authenticated, as it's specific to the logged-in user.- * It needs the `agent_id` from the URL path.--3. **Implement the Database Query:**- * Query the `user_unlocked_skills` table.- * Select the `skill_name` column.- * Filter by the `agent_id` from the URL and the `user_id` from the authenticated session.- * The endpoint should return a simple JSON array of skill name strings, for example: `{"skills": ["advanced_analysis", "creative_writing"]}`.--4. **Add Vercel Routing:**- * In `vercel.json`, add a new route to handle this dynamic endpoint:- `"/api/agents/([^/]+)/unlocked-skills"` should map to `/api/agents/[id]/unlocked-skills?id=$1`.--## Code Example (Backend - `/api/agents/[id]/unlocked-skills.js`)--```javascript-import { sql } from '../../_lib/db.js';-import { getSessionUser } from '../../_lib/auth.js';-import { cors, json, method, wrap, error } from '../../_lib/http.js';--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;- if (!method(req, res, ['GET'])) return;-- const user = await getSessionUser(req);- if (!user) {- // Return empty list for non-logged-in users instead of an error- return json(res, 200, { skills: [] });- }-- const url = new URL(req.url, 'http://x');- const agentId = url.searchParams.get('id');-- if (!agentId) {- return error(res, 400, 'validation_error', 'Agent ID is required.');- }-- const rows = await sql`- SELECT skill_name- FROM user_unlocked_skills- WHERE user_id = ${user.id} AND agent_id = ${agentId}- `;-- const skills = rows.map(r => r.skill_name);-- return json(res, 200, { skills });-});-```--## Code Example (Vercel Routing - `vercel.json`)--```json-{- "routes": [- // ... other routes- {- "src": "/api/agents/([^/]+)/skills-pricing",- "dest": "/api/agents/[id]/skills-pricing?id=$1"- },- {- "src": "/api/agents/([^/]+)/unlocked-skills",- "dest": "/api/agents/[id]/unlocked-skills?id=$1"- },- // ... other routes- ]-}-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/monetization-feature/15-user-skills-api.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/monetization-feature/16-frontend-ui-my-agents-purchased-skills.md b/tasks/monetization-feature/16-frontend-ui-my-agents-purchased-skills.mddeleted file mode 100644index f50bc49ae..000000000--- a/tasks/monetization-feature/16-frontend-ui-my-agents-purchased-skills.md+++ /dev/null@@ -1,56 +0,0 @@-----status: not-started-----# Prompt 16: Display Purchased Skills in "My Agents"--**Status:** Not Started--## Objective-Update the "My Agents" page to display the list of skills, including purchased premium skills, for each agent owned by the user.--## Explanation-Users need to see what skills their agents possess. This task involves enhancing the "My Agents" page to not only list the agents but also their associated skills, visually distinguishing between default/free skills and purchased ones.--## Instructions-1. **Modify the API endpoint that serves data for the "My Agents" page** (e.g., `/api/users/me/agents`).-2. **In the backend query, `JOIN` with the `skill_purchases` and `skills` tables** to retrieve the names of all skills purchased for each agent.-3. **Also include the agent's base/free skills.** The final agent object in the API response should have an array like `skills: [{ name: 'wave', purchased: false }, { name: 'translator', purchased: true }]`.-4. **In the frontend JavaScript for the "My Agents" page, update the rendering logic.**-5. Iterate through the new `skills` array for each agent and display them, perhaps with a special icon or style for `purchased: true` skills.--## Code Example (Frontend rendering)-```javascript-// Inside the function that renders a single agent card-function renderAgent(agent) {- const skillsHtml = agent.skills.map(skill => `- <span class="agent-skill ${skill.purchased ? 'skill-purchased' : 'skill-free'}">- ${skill.name}- ${skill.purchased ? '<i class="premium-icon"></i>' : ''}- </span>- `).join(' ');-- return `- <div class="agent-card">- <h3>${agent.name}</h3>- <div class="agent-skills-list">- ${skillsHtml}- </div>- </div>- `;-}-```-This provides a clear visual inventory for the user.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/monetization-feature/16-frontend-ui-my-agents-purchased-skills.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/monetization-feature/16-user-purchase-history.md b/tasks/monetization-feature/16-user-purchase-history.mddeleted file mode 100644index 9548c9e51..000000000--- a/tasks/monetization-feature/16-user-purchase-history.md+++ /dev/null@@ -1,36 +0,0 @@-----status: not-started------# Prompt 16: User Purchase History--**Status:** Not Started--## Objective-Create a page in the user's dashboard where they can see a history of all their skill purchases.--## Explanation-Users need a way to track their spending and see which skills they've bought. This is important for transparency and user trust.--## Instructions-- [ ] **Create a new API endpoint, e.g., `GET /api/users/me/purchases`**.- - This should query the `skill_sales` table for all records where the `buyer_id` matches the current user.- - It should return a list of purchases with details like agent name, skill name, price, and date.-- [ ] **Create a new page in the user dashboard (e.g., `dashboard/history.html`)**.-- [ ] **On this page, fetch the purchase history** from the new API endpoint.-- [ ] **Display the purchases in a clean, readable table.**-- [ ] **For each purchase, include a link to the Solana transaction on an explorer** like Solscan or X-Ray. The transaction signature is stored in the `skill_sales` table.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/monetization-feature/16-user-purchase-history.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/pump-dashboard-real-apis/README.md b/tasks/pump-dashboard-real-apis/README.mddeleted file mode 100644index a9819db21..000000000--- a/tasks/pump-dashboard-real-apis/README.md+++ /dev/null@@ -1,27 +0,0 @@-# pump-dashboard.html — wire every panel to REAL APIs--Audit target: [/pump-dashboard.html](../../pump-dashboard.html)--Every prompt in this folder is **independent**. Pick any one and ship it end‑to‑end without depending on another file in this folder being done first. No mocks. No fake data. No placeholders. No `Math.random()` standing in for real cryptography. No `setTimeout` fake-loading. No commented-out code. No hardcoded sample arrays. No fallback rows. If credentials are missing, locate them in `.env` or `vercel env ls` — do not stub.--Each task must satisfy [CLAUDE.md](../../CLAUDE.md):-- Wired into the UI and reachable.-- Dev server (`npm run dev`) started, exercised in a real browser, no console errors, network tab shows real upstream calls succeeding.-- Empty / loading / error states are real.-- Existing tests still green (`npm test`).-- Run the **completionist** subagent on the changed files before claiming done.--## Tasks--- [01-featured-agent-real-data.md](01-featured-agent-real-data.md)-- [02-wallet-snapshot-real.md](02-wallet-snapshot-real.md)-- [03-market-chart-real.md](03-market-chart-real.md)-- [04-market-chart-token-selector.md](04-market-chart-token-selector.md)-- [05-vanity-generator-real-keypair.md](05-vanity-generator-real-keypair.md)-- [06-custom-agents-table-real.md](06-custom-agents-table-real.md)-- [07-dashboard-stat-cards-real.md](07-dashboard-stat-cards-real.md)-- [08-revenue-page-real.md](08-revenue-page-real.md)-- [09-api-keys-management-real.md](09-api-keys-management-real.md)-- [10-config-validate-connection.md](10-config-validate-connection.md)-- [11-tts-speech-real.md](11-tts-speech-real.md)-- [12-alerts-server-persist.md](12-alerts-server-persist.md)diff --git a/tasks/pumpfun-upstream/02-skills-drift-report.md b/tasks/pumpfun-upstream/02-skills-drift-report.mddeleted file mode 100644index d641ffbab..000000000--- a/tasks/pumpfun-upstream/02-skills-drift-report.md+++ /dev/null@@ -1,230 +0,0 @@-# Drift report: `pump-fun-skills/` vs official upstream--**First run:** 2026-06-08 · **Re-verified + fix applied:** 2026-06-11-**Task:** [02-pump-fun-skills-upstream-sync.md](02-pump-fun-skills-upstream-sync.md)-**Upstream:** `github.com/pump-fun/pump-fun-skills` — branch `main`,-HEAD `c8aaa6a8` (`Merge pull request #9 from pump-fun/bump-sdk-versions`,-committed + `pushed_at` 2026-04-23). No tags, no releases, **no new commits since-the 2026-06-08 run** — upstream is still dormant at the same HEAD.--## TL;DR--**Upstream has not moved since the first run; our vendored copy remains at or-ahead of upstream HEAD on every shared file, so there is still nothing to _pull_-from upstream.**--The 2026-06-11 re-verification did, however, surface and fix one **three.ws-internal-regression** that the first run missed: the `coin-fees` scripts imported a-pump-sdk symbol (`isCreatorUsingSharingConfig`) that was **removed in-`@pump-fun/[email protected]`** — the version our own manifest pins. The skill ran-only because its stale lockfile silently resolved the old `1.32.0`. Fixed by-renaming to the exact-signature successor `hasCoinCreatorMigratedToSharingConfig`-and regenerating the `coin-fees` lock to `1.36.0` so manifest, lock, and scripts-all agree. Details under [coin-fees SDK-symbol fix](#coin-fees-sdk-symbol-fix-202606-11).--Everything else is unchanged from the first run: the only diffs against upstream-are deliberate three.ws customizations (the `3ws…` brand mark, the `reactive/`-skill, the README row, SDK-version bumps, and the plugin-wrapper files), and the-transaction-building logic is byte-identical to upstream.--## Method--Cloned upstream `main` at HEAD (`c8aaa6a8`) and ran a byte-level recursive diff-(`diff -rq`) of each shared skill folder, plus full-content diffs of every file-that differed. Compared SKILL.md, all `scripts/**`, all `scripts/lib/**`, and all-`references/**` — not just SKILL.md. Cross-checked SDK pins against the live npm-registry and **executed every script with `--help` against the installed-`@pump-fun/[email protected]`** (this is what caught the removed-symbol regression-the first run's `--help` check masked behind a shell pipe).--## Per-skill drift (vs upstream)--| Skill | Shared files differing from upstream | Verdict |-| -------------------- | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |-| **create-coin** | `SKILL.md`, `scripts/build-create-coin-tx.mjs`, `package.json`, `package-lock.json` | All differences are three.ws-deliberate (brand mark + SDK bump) or benign lock noise. Nothing to pull. |-| **swap** | `package.json` only | SDK bump (we're ahead). All scripts + SKILL.md byte-identical. Nothing to pull. |-| **coin-fees** | `package.json`, `package-lock.json`, `SKILL.md`, 5 `scripts/*.mjs` | `package.json` = SDK bump (was already ahead). The rest are **our 2026-06-11 SDK-symbol fix** (see below), not upstream drift. |-| **tokenized-agents** | none | Fully byte-identical to upstream (SKILL.md, SCENARIOS.md, WALLET_INTEGRATION.md, both `references/**`). |--Files present only in our tree (intentional, not upstream regressions):-`reactive/` (our skill), `*/handlers.js`, `*/manifest.json`, `*/tools.json`,-`.claude-plugin/plugin.json` (our plugin-wrapper layer), and-`create-coin/scripts/lib/vanity.mjs` (our brand-mark grinder).--### Critically: the transaction logic still has **zero** upstream drift--Every `scripts/lib/*.mjs` across all four skills — `args`, `coin-api`,-`coin-resolve`, `compute`, `constants`, `env`, `jito`, `tx-build` — is-byte-identical to upstream HEAD. No upstream changes to SDK calls, program IDs,-fee/cashback/mayhem/buyback constants, Jito tip accounts, or instruction-building-have landed since our copy. The `--help` surface of `build-create-coin-tx.mjs`-confirms the full feature set: `--mayhem-mode`, `--cashback`,-`--tokenized-agent`, `--buyback-bps`, `--front-runner-protection` (Jito),-`--alt-address`, RPC priority-fee handling.--## coin-fees SDK-symbol fix (2026-06-11)--**What was wrong.** All five `coin-fees` scripts plus `SKILL.md` imported and-called `isCreatorUsingSharingConfig({ mint, creator })` from-`@pump-fun/pump-sdk`. That export was **removed** somewhere between SDK `1.32.0`-and `1.36.0` and replaced by `hasCoinCreatorMigratedToSharingConfig({ mint, creator })`-— same `{ mint, creator } → boolean` signature, same semantics. Verified directly:--- `@pump-fun/[email protected]` exports `isCreatorUsingSharingConfig`, **not** the new name.-- `@pump-fun/[email protected]` (npm `latest`, what we pin) exports- `hasCoinCreatorMigratedToSharingConfig`, **not** the old name. The two names- never coexist in any single release.--Our `coin-fees/package.json` pins `^1.36.0`, so a fresh `npm install` resolves-`1.36.0` and every script throws `SyntaxError: … does not provide an export named-'isCreatorUsingSharingConfig'` on import. It worked in practice **only** because-the committed `coin-fees/package-lock.json` was stale and still resolved `1.32.0`-(an `npm ci` artifact); the manifest, lock, and scripts disagreed.--This is **not** upstream drift — upstream still uses the old symbol and pins-`^1.33.0`, so upstream's own `coin-fees` skill is equally broken against current-SDK. It is a three.ws-internal regression: our deliberate SDK bump to `^1.36.0`-(commit `ebbd69f8`) was never wired through the scripts or the lock.--**Fix applied.**--1. Renamed `isCreatorUsingSharingConfig` → `hasCoinCreatorMigratedToSharingConfig`- in the 5 scripts (`build-collect-fee-tx`, `build-distribute-fees-tx`,- `build-sharing-config-tx`, `fetch-fee-info`, `fetch-distributable-info`) and in- `SKILL.md` (import example + decision-flow diagram). The other fee-sharing- exports the scripts use — `feeSharingConfigPda(mint)` and- `isSharingConfigEditable({ sharingConfig })` — are unchanged in `1.36.0` and- were left as-is.-2. Regenerated `coin-fees/package-lock.json` (`npm install --package-lock-only`)- so it resolves `@pump-fun/[email protected]` (and `@pump-fun/[email protected]`,- satisfying its `^1.16.0`), matching the manifest and the renamed scripts.--**Verified:** all six `coin-fees` scripts now import and exit 0 on `--help`-against `1.36.0`; the renamed files are byte-identical to upstream **modulo the-single symbol rename** (no reflow, no other change). `coin-fees` is the only skill-affected — `create-coin` and `swap` scripts import no removed symbol and run clean-against `1.36.0` unchanged.--> Direction note: we adapted the scripts **forward** to the SDK we actually ship-> (`1.36.0`, also what the root repo and the other skills use) rather than-> downgrading `coin-fees` back to a `1.3x` pin. Downgrading would split SDK-> versions across skills and contradict the standing "don't downgrade below-> upstream" decision below.--## Deliberate three.ws divergences (preserved — do **not** clobber)--1. **`3ws…` brand mark on created mints.** `create-coin/SKILL.md` and- `create-coin/scripts/build-create-coin-tx.mjs` replace upstream's bare- `Keypair.generate()` with `grindMarkedMint()` from our local- `scripts/lib/vanity.mjs`, so a scripted launch carries the same on-chain- brand provenance as a web-UI launch. The mark string lives in one constant- (`THREE_WS_MARK = "3ws"`) and mirrors the canonical- [`src/solana/vanity/brand.js`](../../src/solana/vanity/brand.js). Added by- commit `14259dff`. The SKILL.md brand section also re-asserts the `$THREE`-only- rule inline.-2. **`reactive/` skill.** Our addition (PumpPortal feed → avatar gestures). Not in- upstream. Untouched. (Also: deliberately kept out of `.prettierignore` so it- stays prettier-enforced — see compliance section.)-3. **README row.** Our README adds one row linking the Reactive Avatar skill;- otherwise identical to upstream.-4. **Plugin-wrapper files.** `handlers.js` / `manifest.json` / `tools.json` per- skill and `.claude-plugin/plugin.json` are our skill→plugin adapter layer, not- upstream files. Note: `handlers.js` calls the hosted pump.fun agent API- (`fun-block.pump.fun/agents/*`); the local `scripts/*.mjs` are the standalone- "custom integration" path. The coin-fees regression above only affected the- script path, not the hosted-API tool path.--## SDK versions: we remain ahead of upstream--`diff` direction below is `upstream → ours`.--| Package | Upstream HEAD | Our `package.json` | npm `latest` (2026-06-11) | Note |-| ------------------------------------------------- | ------------- | ------------------ | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `@pump-fun/pump-sdk` | `^1.33.0` | `^1.36.0` | `1.36.0` | We match npm latest; ahead of upstream. |-| `@pump-fun/pump-swap-sdk` | `^1.15.0` | `^1.16.0` | `1.17.0` | Ahead of upstream; manifests one minor behind npm latest (locks resolve `1.17.0`). |-| `@pump-fun/agent-payments-sdk` (create-coin only) | `^3.0.3` | `^3.0.3` | `3.0.3` | **Now matches upstream + npm.** Settled by [task 04](04-agent-payments-sdk-reconcile.md): the local workspace fork was renamed `@three-ws/agent-payments`; the skill manifest pins the real published `^3.0.3` for external templates. |--**Decision: keep our pins; do not downgrade to upstream.** Reverting to upstream's-`^1.33.0/^1.15.0` would be a regression, and applying upstream's-`bump-sdk-versions` commit is a no-op since we already exceed it.--### Lockfile state (post-fix)--- **`coin-fees`** — lock **regenerated** to `1.36.0` / `1.17.0` as part of the- symbol fix above. Manifest, lock, and scripts now agree.-- **`swap`** — lock still byte-identical to upstream (resolves old `1.32.0/1.15.0`)- while the manifest asks `^1.36.0/^1.16.0`. **Left as-is on purpose:** the swap- scripts import no removed symbol, so they run correctly against both the old and- new SDK — there is no correctness driver, and regenerating would only move the- lock further from upstream. Flagged as harmless drift, not fixed.-- **`create-coin`** — lock differs from upstream only by environment-generated- noise (optional native deps `bufferutil`/`utf-8-validate`, two dropped- `"peer": true` flags) and pins the real `agent-payments-sdk@^3.0.3`. Scripts run- clean against `1.36.0`. Left as-is.--## `$THREE`-only compliance--No other-coin or non-`$THREE` mint references exist in `pump-fun-skills/`, and none-were introduced by the symbol fix (it touches only an SDK function name). A targeted-scan for foreign token names/tickers came back clean. Every base58 string in the-tree is a protocol constant or a synthetic placeholder, all byte-identical to-upstream:--- `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` — USDC mint (real settlement asset- used by `tokenized-agents`, not a meme/launched coin).-- `So11111111111111111111111111111111111111112` — wrapped-SOL native mint.-- `6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P` — pump.fun **program** ID.-- `TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb` — SPL Token-2022 **program** ID.-- Jito tip accounts (`scripts/lib/jito.mjs`) and pump.fun fee/program accounts- (`scripts/lib/constants.mjs`) — protocol constants (byte-identical to upstream).-- `ABcDeFgHiJkLmNoPqRsTuVwXyZ123456789abcdefg`, `CreatorWalletAddress…`,- `BondingCurveAddress…` — explicit synthetic placeholders in sample JSON.--The `$THREE` CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump` is the only mint-presented as a coin (in `create-coin/SKILL.md`).--### Prettier / formatting--The vendored mirror has always followed upstream's formatting, which does **not**-satisfy our repo `prettier` config — upstream's own copies of these files fail-`prettier --check` identically. Reformatting them would diverge the mirror from-upstream wholesale. Resolved the same way as the sibling vendored snapshot-`docs/pumpfun-program/`: added the four vendored skill dirs (`create-coin/`,-`swap/`, `coin-fees/`, `tokenized-agents/`) plus `.claude-plugin/plugin.json` to-[`.prettierignore`](../../.prettierignore) under "Vendored / external library-code." This makes `prettier --check` green, documents intent, and guards against a-future `--write` clobbering the upstream-faithful formatting. **Our own-`reactive/` skill is intentionally left out of the ignore list and remains-prettier-clean and enforced.**--## Duplicates elsewhere in the repo--| Location | What it is | Action |-| ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------- |-| `dist/pump-fun-skills/` | Build output — `cpSync` of `pump-fun-skills/` ([vite.config.js](../../vite.config.js)) and [scripts/build-local-skill-packs.mjs](../../scripts/build-local-skill-packs.mjs). `dist`/`dist-lib`/`dist-artifact` are gitignored (0 tracked files). | **Do not hand-edit.** Regenerates from source on next build. |-| `examples/skills/pump-fun/`, `public/skills/pump-fun/`, `data/skills/**` | A **different**, three.ws-native skill set (e.g. the read-only `pump-fun` market-intel skill that calls `/api/pump-fun-mcp`). **Not** vendored copies of the upstream create-coin/swap/coin-fees skills. | **Out of scope.** No upstream relationship; no update needed. |--## Actions taken (2026-06-11)--- **Re-verified** upstream is unchanged since 2026-06-08 (still HEAD `c8aaa6a8`,- no new commits/tags/releases) — nothing to pull.-- **Fixed** the `coin-fees` removed-SDK-symbol regression: renamed the export in 5- scripts + `SKILL.md`, regenerated `coin-fees/package-lock.json` to `1.36.0`.-- **Added** the four vendored skill dirs + `plugin.json` to `.prettierignore`- (mirror is now `prettier --check` clean; `reactive/` stays enforced).-- **Corrected** the SDK table for the now-settled `agent-payments-sdk@^3.0.3` pin- (task 04).-- No upstream content pulled; no `$THREE`-only violation introduced.--## Follow-ups (not in this task)--1. Optionally bump `@pump-fun/pump-swap-sdk` in the `swap` and `create-coin`- **skill** `package.json` files from `^1.16.0` to `^1.17.0` to match the root- manifest, and regenerate the `swap` lock in the same pass. Independent of- upstream (still on `1.15.0`); no correctness driver today.-2. Re-run this drift check when upstream next pushes (dormant since 2026-04-23).-3. If upstream eventually adopts SDK ≥ `1.34` and updates `coin-fees` to the- `hasCoinCreatorMigratedToSharingConfig` API, our rename will converge with- theirs — re-diff at that point to confirm.- </content>- </invoke>diff --git a/tasks/site-overhaul/E-improve-features/E02-play-walk-newcomer-framing.md b/tasks/site-overhaul/E-improve-features/E02-play-walk-newcomer-framing.mddeleted file mode 100644index 5e1766770..000000000--- a/tasks/site-overhaul/E-improve-features/E02-play-walk-newcomer-framing.md+++ /dev/null@@ -1,42 +0,0 @@-# E02 — `/play` & `/walk` newcomer framing--**Track:** Improve Features · **Size:** M · **Priority:** P2--## Goal-Give `/play` and `/walk` a newcomer-friendly cold open: explain what's happening, give a first-objective, and remove the crypto-first framing — without dumbing down the experience.--## Why it matters-The audit scored `/play` **2/10** for newcomers: it opens on "COIN COMMUNITIES" with no context,-and a user expecting a game lands in a token-economy sim. `/walk` is clearer but assumes the user-already has an avatar.--## Context-- [pages/play.html](pages/play.html), [pages/walk.html](pages/walk.html).-- Memory: **never tell users they're playing single-player in `/play`** ([play-no-singleplayer-framing]); the $THREE home town + NPC agent commerce are real features to surface, not hide.-- Memory: `/walk` has real Rapier physics + companion; respect those.--## Scope-- `/play`: a brief, skippable intro that explains the world in plain words and gives a first goal; provide a guest/just-explore path before any wallet/coin concept; keep the economy discoverable, not mandatory up front.-- `/walk`: if the user has no avatar, offer a default/sample to walk immediately, with a clear path to create their own.-- Honor the existing framing rules and features; don't strip the depth — gate it behind a gentle intro.--## Definition of done-- A first-timer entering `/play` or `/walk` understands what to do within seconds and can act without first grasping crypto; existing features remain intact.--## Verify-- Fresh session into `/play` and `/walk`; confirm the intro/objective appears, a no-wallet path works, and framing rules are respected.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/site-overhaul/E-improve-features/E02-play-walk-newcomer-framing.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/site-overhaul/F-advertise-value/F05-task-oriented-docs.md b/tasks/site-overhaul/F-advertise-value/F05-task-oriented-docs.mddeleted file mode 100644index 9f5d42ee9..000000000--- a/tasks/site-overhaul/F-advertise-value/F05-task-oriented-docs.md+++ /dev/null@@ -1,41 +0,0 @@-# F05 — Task-oriented docs overhaul--**Track:** Advertise & Value · **Size:** M · **Priority:** P2--## Goal-Reorient the docs around what users want to *do* — "Build a customer-service avatar in 5 minutes,"-"Embed an agent on your website," "Launch a coin for your community" — not around internal-architecture.--## Why it matters-Docs are both support and marketing. Task-oriented guides reduce friction, rank in search, and-double as proof the platform works. The audit shows users need plain, goal-driven guidance.--## Context-- Docs hub: [docs/index.html](docs/index.html) (SPA, `/docs/:page`). Existing integration docs (e.g. IBM) are nav-wired — follow that pattern.-- Reuse C02 use-cases, C04 glossary, F02 landing pages; honest examples only.--## Scope-- A "Guides" section with 5–8 task-oriented walkthroughs for the top jobs-to-be-done, each with real steps, screenshots/embeds, and links into the product.-- Keep reference docs but lead with guides; wire glossary terms (C04).-- Ensure docs use the unified design system and are searchable (tie to D01 command palette).--## Definition of done-- The docs lead with task-oriented guides covering the top user goals; each guide is accurate, real, and links into the product; nav-wired and searchable.--## Verify-- Follow one guide end-to-end as a new user and reach the promised outcome; confirm guides appear in nav + command palette.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/site-overhaul/F-advertise-value/F05-task-oriented-docs.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.