Introducing a new way to review your PRs.

Read the announcement

koala73 / worldmonitor

Real-time global intelligence dashboard. AI-powered news aggregation, geopolitical monitoring, and infrastructure tracking in a unified situational awareness interface

View on GitHub

29 documents · Updated Nov 20, 2026

docs / application-state

Persistent application state

WorldMonitor uses Convex as the durable state layer for identity, product access, preferences, alerts, billing, history, and operational work. Convex functions turn client actions, provider events, and scheduled tasks into checked state changes that the web app, API, notification relays, and other product surfaces can read.

State boundary

The state layer sits between product clients and the services that provide or deliver data. Public queries and mutations use the signed-in identity. Internal functions handle trusted service work. HTTP handlers expose selected operations to edge clients, providers, and relays through role-specific trust checks.

The main relationship is shown below.

flowchart LR
    Client[Web and API clients] --> Functions[Convex functions]
    Providers[Clerk, payment, email, and data providers] --> HTTP[Convex HTTP handlers]
    HTTP --> Functions
    Scheduler[Crons and scheduled functions] --> Functions
    Functions --> State[(Durable Convex state)]
    Functions --> Actions[External services and relays]
    Actions --> State

The schema defines durable records and shared validators define allowed values. The function layer checks identity, access, ownership, and state transitions. The HTTP layer adds service boundaries without bypassing those checks. See Convex schema and scheduled workflows for the data model and job details.

Product data

Identity and account lifecycle

The users record is the canonical application record for every Clerk-authenticated user. It stores server-observed email data and product context such as locale, time zone, country, first sighting, last sighting, terms acceptance, and first-touch agent source. Country and source are client-reported context for product use. They are not security facts. The record refreshes only material changes or a bounded last-seen update, which keeps session refreshes from creating avoidable write conflicts. See convex/users.ts• L78-227 and convex/schema.ts• L1082-1142.

The state layer keeps users separate from customers. A customers record represents payment-provider customer history. A user can exist without a customer record, and a customer record does not by itself prove current product access. Terms records distinguish the latest accepted version from the first known acceptance so later legal updates do not erase the original agreement.

Account deletion is a durable, resumable process. It records the requested source, current step, progress, and failure state. A deletion fence prevents new work from recreating personal state while the process removes or anonymizes it. Clerk deletion events start erasure before their event record is treated as complete. The registry gives each schema table an explicit delete, anonymize, retain, delegate, or skip decision. A closed-world check compares the registry with the schema so a new user-scoped table cannot ship without an erasure decision. Batch work uses bounded progress, stale-worker checks, retries, and recovery. A stalled-row sweeper re-arms pending work. Redis brief and alert history use erase markers so a late relay write cannot recreate deleted state. See convex/…/registry.ts• L22-315 and convex/…/batches.ts• L707-1044.

Billing evidence follows a different rule from personal access data. Deletion removes personal access records and tombstones the internal user link in billing rows. It retains provider customer context and payment evidence for complaints, authority requests, and bookkeeping. Retained billing payloads lose internal identity-bridge fields and cancellation feedback. Late billing events update retained evidence without restoring live access or personal ownership. Authenticated payment events with no owner are retained in a separate repair queue until an operator can attribute them. See convex/…/registry.ts• L89-165 and convex/…/unattributedPayments.ts• L58-163.

Agent feedback records connect reports from anonymous and keyed clients to an operator queue. Retry keys prevent duplicate rows during a short retry window. Security reports use a separate private state and notification path. Other reports enter a digest and triage flow. Retention depends on the report status, and filed reports keep only the link needed for issue history. See convex/agentFeedback.ts• L41-85 and convex/agentFeedback.ts• L656-699.

References: convex/users.ts• L78-227 convex/schema.ts• L1082-1142 convex/…/registry.ts• L22-315 convex/…/batches.ts• L707-1044 convex/…/sideEffects.ts• L228-255 convex/…/unattributedPayments.ts• L58-163 convex/agentFeedback.ts• L41-85 convex/agentFeedback.ts• L656-699

Preferences and watchlists

Preferences store a versioned settings record for each user and product variant. The shared contract keeps clients and Convex aligned on supported variants. A sync version lets two devices detect a conflict instead of silently overwriting newer settings. The write path also limits size and rate. Old clients can omit fields that they do not know, so a rolling deploy does not erase newer settings.

Followed countries are a separate watchlist relationship. It supports user scope, country follower counts, alert scope, and anonymous-to-authenticated merging. Lock records make concurrent first writes visible to Convex's conflict system. Scheduled seed and dedupe work repairs the lock tables when deployment or concurrent setup misses a row. Alert rules can copy followed countries into a new unscoped realtime rule, subject to the account's current alert capability.

References: convex/schema.ts• L121-141 convex/schema.ts• L281-359 shared/cloud-preferences-contract.ts• L1-7 convex/http.ts• L691-811 convex/http.ts• L1602-1677 convex/…/alertScopeSeed.ts• L8-58

Shared team dashboards

Team dashboards store layouts that an API Business team or an active Enterprise team shares with its members. The server derives the team from the signed-in caller and current access state, so the record belongs to the team rather than to the member who last changed it. Members can publish, update, and stop sharing layouts.

