Daily Tasks & Echo Economy — Design Document
Status: Foundations live. The Echo ledger, daily tasks, subscription-as-monthly-grant, gift codes, monetary-purchase plumbing, tipping (one-time + per-message engagement), and per-feature subscriptions (Feature Commitments) have all shipped. Per-use compute is Echo-charged too: per-message compute cost lines on built-in models (functions/41m_compute_charge_functions.sql) and AI Task charges (functions/41n_ai_task_charge_functions.sql) are live. Hosted-checkout Echo bundles and prepaid plans by card via PayU are shipped (Beta) (bundles 2026-09-28: slices 0–1c, 1e838a9a, 13f66d98, b6be59a8, f1e44bc1; prepaid plans 0a68a3572, October 2026; charged only at the shown price — 4cf75f5a7) — the checkout lives in the account console's Billing section, behind the admin Card rail switch (off / sandbox / production, Configure → Pricing & tax; sandbox sells only to administrators and named test accounts — 0877ec762). Still to come: creator cashout. (Updated 2026-10-27.)
For the operational reference of what actually shipped, see:
docs-internal/architecture/billing/SUBSCRIPTION_REFACTOR.md— slices 2A–2E (subscription refactor + Feature Commitments)docs-internal/architecture/billing/GIFT_CODE_REDESIGN.md— slices A–D (fn_redeem_gift_code_v2+subscription_credit_queue)docs-internal/architecture/billing/CREATOR_TIPS.md— one-time + engagement tipsdocs-internal/architecture/billing/ECHO_SPEND_PATTERN.md— canonical debit / transfer primitivesdocs-internal/architecture/billing/PAYU_INTEGRATION.md— the card/bank checkout rail (bundles + prepaid plans, live behind the Card rail switch)
(Internal docs are not part of the published site — read them in the repo.)
This page is the design north-star. When it disagrees with the internal docs above, the internal docs win.
Payment-rail context (2026-05-12): SegPay rejected (re-apply 2026-08 to 2026-11), Mollie / Stripe / Adyen / Finby ruled out (see project root CLAUDE.md field report). Patreon is the only live automated rail. Wise is manual reconciliation only (PSD2 SCA blocks programmatic reads for personal-token API users). PayU is live (Beta) for Echo bundles and prepaid plans by card, behind the admin Card rail switch (off / sandbox / production, Configure → Pricing & tax; sandbox sells only to administrators and named test accounts — 0877ec762); where the rail isn't open to an account, gift codes + Patreon-funded subscription grants remain its Echo entry points. (Rail status updated 2026-10-27.)
Implementation State
The table below is what's actually in the code as of 2026-05-12. Everything beneath it is the design target.
| Area | State | Pointer |
|---|---|---|
Echo ledger (echo_transactions, partitioned, ledger-only) |
Shipped | database/v1/20d_tables_echo_ledger.sql |
Daily balance + pool snapshots (echo_daily_balance_snapshots, echo_daily_pool_snapshots) |
Shipped | 20d_tables_echo_ledger.sql, snapshot built by functions/41a_echo_ledger_functions.sql |
4-bucket pool decomposition (daily / sub / expiring_other / persistent) |
Shipped | fn_get_pool_balances in functions/41e_feature_management_functions.sql |
Canonical spend primitives (fn_debit_spendable, fn_debit_persistent, fn_transfer_spendable, EchoSpendOutcome) |
Shipped | functions/41i_echo_spend_helpers.sql + shared/src/types/echoSpend.ts |
| Daily tasks (12 seeded, recurring + one-time) | Shipped | 20e_tables_echo_tasks.sql, claim flow in 41b_echo_task_functions.sql |
| Subscription tiers as monthly Echo grants (Pro parameterized, Premium fixed) | Shipped | 20j_subscription_refactor.sql + functions/39a_subscription_refactor_functions.sql |
| Subscription Credit Queue (multi-month gift passes, pre-purchased renewals) | Shipped | 48_tables_subscription_credits.sql |
| Gift codes — tier / Echo / mixed | Shipped | 20b_tables_gift_codes.sql, functions/40_gift_code_functions.sql |
monetary_purchases audit table + fn_credit_monetary_purchase (Echo item_kind) |
Shipped | 20f_tables_monetary_purchases.sql, functions/41c_*.sql |
payment_orders (provider-agnostic checkout plumbing) |
Shipped | 47_tables_payment_orders.sql |
| Feature Commitments (per-feature monthly Echo subscriptions) | Shipped (slice 2E) | 44_tables_user_feature_commitments.sql, 20l_tables_echo_feature_catalog.sql, FeatureCommitmentEndpoints.cs |
| Creator Tips (one-time + per-message engagement) | Shipped (2026-05-09) | functions/41j_echo_tip_functions.sql, 41k_engagement_tip_functions.sql, EngagementChargeStage.cs |
monetary_purchases tier-kind path (paid subscription via checkout) |
Shipped | A PayU plan purchase (carries pro_value) queues 1 or 12 monthly passes (32b1d140e, 9c760bd99); only the Wise tier shape still raises (Wise tier orders are refused at creation) |
AI Tasks echo_cost charge |
Shipped | fn_charge_ai_task (functions/41n_ai_task_charge_functions.sql, on the shared fn_debit_daily_first_idempotent since 2bbb02ba), called pre-dispatch by AiTasksEndpoints.cs; refund on error |
| Hosted-checkout Echo bundle purchase | Shipped (Beta) | PayU slices 0–1c (2026-09-28): PayUEndpoints.cs, functions/93b_payu_functions.sql, accountConsole /billing/checkout + receipts; price check 4cf75f5a7. The Buy Echoes entry point renders only when checkout-options.available (the Card rail: off / sandbox / production). See PAYU_INTEGRATION.md. |
| Creator cashout / withdraw | Not built | No tables, no functions, no endpoints. v2+. |
| Paid-experience earnings (per-message creator credits) | Not built | See Paid Experiences. Depends on this doc's economy. |
daily_chat_progress counter table |
Removed | Replaced by on-demand fn_get_chat_progress_today reading web_messages. |
echo_wallets (stored-balance design from earlier paid-experiences doc) |
Never existed | Ledger-only from day one. |
Overview
Echoes are the platform's single in-app currency. Every paid surface — features, tips, paid experiences, premium models — debits Echoes. Every earning surface — daily tasks, subscriptions, gift codes, eventually creator income — credits Echoes. One ledger, one currency, four logical pools at read time.
The intent:
- Free tier has a real path. Daily tasks earn ~50–100 Echoes/day. Users can sample paid features without paying us, then convert to paying once they know what they want.
- Subscriptions are a discount, not a gate. Pro and Premium are recurring Echo grants at a better per-Echo rate than buying a bundle. No subscription tier unlocks a feature by virtue of the tier alone — features cost Echoes regardless. The grant just makes the Echoes cheaper.
- Creators are funded directly. Tips (one-time and per-message engagement) move Echoes from audience to creator. Paid experiences (when they ship) move Echoes per assistant message. Once cashout exists, a meaningful portion of the creator's earnings is convertible to USD.
- The platform stays neutral. Echoes are a unit of account, not a profit center. Pricing is set so that the worst-case spend-mix still covers infrastructure cost + margin; the platform doesn't need to take a per-transaction cut on every internal movement.
The base accounting rate is 1 Echo = $0.01 as the internal valuation. Bundle prices and subscription grants apply a markup or discount to that base rate. Final consumer numbers are tuned at launch; the rate is a design target.
Echo Pool Model
The ledger is one table. At read time, every credit is classified into one of four pools based on its transaction_type and expiry. The pool decomposition is computed by fn_get_pool_balances(user_id) and returns:
{
"daily": 120, // resets at UTC midnight
"sub": 1000, // monthly subscription grant, expires when next month's grant arrives
"expiring_other": 2400, // gift-code Echoes or bundle Echoes with a finite expires_at
"persistent": 8200, // task rewards, admin grants, tips received, anything expires_at IS NULL
"spendable": 11600 // sub + expiring_other + persistent (excludes daily)
}
Note: the earlier design called for a fifth bucket — cashable — that paid-experience earnings and tip income would land in. That bucket never materialized as a distinct pool; tip income today lands in persistent. When creator cashout ships, "cashable" will be a flag on individual transaction rows (or a derived computation), not a fifth pool. The pool model stays at four.
Drain order
When a user spends Echoes, the canonical helpers (fn_debit_spendable / fn_debit_persistent) drain pools in this order:
| Spend category | Allowed pools | Drain order |
|---|---|---|
| Per-use compute (chat message, embedding, lorebook-assistant exchange) | daily → sub → expiring_other → persistent |
Daily first to burn the budget before it expires; persistent last to preserve carryover. |
| Per-month commitments (Feature Commitments, paid experiences) | sub → expiring_other → persistent |
daily cannot fund commitments — would let a free user accumulate locked features they can't sustain. |
| Tipping | sub → expiring_other → persistent |
Same as commitments. daily cannot fund tips (closes a money-laundering channel from daily-task farming to creator wallet). |
| Cashout (future) | TBD — likely persistent-only with cashable-flag gating | Daily / sub / expiring-other will never be cashable. |
Drain order is enforced inside the spend helpers — callers don't pick a pool, they call fn_debit_spendable(...) with an intent and the helper picks pools that match the intent.
Why these rules
- Daily is use-it-or-lose-it. The free tier should feel like a real budget you spend down each day, not a slow accumulation you save up. Daily expires at UTC midnight.
- Subscription grants are monthly. Pro / Premium grants attach to the billing period. When the next period grants, the old one's leftovers expire. Encourages spending rather than hoarding.
- Gift codes can be either. A creator-handed-out promo code is typically
expiring_otherwith a 1-year expiry. An admin make-good grant is typicallypersistent. - Daily and sub are deliberately non-tippable. Tips have to come from durable Echoes the user has personally earned, bought, or persistently received. Otherwise a creator could earn Echoes via tasks, tip themselves on another account, and effectively cashout daily budget. The non-tippable pools close that path.
Why the daily budget doesn't scale with tier
The daily budget is 100☆/day for Free, Pro, and Premium alike (configurable platform-wide via echoes.daily_expiring_budget, default 100). Subscription tiers do not raise it — they raise the monthly persistent grant instead.
The reason is platform-cost protection. A daily budget that scales with tier exposes the platform to compounding compute on heavy-use accounts: a user spending 250☆/day every day on hosted-model chat can rack up more LLM cost than a $17 Pro subscription covers, and the gap widens at Premium. By keeping the daily floor flat and putting tier value into the monthly grant, the platform's worst-case daily exposure is bounded by user count, not by tier × user count. Pro and Premium users effectively get more Echoes to spend each month — just delivered as a monthly chunk rather than a higher daily cap.
Why expiring daily budget vs more task rewards
Task rewards are persistent (they accumulate in persistent). A daily budget that expires creates a "use it or lose it" dynamic that:
- Gives everyone enough for casual daily usage without buying or earning anything.
- Doesn't inflate the persistent Echo supply (no wallet accumulation across days).
- Makes purchased and earned Echoes feel premium (they persist; daily doesn't).
The daily budget is a +100 credit row in echo_transactions with expires_at = TODAY — same ledger, different expiry. Balance reads include today's daily row alongside all persistent rows; tomorrow it vanishes from the available total.
What does 100☆/day buy?
Once per-use charging is wired, the daily budget alone covers a meaningful amount of casual use. Illustrative (numbers depend on final platform-cost calibration):
| Mix | Approximate daily reach |
|---|---|
| Embeddings only (assuming ~1☆ / embedding) | ~100 embeddings |
| Lorebook assistant exchanges only (~3☆ / message) | ~30 messages |
| Cheap hosted model (Haiku-class) | A small handful of full chat turns |
| Mid hosted model (Sonnet-class) | A few full chat turns |
Plus whatever the user has earned in persistent from tasks (~25☆/day for a consistent user). A subscriber adds their monthly grant on top. The daily budget alone matches or exceeds the old free-tier limits — the new model is strictly more flexible because the user can mix-and-match what they spend it on.
Earning Echoes
Daily tasks
Twelve tasks ship as the launch catalog (20e_tables_echo_tasks.sql):
| Task key | Type | Reward | Threshold |
|---|---|---|---|
daily_login |
recurring | 10☆ | — |
chat_milestone_1 |
recurring | 5☆ | 10 messages today |
chat_milestone_2 |
recurring | 5☆ | 20 messages today |
chat_milestone_3 |
recurring | 5☆ | 30 messages today |
favorite_entity |
one-time × 10 | 3☆ | per favorite (cap 10) |
bookmark_entity |
one-time × 10 | 3☆ | per bookmark (cap 10) |
complete_bio |
one-time | 10☆ | bio ≥ 30 chars + public |
personalize_identity |
one-time | 10☆ | custom name + slug |
link_discord |
one-time | 20☆ | Discord linked |
link_google |
one-time | 20☆ | Google linked |
link_patreon |
one-time | 20☆ | Patreon linked |
Daily totals. A consistent user clears 10 + 5×3 = 25☆ recurring per day (~750☆/mo). One-time tasks add up to ~190☆ across the first few weeks. The recurring 25☆/day is the design target for "what daily-task farming earns" — enough to sample a paid feature, not enough to live on.
Mechanics.
- Claim flow:
fn_claim_daily_task(user_id, task_key)returns(success, reward, error_message). Validation failures never raise — they returnsuccess = FALSEwith a code. Per-user advisory lock (pg_advisory_xact_lock(user_id, hashtext('echo_task_claim'))) serializes claims. - Recurring tasks reset on the user's local "day" (UTC midnight). Idempotency key on the claim row prevents double-claim within the same day.
- Chat-progress thresholds are derived on-demand by
fn_get_chat_progress_todayagainstweb_messages— there is no separate counter table. Earlier designs had adaily_chat_progresstable; it was dropped in favor of computing on demand. - Rewards land in
daily(recurring tasks) orpersistent(one-time tasks). Task rewardsexpires_at IS NULLeven when they hitdaily— the constraint is the daily bucket expiry, not the row's own expires_at.
Multiplier system
Every task reward is stored as a base amount and an applied multiplier at claim time:
actual_reward = base_echoes_reward × multiplier
The infrastructure ships: fn_claim_daily_task (41b_echo_task_functions.sql) accepts p_multiplier NUMERIC(4,2) DEFAULT 1.00, validates 0 < multiplier ≤ 9.99, and records the multiplied amount on the ledger row. The actual multiplier is hardcoded to 1.00 today — no active source is wired.
Future possibilities the data model is ready for:
| Source | Example | Applies to |
|---|---|---|
| Promotional event | 2× for a weekend | All tasks |
| Streak bonus | 1.1× after 7 consecutive days | Daily login only |
| Seasonal event | 3× on specific tasks | Event-specific |
| Subscription tier | TBD if ever adopted | All tasks |
When a multiplier source is wired, the resolver picks the active multiplier at claim time and passes it to fn_claim_daily_task. Transaction history always shows what was actually awarded — changing a multiplier source affects future claims only.
Anti-abuse
Eligibility is enforced inside fn_claim_daily_task:
| Requirement | Check |
|---|---|
| Verified email or linked OAuth identity | fn_user_has_verified_email(user_id) must return TRUE. Includes password-verified and OAuth-linked accounts. |
| Not banned | users.banned_since IS NULL. |
| No account-age requirement | New users can earn immediately after verification. |
Rate limits live in the function and at the API edge:
| Control | Limit |
|---|---|
| Task claim serialization | Per-user advisory lock (hashtext('echo_task_claim')) — no concurrent double-claims. |
| Chat-progress derivation | fn_get_chat_progress_today reads web_messages on demand — no separate counter table to race against. Idempotency on completion is per (user, task_key, UTC date). |
| One-time task caps | daily_tasks.max_completions enforces lifetime caps (e.g. favorite_entity capped at 10). |
Fraud detection (future). Not in v1. The hooks are there — echo_transactions.metadata JSONB can store claim context (IP, user agent, timestamp patterns) for future analysis without schema changes. Candidate signals: claim patterns clustered on a single timestamp, IP clustering across many accounts, low-quality message generation for chat milestones.
Subscriptions (recurring Echo grants)
Tier = monthly Echo grant. No bundled features. The grant is the value.
| Tier | Price (USD/mo) | Grant (☆/mo) | Per-Echo rate |
|---|---|---|---|
| Free | $0 | 0 (daily tasks only) | n/a |
| Pro (400) | $10 | 400 | ~$0.025 |
| Pro (1K) | $17 | 1,000 | ~$0.017 |
| Pro (2.5K) | $35 | 2,500 | ~$0.014 |
| Pro (5K) | $60 | 5,000 | ~$0.012 |
| Premium | $99 | 10,000 (100,000 until 30 November 2026) | ~$0.0099 |
Pro is parameterized by pro_value — the user picks the grant size at checkout, the price scales via the breakpoint formula in subscription_pricing_config.formula (20j_subscription_refactor.sql). Premium is fixed-shape.
Grants are fired by fn_grant_subscription_echoes(user_id, tier_name, period_start) on each billing cycle. Idempotency is enforced by (user_id, tier_id, period_start) — re-firing the same period is a no-op. A per-user advisory lock (hashtext('sub_echo_grant')) serializes concurrent grants.
Grants land in the sub pool with expires_at = period_start + 1 month. When the next month's grant arrives, the old one's leftovers expire — encouraging steady use rather than hoarding. A grant that fails to land in time (queue lag, webhook delay) is self-healed by fn_ensure_current_period_grant on the next subscription-context read.
Subscription Credit Queue. A user can pre-purchase multiple months (gift code with subscription_passes > 1, or admin pre-grant) and the credits queue in subscription_credit_queue to fire at each upcoming period boundary. Consumer logic in docs-internal/architecture/billing/GIFT_CODE_REDESIGN.md.
No Premium auto-bundle. Premium commits nothing: its top-tier access comes from bypass_limits (below), not from commitment rows. An earlier design auto-committed a default bundle on the first Premium grant; that was replaced — FeatureSetupPending is now a Pro-only first-grant nudge. See Tiers & Limits.
bypass_limits flag. Premium carries the only intrinsic feature flag: bypass_limits = TRUE. This is honored in fn_get_feature_usage_summary to skip usage-based gating — Premium users don't see the "you've hit the cap" prompts. Premium's other intrinsic perk is the priority lane on the built-in models; all other tier behavior is mediated by Echoes.
Gift codes
Three shapes (20b_tables_gift_codes.sql):
| Shape | Grants | Use case |
|---|---|---|
| Tier-only | One or more subscription passes | Promo handouts, refund make-goods, Patreon perks |
| Echo-only | Lump-sum Echoes (with optional echo_expires_in_days) |
Echo bundle equivalent until hosted checkout exists |
| Mixed | Both | "1 month Pro + 500☆ welcome bonus" |
Redemption goes through fn_redeem_gift_code_v2 (slice C of the gift-code redesign). One-shot codes and reusable codes are both supported. Echo grants from gift codes land in expiring_other if echo_expires_in_days IS NOT NULL, else persistent.
Monetary purchases (the durable record)
monetary_purchases is the platform's audit table for every USD-flavored event. fn_credit_monetary_purchase is the dispatcher that converts a purchase record into a ledger credit. Shapes:
item_kind |
Effect | Status |
|---|---|---|
echoes |
Direct Echo bundle purchase → ledger credit, expires_at from the purchase row |
Shipped — waiting on a checkout provider |
tier |
Subscription period payment → fn_grant_subscription_echoes invocation |
Shipped for PayU prepaid plans (32b1d140e, 9c760bd99); the Wise tier shape still raises |
Provider field is free-form (patreon, wise, payu) — schema is provider-agnostic, downstream consumers don't care which rail funded the credit.
monetary_purchases rows are not cascade-deleted with the user (ON DELETE SET NULL on the user_id reference). The financial record survives the account for tax / chargeback / audit retention (typically 7–10 years depending on jurisdiction).
Payment Orders (provider-agnostic checkout plumbing)
payment_orders is the staging table for in-flight checkouts (47_tables_payment_orders.sql). A user clicks "Buy 1,000☆"; a row gets a code + tracking_token, status pending. The matcher pipeline reconciles Wise / PayU / Patreon webhooks against the order and flips it to matched, which fires fn_credit_monetary_purchase. Wise's PSD2 SCA limitation means the matcher receives webhook events but can't fetch sender references — manual reconciliation in the Wise dashboard is the fallback.
The payment-order layer is what makes adding a new processor a config-and-webhook job rather than a schema migration.
Echo bundles (design target — blocked on processor)
Bundles are the user-facing product for direct Echo purchase. The schema is ready (monetary_purchases.item_kind = 'echoes' + amount_echoes); the checkout UI is blocked on processor acceptance. Once unblocked, bundles are sold via:
| Path | What happens | Used for |
|---|---|---|
| Direct purchase | User clicks "Buy Echoes" → provider checkout → webhook → fn_credit_monetary_purchase → ledger credit |
Buyer wants Echoes for themselves |
| Gift code | Buyer purchases a bundle as a code (or admin mints one) → recipient redeems → ledger credit on recipient's account | Birthday gifts, community rewards, beta compensation, event prizes |
Both paths back to the same SKU catalog. The difference is whether the credit lands on the buyer's account or on a code transferable to someone else.
Pricing function, not fixed tiers. Bundle prices are computed by a function rather than hand-set SKUs. The shape (illustrative, coefficients pending real-cost calibration):
price_usd(echoes) = echoes × base_rate × markup(echoes)
where
base_rate = $0.01 / Echo (face value)
markup(N) = M_high − (M_high − M_low) × clamp((N − N_min) / (N_max − N_min), 0, 1)
M_high ≈ 1.6× (smallest bundle — overhead-heavy)
M_low ≈ 1.05× (largest bundle — committed buyer reward)
N_min, N_max = published bundle bracket
The function asymptotes toward face value but never hits it — every bundle has positive markup. Small bundles carry the highest markup because fixed processor fees + fraud monitoring + (during beta) manual reconciliation don't scale linearly. Large bundles thin margin to reward committed buyers without burning it.
Bundle SKUs are placeholders until the pricing function is calibrated against current LLM provider rates, the chosen processor's fee schedule, and observed token-mix data. Earlier drafts named four price points (Starter / Standard / Large / Mega at $5 / $10 / $25 / $50) — those are not committed values.
Purchased Echoes land in the expiring_other pool (configurable expires_at, typically created_at + 1 year). Promotional bundles can carry shorter expiries via the gift-code echo_expires_in_days field.
Gift-code bundles are always single-use (max_uses = 1) and expire 12 months after issue if unredeemed. Admin-issued codes can override max-uses and expiry.
Spending — per use
Per-use Echoes pay for compute that happens now — a chat message, an embedding call, a lorebook-assistant exchange. The cost is per-call, draining from the spend-order above (daily first).
| Surface | Status |
|---|---|
| Chat messages on paid experiences | Not built — see Paid Experiences. |
AI Tasks (echo_cost column) |
Column shipped, charge path not wired. AiTaskRunner.cs has a TODO(echoes) marker; the runner is expected to call fn_debit_spendable allocate-before / commit-on-success / release-on-error once the wrapper lands. |
| Lorebook Assistant compute | Subject to a Feature Commitment, not a per-use charge — covered below. |
| Platform embeddings | Will be charged per-call from the spendable pool (daily-first drain) once the AI Tasks debit wrapper lands. Inside a paid-experience message, embedding cost is folded into the consolidated fn_charge_paid_message charge instead — see Paid Experiences — Embeddings. |
Per-use charges should always use fn_debit_spendable with intent = 'per_use' so the helper picks the right drain order. Never write a parallel ledger path.
Platform models — design intent
Platform-served LLM models (Featherless and successors) charge users per message at real token usage. This is the dominant per-use surface once paid experiences ship. The design (not built yet):
- Estimate before send: UI computes an estimate from the assembled prompt size + a typical output budget for the chosen model. Shown next to the send button as
~N☆. - Charge on real usage after: post-LLM stage reads
input_tokens/output_tokensfrom the provider response, converts to Echoes via per-token rates × margin, commits the debit. - Estimate-then-reconcile allocation: pre-LLM allocation reserves estimate × buffer (~1.3×); post-LLM commits the actual and releases the rest. Overrun above the buffer is capped by a per-model
max_charge_per_messagesetting; anything past the cap is platform-eaten.
echo_cost = (input_tokens × input_rate + output_tokens × output_rate + embedding_cost)
× margin_multiplier
× echoes_per_dollar
The full design — schema, pipeline, multi-leg fn_charge_paid_message orchestrator, embedding leg, engagement-tip composition — lives in Paid Experiences — Pricing Model. The same per-token columns serve both Anthropic / OpenAI (real rate card) and Featherless (synthesized rate = monthly_cost × margin / expected_tokens). Platform-cost variance is invisible to the user; they see one per-message number.
Outside a paid-experience wrapper, the same primitive applies to standalone hosted-model chat — once the platform_model_costs catalog is seeded and the pipeline wires the charge stages, the user picks a model, sees a per-message estimate, and pays real-usage Echoes against their spendable pool.
Spending — per month (Feature Commitments)
Per-month Echoes pay for capacity — gallery storage, retention windows, profile-editor slots, lorebook-assistant runtime. The user commits Echoes for a 30-day cycle; the cycle auto-renews unless cancelled.
Live catalog (from 20l_tables_echo_feature_catalog.sql):
| Feature | Tier | Echoes/mo |
|---|---|---|
| Gallery storage | 100 MB (free) / 1 GB / 5 GB / 25 GB / Unlimited | 0 / 200 / 400 / 800 / 5,000 |
| Conversation history | 7d × 10 (free) / 30d × 50 / 90d × 100 / Unlimited | 0 / 100 / 300 / 1,000 |
| Lorebook assistant | 7d × 3 sessions (free) / 30d × 10 / 90d × 30 / Unlimited | 0 / 200 / 400 / 2,000 |
| Profile slots | per slot (quantity) | 300 each |
| User statistics | tiered | (see catalog) |
| Creator insights | tiered | live — Off / On (1,000☆), the Creator Analytics + Audience Insights tabs |
Two kind shapes: tiered (pick one of a list) and quantity (buy N units of the same per-unit row — currently used by Profile Slots).
Lifecycle.
- Commit (
POST /api/echoes/features/commit) — Echoes debit the spendable pool, the commitment is locked for 30 days, the user is gated into the chosen tier. - Upgrade (
POST /api/echoes/features/upgrade) — diff-pay to a higher tier mid-cycle. - Queue (
POST /api/echoes/features/queue) — pre-purchase the next cycle at the current tier or a different tier. - Auto-renew toggle (
PATCH /api/echoes/features/{key}/auto-renew) — defaults on. - Release (
DELETE /api/echoes/features/{key}) — within the refund window the commitment reverses cleanly; after the window it just disables auto-renew and runs out the cycle.
A grace-period sweep service expires lapsed commitments and dispatches notifications. Detailed flow in docs-internal/architecture/billing/SUBSCRIPTION_REFACTOR.md (slices 2E.1–2E.5).
Tipping Creators
Tipping is the only peer-to-peer Echo flow on the platform. Users tip creators directly; the creator receives the full tip amount. There is no general user-to-user transfer endpoint — open peer-to-peer is a laundering vector, and constraining the flow to a creator-recipient gate is what makes it safe. Gift codes are the other channel for moving Echoes between people, but they're minted from the platform, not transferred between user wallets.
This is what completes the economy loop: users earn via tasks and subscriptions → users tip creators they enjoy → creators accumulate income → (eventually) creators withdraw as USD via the cashout flow.
Tipping shipped 2026-05-09 in two flavors — one-time and engagement (per-message standing order).
Tip mechanics
| Field | Value | Notes |
|---|---|---|
| Tip range (one-time) | Min/max configurable via tips.send.daily_max and per-tip caps |
Lower bound prevents micro-spam; upper bound reduces fraud blast radius. |
| Tip range (engagement) | 1–10☆ per assistant message | Stored on engagement_tip_preferences.rate_per_message with a CHECK constraint. |
| Platform fee | 0% (no fee) | Tipping is fee-free. The platform's revenue from this flow comes structurally from the cashout spread when income converts to USD. May reintroduce a small fee later if data warrants it. |
| Creator share | 100% | Credited to recipient's persistent pool via fn_transfer_spendable. |
| Eligibility | Both users have verified email; tipper not banned; recipient owns the entity being tipped against | Email verification gates multi-account tip-laundering. |
| Self-tip | Disallowed | Hard rejection in fn_send_tip_batch and fn_charge_engagement_tips. |
| Daily caps | tips.send.daily_max (per sender) + tips.receive.daily_max (per recipient) |
Anti-money-laundering. Both configurable per platform setting. |
| Source restrictions | Tippers spend from sub + expiring_other + persistent only. daily cannot fund tips. |
Closes the daily-task-farming → creator-tip → cashout chain. |
Where tipping appears
Tip surfaces sit where the user is consuming a creator's work, so the action is contextually grounded:
| Surface | Tip target |
|---|---|
| Public character / mode / lorebook / package page | The entity's owner |
| Creator profile | The creator |
| Conversation context (chat header) | The character + mode owners (engagement tip per (character, mode)) |
| Inside a paid experience | The package's creator, on top of the per-message charge they're already paying |
Tipping inside a paid experience deserves the special note: the user is already paying the creator per message via the paid-experience charge. A tip there is the "you went above and beyond, here's extra" gesture — explicitly distinct from the metered cost. Both fire as legs of the same multi-leg fn_charge_paid_message call so the user sees one consolidated debit.
One-time tip flow
1. User clicks "Tip [creator]" on a creator surface.
2. Tip modal opens with:
- Slider / preset amounts
- Optional message (length-capped, plain text, content-moderated)
- "Available to tip: X☆" (computed from sub + expiring_other + persistent; excludes daily)
- Anonymity toggle
3. User confirms → fn_send_tip_batch(sender, legs[]):
- Validates eligibility, daily caps, spendable balance
- Acquires per-user advisory lock
- For each leg: paired debit (sender) + credit (recipient via fn_transfer_spendable)
- Mid-batch insufficient balance raises SQLSTATE 40001 (no partial commit)
4. Recipient receives an in-app notification (and optional email) with the message.
5. Tip appears in both sides' transaction history.
Anonymous tips mask sender_user_id to NULL in the recipient-facing DTO. The platform retains the full audit trail — anonymity is a recipient-display concern, not a record-keeping one. Refund notifications also scrub the tip_id for anonymous recipients to prevent cross-reference de-anonymization.
Engagement tip flow (per-message standing order)
1. User opens the engagement bar on a conversation (character + mode context).
2. Sets a per-message rate (1–10☆); engagement_tip_preferences row upserted.
3. is_active = TRUE, paused_reason = NULL.
(every subsequent assistant message)
4. EngagementChargeStage (IPostLlmStage at Order=160) reads the active preference.
5. Pre-checks the partial unique index on (user_id, message_id) for idempotency.
6. fn_charge_engagement_tips: debit sender, credit each recipient. Multi-leg outcome.
7. On insufficient balance / creator opt-out / entity unavailable: skip leg, set
paused_reason on the preference, surface to the user. No retroactive charge.
8. User must explicitly reactivate (paused state never auto-resumes).
The engagement-tip pattern is the canonical "consolidated per-message charge" pattern in the codebase — see also fn_charge_paid_message in Paid Experiences, modeled on the same shape.
Creator tip surfaces
Creators see incoming tips in a dedicated /echoes/tips view:
- Received — chronological list with sender handle (or "Anonymous"), amount, message, timestamp.
- Aggregate stats — week / month / lifetime totals; top supporters (mutual-opt-in only); most-tipped content.
- Engagement standing orders received — active opt-ins across the creator's content, with mute / unmute controls on a per-(viewer, entity) basis via
creator_tip_settings.
The tip notification carries the message in plain text; tipper anonymity is preserved if set.
Cashability of received tips
Today: not cashable. Tip income lands in persistent and is spendable like any other persistent Echo (commit to features, send onward as another tip, fund paid-experience messages).
When cashout ships, tips will likely not be cashable — they're an appreciation channel, not a commercial channel. Paid-experience earnings will be the cashable channel. The split keeps the AML model simple: cashout requires a transactional relationship (someone paid for a creator's experience), not just a goodwill flow (someone tipped a creator they liked). The cooling-period machinery, KYC thresholds, and tipper-diversity checks documented in AML Protections all assume cashout is bounded to the commercial channel.
Anti-abuse for tipping
| Control | Detail |
|---|---|
| Verified email both sides | Same gate as task earning. |
| Outgoing daily cap | tips.send.daily_max setting. |
| Per-recipient cap | tips.receive.daily_max — caps Echoes a single recipient can receive in a UTC day. Stops bot-driven inflation of one creator's tip stats. |
| Banned user gate | Banned users can neither tip nor receive. |
| Self-tip block | Hard rejection in fn_send_tip_batch / fn_charge_engagement_tips. |
| Tip message moderation | Tip messages route through the content-check pipeline before delivery. Egregious messages blocked at send time; borderline messages flag the tip for review (the Echoes still transfer — moderation operates on the message, not the financial transfer). |
| Reversal window | None for the tipper. Admin can refund a tip via AdminEchoTipsEndpoints (POST /api/admin/echoes/tips/{tipId}/refund, gated on AdminArea.Billing × Manage) in egregious cases (fraud, hijacked account). Refund inserts paired clawback rows. |
| Engagement auto-pause | A failing engagement leg pauses the standing order with a paused_reason. Reactivation is explicit by the user — no silent re-arm. |
What tipping isn't
- Not a subscription. One-time tips are one-shot; engagement tips are per-message standing orders, not monthly recurring. A recurring "monthly subscription to a creator" is a future extension.
- Not laundering. The verified-email gate, daily and per-recipient caps, source-pool restriction (no
daily), audit trail inecho_transactions, and (future) cashout spread + cooling + KYC + tipper diversity together make tipping a poor laundering vector. Tips being eventually-cashable is acknowledged — the layered controls exist precisely because of that. - Not a way to bypass paid experiences. A free package stays free even if heavily tipped. A paid package's per-message charge is non-negotiable; tips are additive.
- Not anonymous to the platform. "Anonymous" hides the tipper from the creator. The audit trail is intact for fraud and compliance.
Full operational reference (mechanics, error vocabulary, anomaly detection details): docs-internal/architecture/billing/CREATOR_TIPS.md.
Cashout (Not Built)
Cashout is the design north for "creator earns Echoes → converts to USD." Not built. The shape this will take:
| Concept | Design intent |
|---|---|
| Cashable transactions | Specific credit types (paid-experience earnings primarily) are flagged as cashable. Tips and bundle Echoes and subscription grants are not cashable. |
| Verified creator gate | Existing verified_creators table gates eligibility. |
| Cooling period | 14 days from earn → cashable. Buffer for refunds and disputes. |
| Monthly caps | Tiered by KYC level. Anonymous = low cap; KYC-verified = high cap. |
| Payout rail | Wise manual is the realistic v1. Hosted USD payout depends on processor situation. |
| Minimum payout | TBD — probably $50 equivalent to keep transfer fees as a small percentage. |
Open mechanic decisions before this can ship:
- Cashable as a flag or as a pool? Leaning flag — cleaner ledger semantics, no need for a fifth pool decomposition. Cashable balance =
SUM(amount) WHERE cashable = TRUE AND status = 'committed' AND created_at < NOW() - INTERVAL '14 days'. - Refund / chargeback handling on cashable income. If a user gets a refund on a paid-experience message after the creator already cashed out, do we claw back from the creator or eat it? Design says eat it within reason (creators shouldn't be exposed to chargeback risk on past income), pursue at the platform level if patterns indicate abuse.
- KYC tiering. Reuse whichever provider we eventually integrate for hosted checkout — KYC done once, applies to both Echo purchase and cashout.
This is v2+ work. v1 of paid experiences ships with earnings accumulating in persistent and a Wise-manual "request payout" form for admins to fulfill on a case-by-case basis.
AML Protections
The Echo economy is designed to be a poor laundering vector by construction. Controls in one place:
| Control | Where it's enforced |
|---|---|
| No general peer-to-peer transfer | There is no endpoint that moves Echoes between arbitrary users. The only peer-to-peer flows are fn_send_tip_batch and fn_charge_engagement_tips (functions/41j_* / 41k_*) — both gate on the recipient being an owner of a real entity (character / mode / lorebook / package / creator profile). |
| Daily Echoes are consumption-only | fn_debit_spendable excludes the daily pool when intent ∈ {tip, commitment}. Daily can only fund per-use compute. Closes the daily-task → tip → cashout chain. |
| Subscription grants are non-tippable today | sub-pool drain is allowed for tips (so paying subscribers can tip with their grant), but cashout of received tips is not enabled — see Cashout. |
| Cashout will require Verified Creator + KYC | The verified_creators table exists today as the trust gate; KYC tiering is design-only. |
| Daily caps on tip outflow | tips.send.daily_max setting (read by fn_get_user_tip_limit_int) caps total Echoes a sender can move per UTC day. |
| Anonymity is a data-layer concern | Anonymous tips mask sender_user_id to NULL in recipient DTOs and scrub tip_id from refund notifications. No existence leak. |
| Audit trail | Every Echo movement is a row in echo_transactions with transaction_type, reference_type, reference_id, metadata. Permanent record for fraud investigation. Composite PK (id, created_at) survives partition retention rotation. |
| Verified email gates earning | fn_user_has_verified_email check in fn_claim_daily_task — single gate against multi-account daily-task farming. |
| Beta-state manual processing | While Patreon is the only automated rail and Wise is manual, every USD inflow has human eyes-on review. Friction, not feature, but additional protection during the pre-checkout period. |
Future controls (design target, not built):
| Future control | Notes |
|---|---|
| 14-day cooling on tipped Echoes for cashout | Buffer against chargebacks and fraud claw-backs. Only relevant once cashout ships and only if tips become cashable. |
| KYC tiering | ID + address verification at one monthly cumulative cashout threshold, source-of-funds attestation at a higher one. Tier table referenced by the cashout function. |
| Anomaly review routing | Fast-grown balance, single-tipper concentration, young-account funding, IP / device clustering → routes flagged cashouts to manual review rather than auto-paying. |
| Tipper diversity requirement | Cashouts where one tipper accounts for >80% of the eligible balance route to review. Same data-layer query as anomaly routing. |
| Cashout spread as structural cash-positive guarantee | Echoes credit at the buyer's price; cash out at a lower rate (e.g. 0.7× face value). Spread covers processor fees + platform margin and structurally prevents profitable recycling. |
The platform isn't a money-services business — it's a creative-writing platform with an in-app currency and a constrained creator-payout flow. These controls are sized for that scope, not for general remittance.
Refunds & Chargebacks
Two ways a purchase reverses. The platform's policy on each:
Refunds (platform-controlled)
Default policy: no refunds. The ToS states bundle purchases and subscription payments are non-refundable. This is the default because purchased Echoes can be spent on real per-message LLM costs that can't be unspent.
Exception: admin discretion via ticket. Legitimate or legal reasons — purchase made by a minor, fraud on the user's own account, regulatory requirement in jurisdiction, billing error on our side — get refunds case-by-case. Admins issue refunds via the admin billing console; no self-service refund button.
Mechanics:
- Update
monetary_purchases.status = 'refunded', setrefunded_at, the admin's user id, andrefund_reason. - Insert a negative ledger row:
transaction_type = 'refund',amountmatching the original credit,reference_type = 'monetary_purchase',reference_idpointing to the original. - The clawback draws against the same pool the original credit landed in (
expiring_otherfor bundles,subfor subscription grants). - If the user has already spent the Echoes, the clawback pushes the wallet negative — see Wallet Lifecycle — Negative balance.
- The account is not banned — this is a platform decision, not a user violation.
- Cash is returned via the original payment method using the provider's refund API.
Chargebacks (bank-controlled)
The ToS prohibits chargebacks — users agree to seek refunds via support before disputing charges with their bank. The ToS can't legally stop the bank from processing a chargeback. If a user disputes and the bank approves, the bank pulls the money regardless. The platform can submit evidence; the bank decides.
When a chargeback succeeds:
- Webhook fires (or platform observes the bank reversal directly on the rail).
- Update
monetary_purchases.status = 'chargebacked', setchargebacked_at, store the chargeback id and reason code. - Insert a negative ledger row:
transaction_type = 'chargeback',amountmatching the original credit. - Mark the user
banned_since = NOW(), ban reasonchargeback_violation. Per ToS, chargebacking is grounds for immediate termination. - All active Feature Commitments on the account move to
lapsed. - Any in-flight cashout requests are voided.
- Wallet may go negative for the spent portion.
When a chargeback is disputed and the platform wins: reimbursement lands, no clawback row inserted, monetary_purchases.status resolves to succeeded, the chargeback fee is platform-absorbed, the user is not banned for a dispute that didn't go through.
Platform exposure on a successful chargeback:
- LLM costs already incurred on spent Echoes — real money out, not recoverable.
- Provider chargeback fee (typically $15-25). Recorded on
monetary_purchases.chargeback_fee_centsfor tax expense tracking. - Operational cost of the dispute (admin time, evidence gathering).
- Reputational cost on the processor side — high chargeback ratio can get a merchant dropped. Tracking and keeping it low is itself a platform health metric.
Gift-code chargeback edge case. Buyer A buys a gift-code bundle and then chargebacks; the cash leaves the platform but the Echoes may already be on recipient B's wallet:
- A's account is banned per the chargeback rule (cardholder is responsible for the dispute).
- A's wallet may have nothing to claw back from. A's wallet goes negative for the full face value.
- B is not banned — B did nothing wrong, just received and spent Echoes from a code given in good faith.
- The platform absorbs the LLM-cost loss for whatever B has already spent. Known fraud-cost line item.
Refunds for subscription grants & Feature Commitments
- Subscription grants (Patreon recurring payment, future hosted-checkout): mirror the bundle-refund flow on the
subscription_grantledger row. - Feature Commitments (
feature_commitmentdebits): paid in Echoes, not USD. Nothing to refund or chargeback at the commitment level itself — the commitment release flow (within the refund window) handles user-initiated reversal. If the underlying Echoes that funded the commitment came from a chargebacked purchase, the chain ripples through the wallet's normal negative-balance handling.
Wallet Lifecycle
No wallet table
A user's "wallet" is the sum of their echo_transactions. A new user with zero transactions has a balance of 0 — the first daily-budget grant is their first transaction, inserted lazily on first balance check or first feature use.
Daily budget initialization
On login (or first balance check of the day), AuthService calls fn_ensure_daily_budget(user_id):
0. Check: is the account eligible? (a verified email address, not banned — otherwise: no-op, 0)
1. Check: does a daily_budget grant exist for TODAY? (unique index makes this fast)
2. If not: INSERT (+amount, type='daily_budget', expires_at=TODAY, status='committed')
3. If yes: no-op
The daily budget goes only to an account with a verified email address. An account without one sees no daily Echoes, and a chat turn it can't pay for tells it to verify its email, with a button to do it.
Idempotent — safe to call on every login, every balance check, every allocation attempt. Per-user advisory lock (hashtext('echo_budget')) serializes.
Account deletion
echo_transactions rows are cascade-deleted with the user (ON DELETE CASCADE). No orphaned ledger rows.
monetary_purchases rows are not cascade-deleted — user_id goes to NULL on user deletion (ON DELETE SET NULL), preserving the row for tax / chargeback / audit retention.
Negative balance
A user's wallet can go negative under two scenarios: a refund processed after Echoes have been spent, or a chargeback honored after Echoes have been spent.
When a balance is negative:
- All future credits (task rewards, gift codes, subscription grants, anything) offset the negative balance first before becoming spendable.
- Every spend path requires non-negative spendable balance. The user cannot tip, commit to features, or send paid-experience messages until the balance recovers.
- The platform does not pursue affirmative collection. No debt collectors, no legal action. Negative balance is purely a denial-of-future-services mechanism.
- For banned accounts (chargeback case), negative balance is moot — the account is locked anyway.
- For non-banned accounts (refund case), the user can earn back to zero via daily tasks if they choose. Most won't bother and abandon the account.
Data Model
The schema is large; this section is pointers, not DDL.
Core ledger
echo_transactions(20d_tables_echo_ledger.sql) — append-only, RANGE-partitioned daily. Composite PK(id, created_at)because the partition key has to be in the unique constraint. Columns:user_id,transaction_type,amount(signed),balance_after(nullable — snapshot only),status(committed/allocated/released),expires_at,drain_pool(hint for the helpers),reference_type/reference_id,metadata(JSONB).echo_daily_balance_snapshots— persistent-only closing balance per user per day. Read path uses snapshot + transactions since snapshot.echo_daily_pool_snapshots— per-bucket closing balance for the 4-pool decomposition.
Allocation lifecycle
echo_transactions.status ∈ {committed, allocated, released}:
allocated— reserved byfn_debit_spendablepre-LLM. Counts as debited for balance reads.committed— finalized post-LLM. Permanent.released— rolled back (LLM failure, validation failure post-allocate). Excluded from balance.
Snapshot does NOT include allocated rows — they're transient and the snapshot is a daily-stable artifact.
Daily tasks
daily_tasks(20e_tables_echo_tasks.sql) — task definitions (seed listed above).daily_task_completions— claim history.transaction_idis intentionally not FK'd (may dangle after partition retention drops).
Subscriptions
subscription_tiers(20_tables_subscriptions.sql) — tier definitions.subscription_pricing_config(20j_subscription_refactor.sql) — formula JSON per tier (breakpoints today, can grow).user_subscriptions— current subscription state per user.subscription_credit_queue(48_tables_subscription_credits.sql) — queued pre-purchased passes.
Feature Commitments
user_feature_commitments(44_tables_user_feature_commitments.sql) — per-user, per-feature lock.echo_features+echo_feature_tiers(20l_tables_echo_feature_catalog.sql) — the catalog.
Tipping
echo_tips(20m_tables_echo_tips.sql) — one-time tip records.engagement_tips(20n_tables_engagement_tips.sql) — per-message standing orders.creator_tip_settings(20o_tables_creator_tip_settings.sql) — creator opt-in / opt-out per context.
Monetary purchase plumbing
monetary_purchases(20f_tables_monetary_purchases.sql) — durable purchase audit (provider-agnostic).payment_orders(47_tables_payment_orders.sql) — in-flight checkout staging.
Gift codes
gift_codes(20b_tables_gift_codes.sql) — code definitions (tier / echo / mixed).gift_code_redemptions— claim history.
Service Architecture
Echo economy logic lives in AuthService (/api/echoes/*). AuthService also owns subscriptions, profiles, billing — Echoes are the in-platform currency layer alongside whichever payment provider is currently active.
Other services (ServerAPI, AdminAPI, DiscordBot) interact through the database:
- Direct DB: services that share the Postgres role (all of them today) can call the Echo functions directly —
fn_debit_spendable,fn_charge_engagement_tips, etc. — for in-pipeline work. This is the dominant path.EngagementChargeStagein ServerAPI's chat pipeline callsfn_charge_engagement_tipsdirectly without going through AuthService HTTP. - No internal HTTP for chat progress. The chat-milestone tasks read their progress on demand:
fn_get_chat_progress_todaycounts the qualifying messages a user sent today (UTC) straight fromweb_messages, so the chat pipeline notifies nothing. The internalchat-progressendpoint this section once described was deleted.
Batch principle for internal calls. One user action = one allocation call. If a user action involves multiple Echo costs (e.g. a paid-experience message that also triggers an embedding and an engagement tip), the cost legs batch into a single multi-leg charge (the fn_charge_paid_message / fn_charge_engagement_tips shape). One advisory lock, one balance check, one outcome row.
Earlier designs sketched POST /api/internal/echoes/{allocate,commit,release} as separate internal endpoints. Those were never built; allocation is owned by whichever pipeline stage is doing the work, calling fn_debit_spendable directly. The internal HTTP surface is intentionally minimal.
API Surface (Shipped)
Echoes endpoints live on the AuthService (despite the name — AuthService now fronts user-scoped APIs including the Echo economy).
Balance & tasks (EchoesEndpoints.cs):
GET /api/echoes/balance→{ available, spendingFirst, resetsAt, claimableTaskCount }GET /api/echoes/tasks→ catalog + per-user statePOST /api/echoes/tasks/{key}/claimGET /api/echoes/transactions→ paginated historyGET /api/echoes/catalog→ feature catalog + tip-fee shape
Feature Commitments (FeatureCommitmentEndpoints.cs):
GET /api/echoes/features— bundled view (catalog + state + summary)POST /api/echoes/features/commit//upgrade//queuePATCH /api/echoes/features/{key}/auto-renewDELETE /api/echoes/features/{key}— release / refund-window reversal
Tips:
EchoTipsEndpoints.cs— one-time tips (send / list received / list sent)EngagementTipsEndpoints.cs— engagement standing orders (CRUD)CreatorTipSettingsEndpoints.cs— creator-side opt-in / mute
Internal: none. Chat-milestone progress is derived on demand by fn_get_chat_progress_today.
Webhook entry points (Patreon / Wise): documented in the respective integration docs. They terminate in fn_credit_monetary_purchase.
Cross-Cutting Rules
UTC pinning
All Echo ledger functions must SET LOCAL timezone = 'UTC'. Any new function that joins echo_transactions, daily_*, or ai_task_runs must do the same — CURRENT_DATE, partition routing, and "daily" idempotency keys all depend on consistent UTC reads.
fn_get_feature_usage_summary must be VOLATILE, not STABLE — SET LOCAL is not allowed in STABLE functions. This is a known quirk; don't try to optimize it back.
Advisory locks
Per-user serialization for ledger writes:
| Operation | Lock signature |
|---|---|
| Daily budget refresh | pg_advisory_xact_lock(user_id, hashtext('echo_budget')) |
| Task claim | pg_advisory_xact_lock(user_id, hashtext('echo_task_claim')) |
| Subscription grant | pg_advisory_xact_lock(user_id, hashtext('sub_echo_grant')) |
Two-argument form — the user_id is the second key, so the lock is per-user, not global.
Serialization
Results.Ok(record) boxes to object on .NET 10. Typed JSONB endpoints must use WriteAsJsonAsync<T> with explicit camelCase options — see the project root CLAUDE.md note.
Echo-spend pattern
Every new spend feature must use the canonical primitives (fn_debit_spendable / fn_debit_persistent / fn_transfer_spendable) and return EchoSpendOutcome (single action) or EchoSpendBatchOutcome (multi-leg). Error vocabulary is enumerated in EchoSpendErrorCode (mirrored to TypeScript at shared/src/types/echoSpend.ts). Full pattern in docs-internal/architecture/billing/ECHO_SPEND_PATTERN.md.
Income, Expense & Reconciliation
For tax filing, the platform needs two numbers per period: income (cash in) and expense (cash out). Most other accounting concepts in this document — internal Echo liability, deferred revenue, per-transaction fee allocation — are useful for operational sanity-checking but are not tax requirements for a beta-stage platform on cash-basis accounting.
Tax-simple view
Cash-basis accounting: income is what hits the bank, expense is what leaves.
| Source / use | Where it's tracked |
|---|---|
| Income: provider settlements (Patreon, Wise, future PayU, etc.) | Bank-side; cross-referenced to monetary_purchases.provider_settlement_id where available. |
| Expense: LLM API bills | Outside the Echo ledger (provider invoices). |
| Expense: hosting & infrastructure | Outside the ledger (Railway, Cloudflare). |
| Expense: cashout / payout fees | Future — once payouts ship, transfer fees recorded against the payout row. |
| Expense: refund cash sent back | monetary_purchases.refund_cash_amount_cents on the refunded row. |
| Expense: chargeback amounts + chargeback fees | monetary_purchases.chargeback_cash_amount_cents + chargeback_fee_cents on the chargebacked row. |
Sum income, sum expense, subtract. For tax filing on cash basis, that's it.
Settlement reconciliation
Most payment providers (Patreon, Subscribestar, future PayU) net their fees at settlement time, not per-transaction. We don't see the fee on each user's purchase — we see the deposit when it lands. A payment_provider_settlements table is the future design target for this; not built today. Until it ships, settlement reconciliation is manual against the provider's payout statements.
For Patreon specifically: their "fee" combines platform cut and underlying processor costs. We treat the whole gross-vs-net delta as a single combined fee for accounting simplicity. Breaking it down further is a "nice to have" once Patreon's API gives us itemized data — not a tax requirement.
Internal Echo liability (operational sanity)
The platform has an outstanding obligation to deliver services-or-equivalent for every unredeemed purchased Echo. This is not income (already counted as cash-in). It's a sanity metric: "how much do we owe users in unredeemed purchases?"
-- Outstanding Echo liability snapshot (illustrative)
SELECT SUM(amount) AS face_value_outstanding,
SUM(amount) * 0.01 AS dollar_value_outstanding
FROM echo_transactions
WHERE transaction_type IN ('purchase', 'subscription_grant')
AND status = 'committed'
AND (expires_at IS NULL OR expires_at >= CURRENT_DATE);
Why we track it: don't oversell. If outstanding liability exceeds cash on hand × safety multiplier, we're over-promising. If a wave of redemptions hits the same day (everyone commits to features), compute costs spike. Liability tracking warns about that exposure.
Why it's not a tax thing (today): cash-basis filing recognizes revenue when cash is received, not when services are delivered. Deferred-revenue accounting is accrual-basis, required only for audited GAAP-compliant entities (US threshold ~$25M average gross receipts). At beta scale, document the query, check occasionally as a gut-check, don't wire it into the income statement.
When it becomes a tax thing: outside investment with reporting requirements, revenue crossing the accrual threshold, or a formal audit. The data is already in the ledger; we'd just start using it differently.
Per-transaction cost tracking (optional, for analytics)
For product analytics — "what's our gross margin on Sonnet messages?", "is Premium still profitable?" — we can record actual cash cost on individual debit rows. Not built. Optional schema:
ALTER TABLE echo_transactions ADD COLUMN cost_amount_cents INTEGER;
COMMENT ON COLUMN echo_transactions.cost_amount_cents IS
'Real cash cost incurred by this transaction. Populated on rows where per-row cost is known (typically platform_model debits — provider returns token cost in API response). NULL elsewhere. Informational only; not used for tax recognition.';
For a paid-message debit committed at 8☆ where Anthropic charged $0.045: amount = -8, cost_amount_cents = 5 (rounded). Monthly aggregate gives gross margin by model. Not a tax line item — the tax filing uses provider invoices for the LLM expense line. This is product analytics infrastructure.
Admin Tools
The admin billing console is shipped (AdminBillingEndpoints.cs). Surfaces:
- Gift codes — generate (single or batch up to 500), view redemption history, revoke. Codes carry tier and / or Echo grants in one entity (see Gift codes).
- Subscriptions — paginated table with search, filter by tier / status / source, sort. Admin can grant (active or grandfathered) and revoke subscriptions.
- Wallets — per-user Echo balance, detail modal with transaction history.
- Linked accounts — Patreon and Subscribestar identities linked to platform users; sync queue and webhook event log.
- Patreon sync queue —
IPatreonLinkRepositoryregistered in AdminAPI DI; admin can replay webhook events.
The admin dashboard home page includes a Billing section with the headline metrics (active subscribers, active gift codes, total redemptions, etc.) alongside Users / Characters / Conversations / Messages.
Task management
Tasks are defined in daily_tasks. Admins update directly:
- Toggle
is_activeto enable / disable a task without deletion. - Update
base_echoes_rewardto retune a reward (affects future claims only — past claims are immutable on the ledger). - INSERT a new task — no code deployment needed for threshold-based tasks; the claim flow is data-driven.
No dedicated UI for task CRUD in v1. Direct database updates or a thin admin API endpoint suffice.
Economy monitoring
Key queries the admin console surfaces (or could surface) from echo_transactions:
| Metric | Query shape | Purpose |
|---|---|---|
| Total persistent Echoes outstanding | SUM(amount) over expires_at IS NULL AND status='committed' |
Inflation monitoring |
| Daily Echoes earned (tasks) | SUM(amount) over transaction_type='task_reward' AND created_at >= today |
Earning rate |
| Daily Echoes spent | ABS(SUM(amount)) over commitment / paid-message / per-use debit types, today |
Spending rate |
| Net daily flow | Earned − Spent | Economy health (trend toward equilibrium) |
| Users with zero persistent balance | Per-user SUM(amount) ≤ 0 over persistent rows |
Engagement risk |
| Daily-budget utilization | ABS(SUM(debits)) / grant from today's expires_at = CURRENT_DATE rows |
Is the daily budget calibrated? |
| Stale allocations | COUNT over status='allocated' AND created_at < NOW() - INTERVAL '1 hour' |
Stuck allocations needing cleanup |
Configurable settings
Feature costs (catalog tier prices), daily budget amount, tip caps, and margin multiplier are stored as platform settings:
| Setting key | Used by | Notes |
|---|---|---|
echoes.daily_expiring_budget |
fn_ensure_daily_budget |
Default 100. Per-user override possible via the function's p_amount parameter. |
tips.send.daily_max |
fn_get_user_tip_limit_int |
Cap on total Echoes a sender can move per UTC day. |
tips.receive.daily_max |
fn_get_user_tip_limit_int |
Cap on Echoes a single recipient can receive per UTC day. |
echoes.margin_multiplier (future) |
Paid-experience pricing math | Default 1.5×. Tunable when provider rates shift. |
Task rewards live in daily_tasks.base_echoes_reward, not in settings — admins update the table directly. Feature catalog prices live in echo_feature_tiers.echo_cost.
Setting changes take effect within the in-memory cache TTL (5 min for the platform-settings cache).
Client UI
The shipped UI lives in clientConsole. This section documents the surfaces and what each one shows.
Header balance pill
The user's available Echo balance is always visible in the app header (EchoBalanceIndicator):
┌─ Header ──────────────────────────────────────────────────┐
│ Echo of Dreams [Chat] [Hub] [Vault] 187 ☆ [☰] │
└────────────────────────────────────────────────────────────┘
When balance changes, a brief animation shows the delta. Clicking the pill opens a popover showing what the balance consists of:
┌─ 187 ☆ Available ─────────────────────────────────────────┐
│ │
│ 87 ☆ Wallet (persistent) does not expire │
│ 100 ☆ Daily Budget resets in 4h 23m │
│ │
│ ───────────────────────────────────────────────────────── │
│ ● 2 tasks ready to claim [ Go to tasks ] │
│ ● 0 pending feature commitments │
└────────────────────────────────────────────────────────────┘
Each entry in the expiring section becomes a line with its own countdown. Debits reduce the persistent line first if intent is persistent-only, or daily first if per-use — the popover matches the actual drain order.
Echoes page (/echoes)
The main currency surface. Three subsections:
- Balance summary — same numbers as the header pill, in card form with breakdown.
- Daily tasks panel — recurring tasks (login + chat milestones folded into a single stepped card) and one-time tasks. Each task row shows progress / reward / claim state.
- Recent transactions — paginated ledger view with
All / Credits + / Debits −filter tabs and sign-aware empty states.
Task panel sketch:
┌─ Daily Tasks ─────────────────────────────────────────────┐
│ │
│ Today: 15 / 25 ☆ earned Resets in 4h 23m │
│ ████████████░░░░░ │
│ │
│ ┌─ Recurring ─────────────────────────────────────────┐ │
│ │ ✓ Daily Login +10 ☆ [Claimed] │ │
│ │ ▣ Chat Milestones (3 stages) │ │
│ │ ✓ 10 messages +5 ☆ [Claimed] │ │
│ │ ◐ 20 messages +5 ☆ 14/20 │ │
│ │ ○ 30 messages +5 ☆ 14/30 │ │
│ └──────────────────────────────────────────────────────┘ │
│ │
│ ┌─ Achievements (one-time) ───────────────────────────┐ │
│ │ ◐ Favorite Content +3 ☆ 4/10 │ │
│ │ ◐ Bookmark Content +3 ☆ 7/10 │ │
│ │ ✓ Complete Your Bio +10 ☆ [Done] │ │
│ │ ○ Personalize Identity +10 ☆ [Start] │ │
│ └──────────────────────────────────────────────────────┘ │
│ │
│ Available: 187 ☆ [ Buy Echoes ] │
└────────────────────────────────────────────────────────────┘
Reset countdown uses the resetsAt field from the balance API. Claim buttons transition to success-variant "Claimed today" to keep the slot footprint stable. Claim success refreshes balance + tasks + transactions atomically; one toast per outcome (success / validation-fail / network-fail).
Milestone notifications
When a chat milestone threshold is reached, a subtle toast surfaces:
┌──────────────────────────────────────────┐
│ ☆ Chat milestone reached! +5 Echoes │
│ [Claim] │
└──────────────────────────────────────────┘
Chat milestones are not auto-claimed. The user clicks "Claim" to receive Echoes — makes the reward feel deliberate rather than passive. Unclaimed milestones remain claimable until UTC midnight reset.
Manage Features page (/echoes/features)
The Feature Commitments UI — see Spending — per month. Surfaces the catalog, the user's current commitments, queued next-cycle changes, per-feature auto-renew toggles, and release / refund flow.
Cost indicators (when spending lands)
Per-use spending surfaces (send button on a paid-experience message, embedding-generate button, lorebook-assistant send) show an Echo estimate next to the action. For real-token-cost surfaces, the estimate is labeled "~N☆" and clarifies "charged on real usage." Insufficient-balance states surface "Complete Tasks" / "Buy Echoes" prompts inline rather than blocking the page.
┌─ Chat Input (paid experience) ─────────────────────────────┐
│ [Message input...] │
│ │
│ ~8☆/msg · Mistral Nemo (hosted) · Available: 187☆ │
│ [ Send (~8☆) ] │
└─────────────────────────────────────────────────────────────┘
The cost-indicator pattern is consistent across surfaces: estimate, model identity, available balance, send button echoing the estimate. After the response lands, the receipt shows the actual charge ("Charged 7☆ · 4,820 tokens in / 312 out").
Tip modal
Reached from creator surfaces (character page, mode page, lorebook page, package page, creator profile, conversation header). Shows preset amounts, optional message, anonymity toggle, and the available-to-tip computation (excludes daily).
Transaction history page
/echoes includes a paginated transactions list with filter tabs (All / Credits + / Debits −). Each row shows: type (daily_budget, task_reward, purchase, tip_sent, tip_received, feature_commitment, etc.), amount with sign, description, reference (linked when meaningful), timestamp.
Implementation notes
Only shared components: Card, Button, Badge, Section, ProgressBar, MiniPagination, Tabs, HeaderPopover, EmptyState, LoadingSpinner, ContentWrapper. No local UI primitives. State managed via Zustand stores (echoBalanceStore, etc.). API calls via the typed clients in clientConsole/src/api/echoes.ts.
Implementation Phases
Five phases. Phases 1–2 and most of Phase 4 are shipped; Phase 3 is partial; Phase 5 (tipping) shipped 2026-05-09. The order matters because each phase establishes infrastructure the next phase needs.
Phase 1 — Earning & Accumulating ✅ shipped
Users earn and see Echoes. Nothing costs Echoes yet — this lets the economy build a user base with real balances before flipping the spending switch.
echo_transactionspartitioned daily,echo_daily_balance_snapshots,echo_daily_pool_snapshots(20d_tables_echo_ledger.sql,41a_echo_ledger_functions.sql).- Daily budget —
fn_ensure_daily_budgetlazy grant. - Gift codes with Echo extensions (
echo_amount,echo_expires_in_days,echo_labelongift_codes). - Daily tasks (12 seeded), per-user advisory lock claim flow, chat progress derived on-demand from
web_messages. - AuthService Echo endpoints (
/api/echoes/balance | /tasks | /transactions). - Client UI: header balance pill + popover,
/echoespage with task panel and transaction history. - Admin economy dashboard on the Billing Overview tab.
- Partition maintenance background service.
What users see today: Dreamer logs in → sees 100☆ daily budget in the header pill. Can claim daily_login and the three chat_milestone_* tasks once they've sent enough qualifying messages. One-time tasks claimable when precondition is met. Gift-code redemption credits Echoes per the code's config. Balance / expiring / history all work.
Phase 2 — Purchasing Echoes (shipped, Beta — behind the Card rail switch)
Users can buy Echo bundles with real money.
- ✅ Durable purchase record —
monetary_purchases(20f_tables_monetary_purchases.sql), idempotent webhook reconciliation via(provider, provider_transaction_id)unique constraint, never partition-dropped. - ✅ Payment order staging —
payment_orders(47_tables_payment_orders.sql) for in-flight checkouts. - ✅ Patreon webhook → subscription activation + monthly Echo grant.
- ✅ Self-service Echo bundle checkout — shipped (Beta) (PayU slices 0–1c, 2026-09-28:
1e838a9a,13f66d98,b6be59a8,f1e44bc1; price check4cf75f5a7). The checkout lives in the account console (/billing/checkout, Buy Echoes on the Echoes and Billing pages) and renders only where the Card rail is open to the account. Seedocs-internal/architecture/billing/PAYU_INTEGRATION.md. - ✅ Bundle catalog UI — the account-console checkout's bundle picker (not on the writing client's pricing page).
- ⏳ User-purchased gift codes (mint a code from a checkout flow, single-use, 12-month expiration).
- ✅ Purchase history UI — account console Billing → Payments list + per-payment page, and Receipts (
90b102dc, 2026-09-24; receiptsb6be59a8, 2026-09-28).
What users see when this unblocks: "Buy Echoes" becomes functional. Purchased Echoes land in expiring_other with a 1-year expiry. Bundles also mintable as gift codes for friends.
Phase 3 — Spending Echoes (partial)
Echoes become a real currency. Features start costing Echoes; hosted models become available.
- ✅ Canonical spend primitives (
fn_debit_spendable,fn_debit_persistent,fn_transfer_spendable) with allocate / commit / release lifecycle andEchoSpendOutcome/EchoSpendBatchOutcomeshapes. - ✅ AI Tasks
echo_costcharge —fn_charge_ai_task(functions/41n_ai_task_charge_functions.sql), pre-dispatch debit + refund on error; on the sharedfn_debit_daily_first_idempotentsince2bbb02ba(2026-09-26). - ✅ Embedding charge — the
embeddingcompute cost line on the per-turn allocate/settle rail (docs-internal/architecture/billing/COMPUTE_COST_LINES.md); rate is admin-set. - ✅ Hosted-model chat — pre-LLM estimate + allocation, post-LLM settle on real tokens (
fn_allocate_compute/fn_settle_compute,functions/41m_compute_charge_functions.sql; per-line billing shipped 2026-06-25, Hybrid turns priced per actual call since65e25140, 2026-09-24). Full design in Paid Experiences — Pricing Model. - ✅ Cost indicators —
~Npre-send estimate beside the chat composer, real per-line charge in the message's Info. - ⏳ Allocation cleanup — background job to release stale allocations (status='allocated' older than 1 hour). The snapshot already excludes allocated rows, so this is operational cleanup rather than correctness.
What users see when this lands: embeddings, AI Tasks, and hosted-model chat cost Echoes. Daily budget covers casual use; heavy users spend persistent / sub Echoes. Transition is smooth because Phase 1 and 2 have given users existing balances.
Phase 4 — Feature Commitments ✅ shipped (slice 2E)
The headline subscription refactor: Pro / Premium become Echo grants, every former tier perk is a separately-purchasable per-feature monthly commitment.
echo_features+echo_feature_tierscatalog (20l_tables_echo_feature_catalog.sql,44b_seed_feature_tier_metadata.sql).user_feature_commitmentslifecycle table.- Commit / upgrade / queue / release / auto-renew functions (
41d_*,41e_*,41f_*,41g_*). subscription_credit_queuefor multi-period passes.- ManageFeatures page (
/echoes/features), pricing page calculator, per-feature quantity steppers. - Grace-period sweep service + first-grant Premium auto-bundle trigger.
- Runtime metadata read via
fn_get_user_feature_metadata(replaces the oldfn_get_user_subscription_limitfor migrated features). - Per-feature gates wired against
user_feature_commitments: retention cleanup, gallery cap, lorebook-assistant cap, profile-editor unlock.
What users see: real "build your own subscription" experience. Pro and Premium are predictable monthly Echo grants. Every feature has a transparent price on the pricing page calculator. Cancellations are clean and lapses non-destructive.
Phase 5 — Tipping ✅ shipped (2026-05-09)
Users send Echoes to creators as tips. Depends on Phase 1 (ledger), Phase 3 spend primitives, and creator identity in the codebase.
fn_send_tip_batch(41j_*) — multi-leg one-time tip with mid-batch insufficient-balance safety.fn_charge_engagement_tips(41k_*) — per-message standing order,EngagementChargeStageatIPostLlmStageOrder=160.fn_refund_tip(41l_*) — admin-controlled refund with paired clawback rows.engagement_tip_preferences,creator_tip_settings,echo_tipstables.- AuthService endpoints:
EchoTipsEndpoints,EngagementTipsEndpoints,CreatorTipSettingsEndpoints. - AdminAPI:
AdminEchoTipsEndpoints.HandleRefundTip. - Client UI: tip modal, engagement bar, tips inbox, entity tip badge. Status note (2026-11-23): on the chat site the control that creates / pauses / cancels engagement tips (
ChatTipsPanel) is back: a story's details render it (chatConsole/src/chat/settings/tabs/SupportSection.tsx, throughStoryDetailsSections.tsx). The writing app's chat still doesn't mount it (unmounted since chat-v2 replaced classic chat,0ea3df012, 2026-05-25); existing standing orders charge either way. Was P-1 indocs-internal/reviews/CHAT_DOOR_REVIEW_2026-09-18.md.
What users see: creators have a real way to receive direct support from their audience without leaving the platform. Engagement tips give users a "tip per message" mode that respects opt-out and balance limits gracefully.
Implementation Order — What's Left
Concentrated in three areas:
Hosted Echo purchase (shipped, Beta)
- PayU integration — built 2026-09-28 (slices 0–1c: create-order, signed notify, receipts + VAT substrate, accountConsole checkout). Now live behind the Card rail switch (off / sandbox / production;
0877ec762) — seePAYU_INTEGRATION.md. — shipped for PayU prepaid plans (tier-kind branch offn_credit_monetary_purchase32b1d140e,9c760bd99,0a68a3572).Echo bundle catalog UI— built as the account-console checkout (2026-09-28).
Per-use Echo charging
Wrap— done:AiTaskRunner.csdispatch …fn_charge_ai_taskdebits before dispatch and refunds on error (see Phase 3).- Paid-experience message charge — see Paid Experiences. Depends on
platform_model_costsand the two new pipeline stages.
Creator cashout
- Design decision on cashable-as-flag vs cashable-as-pool (leaning flag).
- Cashout request endpoint + admin fulfillment flow (Wise manual to start).
- KYC tier table + caps. Reuse whichever KYC provider eventually fronts hosted checkout.
The economy primitives themselves (ledger, pools, spend helpers, tipping) are stable and have been carrying production traffic. Net-new economy mechanics should slot into this framework rather than adding new ledger pathways.
Future Extensions
Beyond the phases above, the design has room for:
- Streak bonuses — consecutive daily-login streaks raise the multiplier (e.g. 7-day streak → 1.2×). Infrastructure ready via
fn_claim_daily_task(p_multiplier). - Seasonal / event tasks — limited-time tasks with special rewards. Data-driven via
daily_tasksrows; no code change needed for threshold-based event tasks. - Referral rewards — earn Echoes when referred users verify their email and complete their first task.
- Pro / Premium task multiplier — subscribers earn 1.5× or 2× on daily tasks. Multiplier column on
daily_task_completionsis ready; no source is wired. - Achievement badges — visual rewards for completing all one-time tasks, maintaining streaks, etc.
- Task rotation — weekly or monthly rotating tasks beyond the core set ("This week: try 3 new characters → 15☆").
- Community tasks — tied to social features ("Follow 5 creators," "Rate 3 paid experiences").
- Recurring tipping (subscription-to-creator) — auto-tip a creator a fixed Echo amount monthly. Adds a recurring counterpart to the one-time tip flow. Likely depends on a payment provider that supports per-creator recurring billing.
- Discord bot chat-milestone integration — Discord-side chat messages count toward chat milestones, with claim via reaction or slash command. Blocked on Discord bot promotion to production stability + bot-side message-quality validation.
- Per-creator analytics dashboard for engagement tips — top supporters (mutual opt-in), tip stream graphs, content-attributed earnings.
- Auto-convert tipped Echoes to cashable on cashout-ship — design decision pending: do received tips become cashable income (with cooling + KYC + diversity gates), or do they stay in the appreciation channel and only paid-experience earnings cash out?
These are not on a roadmap commit — they're catalogued as the natural next moves once the existing phases settle.
Related Documents
- Paid Experiences — creator monetization on top of this economy.
- Hosted Inference via Featherless.ai — the first platform-hosted model behind paid experiences.
- Tiers & Limits — subscription tier definitions and
bypass_limitssemantics. - Packages — the entity that paid experiences attach pricing to.
- Creator Analytics — consumes Echo earning / spending data.
- Internal (repo-only, not on the site):
docs-internal/architecture/billing/SUBSCRIPTION_REFACTOR.md,GIFT_CODE_REDESIGN.md,CREATOR_TIPS.md,ECHO_SPEND_PATTERN.md,PAYU_INTEGRATION.md.