Creator Analytics - Design Document
Status: Shipped. All three tabs are live at /analytics —
My Stats (free, every user gets a personal dashboard), Creator
Analytics (Pro, Phase 1.5 with 15 use cases including character
leaderboard, model usage, follower/favorite growth), and Audience
Insights (Pro, Phase 3, anonymized audience aggregation). UC-C18
conversation-origin tracking shipped alongside Phase 2 audience
aggregation. Ghost stat/chart cards render while data loads.
Overview
We already store the data — materialized views (mv_character_stats, mv_user_stats, mv_mode_stats, mv_lorebook_stats) and per-message pipeline stats (web_message_stats) capture everything from conversation counts to token usage over time.
The analytics page has two tiers:
- My Stats (free) — Every user gets a personal activity dashboard: daily chat activity, most chatted characters, favorite creators. Real charts, real data. This is a complete product on its own and serves as a natural visual preview of what the charting experience looks like.
- Creator Analytics (Pro) — Creators who subscribe see how their published content performs: engagement trends, character leaderboard, model usage breakdown, follower/favorite growth. The upsell is a banner at the bottom of My Stats: "Want to see how your content performs? Go Pro."
The same chart components power both tiers, so the free experience is the best advertisement for the paid one.
Strategic Positioning
Free tier is deliberately substantive — by design
The Free My Stats tier is intentionally generous: streaks, themes, word count, regen rate, paused-conversation pickup, drifted-away nudges. This will look like "leaving conversion money on the table" to anyone pattern-matching to typical SaaS funnels. It is not. Echo of Dreams is a passion project where adoption ranks above margin (consistent with the platform's broader pricing posture — see the ecosystem-thinking notes in project memory). A genuinely useful free product is the strongest organic-marketing channel the platform has, and the Pro upgrade story isn't "unlock the same charts about yourself" — it's "unlock charts about your audience." Different surface, different question, different reason to pay.
Pro value proposition
Pro Creator Analytics sells action loops, not status snapshots. Every other metric category in the document gets a column in the breakdown — but the load-bearing UCs for Pro are the iteration loops:
- UC-C14 (greeting performance) — the single most A/B-testable surface a creator owns
- UC-C15 (drop-off curve) — diagnoses where a character runs out
- UC-C17 (regen rate) — automatic quality signal that turns into prompt-tuning work
- UC-C18 (discovery funnel) — strategic question that changes what the creator builds next
The pitch isn't "see how your content performs"; it's "feedback loops the rest of the industry hides." Creators who treat their work as craft want feedback loops. Pro is for them. Creators who don't aren't the target — and that's fine.
Privacy is a competitive moat
The anonymization design (UC-C8 — opaque session-salted IDs, min cohort suppression, no PII to creators, no conversation content) is unusual in this category. Competing RP platforms either don't have analytics or leak more than they should. In a market where users worry about being tracked or studied by creators, "your creator can see engagement, not you" is a brand asset, not just compliance. The anonymization rules aren't a constraint on what we'd otherwise build — they're the design choice that makes the audience-insights tier credible to users at all.
Engagement loops
Individual UCs compose into loops that make the dashboard sticky. Cutting any UC in a loop weakens the whole loop more than its individual contribution suggests:
Creator retention loop (Pro): UC-C9 (notice growth/decline) → UC-C10 / UC-C15 (diagnose where) → UC-C14 / UC-C17 (iterate on what) → return to UC-C9 next week to measure the change. Without UC-C9 the loop has no entry point; without UC-C14 / UC-C17 it has no exit; without UC-C10 / UC-C15 the middle is guesswork.
User retention loop (Free): UC-U10 / UC-U13 (re-engagement nudges find paused stories and drifted characters) → user returns → UC-U1 / UC-U8 (consistency cards reward the return) → UC-U2 / UC-U3 / UC-U12 (discovery shows them new things to try). Pull-shaped re-engagement: the user opens the page voluntarily and finds the nudge, not the other way around.
Creator conversion funnel (Free → Pro): UC-U6 (conversion mechanic) is the only UC in the Free tier whose job is conversion — and it succeeds only if the rest of Free is genuinely good. The upsell card lands harder when the user is already sold on the chart aesthetic and the data quality, not when it's gating their first impression.
Realistic scope
This is a multi-month build. Phase 1 alone is 4–6 weeks. The full design (Phases 1–3) is realistically 3+ months of focused work from one developer, including snapshot jobs, audience aggregation, opaque-ID HMAC, retention pruning, two new schema tables, conversation- origin instrumentation, and the shaped endpoints + frontend tabs. The phasing below is structured so each phase ships a coherent product slice — incremental delivery is non-negotiable.
Use Cases
This feature is grounded in concrete user and creator behaviors observed on the platform. Every dashboard section below maps to at least one of the use cases here — if a section doesn't answer a real question, it shouldn't ship.
My Stats (free) — user use cases
These are the people opening /settings/analytics without a Pro
subscription. The unifying thread: curiosity about themselves, not
about other users.
UC-U1 — "How much have I been chatting?"
- Persona: Long-term roleplayer who has been on the platform for months.
- Trigger: Casual curiosity, end-of-month reflection, or sharing a screenshot in a Discord community.
- Question answered: Total messages, conversations, characters chatted with — and how those have trended.
- Sections used: Overview cards (with deltas), daily activity chart.
- How we'll answer it:
- Daily activity chart — generic stack:
GET /api/stats/messages?granularity=day(User scope, already shipped). Renders throughTimeSeriesChart. - Overview cards (totals + deltas) — shaped:
/api/analytics/my-stats. Deltas = current period total − previous period of equal length, computed server-side fromweb_message_stats+web_conversationsfiltered byuser_id. The generic stack has no period-comparison primitive, so this stays in the shaped endpoint.
- Daily activity chart — generic stack:
- Why it matters: Quantified-self moment. Drives engagement (people share their stats, which is organic marketing) and gives free users a reason to keep coming back to the page.
UC-U2 — "Which character did I vibe with most?"
- Persona: A user who has chatted with 30+ characters across a year and wants to find the one they keep returning to — maybe to subscribe to that creator, or to start a new conversation with the same character.
- Trigger: "I miss that one character but I don't remember which one it was."
- Question answered: Ranked list of characters by message count, with avatar + creator name.
- Sections used: Most chatted characters bar chart.
- How we'll answer it: Shaped endpoint (
/api/analytics/my-stats).web_message_stats WHERE user_id = @caller AND created_at >= @start GROUP BY character_id ORDER BY count DESC LIMIT 10, joined tocharactersfor name/avatar/uuid andusersforcreatorName. Top-N doesn't fit the generic bucket-shaped stack — kept in the shaped endpoint. Deep links each row to/character/{slug}. - Why it matters: This is a discovery use case disguised as a stats page — it surfaces re-engagement opportunities the user didn't know they were looking for.
UC-U3 — "Which creators do I actually follow / spend time with?"
- Persona: A user who has favorited many creators but doesn't know which ones they actually engage with.
- Trigger: Deciding who to support (Patreon, subscribe-star, future creator monetization), or wanting to clean up their following list.
- Question answered: Creators ranked by message volume.
- Sections used: Favorite creators bar chart.
- How we'll answer it: Shaped endpoint (
/api/analytics/my-stats).web_message_stats ms JOIN characters c ON c.id = ms.character_id WHERE ms.user_id = @caller GROUP BY c.created_by_user_id ORDER BY count DESC LIMIT 10, joined tousersfor slug/name/avatar andCOUNT(DISTINCT ms.character_id)per creator for the "characters used" subtitle. Excludes characters owned by the caller (no self-counting). - Why it matters: Funnels engagement toward creators (positive feedback loop) and primes the user for any future creator-tipping or paid-package features.
UC-U4 — "Am I actually using the model I think I'm using?"
- Persona: A user who switches between Claude / GPT / Gemini and wants to validate which one they default to.
- Trigger: Echo-spend question ("why am I burning through my daily budget?"), model preference debate in a Discord, or comparing their behavior to a friend's.
- Question answered: Percentage breakdown of which models the user runs.
- Sections used: Model usage bar chart.
- How we'll answer it: Generic stack:
GET /api/stats/messages?dimensions=model(User scope, already shipped —fn_stats_messagessupportsmodeldim at scope=1). Client aggregates the bucketed series into period totals + percentages and renders viaHorizontalBarChart. No new backend. - Why it matters: Connects to Echo budgeting (informs whether they're using cheap vs. expensive models) and to model-preset choices.
UC-U5 — "When do I chat? Should I cut back?"
- Persona: A user with mild self-awareness about their screen time, or someone curious about their patterns ("am I a night owl on this platform?").
- Trigger: Vague feeling of "I think I've been on this too much" or pure curiosity.
- Question answered: Day-of-week × hour-of-day heatmap, peak hours, busiest day, average session length, total chat hours.
- Sections used: Activity heatmap, peak hours / busiest day callouts, session stat cards.
- How we'll answer it: Shaped endpoint (
/api/analytics/my-stats). Two queries:- Heatmap + callouts —
SELECT EXTRACT(dow FROM created_at), EXTRACT(hour FROM created_at), COUNT(*) FROM web_message_stats WHERE user_id = @caller AND created_at >= @start GROUP BY 1, 2. Peak hours = contiguous 3-hour window with max count; busiest day =argmaxover dow. - Sessions — window-function CTE on the user's messages; gap > 30 minutes between consecutive
created_atstarts a new session. Aggregate yields avg/longest/total/count-this-week. Doesn't fit the generic bucket-shaped stack — stays shaped.
- Heatmap + callouts —
- Why it matters: This is the digital-wellbeing angle — it's informational, not preachy. A user who recognizes their patterns trusts the platform more. Also a strong shareable artifact ("my busiest day is Thursday 10pm — same").
UC-U6 — "Show me proof the platform actually does charts before I pay"
- Persona: A creator-curious user weighing whether Pro is worth it.
- Trigger: Sees the upsell banner at the bottom of My Stats.
- Question answered: "What will Pro look like?" — implicitly answered by My Stats already showing real, polished charts.
- Sections used: All My Stats sections + the upsell banner.
- How we'll answer it: No data query — pure UI render. The
CreatorUpsellBannerreadsfn_get_user_subscription_limit(@user, 'analytics.dashboard'); if value is'user'(free), renders the upsell card under the My Stats sections and shows a centered upsell empty state on the Creator/Audience tabs. The actual upsell value comes from UC-U1…UC-U5/U7 being good — the conversion infrastructure is justButton+navigate('/settings/subscription'). - Why it matters: This is the conversion mechanic. Free users who already love the charts convert to Pro at a higher rate than users who saw a blurred-out preview, because the experience is real, not promised.
UC-U7 — "Are my conversations actually long enough that the AI is summarizing them?"
- Persona: A user doing long-form roleplay sessions who has heard about the summarization / "memory" feature and wants to know if it's actually engaging — or who is troubleshooting "the AI seems to forget things."
- Trigger: Reading the docs on summarization, hitting a context-related quirk, or curiosity about how the platform manages long sessions.
- Question answered: How many summaries the user has triggered over time, average summaries per conversation (proxy for conversation depth), and which model summarized them.
- Sections used: A "Conversation depth" stat card in the Activity Insights section + an optional summaries-over-time mini chart.
- How we'll answer it:
- Total summaries + avg per conversation — shaped (
/api/analytics/my-stats):SELECT COUNT(*) FROM web_summary_stats WHERE user_id = @caller AND created_at >= @startplusCOUNT(DISTINCT conversation_id). The ratio is the "conversations deep enough to summarize" headline. - Summaries over time — generic stack, but requires adding
StatsScope.Userto the existingsummariesmetric inDefaultStatsMetrics.Build()and extendingfn_stats_summarieswith ap_scope = 1branch filtering onweb_summary_stats.user_id. Once added, the chart renders viauseStatsQuery({ basePath: '/stats', metric: 'summaries' }).
- Total summaries + avg per conversation — shaped (
- Why it matters: Summarization is the most opaque part of the chat pipeline from a user's perspective. Surfacing it (a) demystifies "the AI's memory," (b) gives heavy users a status signal ("your conversations are deep enough to need a summary — the platform is working hard for you"), and (c) connects naturally to Echo costs once summarization spend lands in the ledger.
UC-U8 — "What's my streak?"
- Persona: A habitual user who likes consistency signals — Duolingo-streak energy, but lightweight and opt-out-able.
- Trigger: Opens the analytics page, sees the streak card, gets a small dopamine hit. Or: realizes they'd otherwise break a streak and decides to send a message before bed.
- Question answered: Consecutive days with at least one message; longest historical streak; streak status today.
- Sections used: A small "Streak" stat card alongside Activity Insights — visually distinct from the heatmap so it doesn't compete with UC-U5's wellbeing framing.
- How we'll answer it: Shaped (
/api/analytics/my-stats). Compute distinct dates withweb_message_stats WHERE user_id = @caller, run a window-function gap detection (ROW_NUMBER() - DATEtrick) to find consecutive runs, return current streak (must include today or yesterday in caller's timezone) + longest. UTC-pinned consistent with the Echo ledger rule. Opt-out via a settings toggle so wellbeing-conscious users can hide it. - Why it matters: Pairs with UC-U5 honestly — streak is celebratory, heatmap is informational. Two different relationships with the same data, both legitimate. A user can opt into the gamified one and ignore the reflective one, or vice versa.
UC-U9 — "How much have I written?"
- Persona: A user who treats the platform as a creative-writing tool — collaborative storytelling, worldbuilding, journaling-through-fiction — and wants to see their own output, not just consumption stats.
- Trigger: End-of-month reflection, NaNoWriMo-adjacent context, or sharing "I wrote 47k words this month" socially.
- Question answered: Total words the user has personally typed (not the AI's response), averages per session/day/conversation, longest single message, top characters by user-side word count.
- Sections used: A "Your Writing" stat card group, separate from the Activity cards (which are AI-output-shaped).
- How we'll answer it: Shaped (
/api/analytics/my-stats).SELECT SUM(array_length(string_to_array(trim(content), ' '), 1)) FROM web_messages WHERE user_id = @caller AND role = 0 AND created_at >= @start(role 0 = user-authored, per theMessageRoleenum). For per-character or per-day breakdowns, group oncharacter_idordate_trunc('day', created_at). Word count uses whitespace split — imperfect but cheap and consistent. - Why it matters: This is the only stat on the page that respects the manifesto framing — Echo of Dreams is for writers, not consumers. Every other metric counts what the platform did for the user; this one counts what the user did. For users who self-identify as writers, this is the single most validating number.
UC-U10 — "You haven't chatted with [character] in a while."
- Persona: A user with a long history who has favorites they've drifted away from — re-engagement nudge surfaced inside the analytics page (pull, not push).
- Trigger: Opens analytics, notices the "Drifted away" card, clicks through to the conversation.
- Question answered: Characters with high historical engagement and recent silence — "Crystal Dawn was your #2 most-chatted character 6 weeks ago — haven't heard from her since."
- Sections used: "Drifted away" card under Most Chatted Characters.
- How we'll answer it: Shaped (
/api/analytics/my-stats). For each character the user has chatted with:MAX(created_at)and historical message rank. Surface characters that were in the user's top 10 historically but have alast_active < CURRENT_DATE - INTERVAL '21 days'. Cap at 3 cards. Hide entirely if the user has chatted with fewer than 5 characters total (avoids surfacing every character). - Why it matters: Re-engagement is usually push-shaped (notifications, emails) and feels intrusive. This is pull-shaped — the user opens the analytics page voluntarily and finds the nudge waiting. Their agency is preserved, the nudge is contextually relevant, and the platform avoids the feedback-loop trap of notification-spam re-engagement that other consumer apps fall into.
UC-U11 — "Which of my personas do I actually use?"
- Persona: A user who has created 8+ personas over time for different roleplay scenarios and has lost track of which ones are active vs. abandoned.
- Trigger: Persona picker is cluttered, deciding whether to delete some, or curious about their own patterns.
- Question answered: Per-persona: conversation count, message count, last used. Ranked list with a "rarely used" cutoff.
- Sections used: A "Persona usage" panel in My Stats — table or bar chart with one row per persona.
- How we'll answer it: Shaped (
/api/analytics/my-stats).SELECT user_persona_id, COUNT(*) AS convos, SUM(message_count) AS msgs, MAX(updated_at) FROM web_conversations WHERE user_id = @caller AND user_persona_id IS NOT NULL GROUP BY 1, joined topersonasfor name/avatar. Cheap. - Why it matters: Quality-of-life on a UI surface that only gets noisier with time. Tells a user which personas are working for them and which to retire — and surfaces forgotten favorites that might be worth dusting off. Pairs naturally with persona-management actions ("delete unused?") in account settings.
UC-U12 — "What themes do I actually gravitate to?"
- Persona: A user curious about their own patterns — the inward-facing mirror of UC-C19's genre performance.
- Trigger: Self-discovery, feeding a "try something different" recommendation, or just sharing the chart.
- Question answered: Aggregate engagement (messages, conversations) grouped by tag/category over the characters/modes the user has actually chatted with. "82% of your conversations are in fantasy/medieval settings."
- Sections used: A "Your themes" panel — bar chart per top-level tag category (Genre, Setting, Tropes…), category-switchable.
- How we'll answer it: Shaped (
/api/analytics/my-stats).web_message_stats ms JOIN characters c ON c.id = ms.character_id WHERE ms.user_id = @caller, with the same per-category bitfield masking pattern as UC-C19 to avoid the multi-tag double-counting problem. Display name from the[Description]attribute on the matchingCharacterTagsconst. - Why it matters: Self-discovery — people often don't know their own patterns until they see the chart. Sometimes the realization is "oh, I really only do noir-mystery"; sometimes it's "I haven't touched sci-fi in 4 months, maybe I should try X." The data is sitting in the bitfield columns already; user-side aggregation is the same shape as creator-side, just scoped differently.
UC-U13 — "Which conversations should I pick back up?"
- Persona: A user with several long-running roleplays who has paused some mid-scene and forgotten about them.
- Trigger: Opens analytics, wants to find the narrative thread they left hanging — not the character they haven't chatted with, but the specific conversation they want to continue.
- Question answered: Top paused conversations by message count, with character/mode preview, last-activity date, and a "resume" link.
- Sections used: "Pick up where you left off" card group under My Stats — up to 5 conversation cards.
- How we'll answer it: Shaped (
/api/analytics/my-stats).SELECT id, character_id, message_count, updated_at FROM web_conversations WHERE user_id = @caller AND updated_at < CURRENT_DATE - INTERVAL '7 days' AND message_count >= 10 ORDER BY message_count DESC LIMIT 5, joined tocharactersfor the preview. Excluded if archived/deleted. - Relation to UC-U10: UC-U10 surfaces characters you've drifted from (re-engage with the persona). UC-U13 surfaces conversations you've paused (continue the narrative). A user who hasn't chatted with Elara in 3 weeks might want to start fresh; a user with a 47-message paused Elara story wants to continue that specific thread. Different intent, different action — both belong on the page.
- Why it matters: Narrative continuity. The platform is for collaborative storytelling, and stories left mid-scene are the platform's most valuable forgotten artifacts. Surfacing them turns "I have nothing to do tonight" into "oh right, I left Elara on a cliffhanger."
UC-U14 — "How often do I hit regenerate?"
- Persona: A user curious about their own pickiness, or troubleshooting "why am I burning through my Echo budget so fast?"
- Trigger: Opens analytics, sees the regen card, recognizes a pattern.
- Question answered: Personal regeneration rate — % of assistant messages where the user hit regenerate at least once. Optionally split by model so the user can see "Claude lands first try 92% of the time, GPT-4 only 66%."
- Sections used: "Regen rate" stat card in Activity Insights, optional per-model split.
- How we'll answer it: Generic stack (preferred) — add a
StatsScope.Userbranch to the regenerations metric proposed for UC-C17, scoped onweb_message_stats.user_idandevent_type = 'regenerate'. Or compute as a derived ratio on the shaped/api/analytics/my-statsendpoint. The data is already inevent_type; no new instrumentation. - Why it matters: Self-awareness signal. If a user regenerates Claude responses 8% of the time and GPT-4 responses 34%, the implicit nudge is "your prompts land better on Claude — maybe stick with it." Connects directly to Echo budget once that's mature: regenerations are double-spend.
Creator Analytics (Pro) — creator use cases
These are the people who have published content and pay for Pro. The unifying thread: they need to make decisions about what to build next, what to fix, and how to grow.
UC-C1 — "Which of my characters should I invest more time in?"
- Persona: A creator with 5–20 published characters, limited writing time per week, deciding which one deserves a v2 / spinoff / lorebook expansion.
- Trigger: Sitting down on a Sunday to plan the next week's creative work.
- Question answered: Which character drives the most engagement — and is it growing or stagnant?
- Sections used: Character leaderboard, content activity chart, retention by entity.
- How we'll answer it:
- Character leaderboard — shaped (
/api/analytics/creator):web_message_stats ms JOIN characters c ON c.id = ms.character_id WHERE c.created_by_user_id = @caller AND c.is_deleted = FALSE GROUP BY c.id ORDER BY count DESC, joined tomv_character_statsforconversation_countandfavorite_count. - Content activity chart — generic stack:
GET /api/creator/stats/messages(Creator scope, already shipped —fn_stats_messagesfilters on characters owned byp_subject_id). Anonymizer's min-cohort suppression is already wired. - Retention by entity — UC-C10 covers this; reuses
creator_audience_daily.
- Character leaderboard — shaped (
- Why it matters: The single most common question creators ask. A platform that can't answer this is just a publishing tool, not a creator product.
UC-C2 — "Is my lorebook actually being used, or is it dead weight?"
- Persona: A creator who spent 20 hours writing a 200-entry lorebook and has no idea if users actually trigger it during chats.
- Trigger: Considering whether to keep updating the lorebook or abandon it.
- Question answered: Per-lorebook usage volume + trend, derived from conversations whose entity graph includes the lorebook.
- Sections used: Entity usage breakdown (the row that includes lorebooks alongside characters and modes).
- How we'll answer it: Shaped (
/api/analytics/creator). Lorebook usage isn't a column onweb_message_stats— it's derived through the conversation's lorebook bindings. Query:web_message_stats ms JOIN conversation_lorebook_bindings clb ON clb.conversation_id = ms.conversation_id JOIN lorebooks lb ON lb.id = clb.lorebook_id WHERE lb.created_by_user_id = @caller GROUP BY lb.id.userscolumn =COUNT(DISTINCT ms.user_id). Trend = current vs. previous period delta. Same row shape as the character/mode entries in the breakdown so the UI is one table. - Why it matters: Lorebooks are invisible work — they don't show up in conversation lists. Without analytics, creators rationally stop investing in them. This use case rescues a feature category.
UC-C3 — "Is my custom mode actually preferred over the default?"
- Persona: A creator who built a "Fantasy RPG Mode" with a custom system prompt and wants to validate it.
- Trigger: Considering whether to publish more modes or stick to characters.
- Question answered: Mode usage volume relative to standard mode within the creator's audience.
- Sections used: Entity usage breakdown.
- How we'll answer it: Shaped (
/api/analytics/creator).web_message_stats ms JOIN prompt_modes pm ON pm.id = ms.mode_id WHERE pm.created_by_user_id = @caller GROUP BY pm.id. Same row shape as characters/lorebooks in the unified entity-usage table. Mode is a direct column onweb_message_stats— no entity-link join needed. - Why it matters: Validates (or kills) a creator's design hypothesis with hard data instead of vibes.
UC-C4 — "Should I bundle these into a package?"
- Persona: A creator considering whether two of their characters belong in the same Package, and whether to add a lorebook to the bundle.
- Trigger: Designing a new package or refactoring an existing one.
- Question answered: Cross-entity overlap — what % of users who chat with Character A also chat with Character B / use Lorebook X?
- Sections used: Entity correlation matrix.
- How we'll answer it: Shaped (
/api/analytics/creator/audience). Built oncreator_audience_daily(Phase 2 dependency). For each pair of the creator's entities, count audience users whosecharacter_ids/mode_idsarrays contain both entities, divide by the smaller of the two audience sizes — yields a normalized 0–1 overlap. Min-cohort guard: cells where either audience is < 5 users are masked. Returned as{ entities: [...], matrix: [[...]] }for the symmetric matrix renderer. - Why it matters: Packages are the platform's primary creative unit (per the package-direction memo); the correlation matrix is the single best signal for what to bundle. Without it, packaging is guesswork.
UC-C5 — "Am I building a loyal audience or just getting drive-by traffic?"
- Persona: A creator who's been publishing for 3+ months and wants to know if they have a real audience or are churning.
- Trigger: Deciding whether to invest more time on the platform vs. pivot to another platform.
- Question answered: Cohort breakdown (Power / Regular / Casual / Churned) with retention rates.
- Sections used: Cohort overview, retention by entity.
- How we'll answer it: Shaped (
/api/analytics/creator/audience). On-the-fly cohort assignment fromcreator_audience_daily— see the SQL example in Cohort Computation. Each cohort row aggregatesuser_count,total_messages,avg_messages,avg_entities_used, retention rate (cohort users present in current period who were also present in prior period), andtop_model(mode ofmodels_usedflattened across the cohort). Min-cohort suppression: cohorts with fewer than 5 users merge into the next-larger cohort. No rawuser_idever leaves the server. - Why it matters: Retention is the leading indicator of creator long-term value. A creator who can see "I have 23 power users driving 48% of my engagement" stays. A creator who can't see it leaves.
UC-C6 — "When should I publish to maximize visibility?"
- Persona: A creator about to drop a new character and wanting to time it for max impact.
- Trigger: Pre-publish prep, scheduling a launch.
- Question answered: When their audience is most active (hour of day, day of week).
- Sections used: Audience peak hours.
- How we'll answer it: Shaped (
/api/analytics/creator).SELECT EXTRACT(hour FROM created_at), COUNT(*) FROM web_message_stats ms JOIN characters c ON c.id = ms.character_id WHERE c.created_by_user_id = @caller AND created_at >= @start GROUP BY 1. Anonymization is automatic at this aggregation level (hourly counts, no per-user breakdown). Peak label = contiguous 3-hour window with max total. Same query shape as UC-U5 but creator-scoped. - Why it matters: Direct, actionable, immediately testable. Creators trust the page more once a tip pays off.
UC-C7 — "Which model should I optimize my prompts for?"
- Persona: A creator iterating on their character's system prompt and wondering whether to optimize for Claude or GPT-4.
- Trigger: A round of prompt tuning.
- Question answered: Which models the creator's audience uses — and crucially, which models their power users use.
- Sections used: Audience model usage donut, model preferences by cohort.
- How we'll answer it:
- Aggregate audience model usage — generic stack:
GET /api/creator/stats/messages?dimensions=model(Creator scope, already shipped). Anonymizer's min-cohort filter applies. - Model preferences by cohort — shaped (
/api/analytics/creator/audience). Joins the cohort assignment from UC-C5 with each user'smodels_usedarray fromcreator_audience_daily, computes per-cohort percentages. Cohorts with fewer than 5 users still suppressed. The donut in the main creator tab is sufficient for casual reading; the per-cohort breakdown is the deep-dive that makes UC-C7 actionable.
- Aggregate audience model usage — generic stack:
- Why it matters: Prompts that work great on Claude can fall apart on GPT-4. Knowing the audience's model split prevents wasted iteration.
UC-C8 — "Who are my superfans, and what do they have in common?"
Persona: A creator who has heard about audience-of-one effects and wants to design for their most engaged users without violating their privacy.
Trigger: Considering a Patreon, a Discord-tier reward, or a personalized greeting.
Question answered: Top engaged fans with anonymized IDs, the entities they cluster around, how often they're active.
Sections used: Biggest fans table.
How we'll answer it: Shaped (
/api/analytics/creator/audience).creator_audience_daily WHERE creator_user_id = @caller GROUP BY audience_user_id ORDER BY SUM(message_count) DESC LIMIT 20. Server then:- Generates a per-request session salt and computes
opaqueId = HMAC(audience_user_id, session_salt)rendered asFan #Nby stable rank within the response. Salt is discarded after serialization — IDs are not stable across calls. - Resolves
character_ids/mode_idsarrays to entity names (no IDs, no slugs). - Rounds
MIN(snapshot_date)/MAX(snapshot_date)to ISO week (2026-W09). - Drops the row entirely if its message count is below
MinCohortSizefrom the anonymizer policy.
This is where the
HashDimensionKeyspolicy hook described inSTATS_SYSTEM.mdfinally gets wired.- Generates a per-request session salt and computes
Why it matters: The creator gets actionable signal (these users overlap on Elara + RPG Mode + Forgotten Realms — they want lore-heavy fantasy) without the platform leaking PII. This is the use case that makes the anonymization design non-negotiable.
UC-C9 — "Am I growing? Show me the line going up."
- Persona: A creator wanting motivation, social-share material, or proof for an external pitch (Patreon page, sponsorship application).
- Trigger: End of month, milestone moment, or feeling discouraged.
- Question answered: Follower / favorite trend over time.
- Sections used: Follower trend chart, creator overview cards with deltas.
- How we'll answer it: Requires
creator_daily_statssnapshot table +fn_snapshot_creator_daily_statsdaily job (Phase 1.5 dependency). Two surfaces:- Follower trend chart — the snapshot data is a daily series, not an event count, so it doesn't fit
fn_stats_messagesshape directly. Two valid options: (a) shape it through the generic stack as a newfn_stats_followersmetric that readscreator_daily_statsvialast(value)per bucket, or (b) return it from the shaped/api/analytics/creatorendpoint asfollowerTrend.dataPoints[]. Option (b) is simpler for v1 and consistent with the rest of the shaped sections; promote to (a) only if the same chart needs to appear elsewhere. - Overview deltas — current snapshot vs. snapshot 30 days ago for
follower_count/total_favorite_count/total_message_count/ published-content counts. Returned increatorOverviewof the shaped response.
- Follower trend chart — the snapshot data is a daily series, not an event count, so it doesn't fit
- Why it matters: Emotional value. A creator who can screenshot "1,280 followers (+48 this month)" stays engaged. This use case is the reason the daily snapshot tables exist.
UC-C10 — "Why did I lose users on this character?"
- Persona: A creator whose Tavern Keeper Bob character used to be popular and isn't anymore.
- Trigger: Noticing a drop in the activity chart and wanting to diagnose.
- Question answered: Per-character retention curve + churned cohort breakdown showing which character the churned users were on.
- Sections used: Retention by entity, churned cohort card.
- How we'll answer it: Shaped (
/api/analytics/creator/audience). For each of the creator's entities, take the set of audience users who appear increator_audience_dailywith that entity incharacter_ids/mode_idsduring week N, intersect with the same set for week N+1, divide. Yieldsweek1to2 / week2to3 / week3to4retention values per entity. The churned-cohort card from UC-C5 surfaces which entity the churned users were primarily on (mode ofcharacter_idsfor the churned cohort) — that's the diagnostic glue connecting the two sections. - Why it matters: Diagnostic. Tells the creator whether to rework Bob's prompt, add a lorebook, or sunset the character.
UC-C11 — "Are users having deep, sustained sessions with my characters, or short ones?"
- Persona: A creator who has high message counts on a character but is unsure if those represent a few long roleplays or many short visits — needs a quality signal beyond raw volume.
- Trigger: Comparing two characters with similar message counts and trying to figure out which one is "stickier."
- Question answered: Summary frequency per character (proxy for conversation depth — a character whose conversations regularly get long enough to trigger summarization is sustaining real engagement).
- Sections used: "Avg conversation depth" column in the entity usage breakdown + a per-character summary-rate trend in the entity drill-down.
- How we'll answer it:
- Aggregate per-character summary count — shaped (
/api/analytics/creator).web_summary_stats ss JOIN web_conversations c ON c.id = ss.conversation_id JOIN characters ch ON ch.id = c.character_id WHERE ch.created_by_user_id = @caller GROUP BY ch.id. Joined with the message count for the same character to computesummaries_per_100_messages— a normalized depth indicator that doesn't reward sheer volume. - Summary trend over time (creator scope) — generic stack, but requires the same
summariesmetric extension as UC-U7: addStatsScope.CreatortoAllowedScopesinDefaultStatsMetricsand add ap_scope = 2branch tofn_stats_summariesthat joinsweb_summary_stats→web_conversations.character_id→characters.created_by_user_id. Once added,GET /api/creator/stats/summariesworks automatically. Anonymizer min-cohort suppression applies to creator scope.
- Aggregate per-character summary count — shaped (
- Why it matters: Volume tells you if users showed up; summary rate tells you whether they stayed. A creator with 5,000 messages but zero summaries has a popular thumbnail and a shallow product. A creator with 2,000 messages and 80 summaries has a smaller, deeply engaged audience. These two creators need completely different next steps.
UC-C12 — "Which of my characters / packages has the longest conversations?"
- Persona: A creator wanting a direct depth signal — how many turns does a typical roleplay last with each entity, and what's the max?
- Trigger: Evaluating a package's design ("did bundling Elara + RPG Mode + Forgotten Realms actually produce longer sessions than Elara alone?"), comparing two characters with similar headline numbers, or showcasing a long-form character to a sponsor.
- Question answered: Per-character and per-package: average messages per conversation, median, longest single conversation, and the trend in those values over time.
- Sections used: New
Avg msgs/convoandLongest convocolumns on the entity usage breakdown; per-entity drill-down chart of conversation-length distribution. - How we'll answer it: Shaped (
/api/analytics/creator).- Per character/mode —
WITH per_convo AS (SELECT conversation_id, character_id, COUNT(*) AS msgs FROM web_message_stats WHERE created_at >= @start GROUP BY conversation_id, character_id) SELECT character_id, AVG(msgs), percentile_cont(0.5) WITHIN GROUP (ORDER BY msgs), MAX(msgs) FROM per_convo JOIN characters c ON c.id = character_id WHERE c.created_by_user_id = @caller GROUP BY character_id. Same shape formode_id. - Per package — packages reference their primary character and mode by direct column (
packages.character_id,packages.mode_id, both nullable for "BYO" patterns) plus N lorebooks viapackage_lorebook_bindings. So the aggregation joinsweb_message_stats mstopackages p ON p.character_id = ms.character_id(and/orp.mode_id = ms.mode_idfor mode-based packages), filtersWHERE p.created_by_user_id = @caller, and computes the sameAVG/percentile_cont/MAXover per-conversation message counts — no membership-table indirection needed. Conversations that involve both a packaged character and a packaged mode count once toward the package row (DISTINCT conversation_id). - Anonymization — depth metrics over fewer than 5 conversations on a given entity are masked, since a single user's habits could otherwise dominate the average.
- Per character/mode —
- Relation to UC-C11: This is the direct depth measure; UC-C11's summary rate is the threshold-triggered depth measure. Both can disagree usefully: a character with high avg-messages-per-conversation but low summary rate has steady but bounded sessions; a character with moderate avg but high summary rate has bimodal sessions (some users go very deep, others bounce).
- Why it matters: Avg messages per conversation is the cleanest single number that reflects "did users actually settle in with this character?" It's also the most natural fit for a package-level summary — the creator can finally see whether a package premise produces longer sessions than the parts in isolation, which is the core question packages were built to answer.
UC-C13 — "Which entity reaches the most unique users — am I going broad or deep?"
- Persona: A creator with a few popular characters trying to understand whether engagement is spread across a broad audience or concentrated in a small superfan group — informs whether to optimize for discovery (breadth) or retention (depth).
- Trigger: Pitching the platform to peers, planning a marketing push, deciding whether to make a character free vs. premium, or just curiosity after a viral moment.
- Question answered: Per-character / per-mode / per-lorebook / per-package: distinct users in the period, alongside the existing message count and avg-msgs-per-conversation columns.
- Sections used: Existing
Userscolumn on the entity usage breakdown (already in the design's example table — formalizing it here as a first-class metric). - How we'll answer it: Shaped (
/api/analytics/creator).- Per character/mode —
SELECT character_id, COUNT(DISTINCT user_id) FROM web_message_stats WHERE created_at >= @start GROUP BY character_idjoined to the creator's owned characters. Direct. - Per lorebook — same pattern as UC-C2: distinct users on conversations whose entity graph included the lorebook.
- Per package —
COUNT(DISTINCT ms.user_id)overweb_message_stats msjoined topackages ponp.character_id = ms.character_id OR p.mode_id = ms.mode_id, filtered to the creator's packages. TheDISTINCTdoes the dedupe — a user who chats with both the packaged character and the packaged mode counts once. Lorebook membership (package_lorebook_bindings) is not added to the package's user set: a user who only triggered the lorebook (but didn't use the package's character or mode) wasn't really "using" the package as a unit. - Anonymization — entities with
unique_users < 5over the requested period are suppressed from the breakdown (or shown with the count masked as<5), consistent with the platform-wide min-cohort policy.
- Per character/mode —
- Relation to UC-C5: UC-C5 segments the creator's whole audience into cohorts. UC-C13 is the per-entity breadth dimension — useful even before the audience-cohort backend lands, since it only needs
web_message_stats. - Why it matters: Message count alone hides the breadth/depth ratio. A character with 5,000 messages from 50 users is a niche superfan magnet; a character with 5,000 messages from 1,200 users is a discovery channel. They demand different next moves (deepen the lore vs. add greetings to capture more conversion). Without this column, the leaderboard is misleading.
UC-C14 — "Which greeting hooks people, which one bounces them?"
- Persona: A creator with multiple greetings on a character iterating to find the one that converts visitors into actual roleplays.
- Trigger: Just added a new greeting and wants to A/B test it. Or: noticed a character is getting clicks but not conversations.
- Question answered: Per-greeting: how many users picked it, what % sent at least one message, what % sent two or more, average resulting conversation length.
- Sections used: New "Greeting performance" panel inside each character's drill-down view, with one row per greeting.
- How we'll answer it: Shaped (
/api/analytics/creator).web_conversations.greeting_idis already in the schema, so the join is direct:SELECT greeting_id, COUNT(*) AS picks, COUNT(*) FILTER (WHERE msg_count >= 1) AS first_msg, COUNT(*) FILTER (WHERE msg_count >= 2) AS second_msg, AVG(msg_count) FROM (web_conversations c LEFT JOIN LATERAL (SELECT COUNT(*) AS msg_count FROM web_messages m WHERE m.conversation_id = c.id AND m.role = 0) ON TRUE) WHERE c.character_id = @character_id GROUP BY greeting_id. Greeting body fetched fromcharacter_greetingsfor display. Min-cohort: greetings with<5picks in the period are masked. - Deleted greetings: rows with
greeting_idpointing at a since-deletedcharacter_greetingsrow are rendered asDeleted greeting #{id}with stats intact. Historical attribution outweighs the visual cost of an inactive row, and creators sometimes want to verify a deletion was the right call after the fact. - Why it matters: The single most A/B-testable creator surface. Greetings are cheap to write, the cost-per-iteration is low, and the signal is fast — you'd see results within days of changing a greeting, not weeks. It's the one creator action loop where data → change → see new data is genuinely tight. Without this view, greeting selection is gut-feel.
UC-C15 — "Where does my character run out of steam?"
- Persona: A creator whose character's avg-messages-per-conversation is mediocre and wants to diagnose: do users leave at exactly message 8 (a fixable cliff) or do they leave uniformly across 4–12 (a different problem)?
- Trigger: UC-C12 surfaced a low avg conversation length; this drills in to find the shape.
- Question answered: Survival curve — of users who reached message N, what % reached N+1? Where's the cliff?
- Sections used: Per-character drill-down chart — line chart with x-axis = message number, y-axis = % of conversations still going.
- How we'll answer it: Shaped (
/api/analytics/creator).WITH per_convo AS (SELECT conversation_id, COUNT(*) AS msgs FROM web_message_stats WHERE created_at >= @start GROUP BY conversation_id) SELECT n, COUNT(*) FILTER (WHERE msgs >= n) FROM per_convo CROSS JOIN generate_series(1, 50) AS n JOIN web_conversations wc ON ... WHERE wc.character_id = @character_id GROUP BY n. Cap the x-axis at the 95th percentile or 50, whichever's lower. Min-cohort guard: if<5conversations on the character, don't render the curve at all. - Why it matters: Pairs with UC-C12 (avg length) — UC-C12 gives the headline number, UC-C15 gives the diagnostic shape. A cliff at message 8 is a creator's biggest signal that their character has a specific narrative dead-end (probably the greeting hook didn't resolve into a sustained scenario). Almost no other metric tells you what to fix.
UC-C16 — "Are users coming back to this character, or is it one-and-done?"
- Persona: A creator wanting to distinguish "Elara is sticky — users return repeatedly" from "Elara is a novelty — users try once and never come back." Two completely different products with similar-looking message counts.
- Trigger: Looking at a character that has high distinct-user count (UC-C13) but low avg conversation length (UC-C12) — is this breadth or shallowness?
- Question answered: Per-character: what % of audience users started ≥2 separate conversations with this character? Median days between repeat visits?
- Sections used: New "Repeat rate" and "Revisit interval" columns on the entity usage breakdown.
- How we'll answer it: Shaped (
/api/analytics/creator).SELECT character_id, COUNT(DISTINCT user_id) AS unique_users, COUNT(DISTINCT user_id) FILTER (WHERE c >= 2) AS repeat_users FROM (SELECT user_id, character_id, COUNT(*) AS c FROM web_conversations WHERE created_at >= @start GROUP BY 1, 2) GROUP BY character_id. Median revisit interval =percentile_cont(0.5)overLEAD(created_at) - created_atper(user_id, character_id). Min-cohort guard on unique users. - Relation to UC-C5: UC-C5 is creator-wide cohort segmentation. UC-C16 is the per-entity stickiness lens — useful even before
creator_audience_dailylands, since it only needsweb_conversations. - Why it matters: Distinguishes characters built for novelty (one-shot premise, no return value) from characters built for narrative depth (users come back to continue the same story or start a new one with the same character). Both are valid; knowing which kind a character is changes how to invest in it.
UC-C17 — "How often do users hit regenerate on my character?"
- Persona: A creator iterating on a character's prompt and wanting an automatic quality signal that doesn't require asking users for feedback.
- Trigger: Just deployed a new system prompt and wants to know if it improved or degraded first-response quality.
- Question answered: Per-character regeneration rate — % of assistant messages where the user hit regenerate at least once.
- Sections used: New "Regen rate" column on the entity usage breakdown.
- How we'll answer it: Generic stack — but a new metric.
web_message_stats.event_typealready records'regenerate'. Add afn_stats_regenerationsSQL function and aregenerationsmetric toDefaultStatsMetricswith Creator + Global scopes; or expose it as a derived ratio (regenerations / messages) directly on the shaped/api/analytics/creatorentity rows. The latter is simpler for v1 since the regen rate is most useful as a column next to message count rather than a standalone time series. - Why it matters: The cheapest quality signal we already collect. A character with a 40% regen rate has a real prompt problem; one with 5% is hitting first time. Immediately turns into prompt-tuning work. Doesn't require any new instrumentation — the data has been sitting in
event_typethe whole time.
UC-C18 — "Where is my audience coming from? Browse, package, direct link, share?"
Persona: A creator deciding whether to invest in being discoverable (more tags, better thumbnails), in package-bundling (collab with another creator), or in social distribution (shareable links). Right now they're guessing.
Trigger: Planning a marketing push or strategy review for the quarter.
Question answered: Per-character: what % of conversations originated from each source —
browse,package(which package?),direct_link,shared_conversation,featured,embedded(Discord)?Sections used: Stacked bar chart per character + a top-line donut for the creator overall.
How we'll answer it: Requires modest new instrumentation, but less work than originally feared — the existing codebase already structurally distinguishes three creation paths:
fn_create_conversation(11_conversation_migration_functions.sql) — generic "start chat"fn_create_conversation_from_package(47_package_functions.sql)fn_branch_conversation(38_branch_conversation.sql)
So
packageandbranch/forkorigins are already identifiable at the SQL function level. Only the generic path needs frontend-supplied tagging. Scope:- Schema — add
web_conversations.source VARCHAR(32) NOT NULL DEFAULT 'unknown',origin_ref_id INTEGER NULL(package ID, branched-from conversation ID, etc.),referrer_host VARCHAR(255) NULL(host only — never full URL — for external referrers). - SQL — extend the three creation functions with optional
p_source/p_origin_ref_idparameters. Package and branch functions default to'package'/'branch'if caller doesn't override. - C# repo + endpoint —
CreateConversationAsync(... ConversationOrigin source, int? originRefId, string? referrerHost ...);ConversationsEndpointsaccepts asourcefield on the create-conversation request body. - Frontend audit — every "start chat" call site passes a source string. Known call sites:
browse/search/character_detail/package_detail/featured/hub/profile/share/unknown. Vocabulary is a string enum, not int — adding new entry points shouldn't require a migration. - Optional cf-worker layer — capture the
Refererheader host on conversation-create requests for external traffic (reddit.com/twitter.com/ etc.). Strip path and query.
Caveats: "URL paste" can't be cleanly distinguished from "browse → click" at the API layer — the frontend must assert a source. Reframe the question as "which page in the app did the user click 'start chat' from?"; pasted URLs land on
character_detailand bucket there, which is more useful than adirect_linkbucket would be. Backfill is impossible — rows created before this lands getsource = 'unknown'. Clean-data window starts the day instrumentation ships.Effort: roughly 3–5 working days (schema + SQL + C# + frontend audit + tests; cf-worker is optional add-on).
Phasing implication: Promote prerequisite tracking to Phase 1. The data is forward-only — every day deferred is a day of lost discovery-attribution data, and no amount of later effort recovers it. Even if the dashboard panel ships in Phase 2, the column + tagging discipline lands now. The previous "Phase 4 unknown" framing turned out to be wrong once the codebase was actually checked.
Why it matters: Strategy-defining. "70% of Elara's traffic comes from her being in a package with Crystal Dawn" changes what a creator builds next. Without this, distribution decisions are blind. This is the single most upgrade-driving UC in the entire Pro tier — the question no other RP platform answers.
UC-C19 — "Which genres / themes do my characters perform best in?"
- Persona: A creator with content across multiple genres (fantasy, sci-fi, slice-of-life) trying to figure out where they have a comparative advantage and whether to niche down.
- Trigger: Strategy review, considering whether to focus or diversify.
- Question answered: Aggregate engagement (messages, unique users, avg conversation length) grouped by genre/theme tag bit, scoped to the creator's owned characters.
- Sections used: New "Performance by genre" panel — bar chart with one bar per top-level category (Genre, Setting, Tropes, etc.), with the user able to drill into sub-tags.
- How we'll answer it: Shaped (
/api/analytics/creator). The tag system is a closed, curated bitfield set (~456 indices across 7BIGINTcolumns, defined asconst intinCore/Tags/CharacterTags.csetc.) — not free-form strings, so the schema is stable. Aggregateweb_message_statsjoined tocharacters.tags_5(or whichever column holds the relevant category) with a category mask:WHERE c.created_by_user_id = @caller AND (c.tags_5 & @genre_mask) <> 0 GROUP BY tag_bit. Display name resolved from the[Description]attribute.- The presentation problem: characters typically carry 10–30 tags simultaneously. Showing engagement per tag double-counts massively. Mitigation: filter to a curated single category at a time (Genre, Setting, Tropes…) so each tag is mostly mutually exclusive within the view, and let the creator switch categories. Don't try to show all 448 tags on one chart.
- Why it matters: Surfaces comparative advantage in a way that informs the next "what should I build" decision. "My fantasy characters get 3× the engagement of my sci-fi ones" is the kind of finding that genuinely changes strategy. The data is sitting in the bitfield columns already — just needs an aggregation pattern.
Non-goals (use cases we are deliberately NOT serving)
- "Who is the user behind Fan #1?" — Creator analytics never reveals user identity. UC-C8 is the boundary; we will not extend it.
- "How does my content compare to other creators on the platform?" — Comparative ranking against other creators is a future extension (
vw_hub_statisticsbaselining), not Phase 1–3. Risk of creating a status hierarchy that demotivates new creators outweighs early-cycle value. - "What were users saying when they used my character?" — Conversation content is never surfaced to creators. Even aggregated topic clustering is out of scope until a separate privacy review.
- "Real-time / live engagement counters." — Daily snapshot granularity is enough for every use case above. Real-time analytics would force expensive infrastructure with no proportionate creator-value gain.
- Discord — completely out of scope. Every UC, every endpoint, every shaped response in this document is web-only. Discord conversations live in
discord_messages(notweb_conversations/web_message_stats), aren't joined into any analytics query, and don't get asourcevalue under UC-C18. Discord-side analytics is a future product, not a future scope expansion of this product. Creators who run primarily on Discord will see this gap and that's accepted — the deferral is deliberate, not an oversight. Reviewers should reject any PR that quietly drags Discord tables into an analytics query "just for completeness." - Echo-cost-attribution analytics. — UCs that mention Echo budget connections (UC-U4, UC-U7, UC-U14) are forward-compatible — they'll connect to per-feature spend data once the Echo allocate/commit/release pipeline lands per the Phase 1 Echo work in CLAUDE.md. Until then the analytics page surfaces consumption shape (model usage, regen rate, summarization frequency) without claiming Echo-cost numbers it doesn't have. Don't ship Echo-cost columns before the ledger has the data.
What We Already Store
Materialized Views (snapshot stats, trigger-refreshed)
| View | Key Columns |
|---|---|
mv_character_stats |
conversation_count, message_count, favorite_count, greeting_count |
mv_user_stats |
public_character_count, public_mode_count, public_lorebook_count, follower_count, following_count, conversation_count |
mv_mode_stats |
usage_count, favorite_count, sub_prompt_count, estimated_token_count |
mv_lorebook_stats |
entry_count, favorite_count, always_on_entry_count |
Time-Series Data (web_message_stats)
| Column | Use |
|---|---|
user_id + created_at |
Messages over time (indexed: idx_web_message_stats_user_created) |
character_id + created_at |
Per-character activity over time |
provider, model |
Model usage breakdown |
prompt_tokens, completion_tokens, total_tokens |
Token consumption |
pipeline_duration_ms |
Response time trends |
event_type |
Fresh vs. regeneration ratio |
error_type |
Error rate tracking |
Hub Statistics (vw_hub_statistics)
Platform-wide counts (public characters, modes, lorebooks, users, creators) — useful for contextualizing a creator's share of platform activity.
Dashboard Design
Route
/settings/analytics (tabbed: My Stats | Creator Analytics)
/creator/:id/analytics (public analytics — future, opt-in)
Sections
1. Overview Cards (top row)
Quick-glance summary cards showing current totals from materialized views.
┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ Characters │ │ Modes │ │ Lorebooks │ │ Followers │
│ 12 │ │ 4 │ │ 3 │ │ 1,280 │
│ ↑2 this mo │ │ ↑1 this mo │ │ — no change │ │ ↑48 this mo │
└──────────────┘ └──────────────┘ └──────────────┘ └──────────────┘
Data source: mv_user_stats (current values), delta computed from entity_changelog or snapshot comparison.
2. Activity Over Time (line chart)
Messages per day/week/month across all the creator's characters.
Messages (30d)
400 ┤
300 ┤ ╭──╮
200 ┤ ╭───╯ ╰──╮ ╭───╮
100 ┤──╯ ╰────╯ ╰──
0 ┤
└──────────────────────────→
Feb 15 Mar 1 Mar 15
Data source: web_message_stats aggregated by created_at where character_id IN (creator's characters).
Query pattern:
SELECT
date_trunc('day', created_at) AS day,
COUNT(*) AS message_count,
COUNT(*) FILTER (WHERE event_type = 'regenerate') AS regenerate_count
FROM web_message_stats
WHERE character_id = ANY(@CharacterIds)
AND created_at >= @StartDate
GROUP BY 1
ORDER BY 1
3. Character Leaderboard (bar chart / table)
Ranked list of the creator's characters by engagement.
Character Performance (30d)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Elara the Narrator ████████████████ 2,340 msgs ♥ 89
Crystal Dawn Merchant ████████ 1,120 msgs ♥ 42
Tavern Keeper Bob ████ 580 msgs ♥ 23
Data source: mv_character_stats for totals, web_message_stats for period-filtered counts.
4. Model Usage Breakdown (donut/pie chart)
Which LLM models users choose when chatting with this creator's characters.
Model Usage (30d)
┌──────────────────────┐
│ claude-sonnet 48% │
│ gpt-4o 31% │
│ gemini-pro 15% │
│ other 6% │
└──────────────────────┘
Data source: web_message_stats grouped by model.
5. Favorites & Followers Trend (sparkline or line chart)
Growth of favorites and followers over time.
Data source: entity_changelog entries for follow/favorite events, or a new daily snapshot table (see New Data Needed).
6. Entity Usage Breakdown (table with sparklines)
Not just characters — which modes and lorebooks are being used in conversations with the creator's content.
Entity Usage (30d)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Entity Type Messages Users Trend
Fantasy RPG Mode Mode 4,280 189 ↗ +12%
Elara the Narrator Character 2,340 142 → flat
Standard Chat Mode Mode 1,820 98 ↘ -8%
Forgotten Realms Lore Lorebook 890 67 ↗ +22%
Crystal Dawn Merchant Character 580 45 → flat
Why this matters to creators: "Are users actually using my RPG mode or defaulting to the standard one? Is my lorebook getting picked up?" This informs what to invest time in next.
Data source:
- Characters:
web_message_stats.character_id(already tracked) - Modes:
web_message_stats.mode_id(already tracked) - Lorebooks:
web_message_stats ms JOIN conversation_lorebook_bindings clb ON clb.conversation_id = ms.conversation_id. The lorebook isn't directly onweb_message_stats, so it's derived from the conversation's bound lorebooks at the time the message was sent.
7. Audience Insights (anonymized cohort analysis)
The centerpiece of Creator Analytics. Creators see their audience broken into behavioral cohorts with cross-entity engagement patterns. All data is fully anonymized — see Privacy & Anonymization.
Every metric in this section answers a specific question the creator actually has:
Cohort Overview
Users are segmented based on their engagement depth with the creator's content:
Your Audience (30d)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
┌───────────┐ ┌───────────┐ ┌───────────┐ ┌───────────┐
│ Power │ │ Regular │ │ Casual │ │ Churned │
│ Users │ │ Users │ │ Users │ │ Users │
│ 23 │ │ 87 │ │ 312 │ │ 45 │
│ 6,420 msgs│ │ 4,180 msgs│ │ 2,890 msgs│ │ — inactive│
│ 3.8 chars │ │ 2.1 chars │ │ 1.2 chars │ │ 1.4 chars │
│ 92% ret. │ │ 68% ret. │ │ 31% ret. │ │ 0% ret. │
└───────────┘ └───────────┘ └───────────┘ └───────────┘
"23 power users drive 48% of your total engagement"
Cohort definitions:
| Cohort | Criteria | What it tells the creator |
|---|---|---|
| Power users | >100 messages in period, active in last 7 days | "These are my superfans — they drive the most engagement and are worth building for" |
| Regular | 20–100 messages, active in last 14 days | "My core audience — steady, returning users" |
| Casual | 5–19 messages, active in last 30 days | "Drive-by visitors — could I convert them to regulars?" |
| Churned | Had activity before the period but none during it | "Who am I losing and which characters were they using?" |
Per-cohort metrics:
- User count — how many users in this segment
- Total messages — volume of engagement from this cohort
- Avg messages per user — engagement depth
- Avg entities used — cross-entity overlap ("Power users engage with 3.8 of your characters on average")
- Retention rate — what % of this cohort from last period returned this period
- Top model — which LLM model this cohort prefers
Creator question answered: "Am I building a loyal audience or just getting drive-by traffic?"
Cross-Entity Correlation Matrix
Shows how users flow between the creator's entities. If someone chats with Character A, how likely are they to also use Character B or Mode C?
Entity Overlap
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Elara Crystal Bob RPG Mode
Elara — 78% 34% 82%
Crystal Dawn 78% — 52% 61%
Tavern Bob 34% 52% — 45%
Fantasy RPG Mode 82% 61% 45% —
How to read: "78% of users who chat with Elara also chat with Crystal Dawn." The matrix is symmetric.
Creator questions answered:
- "Should I bundle these characters into a package?" (High overlap = natural bundle)
- "Which lorebook should I link to which character?" (If users of Character A also use Lorebook X, link them)
- "Which character could I cross-promote?" (Low overlap = untapped audience)
Data source: creator_audience_daily aggregated — for each pair of entities, count users who appear in both entity's audiences and divide by the smaller audience.
Anonymized Fan Table ("Biggest Fans")
Top N users by engagement, shown with opaque identifiers. No usernames, no avatars, no profile links.
Your Biggest Fans (30d)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Fan Messages Entities Used Active Days
#1 892 Elara, Crystal Dawn, RPG Mode, Lore 28 of 30
#2 634 Elara, Tavern Bob, Standard Mode 22 of 30
#3 451 Crystal Dawn, RPG Mode 18 of 30
#4 387 Elara, Crystal Dawn, Tavern Bob 15 of 30
#5 244 Tavern Bob 12 of 30
What the creator sees per fan:
- Fan #N — opaque sequential identifier, stable within a session but not across sessions (prevents tracking individuals over time)
- Messages — total message count in the period
- Entities used — which of the creator's characters, modes, lorebooks this fan engaged with (by entity name, not by user identity)
- Active days — how many days in the period the fan was active
- First seen / Last active — approximate dates (rounded to the week to reduce re-identification risk)
Creator question answered: "Users who like THIS character also liked 3 others — what do they have in common? What should I build next?"
What the creator does NOT see: Username, avatar, profile link, email, conversation content, message content, IP address, or any other PII. The fan identifiers are session-scoped hash-based opaque IDs — even the creator can't correlate "Fan #1" across different analytics sessions.
Retention by Entity
Which entities keep users coming back vs. which lose them?
Retention by Entity (30d)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Entity Week 1→2 Week 2→3 Week 3→4
Elara the Narrator 82% 78% 75%
Crystal Dawn Merchant 71% 65% 58%
Fantasy RPG Mode 88% 85% 82%
Tavern Keeper Bob 45% 28% 15%
Creator question answered: "Elara has 82% week-over-week retention, Bob has 45% — what's different? Should I rework Bob's system prompt?"
Data source: creator_audience_daily — for each entity, count users present in consecutive weeks and compute the ratio.
Peak Activity Times (Creator View)
When do users engage with the creator's content?
Audience Activity by Hour (30d)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
░░▒▒▒▒░░░░░░▒▓████▓▒░░░░
6am 9am 12pm 3pm 6pm 9pm 12am
Peak: 8 PM – 11 PM (62% of daily activity)
Creator question answered: "When should I publish new content for maximum visibility? When are my users online?"
Data source: web_message_stats.created_at bucketed by hour, filtered to the creator's character IDs.
Model Preferences by Cohort
Model Usage by Cohort (30d)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Claude GPT-4o Gemini Other
Power users 62% 22% 12% 4%
Regular 48% 31% 15% 6%
Casual 35% 38% 20% 7%
Creator question answered: "Should I optimize my system prompts for Claude or GPT? My power users prefer Claude — maybe my long system prompts work better there."
Privacy & Anonymization
Creator analytics show engagement patterns, not individual user behavior. This section defines the anonymization guarantees enforced at the server level — the client never receives identifiable user data in creator analytics responses.
Hard Rules
| Rule | Enforcement |
|---|---|
| No user IDs | The creator analytics API endpoints never return user_id, username, avatar_url, email, or any user profile fields. The server strips these before serialization. |
| No conversation content | Analytics show message counts, not message text. The creator never sees what users said. |
| Opaque fan identifiers | The "Biggest Fans" table uses session-scoped hash-based IDs (HMAC(user_id, session_salt)). A different salt is generated per API call, so "Fan #1" in one session is not the same as "Fan #1" in another. |
| Minimum cohort size | Cohort metrics are only shown when the cohort has ≥5 users. A cohort of 1–4 users is merged into the next larger cohort to prevent singling out individuals. |
| Date rounding | "First seen" and "Last active" dates in the fan table are rounded to the nearest week to reduce re-identification risk. |
| No cross-creator leakage | A creator only sees engagement with their own entities. They cannot see which other creators their audience engages with. |
Server-Side Enforcement
// The creator analytics response types NEVER include user identification fields.
// This is enforced by the DTO design — there is no UserName or UserId property to accidentally populate.
public record CohortSummary(
string CohortName,
int UserCount, // aggregate only
int TotalMessages,
decimal AvgMessagesPerUser,
decimal AvgEntitiesUsed,
decimal RetentionRate,
string TopModel
);
public record AnonymizedFan(
string OpaqueId, // HMAC(user_id, session_salt) — not stable across sessions
int MessageCount,
string[] EntitiesUsed, // entity names only — no entity IDs
int ActiveDays,
string FirstSeenWeek, // "2026-W09" — week granularity, not date
string LastActiveWeek
);
Why This Level of Anonymization
- Legal: Aggregate analytics with no PII don't trigger GDPR individual data access rights from the creator's perspective. The platform still holds the underlying data (and users can request their own data via their own analytics), but the creator never becomes a data controller for their audience's PII.
- Trust: Users should feel comfortable chatting with characters knowing the creator can see "48% of my audience uses Claude" but NOT "user JohnDoe42 sent 892 messages last month."
- Utility: Creators don't need to know WHO their fans are — they need to know what content resonates, what to build next, and whether their audience is growing. Anonymized cohorts answer all of these.
Privacy Acceptance Criteria
UC-C8 (anonymized fans) and UC-C5 (cohorts) are the privacy-critical surfaces of this entire feature. Before the Phase 3 audience tab ships, the following must all have passing tests:
- No raw
user_idin any creator-tier response payload. Test: serialize every shaped creator endpoint response over a fixture audience and assert the JSON contains nouser_idfield at any depth. - Opaque fan IDs rotate per request. Test: call
/api/analytics/creator/audiencetwice in succession with the same query and assert theopaqueIdfor the same underlying user differs between responses (per-request session salt is doing its job). - Min cohort size is enforced everywhere it should be. Test fixtures with cohorts of size 1, 2, 3, 4, 5, 6 — verify the
<5cohorts are merged into the next-larger bucket and never returned as their own row. Apply to: cohorts, fan table, retention by entity, model preferences by cohort, correlation matrix cells. - Date rounding to ISO week. Test: a fan's
firstSeenWeekandlastActiveWeekalways match the ISO-week format (YYYY-Www); never expose a calendar date. - No conversation content. Test: assert no
content,text,body,messageor similar field appears anywhere in any creator-tier response. - Anonymizer policy runs even when caller is the creator themselves. Test: a creator who has chatted with their own characters (rare but possible — admin testing, etc.) is also subject to the min-cohort guard. The anonymizer doesn't get a "you're the creator, see everything" bypass.
- Cohort assignment doesn't leak through metric counts. Test: a cohort with a single user (size 1, suppressed in the cohort row) doesn't have its message volume bleed into the totals shown in adjacent metrics. Aggregate totals across all cohorts should equal the un-cohorted total exactly — no rounding artifacts that hint at the suppressed user.
- Self-traffic is excluded from
creator_audience_daily. Already enforced infn_snapshot_creator_audience_daily(WHERE c.created_by_user_id != ms.user_id). Verify with a fixture where the creator has chatted with their own character — that activity must not appear in their own audience analytics.
These tests live in EchoOfDreams.Database.Tests (for the SQL functions)
and in the relevant ServerAPI test project (for the endpoint responses).
They are blocking acceptance criteria for the Phase 3 release, not
nice-to-haves.
Operational Policies
Cross-cutting concerns that apply uniformly across the analytics endpoints. Decided up-front so PR reviews don't relitigate.
Caching policy (per-endpoint)
Different endpoints have different freshness needs and query costs. Don't apply a single TTL to the whole feature.
| Endpoint | Cache-Control |
Rationale |
|---|---|---|
GET /api/stats/{metric} (User scope) |
private, max-age=60, must-revalidate |
Per-user data; user expects same numbers within the minute |
GET /api/creator/stats/{metric} (Creator scope) |
private, max-age=300, must-revalidate |
Creator-side aggregates change slowly; 5 min is fine |
GET /api/analytics/my-stats |
private, max-age=60, must-revalidate |
Same as user-scope generic |
GET /api/analytics/creator |
private, max-age=300, must-revalidate |
Same as creator-scope generic |
GET /api/analytics/creator/audience |
private, max-age=900, must-revalidate |
Heaviest endpoint (cohort assignment + correlation matrix); 15 min cache prevents repeated re-computation when a creator stares at the page |
GET /api/analytics/creator/entity/{type}/{uuid} |
private, max-age=300, must-revalidate |
Per-entity drill-down; matches the parent creator endpoint |
All responses include Vary: Authorization because cache state must
not leak across users. All private because no analytics response is
shareable across viewers.
Rate limiting policy
Lower than the profile-page limits because the queries are heavier and each call composes multiple aggregations. Per authenticated user, not per IP (analytics is auth-required).
| Endpoint group | Limit |
|---|---|
/api/stats/*, /api/creator/stats/* |
30 calls / minute, 600 / hour |
/api/analytics/my-stats, /api/analytics/creator |
20 calls / minute, 300 / hour |
/api/analytics/creator/audience, /api/analytics/creator/entity/* |
10 calls / minute, 120 / hour |
Exceeding the limit returns 429 Too Many Requests with the standard
retry-after header. The frontend should debounce filter changes (250 ms
default) so a user dragging a date slider doesn't burn through their
budget.
Pro gate enforcement
The Pro gate is server-enforced as the last line of defense, not trusted to the frontend. The frontend's job is to never send a Free user to a Pro endpoint in normal flow; the server's job is to refuse the request anyway.
- Every
/api/analytics/creator*and/api/creator/stats/*handler runsfn_get_user_subscription_limit(@caller, 'analytics.dashboard'). - If the result is anything other than
'full', the response is403with an empty body. No{ "upgrade": "pro", "message": ... }, no enumeration of what's missing, no hint at what tier names exist. Telling the client what's "valid" is information the client doesn't need and an attacker probably wants. The frontend already knows the user's tier from the subscription store; the 403 is a fence, not a signpost. - The
tierfield has been removed from/api/analytics/my-statsand/api/analytics/creatorresponse bodies for the same reason — responses don't enumerate valid parameter values.
Data retention
| Table | Retention | Rationale |
|---|---|---|
web_message_stats |
Existing platform retention (TBD, set elsewhere) | Source of truth; out of scope for this feature |
web_summary_stats |
Existing platform retention | Same |
creator_daily_stats |
Indefinite | One row per creator per day. At a realistic platform size of 10k creators × 5 years = 18M rows — small. Indefinite retention enables long-horizon trend charts (UC-C9). Revisit only if storage costs become material, which won't happen in the foreseeable future given the platform's current ~50 days of accumulated data. |
creator_audience_daily |
90 days | Already specified. Larger table (creator × audience-user × day), retention bounds growth. Cohort window of 90 days is operationally meaningful. |
Empty-state policy
A unified, simple copy convention. Don't bikeshed individual empty states per UC; pick one of two and apply consistently.
| Condition | Copy | Component |
|---|---|---|
| User has zero conversations / messages | "Chat to see your stats." | EmptyState + Button → /browse |
| Creator has zero published content | "Publish content to see how it performs." | EmptyState + Button → /creator |
| Selected period has no data (but historical data exists) | "Nothing to show for this period." | EmptyState (no CTA) |
| Anonymizer wiped all cohorts (every cohort < 5) | "Not enough audience activity yet." | EmptyState (no CTA) |
| Snapshot job hasn't run yet (Day-1) | "Stats will appear here tomorrow." | EmptyState (no CTA) |
Per-UC ad-hoc copy is forbidden — drift across 30+ UCs becomes unmanageable. If a future UC genuinely needs different wording, extend this table, don't bypass it.
Deferred — design decisions intentionally not made
- Mobile responsiveness — the design is desktop-first. Mobile layout for
Heatmap(7×24 grid),CorrelationMatrix, and the entity usage table will be figured out as we go. If a UC's mobile rendering is wrong on first preview, log it; don't block on it.
Two Tiers: My Stats (Free) vs. Creator Stats (Pro)
The analytics page serves two audiences with the same UI framework. Free users get a genuinely useful personal stats dashboard — their own chat activity visualized in real charts. This isn't a crippled preview; it's a complete product that happens to make the creator-tier upsell feel natural because users already love the charts.
Free Tier: "My Stats"
Every user gets a full personal analytics dashboard showing their own chat activity. Real charts, real data, no blurring.
┌─ My Stats ───────────────────────────────────────────────────────┐
│ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Messages │ │ Conversations│ │ Characters │ │
│ │ 1,842 │ │ 23 │ │ Chatted │ │
│ │ ↑124 this wk │ │ ↑3 this wk │ │ 14 │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
│ │
│ ┌─ Daily Activity (30d) ──────────────────────────────────┐ │
│ │ 40 ┤ ╭╮ │ │
│ │ 30 ┤ ╭───╯╰──╮ ╭───╮ │ │
│ │ 20 ┤──╯ ╰────╯ ╰── │ │
│ │ 10 ┤ │ │
│ └──────────────────────────────────────────────────────────┘ │
│ │
│ ┌─ Most Chatted Characters ───────────────────────────────┐ │
│ │ Elara the Narrator ████████████████ 312 msgs │ │
│ │ Crystal Dawn Merchant ████████ 180 msgs │ │
│ │ Tavern Keeper Bob ████ 92 msgs │ │
│ └──────────────────────────────────────────────────────────┘ │
│ │
│ ┌─ Favorite Creators ─────────────────────────────────────┐ │
│ │ WorldBuilder42 ████████████████ 492 msgs │ │
│ │ NightfallStories ████████ 201 msgs │ │
│ │ RuneMaster ████ 88 msgs │ │
│ └──────────────────────────────────────────────────────────┘ │
│ │
│ ┌─ Model Usage ──────────────────────────────────────────┐ │
│ │ claude-sonnet-4-6 ████████████████ 48% │ │
│ │ gpt-4o ████████ 31% │ │
│ │ gemini-2.5-flash ████ 15% │ │
│ │ other ██ 6% │ │
│ └──────────────────────────────────────────────────────────┘ │
│ │
│ ┌─ Activity Insights ────────────────────────────────────┐ │
│ │ │ │
│ │ When you chat Activity Heatmap (4 weeks) │ │
│ │ ┌──────────────┐ ┌─────────────────────────────┐ │ │
│ │ │ Peak hours: │ │ Mon ░░░░▒▒░░░░░░▓▓██░░░░░░ │ │ │
│ │ │ 10 PM – 1 AM│ │ Tue ░░░░▒░░░░░░░▒▓██▒░░░░░ │ │ │
│ │ │ │ │ Wed ░░░░░░░░░░░░░▒▓█▓░░░░░ │ │ │
│ │ │ Busiest day: │ │ Thu ░░░░▒▒░░░░░░▓███▓░░░░░ │ │ │
│ │ │ Thursday │ │ Fri ░░░░░░░░░░░░▒▓██░░░░░░ │ │ │
│ │ │ │ │ Sat ░░░░░░░░░▒▓████▓▒░░░░░ │ │ │
│ │ │ This week: │ │ Sun ░░░░░░░░▒▓████▓▒░░░░░░ │ │ │
│ │ │ 42 msgs/day │ │ 6a 9a 12p 3p 6p 9p 12a│ │ │
│ │ │ ~3.2 hrs │ └─────────────────────────────┘ │ │
│ │ └──────────────┘ │ │
│ │ │ │
│ │ ┌── Session Stats (30d) ─────────────────────────────┐ │ │
│ │ │ Avg session: 28 min │ Longest: 3h 12m │ Total: 47h│ │ │
│ │ └────────────────────────────────────────────────────┘ │ │
│ │ │ │
│ └──────────────────────────────────────────────────────────┘ │
│ │
│ ┌──────────────────────────────────────────────────────────┐ │
│ │ 📊 Want to see how YOUR content performs? │ │
│ │ Creator Analytics shows engagement, favorites, follower │ │
│ │ growth, and model usage across your published content. │ │
│ │ [ Upgrade to Pro → ] │ │
│ └──────────────────────────────────────────────────────────┘ │
│ │
└───────────────────────────────────────────────────────────────────┘
Free tier sections:
| Section | Chart Type | Data Source |
|---|---|---|
| Overview cards | Stat cards with deltas | web_message_stats aggregated by user_id |
| Daily activity | Line chart (messages per day) | web_message_stats WHERE user_id = @UserId |
| Most chatted characters | Horizontal bar chart | web_message_stats grouped by character_id, top 10 |
| Favorite creators | Horizontal bar chart | web_message_stats → characters.created_by_user_id, grouped by creator, top 10 |
| Model usage | Horizontal bar chart | web_message_stats grouped by model, top 10 |
| Activity heatmap | Day × hour grid (GitHub-style) | web_message_stats.created_at bucketed by EXTRACT(dow) × EXTRACT(hour) |
| Peak hours & busiest day | Text callouts | Derived from heatmap aggregation — highest hour range and highest day |
| Session stats | Stat cards | web_message_stats.created_at with >30 min gap = new session boundary. Avg/longest/total session time. |
All queries filter on user_id using the existing idx_web_message_stats_user_created index. No new tables needed — this is purely a read view over web_message_stats.
Model Usage Details
Which LLM models the user chats with most. Shown as a horizontal bar chart with percentages.
Data source: web_message_stats grouped by model where user_id = @UserId.
SELECT model, COUNT(*) AS count
FROM web_message_stats
WHERE user_id = @UserId AND created_at >= @StartDate
GROUP BY model
ORDER BY count DESC
LIMIT 10
Activity Insights (Time Ranges & Screen Time)
A "digital wellbeing" style section that shows when and how much the user chats. Framed as informational and fun — "Your busiest day was Thursday" not "You spent too much time."
Activity heatmap: A day-of-week × hour-of-day grid (7 rows × 24 columns) showing message density over the selected period. Each cell is shaded by message count — like GitHub's contribution graph, rotated.
SELECT
EXTRACT(dow FROM created_at)::int AS day_of_week, -- 0=Sun, 6=Sat
EXTRACT(hour FROM created_at)::int AS hour, -- 0-23
COUNT(*) AS message_count
FROM web_message_stats
WHERE user_id = @UserId AND created_at >= @StartDate
GROUP BY 1, 2
Peak hours: Derived from the heatmap — find the contiguous 3-hour window with the most messages. Displayed as "You're most active between 10 PM – 1 AM."
Busiest day: The day of the week with the highest total. "Your busiest day is Thursday."
Session estimation: Sessions are derived from message timestamps — a gap of >30 minutes between consecutive messages starts a new session. This is an approximation (the user may be reading, not sending) but good enough for self-reflection.
-- Session detection uses a window function on the user's messages
WITH ordered AS (
SELECT created_at,
LAG(created_at) OVER (ORDER BY created_at) AS prev_at
FROM web_message_stats
WHERE user_id = @UserId AND created_at >= @StartDate
),
sessions AS (
SELECT created_at,
SUM(CASE WHEN prev_at IS NULL OR created_at - prev_at > INTERVAL '30 minutes' THEN 1 ELSE 0 END)
OVER (ORDER BY created_at) AS session_id
FROM ordered
)
SELECT
session_id,
MIN(created_at) AS session_start,
MAX(created_at) AS session_end,
MAX(created_at) - MIN(created_at) AS session_duration,
COUNT(*) AS message_count
FROM sessions
GROUP BY session_id
Session stat cards:
- Average session: mean session duration
- Longest session: max session duration
- Total chat time: sum of all session durations (this period)
- Sessions this week: count of sessions in the last 7 days
Tone: The UI copy is lighthearted and self-aware. The header could be "Your Chat Habits" with a subtext like "Because someone was going to count eventually." No judgment — just data.
Why this works as an upsell funnel: Users see polished, interactive charts of their own activity. At the bottom, a non-intrusive banner says "Want to see how YOUR content performs?" — a natural next step, not a paywall. The charting components (line chart, bar chart, cards) are the exact same ones the Pro tier uses, so the user already knows what creator analytics will look like.
Pro Tier: "Creator Analytics"
Pro users see everything from the free tier plus the creator-focused sections from the Dashboard Design above:
| Section | Free | Pro |
|---|---|---|
| Overview cards (personal) | Yes (with deltas) | Yes |
| Daily activity (personal) | Yes | Yes |
| Most chatted characters | Yes | Yes |
| Favorite creators | Yes | Yes |
| Model usage (personal) | Yes | Yes |
| Activity insights (heatmap, sessions) | Yes | Yes |
| Creator overview cards | — | Followers, favorites, published content counts with deltas |
| Content activity chart | — | Messages across creator's characters over time |
| Entity usage breakdown | — | Characters + modes + lorebooks ranked by engagement |
| Character leaderboard | — | Ranked table of creator's characters by engagement |
| Model usage by audience | — | Donut chart of which models users choose for creator's content |
| Follower/favorite trends | — | Line chart from creator_daily_stats |
| Audience cohort overview | — | Power / Regular / Casual / Churned segmentation with metrics |
| Cross-entity correlation | — | Matrix showing user overlap between creator's entities |
| Biggest fans (anonymized) | — | Top N fans by engagement with opaque IDs, entities used, active days |
| Retention by entity | — | Week-over-week retention per character/mode |
| Audience peak times | — | When the creator's audience is most active |
| Model preferences by cohort | — | Which models each cohort prefers |
| CSV export | — | Download stats data |
The page is organized into two tab groups: My Activity (free) and Creator Analytics (Pro). Free users see the Creator Analytics tab but it shows the upsell banner instead of charts.
Subscription Limit Key
-- Add to subscription_tier_limits seed data
INSERT INTO subscription_tier_limits (tier_id, limit_key, limit_value, category, display_name, description)
VALUES
((SELECT id FROM subscription_tiers WHERE name = 'free'), 'analytics.dashboard', 'user', 'Analytics', 'Analytics', 'Personal chat stats and activity charts'),
((SELECT id FROM subscription_tiers WHERE name = 'pro'), 'analytics.dashboard', 'full', 'Analytics', 'Analytics', 'Personal stats + creator analytics, trends, and export');
Application-side check:
var level = await connection.QueryFirstAsync<string?>(
"SELECT fn_get_user_subscription_limit(@UserId, @Key)",
new { UserId = userId, Key = "analytics.dashboard" });
// level: "user" = personal stats only, "full" = personal + creator analytics
New Data Needed
Daily Stats Snapshots
The materialized views give current values but not history. To show trends (follower growth, favorite growth over time), we need daily snapshots.
CREATE TABLE creator_daily_stats (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
snapshot_date DATE NOT NULL DEFAULT CURRENT_DATE,
-- From mv_user_stats
public_character_count INTEGER NOT NULL DEFAULT 0,
public_mode_count INTEGER NOT NULL DEFAULT 0,
public_lorebook_count INTEGER NOT NULL DEFAULT 0,
follower_count INTEGER NOT NULL DEFAULT 0,
-- Aggregated from mv_character_stats for this user's characters
total_conversation_count INTEGER NOT NULL DEFAULT 0,
total_message_count INTEGER NOT NULL DEFAULT 0,
total_favorite_count INTEGER NOT NULL DEFAULT 0,
UNIQUE(user_id, snapshot_date)
);
CREATE INDEX idx_creator_daily_stats_user_date
ON creator_daily_stats (user_id, snapshot_date DESC);
COMMENT ON TABLE creator_daily_stats IS 'Daily snapshot of creator statistics for trend charts. Populated by a scheduled job.';
Population: A scheduled function (cron or Railway scheduled task) runs once daily:
CREATE OR REPLACE FUNCTION fn_snapshot_creator_daily_stats()
RETURNS INTEGER AS $$
DECLARE
v_count INTEGER;
BEGIN
INSERT INTO creator_daily_stats (
user_id, snapshot_date,
public_character_count, public_mode_count, public_lorebook_count,
follower_count, total_conversation_count, total_message_count, total_favorite_count
)
SELECT
us.user_id,
CURRENT_DATE,
us.public_character_count,
us.public_mode_count,
us.public_lorebook_count,
us.follower_count,
us.conversation_count,
COALESCE(msg.total, 0),
COALESCE(fav.total, 0)
FROM mv_user_stats us
LEFT JOIN LATERAL (
SELECT SUM(cs.message_count) AS total
FROM mv_character_stats cs
JOIN characters c ON c.id = cs.character_id
WHERE c.created_by_user_id = us.user_id AND c.is_deleted = FALSE
) msg ON TRUE
LEFT JOIN LATERAL (
SELECT SUM(cs.favorite_count) AS total
FROM mv_character_stats cs
JOIN characters c ON c.id = cs.character_id
WHERE c.created_by_user_id = us.user_id AND c.is_deleted = FALSE
) fav ON TRUE
ON CONFLICT (user_id, snapshot_date) DO UPDATE SET
public_character_count = EXCLUDED.public_character_count,
public_mode_count = EXCLUDED.public_mode_count,
public_lorebook_count = EXCLUDED.public_lorebook_count,
follower_count = EXCLUDED.follower_count,
total_conversation_count = EXCLUDED.total_conversation_count,
total_message_count = EXCLUDED.total_message_count,
total_favorite_count = EXCLUDED.total_favorite_count;
GET DIAGNOSTICS v_count = ROW_COUNT;
RETURN v_count;
END;
$$ LANGUAGE plpgsql;
COMMENT ON FUNCTION fn_snapshot_creator_daily_stats IS 'Takes a daily snapshot of all creator statistics. Idempotent — safe to run multiple times per day.';
Audience Daily Aggregates
Per-user-per-creator daily activity, used to compute cohorts, cross-entity overlap, and the anonymized fan table. This table is internal only — never exposed to creators directly. The server reads it, computes aggregates, and returns anonymized results.
CREATE TABLE creator_audience_daily (
creator_user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
audience_user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
snapshot_date DATE NOT NULL DEFAULT CURRENT_DATE,
message_count INTEGER NOT NULL DEFAULT 0,
character_ids INTEGER[] NOT NULL DEFAULT '{}', -- which of creator's characters were used
mode_ids INTEGER[] NOT NULL DEFAULT '{}', -- which modes were used
models_used TEXT[] NOT NULL DEFAULT '{}', -- which LLM models were used
PRIMARY KEY (creator_user_id, audience_user_id, snapshot_date)
);
CREATE INDEX idx_creator_audience_daily_creator_date
ON creator_audience_daily (creator_user_id, snapshot_date DESC);
CREATE INDEX idx_creator_audience_daily_audience
ON creator_audience_daily (audience_user_id, snapshot_date DESC);
COMMENT ON TABLE creator_audience_daily IS
'Per-user-per-creator daily engagement aggregates. Internal only — used for cohort computation, '
'never returned to creators. Populated by fn_snapshot_creator_audience_daily.';
Population: Runs daily alongside fn_snapshot_creator_daily_stats:
CREATE OR REPLACE FUNCTION fn_snapshot_creator_audience_daily()
RETURNS INTEGER AS $$
DECLARE
v_count INTEGER;
BEGIN
INSERT INTO creator_audience_daily (
creator_user_id, audience_user_id, snapshot_date,
message_count, character_ids, mode_ids, models_used
)
SELECT
c.created_by_user_id AS creator_user_id,
ms.user_id AS audience_user_id,
CURRENT_DATE,
COUNT(*) AS message_count,
ARRAY_AGG(DISTINCT ms.character_id) FILTER (WHERE ms.character_id IS NOT NULL),
ARRAY_AGG(DISTINCT ms.mode_id) FILTER (WHERE ms.mode_id IS NOT NULL),
ARRAY_AGG(DISTINCT ms.model) FILTER (WHERE ms.model IS NOT NULL)
FROM web_message_stats ms
JOIN characters c ON c.id = ms.character_id AND c.is_deleted = FALSE
WHERE ms.created_at >= CURRENT_DATE
AND ms.created_at < CURRENT_DATE + INTERVAL '1 day'
AND c.created_by_user_id != ms.user_id -- exclude creator chatting with their own characters
GROUP BY c.created_by_user_id, ms.user_id
ON CONFLICT (creator_user_id, audience_user_id, snapshot_date) DO UPDATE SET
message_count = EXCLUDED.message_count,
character_ids = EXCLUDED.character_ids,
mode_ids = EXCLUDED.mode_ids,
models_used = EXCLUDED.models_used;
GET DIAGNOSTICS v_count = ROW_COUNT;
RETURN v_count;
END;
$$ LANGUAGE plpgsql;
COMMENT ON FUNCTION fn_snapshot_creator_audience_daily IS
'Snapshots per-user engagement with each creator''s content. Excludes self-usage. Idempotent.';
Retention policy: creator_audience_daily rows older than 90 days are pruned by a weekly cleanup job. This bounds storage growth and limits the analytics window to a meaningful timeframe.
Cohort Computation
Cohorts are computed server-side on the fly from creator_audience_daily — there is no separate cohort table. The query aggregates the daily rows for the requested period:
-- Cohort assignment for a creator's audience over a 30-day period
WITH audience AS (
SELECT
audience_user_id,
SUM(message_count) AS total_messages,
COUNT(DISTINCT snapshot_date) AS active_days,
MAX(snapshot_date) AS last_active,
-- Flatten arrays across days
ARRAY(SELECT DISTINCT unnest(array_agg_cat(character_ids))) AS all_character_ids
FROM creator_audience_daily
WHERE creator_user_id = @CreatorId
AND snapshot_date >= @StartDate
GROUP BY audience_user_id
)
SELECT
CASE
WHEN total_messages > 100 AND last_active >= CURRENT_DATE - INTERVAL '7 days' THEN 'power'
WHEN total_messages BETWEEN 20 AND 100 AND last_active >= CURRENT_DATE - INTERVAL '14 days' THEN 'regular'
WHEN total_messages BETWEEN 5 AND 19 AND last_active >= CURRENT_DATE - INTERVAL '30 days' THEN 'casual'
ELSE 'churned'
END AS cohort,
COUNT(*) AS user_count,
SUM(total_messages) AS total_messages,
AVG(total_messages)::numeric(10,1) AS avg_messages,
AVG(array_length(all_character_ids, 1))::numeric(10,1) AS avg_entities_used
FROM audience
GROUP BY 1
Note: array_agg_cat is a custom aggregate that concatenates arrays — a utility function in the migration.
API
Endpoints
GET /api/analytics/my-stats # Personal shaped sections (all users)
GET /api/analytics/creator # Creator shaped sections (Pro only)
GET /api/analytics/creator/audience # Audience cohorts + fans + correlation (Pro only)
GET /api/analytics/creator/entity/{entityType}/{uuid} # Entity drill-down (Pro only)
All authenticated. /my-stats returns the requesting user's own shaped sections (overview deltas, heatmap, sessions). /creator returns the creator's shaped sections (overview deltas, entity usage breakdown, leaderboard). /creator/audience returns the anonymized audience insights (cohorts, fans, correlation matrix). Time-series charts on these pages are fetched separately through the generic stats endpoints.
Response: /api/analytics/my-stats (all users)
{
"overview": {
"messagesSent": { "count": 1842, "delta": 124 },
"conversations": { "count": 23, "delta": 3 },
"charactersUsed": { "count": 14, "delta": 2 }
},
"dailyActivity": {
"period": "30d",
"dataPoints": [
{ "date": "2026-02-15", "messages": 38, "regenerations": 3 },
{ "date": "2026-02-16", "messages": 42, "regenerations": 1 }
]
},
"mostChattedCharacters": [
{ "characterUuid": "a1b2...", "name": "Elara the Narrator", "avatarUrl": "...", "creatorName": "WorldBuilder42", "messages": 312 },
{ "characterUuid": "c3d4...", "name": "Crystal Dawn Merchant", "avatarUrl": "...", "creatorName": "WorldBuilder42", "messages": 180 }
],
"favoriteCreators": [
{ "creatorSlug": "worldbuilder42", "name": "WorldBuilder42", "avatarUrl": "...", "messages": 492, "charactersUsed": 4 },
{ "creatorSlug": "nightfallstories", "name": "NightfallStories", "avatarUrl": "...", "messages": 201, "charactersUsed": 2 }
],
"modelUsage": [
{ "model": "claude-sonnet-4-6", "count": 884, "percentage": 48 },
{ "model": "gpt-4o", "count": 571, "percentage": 31 },
{ "model": "gemini-2.5-flash", "count": 276, "percentage": 15 },
{ "model": "other", "count": 111, "percentage": 6 }
],
"activityInsights": {
"heatmap": [
{ "dayOfWeek": 0, "hour": 22, "count": 48 },
{ "dayOfWeek": 0, "hour": 23, "count": 52 },
{ "dayOfWeek": 4, "hour": 21, "count": 61 }
],
"peakHours": { "start": 22, "end": 1, "label": "10 PM – 1 AM" },
"busiestDay": { "dayOfWeek": 4, "label": "Thursday" },
"sessions": {
"avgDurationMinutes": 28,
"longestDurationMinutes": 192,
"totalHours": 47,
"countThisWeek": 14
},
"avgMessagesPerDay": 42
}
}
Response: /api/analytics/creator (Pro only)
{
"creatorOverview": {
"publishedCharacters": { "count": 12, "delta": 2 },
"publishedModes": { "count": 4, "delta": 1 },
"publishedLorebooks": { "count": 3, "delta": 0 },
"followers": { "count": 1280, "delta": 48 },
"totalFavorites": { "count": 342, "delta": 19 },
"totalMessages": { "count": 18420, "delta": 1830 }
},
"contentActivity": {
"period": "30d",
"dataPoints": [
{ "date": "2026-02-15", "messages": 142, "regenerations": 12 },
{ "date": "2026-02-16", "messages": 168, "regenerations": 8 }
]
},
"entityUsage": [
{ "entityType": "mode", "name": "Fantasy RPG Mode", "uuid": "...", "messages": 4280, "users": 189, "trend": 12.5 },
{ "entityType": "character", "name": "Elara the Narrator", "uuid": "...", "messages": 2340, "users": 142, "trend": 0.2 },
{ "entityType": "lorebook", "name": "Forgotten Realms Lore", "uuid": "...", "messages": 890, "users": 67, "trend": 22.1 }
],
"characterLeaderboard": [
{ "characterUuid": "a1b2...", "name": "Elara the Narrator", "avatarUrl": "...", "messages": 2340, "conversations": 189, "favorites": 89 }
],
"modelUsage": [
{ "model": "claude-sonnet-4-6", "count": 4820, "percentage": 48 },
{ "model": "gpt-4o", "count": 3100, "percentage": 31 }
],
"followerTrend": {
"period": "30d",
"dataPoints": [
{ "date": "2026-02-15", "followers": 1232 },
{ "date": "2026-02-16", "followers": 1235 }
]
},
"audiencePeakHours": {
"hourlyDistribution": [
{ "hour": 20, "percentage": 18 },
{ "hour": 21, "percentage": 22 },
{ "hour": 22, "percentage": 22 }
],
"peakLabel": "8 PM – 11 PM (62% of daily activity)"
}
}
Response: /api/analytics/creator/audience (Pro only)
Separate endpoint for the heavy audience analytics — called on demand when the creator opens the Audience tab.
{
"cohorts": [
{ "name": "power", "userCount": 23, "totalMessages": 6420, "avgMessagesPerUser": 279.1, "avgEntitiesUsed": 3.8, "retentionRate": 0.92, "topModel": "claude-sonnet-4-6" },
{ "name": "regular", "userCount": 87, "totalMessages": 4180, "avgMessagesPerUser": 48.0, "avgEntitiesUsed": 2.1, "retentionRate": 0.68, "topModel": "claude-sonnet-4-6" },
{ "name": "casual", "userCount": 312, "totalMessages": 2890, "avgMessagesPerUser": 9.3, "avgEntitiesUsed": 1.2, "retentionRate": 0.31, "topModel": "gpt-4o" },
{ "name": "churned", "userCount": 45, "totalMessages": 0, "avgMessagesPerUser": 0, "avgEntitiesUsed": 1.4, "retentionRate": 0, "topModel": null }
],
"topFans": [
{ "opaqueId": "Fan #1", "messageCount": 892, "entitiesUsed": ["Elara", "Crystal Dawn", "RPG Mode", "Forgotten Realms Lore"], "activeDays": 28, "firstSeenWeek": "2026-W05", "lastActiveWeek": "2026-W13" },
{ "opaqueId": "Fan #2", "messageCount": 634, "entitiesUsed": ["Elara", "Tavern Bob", "Standard Mode"], "activeDays": 22, "firstSeenWeek": "2026-W07", "lastActiveWeek": "2026-W13" }
],
"entityCorrelation": {
"entities": ["Elara", "Crystal Dawn", "Tavern Bob", "RPG Mode"],
"matrix": [
[1.0, 0.78, 0.34, 0.82],
[0.78, 1.0, 0.52, 0.61],
[0.34, 0.52, 1.0, 0.45],
[0.82, 0.61, 0.45, 1.0]
]
},
"retentionByEntity": [
{ "name": "Elara the Narrator", "entityType": "character", "week1to2": 0.82, "week2to3": 0.78, "week3to4": 0.75 },
{ "name": "Fantasy RPG Mode", "entityType": "mode", "week1to2": 0.88, "week2to3": 0.85, "week3to4": 0.82 },
{ "name": "Tavern Keeper Bob", "entityType": "character", "week1to2": 0.45, "week2to3": 0.28, "week3to4": 0.15 }
],
"modelByCohort": [
{ "cohort": "power", "models": [{ "model": "claude-sonnet-4-6", "percentage": 62 }, { "model": "gpt-4o", "percentage": 22 }] },
{ "cohort": "regular", "models": [{ "model": "claude-sonnet-4-6", "percentage": 48 }, { "model": "gpt-4o", "percentage": 31 }] },
{ "cohort": "casual", "models": [{ "model": "gpt-4o", "percentage": 38 }, { "model": "claude-sonnet-4-6", "percentage": 35 }] }
]
}
A caller without Creator insights on gets an empty-body 403 from /api/analytics/creator* and /api/creator/stats/{metric} ("fence, not signpost" — no upgrade body was ever sent). The tabs read that 403 and show the Turn on Creator insights card; the server is the only place the answer is decided.
Client Implementation
Shared component dependencies
Every chart, card, and row in this design uses a shared primitive.
Before building anything in clientConsole/src/pages/settings/analytics/,
check the table below. This is the canonical reuse map — adding a
custom component (or a custom CSS-in-JS card style) requires justifying
why none of these worked.
Already shipped — use directly
These live in @shared/components (and @shared/components/common/stats/
for the chart subsystem) today. No promotion needed.
| Shared primitive | UCs that consume it |
|---|---|
TimeSeriesChart |
UC-U1, UC-U4, UC-U7, UC-C1, UC-C7, UC-C9, UC-C11, UC-C17 trends |
StatsFilterBar |
Top-of-page date/granularity selector for both tabs |
useStatsQuery |
Every generic-stack consumer |
chartTheme (chartColors, chartAxis, chartTooltip, formatCompact, formatMs, formatBucketLabel, seriesColor) |
All chart styling — do not invent new color palettes |
sumStatsResponse, sumSeriesByKey |
Period totals for overview cards / leaderboards |
TabbedLayout |
Top-level My Stats / Creator / Audience tabs |
Tabs |
Sub-tab switchers (e.g. "by category" in UC-U12 / UC-C19) |
Card |
Every panel wrapper |
Section (+ InfoSection, WarningSection) |
Empty states, anonymization disclosures, "tracking starts here" notices on UC-C18 |
EmptyState |
Day-0 state, Pro-gated tab empty states for Free users |
Button (incl. iconOnly — never IconButton) |
Refresh, Export CSV, Resume conversation (UC-U13), Upgrade to Pro |
Avatar |
Character / creator / persona avatars in every list-shaped UC |
Badge |
Cohort labels (UC-C5), tier indicators, draft/state markers |
ProBadge, ProPreviewNote |
UC-U6 conversion banner, Free-vs-Pro comparison, every Pro-tab empty state |
ProgressBar |
Bar fills inside entity-usage rows, drop-off curve cells |
LoadingSpinner, LoadingOverlay |
Initial query loads |
MiniPagination |
Top-N+ pagination on leaderboards, biggest-fans table |
MemberRow (extend it — don't replace it) |
UC-U2, UC-U3, UC-U10, UC-U13, UC-C1 leaderboard — avatar + title + secondary + value rows |
RecentActivity (reference design) |
UC-U13 paused conversations — closest existing pattern; reuse if it fits, mirror its layout if it doesn't |
Promote from local to shared before clientConsole work begins
The AdminConsole already has these as local components and the analytics design proposes the exact same patterns. Don't duplicate — promote.
| Currently | Should become |
|---|---|
adminConsole/src/components/statistics/ChartCard.tsx (local) |
shared/src/components/common/stats/ChartCard.tsx |
StatSummary (local, in same file as ChartCard) |
shared/src/components/common/stats/StatSummary.tsx (or merge into the new StatCard below) |
Both are ~90 lines of CSS-in-JS that admin and clientConsole would otherwise re-implement. Do this before clientConsole analytics lands — two copies of the same component drift apart fast.
Build new in shared/src/components/common/stats/
Each is referenced by multiple UCs across both tiers. Build once, add a showcase entry, reuse forever.
| New shared component | Used by | Notes |
|---|---|---|
StatCard (with optional delta) |
UC-U1 overview, UC-U8 streak, UC-U9 word count, UC-U14 regen rate, UC-C9 creator overview | Big number + label + optional delta (+12 ↑) + optional secondary line. Could replace StatSummary entirely if designed flexibly enough. |
HorizontalBarChart |
UC-U2, UC-U3, UC-U4 (alt view), UC-U11, UC-U12, UC-C1 leaderboard, UC-C13, UC-C19 | Avatar/icon prefix + label + bar + value. The most-reused chart shape in the entire design. Recharts wrapper. |
Heatmap |
UC-U5 user heatmap, UC-C6 audience peak hours | Day × hour 7×24 grid. Same component, two scopes. Cell-shading scale + tooltip. |
CorrelationMatrix |
UC-C4 entity overlap | Symmetric matrix, color-scaled cells, axis labels. Borderline whether shared — keep shared so the showcase forces a clean API. |
Try-before-build
These are tempting to build but probably aren't necessary if existing components are pushed a little:
| Tempting | Try first |
|---|---|
SurvivalCurve for UC-C15 |
Parameterize TimeSeriesChart with a custom x-axis (message number, not timestamp). Only build a new component if TimeSeriesChart's API can't be cleanly extended. |
EntityRankRow for leaderboards |
Extend MemberRow with stat slots. Build new only if the prop surface gets unwieldy. |
CreatorUpsellBanner |
It's Card + ProBadge + Button composed. Three primitives, not a new component. |
PausedConversationCard for UC-U13 |
Card + Avatar + Button composed; or extend MemberRow. |
| New stat-panel layout component | Card + StatCard × N in a grid. Don't wrap a wrap. |
Forbidden
Per project conventions and reuse memory:
- No
IconButton— use<Button iconOnly>(xs/sm/md/lg). - No raw
<div>for card surfaces —Cardexists. - No raw
<ul>/<li>for ranked lists — compose with shared row primitives. - No new color palettes — use
chartColorsfromchartTheme. Custom palettes get reverted. - No
FormFieldwrappers — when settings toggles land (e.g. UC-U8 streak opt-out),Input/Toggle/Checkboxalready havelabel/description/mandatoryprops.
Component Structure
clientConsole/src/pages/settings/analytics/
├── AnalyticsPage.tsx # Main page with tabs (My Stats | Creator | Audience)
├── my-stats/
│ ├── MyStatsTab.tsx # Personal activity tab (all users)
│ ├── PersonalOverviewCards.tsx # Messages sent, conversations, characters used
│ ├── DailyActivityChart.tsx # Personal messages per day
│ ├── MostChattedCharacters.tsx # Bar chart of favorite characters
│ ├── FavoriteCreators.tsx # Bar chart of most-engaged creators
│ ├── ModelUsageChart.tsx # Bar chart of user's model usage
│ └── ActivityInsights.tsx # Heatmap, peak hours, session stats
├── creator/
│ ├── CreatorTab.tsx # Creator analytics tab (Pro)
│ ├── CreatorOverviewCards.tsx # Published content, followers, favorites
│ ├── ContentActivityChart.tsx # Messages across creator's characters
│ ├── EntityUsageTable.tsx # Characters + modes + lorebooks ranked
│ ├── CharacterLeaderboard.tsx # Ranked table
│ ├── AudienceModelUsage.tsx # Donut chart of audience model choices
│ ├── FollowerTrendChart.tsx # Follower growth line chart
│ └── AudiencePeakHours.tsx # When the audience is active
├── audience/
│ ├── AudienceTab.tsx # Audience insights tab (Pro)
│ ├── CohortOverview.tsx # Power/Regular/Casual/Churned cards
│ ├── EntityCorrelation.tsx # Cross-entity overlap matrix
│ ├── BiggestFans.tsx # Anonymized fan table
│ ├── RetentionByEntity.tsx # Week-over-week retention chart
│ └── ModelByCohort.tsx # Model preferences per cohort
├── shared/
│ ├── StatCard.tsx # Reusable stat card with delta
│ ├── HorizontalBarChart.tsx # Reusable bar chart
│ ├── LineChart.tsx # Reusable line chart
│ ├── Heatmap.tsx # Day × hour grid (reused: my-stats + audience peak times)
│ └── CorrelationMatrix.tsx # Reusable matrix/table with color-scaled cells
├── CreatorUpsellBanner.tsx # Non-intrusive upgrade prompt
└── useAnalytics.ts # Data fetching hooks (all endpoints)
Chart Library
Use a lightweight chart library. Candidates:
| Library | Size | Fit |
|---|---|---|
| Recharts | ~45 KB gzip | React-native, declarative, good defaults |
| Chart.js + react-chartjs-2 | ~60 KB gzip | More chart types, canvas-based |
| Lightweight custom (SVG) | ~5 KB | Minimal, but more work |
Recommendation: Recharts — aligns with the React stack, declarative API, handles responsive sizing.
Creator Upsell Banner
The upsell is a styled card at the bottom of the My Stats tab — not a blocking overlay. It sits naturally below the user's real charts.
function CreatorUpsellBanner() {
return (
<Card style={styles.upsellCard}>
<h3 style={styles.heading}>Want to see how your content performs?</h3>
<p style={styles.subtext}>
Creator Analytics shows engagement, favorites, follower growth,
and model usage across your published characters and content.
</p>
<Button variant="primary" onClick={() => navigate('/settings/subscription')}>
Upgrade to Pro
</Button>
</Card>
)
}
The Creator Analytics tab itself shows the same banner in a centered empty state if the user is on the free tier. No blurring, no fake charts — just a clean prompt explaining what they'd get. The My Stats charts they already have are the best advertisement.
Implementation Order
The phasing below is structured so each phase ships a coherent product slice. Phase 1 lands a real free product. Phase 1.5 lands a credible day-one Pro tier before Phase 2/3 commit to the heavier audience backend. Phase 2/3 are deeper investments that should only be greenlit once Pro upgrade economics support the work.
Phase 1: Foundation (4–6 weeks)
Goal: ship the free tier as a complete product, plus capture forward-only data the later phases depend on.
- Shared chart components —
StatCard,HorizontalBarChart,LineChart,Heatmap,CorrelationMatrix(reused across all tabs). - My Stats API + tab —
GET /api/analytics/my-statswith all sections: overview cards, daily activity, most chatted characters, favorite creators, model usage, activity insights (heatmap + sessions), summarization depth (UC-U7), streak (UC-U8), word count (UC-U9), drifted-away (UC-U10), personas usage (UC-U11), themes (UC-U12), paused conversations (UC-U13), regen rate (UC-U14). - Creator upsell banner — Non-intrusive card on My Stats tab + empty state on Creator/Audience tabs.
- Conversation-origin instrumentation (UC-C18 prerequisite — START NOW) — schema columns, SQL function parameters, C# repo + endpoint plumbing, frontend audit on every "start chat" call site. The dashboard panel ships in Phase 1.5; the data capture must start in Phase 1 because backfill is impossible. ~3–5 days of work, ~1 day of which is the frontend audit.
- Summaries metric scope expansion — add
StatsScope.UserandStatsScope.Creatorto thesummariesmetric inDefaultStatsMetrics.Build()and add the correspondingp_scope = 1 / 2branches tofn_stats_summaries. Unblocks UC-U7 and UC-C11 chart panels for both tiers.
Phase 1.5: Pro day-one offering (4–6 weeks)
Goal: ship a credible Pro tier that justifies the upgrade on day one — does not depend on the audience aggregation backend.
- Daily snapshot job —
creator_daily_statsonly —fn_snapshot_creator_daily_stats+ scheduled task. Skipcreator_audience_dailyfor now (Phase 2 dependency). - Creator Analytics API + tab — Pro gate —
GET /api/analytics/creatorwith: creator overview cards + deltas (UC-C9, UC-C1), content activity chart (UC-C1 reusing existingfn_stats_messagesCreator scope), entity usage breakdown with characters / modes / lorebooks / packages columns: messages / unique users / avg msgs/convo / repeat rate / regen rate (UC-C2, UC-C3, UC-C12, UC-C13, UC-C16, UC-C17), character leaderboard (UC-C1), follower trend chart (UC-C9), audience peak hours (UC-C6), audience model donut (UC-C7). - Subscription limit seed — Add
analytics.dashboardto tier limits. - Greeting performance panel (UC-C14) — per-character drill-down using existing
web_conversations.greeting_id. No new data needed. - Drop-off curve panel (UC-C15) — per-character drill-down via window-function CTE on
web_message_stats. - Discovery funnel panel (UC-C18 dashboard) — once data has accumulated for ~2–4 weeks since Phase 1 instrumentation lands, surface the breakdown.
- Genre performance panel (UC-C19) — per-category bitfield aggregation on the creator's owned characters.
- Entity drill-down endpoint —
GET /api/analytics/creator/entity/{entityType}/{uuid}returning a per-entity composite payload (time series, conversation-length distribution for UC-C12, drop-off curve for UC-C15, greeting performance for UC-C14, summary rate for UC-C11). Click an entity row in the breakdown to open the drill-down. Endpoint contract is shared with the parent creator endpoint — it's the same shaped responses, scoped to one entity instead of all of them.
Phase 2: Audience Aggregation (4–6 weeks)
Goal: land the audience-insights backend that powers cohorts, fans, correlation, retention.
creator_audience_dailytable +fn_snapshot_creator_audience_daily+ scheduled task + 90-day retention cleanup.array_agg_catcustom aggregate for flattening arrays across rows.- Anonymization enforcement — server-side session-salted HMAC for opaque fan IDs (
HashDimensionKeyspolicy hook in the existing anonymizer), minimum cohort size (≥5) enforcement, date rounding to ISO week.
Phase 3: Audience Insights UI (2–3 weeks)
Goal: surface the audience aggregation backend as the deepest creator tab.
- Audience Insights API + tab — Pro gate —
GET /api/analytics/creator/audience: cohort segmentation (UC-C5), anonymized fan table (UC-C8), entity correlation matrix (UC-C4), retention by entity (UC-C10), model preferences by cohort (UC-C7 deep-dive), bundle/package recommendations.
Phase 4: CSV Export (1–2 weeks)
Goal: power creators can take data offline for external pitches, sponsorship applications, and personal records.
- CSV export endpoint —
GET /api/analytics/creator/export?metric={key}&from=&to=&granularity=returnsContent-Type: text/csv. Reuses the existing shaped-endpoint queries; serializes to CSV instead of JSON. Pro-gated. Filename pattern:eod-analytics-{metric}-{from}-{to}.csv. Anonymization rules apply equally to the export — opaque fan IDs, min-cohort suppression, no PII. The export is NOT a backdoor. - Frontend export button —
Buttonwith download icon on each Pro tab; calls the export endpoint and triggers a browser download. No new component.
Phase 4 is decoupled from Phases 1–3 — the endpoints designed in earlier phases already support a CSV serializer alternative, so this is mostly serialization plumbing plus a button. Ships when the rest is stable, not before.
Future / not phased
- Webhook notifications, public opt-in analytics, comparative-rank baselines — see Future Extensions.
Future Extensions
- Public analytics — Opt-in public stats page at
/creator/:id/analytics(vanity metrics for creator profiles) - Webhook notifications — "Your character hit 1,000 messages" milestone alerts
- Comparative stats — "Your character ranks in the top 10% for engagement" using
vw_hub_statisticsas baseline - Conversion funnel — Track casual → regular → power user progression over time. "You converted 12 casual users to regulars this month"
- Content recommendations — Based on entity correlation: "Users who love Elara might enjoy a companion character — 78% also chat with Crystal Dawn"
- A/B insights — If a creator updates a system prompt, show before/after engagement metrics (requires entity_changelog integration)
- Audience geography — Anonymized timezone distribution (derived from peak activity hours, not user profile data) to inform publishing schedules