Each layout is tied to a product variant and has a name, version, and saved panel and map choices. It may also carry a focus scope and panel filters. The shared layout contract checks that stored focus data is normalized and that panel, map, and filter values stay within safe bounds.

The read path hides focused layouts from clients that cannot render focus. Publishing a focused layout requires the caller's current focus capability. Updates use the version last seen by the caller, so a stale tab cannot replace a teammate's newer layout. Each team can share at most 25 dashboards for a variant. See Convex schema and scheduled workflows for the schema contract and related state rules.

References: convex/teamDashboards.ts• L39-81 convex/teamDashboards.ts• L108-169 convex/teamDashboards.ts• L172-241 convex/schema.ts• L2007-2019 convex/…/teamDashboardLayout.ts• L5-108

Alerts and delivery

Alert rules express what a user wants to receive. A rule can select event types, severity, delivery mode, channels, quiet hours, digest timing, countries, followed tickers, monitored chokepoints, watched orbital sites, and strategic reservoirs. Reservoir alerts can use a level threshold or a seasonal-drop condition for selected reservoirs. The state boundary checks related fields together, so real-time delivery is reserved for critical events and a partial update does not silently narrow an existing rule.

Notification access uses a capability ladder rather than one binary paid check. Free accounts can hold a small rule shape with critical events, a limited country scope, realtime delivery, and email or web push. Paid plans can use the full alert surface. Watched-site and reservoir alerts remain separately Pro-only. Capability checks run on the Convex write path and return structured upgrade errors to the HTTP boundary. See convex/…/alertCapabilities.ts• L13-77 and convex/alertRules.ts• L84-135.

Country scope has an explicit migration boundary. An operator-run migration visits enabled unscoped realtime rules once, copies followed countries within the current plan cap, and records a notice result. A user with no followed countries keeps a global-only result when the account can receive it. A free account without a scoped realtime rule is told to choose countries. The marker prevents a later run from undoing a user's choice to clear the scope. See convex/alertScopeMigration.ts• L1-29 and convex/alertScopeMigration.ts• L57-114.

Notification channels hold verified destinations for email, Telegram, Slack, Teams, Discord, generic webhooks, and browser push. Email ownership comes from the account email, while Telegram ownership comes from a verified bot callback. A browser push endpoint belongs to one account at a time, so a shared browser subscription transfers rather than serves two accounts. Removing or deactivating a channel remains possible after paid access ends so stale destinations can be cleared.

A new channel can schedule a durable welcome event after the channel write. The event uses the channel connection identity, so a retry cannot welcome a replaced connection. Delivery attempts carry a sequence and failure record. The relay reports results only for the current connection, which prevents an old worker from disabling a newly replaced channel. Delivery reads filter hard-suppressed email addresses and add one-click unsubscribe links for brief and alert mail. One-click unsubscribe has separate lists for the brief, alerts, and marketing mail. A marketing unsubscribe does not block account or billing mail. See convex/notificationChannels.ts• L21-185, convex/notificationChannels.ts• L193-219, and convex/…/notificationDelivery.ts• L3-27.

References: convex/schema.ts• L143-279 convex/alertRules.ts• L84-135 convex/alertRules.ts• L366-475 convex/alertScopeMigration.ts• L57-114 convex/…/alertCapabilities.ts• L22-77 convex/…/alertScopeSeed.ts• L25-58 convex/notificationChannels.ts• L21-219 convex/notificationChannels.ts• L285-379 convex/http.ts• L1023-1086 convex/http.ts• L1183-1219

Company Monitoring state

Company Monitoring keeps customer portfolios separate from the global intelligence corpus. An account root records entitlement and deletion state. Company, claim, evidence, candidate, admission-decision, scan-obligation, and scan-work records remain tied to that root so product work can be replayed, audited, or purged by account.

Admission is the decision point between collected evidence and publishable company findings. It checks that the account and company are active, that the referenced evidence is current, and that the evidence snapshot has not changed. A worker lease and run identity prevent two workers from deciding the same candidate at once. The resulting decision records the policy and evidence versions that explain whether the candidate is published, held, rejected, or expired. Holds use fixed retry checkpoints and end when the candidate expires.

The classifier uses the fixed OpenRouter route. An AI routing policy can exclude that provider for one user or for an Enterprise member through an inherited account policy. When the policy blocks the classifier, the candidate is rejected before customer evidence reaches that provider. See convex/…/admission.ts• L216-270 and convex/…/admission.ts• L301-661.

References: convex/schema.ts• L1249-1807 convex/…/admission.ts• L216-270 convex/…/admission.ts• L301-435 convex/…/admission.ts• L437-661 convex/…/companyMonitoringAdmissionPersistence.test.ts• L171-336

Broadcast audiences

Broadcast state turns registrations and account context into controlled email audiences. A registration receives one wave stamp after it is selected, while normalized customer and user emails support deduplication and locale filtering. This lets later waves exclude contacts already sent and avoid sending a paid-user acquisition message to an existing customer.

The ramp state records the active tier, the last wave, the prior-wave delivery gate, and operator actions. An in-flight wave has a run record and one row per picked contact, so selection, provider segment membership, push progress, and recovery remain durable. Provider contact linking checks consent and treats duplicate responses as a link or no-op.

