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
feat(analytics): roll up owner return visits weekly so the retention metric is queryable
nirholas9cbd3d13354f
diff --git a/CLAUDE.md b/CLAUDE.mdindex c7a785ec3..40742f0c8 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -305,7 +305,7 @@ The whole build + submit + purge in one command: `npm run deploy:gcp:full`.- Frontend: vanilla JS modules + Vite (`npm run dev`, port 3000).- 3D: Three.js with glTF/GLB.- Backend touchpoints: serverless-style handlers in `api/`, workers in `workers/`.-- **Production runs on Google Cloud Run, NOT Vercel** (migrated 2026-07-07 after Vercel disabled the deployment). One container ([server/index.mjs](server/index.mjs)) serves the static frontend, the vercel.json route table, and all `api/**` handlers; the crons (104 as of 2026-08-06, see vercel.json) run on Cloud Scheduler. `vercel.json` is a LIVE config file: `server/index.mjs` reads its `routes` array on boot (split at the `{handle:"filesystem"}` marker into pre- and post-filesystem phases), and `scripts/create-gcp-scheduler.mjs` reads its `crons` array to sync Cloud Scheduler jobs. The server itself never reads `crons`. Never delete `vercel.json` as a leftover. GCP builds/deploys must pin the `three-ws-build@` (build) and `three-ws@` (runtime) service accounts; the project's default compute SA was deleted. Deploys: see the "Deploy runbook" section above.+- **Production runs on Google Cloud Run, NOT Vercel** (migrated 2026-07-07 after Vercel disabled the deployment). One container ([server/index.mjs](server/index.mjs)) serves the static frontend, the vercel.json route table, and all `api/**` handlers; the crons (105 as of 2026-08-11, see vercel.json) run on Cloud Scheduler. `vercel.json` is a LIVE config file: `server/index.mjs` reads its `routes` array on boot (split at the `{handle:"filesystem"}` marker into pre- and post-filesystem phases), and `scripts/create-gcp-scheduler.mjs` reads its `crons` array to sync Cloud Scheduler jobs. The server itself never reads `crons`. Never delete `vercel.json` as a leftover. GCP builds/deploys must pin the `three-ws-build@` (build) and `three-ws@` (runtime) service accounts; the project's default compute SA was deleted. Deploys: see the "Deploy runbook" section above.- **Env-var trap:** `vercel env pull` returns EMPTY for secret-type vars. Never trust a Vercel env export as complete. Production env lives on the Cloud Run service (`gcloud run services describe/update three-ws-api --region us-central1`).- Solana/agent SDKs in `sdk/`, `solana-agent-sdk/`, `agent-payments-sdk/`.- Real APIs in use: Pump.fun feed, Solana RPC, OpenAI/Anthropic via worker proxies. Never mock these.diff --git a/api/_lib/schema.sql b/api/_lib/schema.sqlindex c9f15ce2b..91398efcc 100644--- a/api/_lib/schema.sql+++ b/api/_lib/schema.sql@@ -993,6 +993,55 @@ create table if not exists solana_attestations_cursor (last_indexed_at timestamptz not null default now());+-- ── agent_onchain_events — cross-chain agent lifecycle index (Solana first) ──+-- One row per indexed on-chain event, every chain in one table. Written by the+-- erc8004-crawl (EVM registry logs) and solana-attestations-crawl (Solana+-- account signatures) crons; read by /api/agents/onchain-history and the index+-- lag monitor on /status. `chain_id` is 0 on Solana so the uniqueness index+-- never sees a NULL. occurred_at is the ABSOLUTE on-chain timestamp; indexed_at+-- is ingestion time. Mirrors api/_lib/migrations/20260811090000_agent_onchain_events.sql.+create table if not exists agent_onchain_events (+ id bigserial primary key,+ chain text not null,+ chain_id integer not null default 0,+ network text not null default 'mainnet',+ agent_ref text not null,+ event_class text not null,+ event_name text not null,+ tx text not null,+ log_index integer not null default 0,+ block_number bigint,+ occurred_at timestamptz not null,+ actor text,+ counterparty text,+ payload jsonb not null default '{}'::jsonb,+ indexed_at timestamptz not null default now()+);+create unique index if not exists agent_onchain_events_uniq+ on agent_onchain_events(chain, chain_id, tx, log_index);+create index if not exists agent_onchain_events_agent_time+ on agent_onchain_events(agent_ref, occurred_at desc);+create index if not exists agent_onchain_events_class_time+ on agent_onchain_events(event_class, occurred_at desc);+create index if not exists agent_onchain_events_chain_indexed+ on agent_onchain_events(chain, indexed_at desc);++create table if not exists agent_event_cursor (+ chain text not null,+ chain_id integer not null default 0,+ agent_ref text not null,+ network text not null default 'mainnet',+ last_tx text,+ last_slot bigint,+ last_event_at timestamptz,+ last_indexed_at timestamptz not null default now(),+ scanned integer not null default 0,+ error text,+ primary key (chain, chain_id, agent_ref)+);+create index if not exists agent_event_cursor_stale+ on agent_event_cursor(last_indexed_at nulls first);+-- ── SAS credentials (credentialed attestations issued by three.ws authority) ──-- Permissionless attestations live in solana_attestations (memo-based);-- this table is the credentialed counterpart for things only we can issuediff --git a/api/analytics/retention.js b/api/analytics/retention.jsnew file mode 100644index 000000000..54d72b1ff--- /dev/null+++ b/api/analytics/retention.js@@ -0,0 +1,59 @@+/**+ * GET /api/analytics/retention — week-2 retention on minted agents.+ *+ * Serves the cohort table `api/cron/retention-rollup.js` writes: owners grouped+ * by the ISO week they minted their first agent on-chain, and how many of them+ * came back to that agent during days 7..13. It is the read side of the README+ * roadmap's phase-2 verification metric.+ *+ * Query params+ * metric — `week2_converse` (default; the roadmap's "return to converse")+ * or `week2_return` (came back at all, conversation or not).+ * weeks — how many cohort weeks to return, 1..104. Default 26.+ *+ * Admin-only. The numbers are platform-wide business metrics, not the caller's+ * own data, so the gate is the same `requireAdmin` every other platform-internal+ * surface uses. A signed-in non-admin gets a 403, which the dashboard treats as+ * "hide the panel" rather than an error.+ */++import { cors, json, method, wrap } from '../_lib/http.js';+import { requireAdmin } from '../_lib/admin.js';+import {+ RETENTION_METRICS,+ RETENTION_METRIC_LABELS,+ WEEK2_TARGET_RATE,+ readCohorts,+ summarizeCohorts,+} from '../_lib/retention.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;+ if (!(await requireAdmin(req, res))) return;++ const url = new URL(req.url, 'http://internal');+ const requested = url.searchParams.get('metric') || RETENTION_METRICS[0];+ const metric = RETENTION_METRICS.includes(requested) ? requested : RETENTION_METRICS[0];+ const weeks = Math.min(Math.max(parseInt(url.searchParams.get('weeks') || '26', 10) || 26, 1), 104);++ const cohorts = await readCohorts({ metric, limit: weeks });++ return json(res, 200, {+ metric,+ metric_label: RETENTION_METRIC_LABELS[metric],+ target: WEEK2_TARGET_RATE,+ // Oldest first — chart order, so the client never has to re-sort.+ cohorts: cohorts.map((c) => ({+ cohort_week: c.cohort_week,+ minted_owners: c.minted_owners,+ retained_owners: c.retained_owners,+ retention_rate: Number(c.retention_rate),+ window_start: c.window_start,+ window_end: c.window_end,+ is_complete: c.is_complete,+ computed_at: c.computed_at,+ })),+ summary: summarizeCohorts(cohorts),+ });+});diff --git a/api/cron/retention-rollup.js b/api/cron/retention-rollup.jsnew file mode 100644index 000000000..9ff7f69ab--- /dev/null+++ b/api/cron/retention-rollup.js@@ -0,0 +1,89 @@+// @ts-check+// GET /api/cron/retention-rollup — weekly week-2 retention rollup on minted agents.+//+// This is the cron that makes the README roadmap's phase-2 verification metric a+// number instead of an aspiration: "users return to converse with their own+// agent; >=30% week-2 retention on minted agents".+//+// Once a week it recomputes every cohort in the trailing window (owners grouped+// by the ISO week they minted their first agent on-chain) and upserts one row per+// (cohort week, metric) into `agent_retention_cohorts`. Recomputing the tail on+// every run rather than only the newest week is deliberate: a cohort's window+// stays open for 14 days after each member's mint, and a visit recorded today can+// legitimately move a cohort that was rolled up last week. Rows carry+// `is_complete` so a consumer can tell a final number from a moving one, and the+// upsert is idempotent, so a re-run (or a retry after a partial failure) converges+// instead of double-counting.+//+// Weekly cadence matches the metric: a daily run would rewrite the same rows with+// the same values six times for nothing. The trailing window is wide enough that+// a missed week is repaired by the next run with no backfill step.++import { json, method, wrapCron } from '../_lib/http.js';+import { requireCron } from '../_lib/cron-auth.js';+import { sendOpsAlert } from '../_lib/alerts.js';+import {+ computeRetentionCohorts,+ cohortRecords,+ upsertCohortRecord,+ utcDay,+} from '../_lib/retention.js';++// Half a year of cohorts. Wide enough that a skipped run, a late visit, or a+// retroactive mint correction is absorbed on the next tick; small enough that the+// whole rollup is a single cheap aggregate plus a bounded set of upserts.+const COHORT_WEEKS = 26;++export default wrapCron(async (req, res) => {+ if (!method(req, res, ['GET'])) return;+ if (!requireCron(req, res)) return;++ const today = utcDay();+ const rows = await computeRetentionCohorts({ weeks: COHORT_WEEKS, today });+ const records = cohortRecords(rows, today);++ let written = 0;+ let errors = 0;+ for (const rec of records) {+ try {+ await upsertCohortRecord(rec);+ written += 1;+ } catch (err) {+ errors += 1;+ console.error(+ `[retention-rollup] upsert failed for ${rec.cohortWeek}/${rec.metric}:`,+ err?.message,+ );+ }+ }++ if (errors > 0) {+ sendOpsAlert(+ 'retention rollup write errors',+ `${errors}/${records.length} cohort upserts failed. Week-2 retention will read stale until the next run.`,+ { signature: 'retention-rollup-errors' },+ );+ }++ // The newest cohort whose window has fully closed — the number the roadmap+ // gate is actually read against.+ const latestComplete = records+ .filter((r) => r.metric === 'week2_converse' && r.isComplete)+ .sort((a, b) => (a.cohortWeek < b.cohortWeek ? 1 : -1))[0] ?? null;++ return json(res, 200, {+ ok: true,+ cohorts: rows.length,+ written,+ errors,+ latestComplete: latestComplete+ ? {+ cohortWeek: latestComplete.cohortWeek,+ mintedOwners: latestComplete.mintedOwners,+ retainedOwners: latestComplete.retainedOwners,+ retentionRate: latestComplete.retentionRate,+ }+ : null,+ ranAt: new Date().toISOString(),+ });+});diff --git a/vercel.json b/vercel.jsonindex 972fcac5f..04054c4cb 100644--- a/vercel.json+++ b/vercel.json@@ -5950,6 +5950,10 @@"path": "/api/cron/leaderboard-rollup","schedule": "0 9 * * *"},+ {+ "path": "/api/cron/retention-rollup",+ "schedule": "35 9 * * 1"+ },{"path": "/api/cron/changelog-push","schedule": "*/20 * * * *"