References: convex/schema.ts• L360-592 convex/…/backfillCanaryWaveStamps.ts• L53-87 convex/…/_resendContacts.ts• L45-169 convex/crons.ts• L77-93

Access and commercial state

Entitlements and product catalog

Billing history and product access are separate views. Subscription records preserve provider lifecycle and paid-through dates. The entitlement record provides the current plan and named capabilities used by dashboards, API access, MCP, exports, embeds, alerts, desktop keys, and usage limits.

The product catalog is the shared source for plan features, limits, provider product mappings, checkout visibility, and plan precedence. Checkout admits only products marked as current and self-serve. Entitlements are recomputed from all covering subscriptions, accepted Business Pro grants, live Enterprise membership, and any active complimentary entitlement floor. The strongest valid source wins by capability tier, plan precedence, and then paid-through date. A scheduled recheck changes the result when a stronger source ends before another source. Read-time catalog merging lets new product fields reach older rows without waiting for a billing event.

Named capability flags keep similar plan tiers distinct. API access, MCP access, partner embeds, data export, desktop-key access, dashboard focus, travel risk assessment, and alert capabilities are separate decisions. Shared API plans charge MCP use against the REST budget instead of creating a hidden second budget. The same feature shape is accepted by the durable entitlement row and the cache sync path. Legacy product IDs remain mapped so existing subscriptions continue to resolve to a known plan. See convex/…/productCatalog.ts• L67-265, convex/…/entitlementFeaturesValidator.ts• L4-88, and convex/…/entitlements.ts• L39-120.

AI routing policy is a separate user-level control. It lists the providers that may process that user's data and records why the restriction exists. A per-user policy can narrow an Enterprise account policy but cannot widen it. The edge can read the result through a delivery-scoped or server-to-server route, while a policy change clears its short-lived cache.

References: convex/…/productCatalog.ts• L67-265 convex/…/entitlementFeaturesValidator.ts• L4-88 convex/…/entitlements.ts• L18-120 convex/entitlements.ts• L26-97 convex/schema.ts• L944-1002 convex/…/enterpriseAccounts.ts• L77-139 convex/enterpriseAccounts.ts• L147-187

Enterprise accounts and seats

Enterprise state represents a contract customer whose members share one request pool and one AI token allowance. The account stores contract dates, limits, provider policy, and a seat cap. Membership rows identify active users, pending email invites, and removed history. A pending unexpired invite consumes a seat.

Account admins can invite corporate-domain users through a signed, row-bound link. Acceptance requires the matching signed-in email, a live contract, and no active membership in another Enterprise account. Seat changes use an account lock so concurrent changes cannot pass the cap check twice. Invite mail is scheduled after the seat row is stored, and a failed or suppressed send remains visible to the admin. Member changes recompute entitlement and clear both entitlement and routing caches.

Enterprise routing survives contract end while the membership remains active. Product access does not: the entitlement source ends at contractEnd, then another subscription or the free tier can win. This separates a lasting data-processing policy from time-limited commercial coverage. Business Pro seats follow the same broad model through a separate grant linked to the owner's covering subscription. They use their own cap, expiry, signed acceptance, and revocation path.

References: convex/schema.ts• L977-1037 convex/enterpriseSeats.ts• L45-145 convex/enterpriseSeats.ts• L147-325 convex/enterpriseSeats.ts• L346-407 convex/…/businessSeats.ts• L57-123 convex/…/businessSeats.ts• L426-527 convex/…/enterpriseAccounts.ts• L52-139

Credentials and usage

REST API keys, desktop keys, Pro MCP tokens, and partner embed keys are separate credential surfaces. API and desktop key rows store only a hash and retain revoked history. API keys can carry Company Monitoring scope. Desktop keys have their own plan-based active set and can be suspended by a rollout switch. Partner embed keys use a separate table because they authorize public embeds and have a different paid-access rule. Pro MCP tokens identify OAuth grants and do not store bearer key material.

Validation returns only active credentials. Key use updates are debounced and spread across a short delay so busy credentials do not create a write for every request. MCP token issuance enforces the Pro or confirmed-free gate and keeps a visible revoked history. It rotates the least recently used active rows when a user reaches the five-token cap. Usage records connect plan limits to measured API and MCP activity.

Hourly scans create usage rollups and current limit notices. They skip Enterprise members because pooled contract limits are handled by the account. A missing usage source becomes a blocked state rather than zero usage, so a source outage cannot clear a real warning. Shared-budget plans avoid reporting the same MCP and REST allowance twice.

References: convex/schema.ts• L1039-1079 convex/schema.ts• L1943-2019 convex/apiKeys.ts• L16-45 convex/embedKeys.ts• L10-38 convex/mcpProTokens.ts• L31-155 convex/mcpProTokens.ts• L160-218 convex/apiPlanLimitUsage.ts• L567-675 convex/apiPlanLimitUsage.ts• L719-839

Billing state

Payment webhooks are the main source of subscription changes. A verified event updates payment, customer, subscription, and entitlement state as one product transition. Pending payment rows prevent duplicate checkout attempts while a provider payment is still in progress. Provider identity is carried by signed metadata, so a client-supplied user ID cannot claim another account's payment.

The state layer also records work that a provider retry cannot solve by itself. An authenticated event with no user link becomes an unattributed payment record for operator assignment. Charged events trigger prompt operator notice. Repeated uncharged attempts from one provider customer are kept for evidence but share a quiet period for notification. An authenticated but malformed or failed event becomes a bounded webhook failure record. These records preserve repair context without treating a permanent identity gap as an endless provider retry.

Subscription transitions recompute access from every subscription for the user rather than from only the event that arrived. A cancelled or payment-held subscription keeps access only through its paid-through date. A lower-tier event cannot replace a stronger live subscription, and a late event cannot re-elect a source that has already lapsed. Active complimentary coverage, accepted Business grants, and Enterprise membership participate in the same decision. The webhook boundary also keeps malformed transactions atomic and rejects equal-time lifecycle replays, so a failed or stale event does not leave partial access state. convex/…/webhook-rollback-boundaries.test.ts• L93-153 and convex/…/webhook-rollback-boundaries.test.ts• L240-272 preserve these rules.

Current billing state can be repaired in two directions. A request-time check can re-confirm a recently stale subscription for a customer-facing access decision. A scheduled reconciliation checks older stale rows, uses bounded pages and backoff, and downgrades only after repeated definitive provider evidence. A mass-not-found circuit stops broad downgrades when a provider or environment error looks more likely than many real cancellations. Late billing events for an account being erased retain billing evidence but do not restore live access or personal ownership.

The cache is a derived access view, not the source of truth. Entitlement writes schedule a cache update and a delayed read of current database state. Enterprise account blocks and AI routing policies are included or invalidated with the same account change. A cache failure can leave a short-lived stale view, while the gateway can fall back to Convex state.

References: convex/…/billing.ts• L117-190 convex/…/billing.ts• L2172-2479 convex/…/unattributedPayments.ts• L58-163 convex/…/subscriptionHelpers.ts• L121-260 convex/…/cacheActions.ts• L37-80 convex/enterpriseAccounts.ts• L136-187 convex/…/webhook-rollback-boundaries.test.ts• L93-153 convex/…/webhook-rollback-boundaries.test.ts• L204-237 convex/…/webhook-rollback-boundaries.test.ts• L240-331 convex/…/webhook-rollback-boundaries.test.ts• L335-399

Checkout state

Checkout state protects the purchase path from duplicate or unsupported work and records whether a buyer reached the hosted payment form. The product catalog admits only current self-serve products. A short account window limits admission, while subscription and pending-payment checks stop known duplicate purchases before the provider call.

After the provider creates a session, the system records the product, account, anonymous status, and provider session identity. This checkout-session log fills the gap between an upgrade click and a payment attempt. It supports funnel counts and joins to later payment evidence, while bounded retention and account deletion keep the record from becoming permanent personal history. Failure to write this measurement does not cancel a live checkout.

References: convex/…/checkout.ts• L55-95 convex/…/checkout.ts• L321-503 convex/…/checkoutSessionLog.ts• L17-65 convex/schema.ts• L1291-1348

Product history and operational records

Historical intelligence

Historical intelligence preserves events beyond short live snapshots. Seeders append distinct records, product reads return timelines or semantic matches, and retractions suppress a bad identity so the next seed run cannot restore it. Retention bounds both history and its retraction records.

The history boundary is internal. Secret-guarded HTTP routes admit bounded ingest and reads for seeders and edge services, while retraction and restore use a separate operator credential. Timeline pages carry opaque cursors, and invalid cursors return a clear client error instead of being confused with a store failure. Append, retraction, and retention work use bounded batches so a large backlog does not block normal product writes.

References: convex/schema.ts• L2004-2105 convex/intelHistory.ts• L11-30 convex/intelHistory.ts• L198-324 convex/intelHistory.ts• L434-644 convex/intelHistory.ts• L762-940 convex/http.ts• L2160-2185 convex/http.ts• L2358-2614 convex/paginationCursor.ts• L1-44

Email delivery state

Email delivery uses durable suppression and delivery evidence. Hard bounces, complaints, and operator blocks stop transactional mail. Marketing unsubscribe blocks marketing mail only. Transient bounces become strikes and suppress an address after repeated failures in the active window. A later delivery clears earlier transient strikes.

The shared Resend library checks suppression before every transactional or marketing email and supplies a reply address by default. Subscription, seat, dunning, winback, operational, and alert-scope migration sends therefore share the same delivery boundary. Dunning and winback rows are keyed to a subscription episode, so recovery, cancellation, and a later payment failure do not reuse the wrong send history. A pacing record spreads sends across the provider rate limit. Broadcast delivery keeps only non-recipient event metadata in Convex while Resend remains the provider record for recipient-level inspection.

References: convex/…/resendEmail.ts• L1-19 convex/…/resendEmail.ts• L29-120 convex/resendWebhookHandler.ts• L46-170 convex/…/subscriptionEmails.ts• L736-910 convex/…/businessSeats.ts• L246-290 convex/alertScopeMigration.ts• L117-220 convex/schema.ts• L1930-2018

Feedback operations

Agent feedback is an operational record for reports from WorldMonitor clients and agent surfaces. The state model separates receipt, owner notice, triage, filing, dismissal, duplication, and closure. It gives operators a bounded queue without exposing security-report text through ordinary triage or digest mail.

Security reports can receive an immediate notice within a daily cap. Reports held by the cap or failed sends appear in a daily security digest. Other reports are summarized by kind and surface type. The record is marked as seen only after the email succeeds or an operator takes it into triage, so a delivery failure remains visible for the next recovery pass.

References: convex/agentFeedback.ts• L101-120 convex/agentFeedback.ts• L270-374 convex/agentFeedback.ts• L442-501 convex/agentFeedback.ts• L515-648 convex/crons.ts• L95-124 convex/schema.ts• L687-731

Asynchronous workflows

Workflow model

Convex scheduled work turns a short request into a durable process. A mutation records intent and progress. An action performs external I/O when needed. A later mutation records the result and either finishes the process or schedules the next step.

The flow is shown below.

sequenceDiagram
    participant Actor as Client or provider
    participant Function as Convex function
    participant State as Durable state
    participant Job as Scheduled job
    participant External as External service

    Actor->>Function: Request or event
    Function->>State: Validate and record intent
    Function-->>Job: Schedule work
    Job->>External: Read or send
    External-->>Job: Result or failure
    Job->>State: Record outcome
    State-->>Function: State for the next read

This pattern supports payment retries, account deletion, notification welcomes, billing email, history retention, usage notices, entitlement cache refresh, Company Monitoring admission and scans, Enterprise contract boundaries, seat invitations, Business seat revocation, alert-scope notices, and broadcast delivery. The scheduler is a wake-up mechanism. Durable rows hold the meaning and progress of the work.

References: convex/…/batches.ts• L707-837 convex/…/sideEffects.ts• L70-123 convex/…/admission.ts• L547-661 convex/enterpriseAccounts.ts• L165-187 convex/enterpriseSeats.ts• L227-245 convex/notificationChannels.ts• L80-185 convex/…/billing.ts• L2172-2479 convex/…/cacheActions.ts• L45-80 convex/alertScopeMigration.ts• L187-220

Provider events

Provider events enter through signed HTTP handlers and move into internal state functions. Stable provider event IDs make retries repeatable. A successful payment event commits the product transition. A failed transition records a repairable incident. Resend delivery events update suppression, soft-bounce, and broadcast records so later sends use current delivery state.

Subscription lifecycle events are ordered by their event time. A late event for a deleted account updates retained billing evidence under a tombstone and never restores personal access. An authenticated payment event with no owner is acknowledged only after its repair record is durable. This separates an identity gap from a provider processing failure.

Signature checks are shared across webhook types. Checkout metadata identity, anonymous claims, Business invites, Enterprise invites, Company Monitoring owner fences, and checkout login-email proofs use separate signed purposes. Each proof binds to the expected account, grant, member, or workflow and expires when that workflow no longer needs it. This prevents a token issued for one boundary from becoming authority at another boundary.

References: convex/…/subscriptionHelpers.ts• L147-260 convex/…/webhookHandlers.ts• L41-53 convex/…/webhookHandlers.ts• L287-361 convex/…/unattributedPayments.ts• L90-163 convex/resendWebhookHandler.ts• L173-253 convex/…/svixVerify.ts• L179-229 convex/…/identitySigning.ts• L147-181 convex/…/identitySigning.ts• L242-370 convex/enterpriseSeats.ts• L286-330 convex/…/webhook-rollback-boundaries.test.ts• L93-237

Scheduled work

Crons provide regular wake-up points for work that must continue without a user request. They clean expired pairing state, scan usage, send limit notices, recover stalled deletions, reconcile billing and Enterprise memberships, run lifecycle email, prune history and delivery evidence, seed lock state, send feedback digests, and advance broadcast work.

Each scheduled process checks durable state before it acts. It can do nothing when work is paused, already owned, outside its time window, or no longer needed. Large cleanup and reconciliation tasks use bounded batches and continuations. Lease-backed work records ownership and terminal results, so a stale worker stops before making another external side effect. Contract boundary jobs recompute Enterprise members at start and end. The daily reconciliation remains a safety net for lost membership triggers. See Convex schema and scheduled workflows for the full schedule and child workflow rules.

References: convex/crons.ts• L6-75 convex/crons.ts• L84-181 convex/crons.ts• L241-270 convex/…/batches.ts• L995-1044 convex/…/billing.ts• L2172-2479 convex/…/subscriptionEmails.ts• L1226-1371 convex/enterpriseAccounts.ts• L165-187 convex/agentFeedback.ts• L472-648

Consistency model

Ownership and access

Public functions derive ownership from the authenticated identity. Internal functions accept a user ID only after a trusted caller establishes it. Product feature gates run at the state boundary, not only in the UI. Service routes use separate secrets for gateway, delivery, suppression, and history-retraction roles so one service cannot gain another service's authority.

Credential and billing paths use signed identity proofs when an external provider must carry a user identity. One token purpose cannot be reused as another because signing payloads are domain-separated. Account deletion checks apply to delayed work as well as direct writes. Company Monitoring checks the account lifecycle and entitlement before admission work or classifier results can change state. Enterprise and Business seat changes check current membership and use account or subscription locks before changing capacity. Alert writes check the current capability ladder before durable intent is stored.

References: convex/users.ts• L134-145 convex/alertRules.ts• L366-431 convex/notificationChannels.ts• L223-249 convex/http.ts• L94-119 convex/http.ts• L474-537 convex/…/admission.ts• L216-270 convex/enterpriseSeats.ts• L147-217 convex/…/businessSeats.ts• L129-219 convex/…/identitySigning.ts• L147-181 convex/…/identitySigning.ts• L242-370

Repeatable transitions

Retries are normal for browser calls, provider webhooks, and scheduled actions. State changes therefore use event IDs, dedupe keys, sync versions, episode keys, ownership checks, terminal markers, or opaque pagination cursors. A repeat should return the existing result or move the same record forward rather than create a second payment effect, alert destination, history record, grant, seat, token, or email ledger row.

Some transitions intentionally keep history while changing current access. Revoked credentials remain visible as history. Payment events remain append-only while terminal state decides whether a pending payment still blocks checkout. Dunning and winback ledgers are keyed to a subscription episode. Welcome events are keyed to the channel connection. Alert-scope notices are keyed to the visited rule. Company Monitoring decisions are fenced by evidence revision and classification run. Enterprise invite rows, Business grants, MCP token rows, and feedback reports use the same rule: current state controls action while prior state supports audit or triage.

References: convex/schema.ts• L687-731 convex/schema.ts• L399-592 convex/schema.ts• L1517-1602 convex/schema.ts• L1866-1994 convex/notificationChannels.ts• L86-185 convex/…/unattributedPayments.ts• L90-163 convex/…/businessSeats.ts• L151-239 convex/enterpriseSeats.ts• L204-239 convex/…/admission.ts• L463-506 convex/…/subscriptionEmails.ts• L870-910

Bounded cleanup and recovery

Cleanup is part of the state contract. Retention, deletion, stale billing repair, soft-bounce cleanup, discarded broadcast cleanup, expired invite recovery, feedback pruning, usage-notice pruning, and checkout-session pruning use bounded work and continue until the backlog is drained. A missing lock or seed record fails closed when allowing a race would damage ownership, dedupe, or a cap. An operator can inspect failed work and resume or discard it without guessing which external steps already completed.

External failures keep their retry state in durable rows. Account deletion uses separate batch and provider retry limits. Billing reconciliation backs off poison rows and limits broad downgrade damage. Email and alert-scope notices record suppressed or failed delivery instead of treating a missing message as success. Redis erase markers protect the deletion boundary while external cleanup catches up.

References: convex/…/batches.ts• L855-1044 convex/…/sideEffects.ts• L70-123 convex/…/registry.ts• L317-327 convex/crons.ts• L26-75 convex/crons.ts• L95-149 convex/crons.ts• L157-222 convex/…/billing.ts• L2248-2479 convex/alertScopeMigration.ts• L187-220 convex/intelHistory.ts• L844-940 convex/schema.ts• L491-588

Change checklist

When these files or sections are changed, remember to consider these:

  • A state field or value must stay aligned across convex/schema.ts, its validator or shared constant, the writer, the reader, and generated Convex types.
  • A plan or feature change must stay aligned across the product catalog, entitlement merge, write gates, provider mappings, usage limits, cache views, Enterprise account rules, and checkout surfaces.
  • A change to entitlement coverage must preserve recomputation from all subscriptions, complimentary source provenance, Enterprise membership, paid-through dates, plan precedence, and the single pending coverage recheck.
  • A new credential surface must define its owner, storage proof, revocation path, validation route, active-row limit, and account-deletion action. Do not reuse a stronger or weaker credential family by accident.
  • A change to API, desktop, embed, or MCP credentials must keep issuance, validation, credential kind, plan limits, rollout control, edge cache expiry, revocation history, and downgraded-owner ranking aligned.
  • A provider event change must preserve signature verification, stable event identity, failure records, attribution rules, billing deletion handling, and retry behavior. Preserve atomic rollback if processing fails after a state write, and keep equal-time lifecycle events from reordering subscription state.
  • A checkout or invite signing change must preserve domain separation, expiry, identity binding, row binding, and the distinct secret or key-rotation contract for each token purpose.
  • A new scheduled step must define durable progress, ownership, retry limits, external side effects, terminal state, and recovery before it is added to convex/crons.ts.
  • A deletion step must keep the account fence active, save progress, retry external work safely, and avoid recording Clerk completion before erasure starts.
  • The deletion registry and batch table list must remain closed over user-scoped schema records. A new record needs an explicit delete, anonymize, retain, delegate, or skip decision and a matching batch action when required.
  • A change to alert-rule fields must keep schema values, shared shape validation, the authenticated relay write contract, structured HTTP errors, atomic notification updates, service-role separation, and byte-bounded delivery reads aligned.
  • A new alert scope must keep its event type, stored criteria, shared bounds, entitlement gate, relay filter, migration behavior, notice state, and cleanup path aligned. Empty scope values must not change the meaning of an existing rule.
  • A change to notification channels must keep schema channel types, capability gates, ownership proof, connection identity, delivery-result validation, deactivation, welcome queue version, and account deletion aligned.
  • A new Company Monitoring state must define its account scope, evidence revision, lease or replay fence, terminal result, AI routing policy, and delegated deletion path.
  • Enterprise and Business seat changes must keep contract or subscription coverage, invite expiry, signed row binding, seat locks, email failure state, entitlement recomputation, and cache invalidation aligned.
  • A new entitlement feature must be accepted by the entitlement table and cache action, merged for legacy rows, and represented in checkout, usage notices, alert capability resolution, and product admission rules.
  • A change to renewal verification must keep request-time leases separate from cron backoff and must preserve the source-of-truth re-read before access denial. Keep provider error classification narrow so only confirmed not-found evidence can cause a downgrade.
  • A billing email change must keep episode keys, suppression purpose, send pacing, and post-send ledger behavior aligned.
  • A history pagination change must preserve opaque cursor handling and distinguish an invalid cursor from a database or provider failure.
  • A feedback state change must keep retry identity, reporter ownership, security privacy, notification markers, triage transitions, retention, and deletion coverage aligned.
  • An unattributed payment change must keep webhook acknowledgement after durable recording, charged-event urgency, duplicate event handling, operator attribution, and entitlement replay aligned.
  • A change to the default-brief or alert-scope selection must keep paid-entitlement filtering, digest-rule detection, AI-digest opt-out handling, byte-bounded pagination, country scope, and the delivery relay contract aligned.
  • A team dashboard change must keep team derivation, live Business or Enterprise access, variant scope, focus capability checks, layout validation, version conflicts, and the per-variant sharing cap aligned.

Important failure modes

TriggerConsequenceGuard
A new user-scoped table has no deletion registry entryPersonal data can survive account erasure without an explicit owner decision.Closed-world registry checks compare every schema table with the registry and its steppers.
Account deletion loses a continuationThe account can remain write-fenced with incomplete erasure and billing work still pending.Bounded progress, stale-worker checks, retries, and the stalled-deletion reaper restart pending work.
A late billing event targets a deleted accountThe event can restore personal access or ownership.Billing rows use tombstones and redacted payloads; deleted events never recompute live entitlement.
An unattributed paid event is acknowledged before its repair row is storedA customer can pay without durable evidence or a path to grant access.The webhook path records the event before acknowledgement and notifies operators for charged events.
A malformed webhook fails after subscription or entitlement writesA partial transition can make retry behavior unsafe or leave access without its billing record.Convex rolls back the mutation, including the dedup row; the same provider event can then retry.
A plan feature exists in the row but not in the catalog or cache shapeA paid capability can be denied or cache synchronization can fail.The catalog merge and shared entitlement validator cover stored and cached views.
Enterprise contract dates change without member recomputationA member can keep the wrong access or account limit block.Boundary jobs are replaced on edit and active members are recomputed.
Two seat changes pass the cap check togetherAn Enterprise or Business account can exceed its seat cap.Every seat mutation reads and writes the relevant account or subscription lock.
An expired or forged invite is acceptedAccess can be assigned to the wrong person or after coverage ends.The token binds to one row and expiry; acceptance checks email, status, coverage, and membership.
A per-user AI policy widens an Enterprise account policyCustomer data can reach a provider excluded by contract.The resolved provider set is the intersection of the user policy and every active account policy.
A usage source is unavailableA real limit warning can be cleared as zero usage.The scan records a blocked source and does not treat it as recovery.
A shared REST/MCP budget is counted twiceCustomers can receive false usage notices or an unintended second allowance.Catalog structure identifies the shared budget and the scan suppresses duplicate zero readings.
A Pro MCP token is treated as entitlement proofA revoked or downgraded user can retain access through an old grant.Token validation proves identity only; each gated call rechecks current access and limits.
A provider event is delivered twicePayment, access, delivery, or seat state can be applied twice.Stable provider IDs, episode keys, row-bound tokens, and idempotent mutations.
A provider sends a same-time lifecycle event after a newer stateA replay can undo a valid subscription state.Event ordering requires a strictly newer event time; equal and older events are ignored.
A transient provider error is treated as a definitive not-found resultReconciliation can downgrade a paying customer during an outage.Only the provider's confirmed not-found error is downgrade evidence; connection, auth, rate, and server errors remain non-definitive.
A relay secret is reused across service rolesOne internal service can read or change another service's tenant state.The HTTP boundary has a role matrix and rejects shared or reused secrets.
A free account writes a wider alert rulePaid-only delivery can be configured without access, or a free rule can consume too much scope.The capability ladder validates durable writes and the relay applies a delivery-time clamp.
An unscoped realtime rule is migrated twiceA user who cleared a scope can receive countries they did not choose.One notice marker is stored per visited rule and later runs skip it.
A channel connection is replaced while a welcome or delivery retry is in flightAn old connection can receive a welcome or be disabled by a stale result.Connection IDs and delivery sequences must match the current channel row.
A web push endpoint remains linked to two usersAlerts can cross account boundaries on a shared browser.Registration removes matching endpoint rows from other accounts before it writes the current owner.
A Company Monitoring result uses an old evidence revision or leaseA stale model result can publish or overwrite a newer decision.Evidence digests, revision checks, worker leases, and replay fences reject it.
A scheduled worker loses progress or overlaps another workerExternal work can duplicate or remain incomplete.Durable progress, leases, terminal markers, bounded retry, and operator recovery.
A security feedback notice fails after the row is storedThe owner may never learn about the report.notifiedAt stays unset and the daily digest selects failed or capped notices.
A feedback report is filed without removing its reporter fieldsPersonal reporter data can remain in a long-lived issue record.Filing keeps only operational linkage and replaces reporter identifiers with a tombstone.
A history row is deleted without suppressing its identityThe next seeder run restores the bad event.Retraction deletes the row and writes a matching tombstone.
Redis entitlement sync failsEdge access can use a stale cache until expiry.Convex remains authoritative, the gateway falls back on cache miss, and sync failure is observable.
A focused dashboard is published without focus capabilityA shared layout can contain a view that the publisher is not allowed to use.The publish path checks the caller's current focus capability, including on updates.
An older client opens a focused dashboardThe client can show an unfiltered view that hides the intended scope.Listing omits focused layouts unless the client declares focus support.
Two members update the same dashboard from an old versionOne member can silently overwrite a teammate's newer layout.The update requires the last-seen version and returns a version conflict when it is stale.
A user loses team access while publishing or removing a dashboardA former member can change shared team state.The server derives the team from current live access and checks the account write fence.

Key files

FileWhy to read it
convex/schema.tsThe durable records and relationships for users, settings, alerts, access, billing, checkout, Enterprise accounts, Company Monitoring, history, broadcasts, usage, deletion, credentials, team dashboards, and workflows.
convex/crons.tsThe recurring wake-up points for cleanup, recovery, reconciliation, notices, and lifecycle work.
convex/http.tsThe HTTP, provider, relay, preference, entitlement, credential, notification, checkout, history, and unsubscribe boundaries.
convex/users.ts, convex/userPreferences.ts, and convex/followedCountries.tsThe identity, settings, and watchlist state used by the product shell.
convex/teamDashboards.ts and convex/…/teamDashboardLayout.tsTeam-owned dashboard sharing, team access resolution, focus capability checks, layout validation, version conflicts, and per-variant limits.
convex/alertRules.ts, shared/alert-rule-shape.ts, convex/…/alertCapabilities.ts, and convex/notificationChannels.tsSaved alert intent, capability tiers, scoped alert criteria, shared row bounds, verified destinations, channel ownership, delivery results, and asynchronous welcome work.
convex/alertScopeMigration.ts and convex/…/alertScopeSeed.tsThe one-time transition from unscoped realtime rules to followed-country scope and the rules for later country seeding.
convex/…/productCatalog.ts, convex/…/entitlementFeaturesValidator.ts, convex/…/entitlements.ts, and convex/entitlements.tsPlan capabilities, limits, provider mappings, precedence, legacy-row behavior, alert capabilities, and entitlement reads.
convex/enterpriseAccounts.ts, convex/enterpriseSeats.ts, and convex/…/enterpriseAccounts.tsContract accounts, pooled limits, member policy, seat lifecycle, invite rules, and cache updates.
convex/…/checkout.ts, convex/…/subscriptionHelpers.ts, and convex/…/billing.tsProduct admission, provider transitions, all-source entitlement recomputation, customer portal access, renewal verification, and reconciliation.
convex/…/webhookMutations.ts and convex/…/webhook-rollback-boundaries.test.tsProvider event application, retry and dedup boundaries, transactional rollback, lifecycle ordering, and exact checkout-blocking time rules.
convex/…/businessSeats.tsBusiness grants, domain-gated invites, seat locks, acceptance, revocation, and team-access email.
convex/…/unattributedPayments.tsDurable repair records and operator notices for authenticated payment events with no account owner.
convex/…/cacheActions.tsThe asynchronous bridge from current Convex entitlement and routing state to the edge cache.
convex/…/subscriptionEmails.tsPayment-failure, cancellation, reactivation, winback, pacing, suppression, and send history.
convex/…/registry.ts, convex/…/batches.ts, convex/…/erase.ts, and convex/…/sideEffects.tsThe account-erasure scope, durable progress steps, billing anonymization, external cleanup, bounded retry, stale-row recovery, and closed-world coverage.
convex/…/admission.tsEvidence-backed candidate admission, classifier policy checks, leases, retry holds, and replay-safe decisions.
convex/apiPlanLimitUsage.ts and convex/schema.ts• L1039-1079Usage-source checks, plan-limit rollups, notices, recovery, and Enterprise exclusions.
convex/mcpProTokens.ts, convex/apiKeys.ts, and convex/embedKeys.tsSeparate API, desktop, partner-embed, and MCP credential lifecycles, access checks, revocation, and active-set limits.
convex/agentFeedback.tsDurable client reports, security notice state, operator triage, digest delivery, and retention.
convex/…/svixVerify.ts and convex/…/identitySigning.tsShared webhook proof and domain-separated signed identity tokens used across external boundaries.
convex/intelHistory.ts and convex/paginationCursor.tsAppend, search, retraction, pagination, and retention for durable intelligence history.
convex/…/resendEmail.ts, convex/resendWebhookHandler.ts, and convex/emailUnsubscribe.tsShared email sending, delivery feedback, suppression, and one-click opt-out state.