Introducing a new way to review your PRs.

Read the announcement

capsoftware / cap

Open source Loom alternative. Beautiful, shareable screen recordings.

View on GitHub

31 documents · Updated Nov 23, 2026

docs / customer-lifecycle-automation

Customer lifecycle automation

Customer lifecycle automation turns product, billing, organization, license, and recording signals into safe customer profiles and targeted email journeys. It keeps the product database as the source of truth while checkout web APIs, Stripe events, scheduled syncs, directory reconciliation, and operator-run scripts move eligible changes to Loops.

The page sits under Data and identity platform. Read Database schema and migrations for the wider database model and the rules for changing its durable records. Read Web API and domain services for the scheduled API boundaries that run lifecycle and directory syncs.

Lifecycle model

Customer lifecycle automation joins four concerns: product state, audience decisions, contact synchronization, and email delivery. Each concern has a different role, so a change in one area must not silently bypass the checks in the next area.

Product signals

The lifecycle profile is a view of a person’s current product relationship. It combines the Cap user record with organization membership, invitations, SSO use, directory-managed membership, billing state, separate desktop or self-hosted license state, and recording activity.

Product sharing adds a separate access signal. Organizations can choose a private default for new videos, and a video can hold a named viewer grant with a revocation time. These records control who can view a recording. They do not replace lifecycle audience classification or marketing consent.

The main signals have these meanings:

Signal groupPurpose
Identity and signupIdentifies the person and shows whether signup is complete.
Organization accessSeparates an independent user from a teammate, SSO member, or directory-managed member.
EntitlementDetects Cap Pro, paid seats, desktop licenses, and self-hosted licenses.
Product activityShows whether the person has made or shared a usable cloud recording.
Product sharingControls recording access for a new video or a named viewer.
Subscription statePreserves global and mailing-list opt-outs before any marketing action.

This model keeps product facts in Cap and sends derived lifecycle fields to the email system. It does not make the email provider a second source of truth for billing, access, or consent.

References: packages/…/sources.ts• L24-40 packages/…/sources.ts• L48-106 packages/…/schema.ts• L78-155 packages/…/schema.ts• L212-228 packages/…/schema.ts• L561-580 packages/…/video-sharing-default.ts• L7-24

Identity admission

Identity admission decides whether an email may create or continue a Cap account before the lifecycle system can classify the person. Sign-in inputs use one normalized email form, allowed-domain rules limit new accounts when configured, and blocked domains or addresses refuse sign-in for both new and existing accounts.

SSO admission adds organization and identity checks before an SSO account can create or continue a membership. The sign-in must match the active organization connection, a verified organization domain, and one product user. A successful SSO membership update marks the user as a teammate and requests a lifecycle profile refresh.

Cap also screens throwaway inbox domains on the main service. The check uses a maintained domain list and mail-server evidence, but a DNS failure does not block a signup. It rejects new unverified accounts while preserving access for people who have already verified an account, paid, or linked an account through an existing sign-in provider. This keeps abuse control separate from customer access and from later lifecycle consent decisions.

References: packages/…/auth-options.ts• L417-464 packages/…/auth-options.ts• L50-76 packages/…/domain-utils.ts• L4-20 packages/…/domain-utils.ts• L40-77 packages/…/disposable-email.ts• L74-115 packages/…/disposable-signup.ts• L7-38 packages/…/sso.ts• L90-185 packages/…/sso.ts• L187-313

Audience classification

The profile classifier maps the signals into a small set of lifecycle audiences. A teammate classification has priority over customer or free-user status because a person who acts on behalf of an organization should receive workspace help rather than a sales journey.

Directory-managed SSO users follow the same teammate path as invited or directly provisioned members. Directory reconciliation records the organization link and requests a profile refresh when it adds a member or changes access.

AudienceHigh-level meaningLifecycle use
freeIndependent user without a current paid entitlementProduct activation and Pro education
customerCurrent cloud, seat, desktop, or self-hosted customerPlan-aware onboarding and feedback
teammateInvite, SSO, organization membership, or retained teammate historyWorkspace setup and handoff help
formerCanceled cloud customer without license historyDelayed feedback request
unknownMissing or conflicting evidenceNo lifecycle journey

Teammate history is retained in the product identity. A later purchase does not automatically turn that person into a promotional audience. This protects team members from receiving the wrong kind of message.

References: packages/…/profile.ts• L78-142 packages/…/profile.ts• L157-191 packages/…/schema.ts• L132-135 packages/…/sso.ts• L187-313 apps/…/directory-sync.ts• L152-249

Lifecycle stages

The lifecycle stage is the provider-facing state that starts a journey. A contact stays at idle until the sync has enough evidence that signup is complete, subscription and list rules permit contact, the enrollment boundary allows the account, and the audience is known.

The stage names describe the message path rather than a billing state:

  • free starts independent free-user onboarding.
  • free-v2 starts the controlled free-user activation experiment.
  • customer starts customer onboarding.
  • teammate starts workspace help.
  • former starts the delayed former-customer follow-up.
  • idle means that no lifecycle journey may start.

The free-user experiment assigns a variant once at eligible entry and keeps that assignment stable. A malformed existing assignment stops synchronization instead of silently moving the contact to another path. This separation lets billing or organization changes turn off eligibility without rewriting the underlying product record.

References: packages/…/lifecycle.ts• L64-153 emails/delivery-safety.ts• L4-14 emails/audiences.ts• L41-54 scripts/…/lifecycle.test.ts• L116-246

Profile synchronization

Profile synchronization is the controlled path from current Cap data to a Loops contact. It updates contact properties and lifecycle eligibility, but it does not grant permission to resubscribe a person or recreate a removed identity.

Profile construction

The sync reads current data from the Cap database and the separate license database. It normalizes email addresses, derives audience and plan copy, and adds product properties such as signup time, lifecycle stage, video readiness, and teammate status.

Plan-aware customer copy is selected from the entitlement view. The same profile can therefore support a Pro welcome, a self-hosted welcome, a desktop-license welcome, or a general Cap welcome without making the journey graph know the billing details.

The profile can also carry targeted customer fields such as a multi-seat-owner marker and a safe greeting. These fields let campaign or journey content personalize a message without changing the source product facts.

References: packages/…/profile.ts• L1-5 packages/…/profile.ts• L78-191 packages/…/sources.ts• L84-106 emails/customer-copy.ts• L1-22 scripts/…/profile.ts• L1-9 scripts/…/profile.test.ts• L60-145

Billing transitions

Billing APIs start subscription attempts, while Stripe webhooks turn completed or changed billing events into durable product state. A signed-in checkout keeps the product user identity with the payment session. A guest checkout can create the product user after payment when no existing identity matches the Stripe customer.

The webhook updates the user’s subscription and seat state, then requests a Loops profile refresh. This ordering keeps lifecycle classification tied to the database state that records the billing result. Payment-failure notices remain transactional billing email and do not replace the later profile sync.

The billing path supports both a product checkout route and hosted Stripe checkout. Both paths must preserve enough identity and plan information for the webhook to associate the payment with the correct product user.

References: apps/…/route.ts• L12-109 apps/…/route.ts• L10-91 apps/…/route.ts• L382-650 apps/…/route.ts• L675-786 apps/…/route.ts• L883-968

Durable synchronization queue

Product events place a user into loops_sync_jobs in the same transaction as the related product change. Signup, invite acceptance, SSO provisioning, directory provisioning, organization changes, billing updates, and completed checkout can therefore request a profile refresh without calling the external email API inside the product request.

The queue stores delivery state rather than marketing preference state. It tracks the requested revision, retry timing, lease, profile fingerprint, last synced email, and teammate-join time. A newer revision wins over an older worker result, which prevents a late update from erasing a more recent product change.

References: packages/…/queue.ts• L6-27 packages/…/schema.ts• L141-159 apps/…/route.ts• L145-157 apps/…/route.ts• L616-626 apps/…/route.ts• L777-786 apps/…/route.ts• L954-962 packages/…/sso.ts• L273-312 apps/…/directory-sync.ts• L228-249

Scheduled synchronization

The scheduled web API processes a bounded queue batch after checking the cron bearer secret. The worker reads fresh source data, checks identity and signup state, compares a profile fingerprint, and updates Loops only when the effective profile has changed. The endpoint reports the run status and treats any failed job as a server error for the scheduler.

The normal path is eventual consistency. A failed job remains pending with backoff, while rate-limit responses stop the current run so the provider is not overloaded. Hourly and daily profile checks provide reconciliation for changes that do not have a direct product event.

The following flow shows how a product or billing change becomes a guarded provider update.

flowchart LR
    A[Cap product or billing change] --> B[Queue sync revision]
    B --> C[Authenticated scheduled sync API]
    C --> D[Read Cap and license state]
    D --> E{Profile changed?}
    E -->|No| F[Schedule next check]
    E -->|Yes| G[Update Loops contact]
    G --> H[Evaluate lifecycle guards]
    H --> I[Journey or campaign audience]

The worker refuses ambiguous identities, changed synced emails, incomplete signups, and removed remote contacts. These cases become operational holds for reconciliation instead of automatic contact creation.

References: apps/…/route.ts• L15-59 packages/…/worker.ts• L38-81 packages/…/worker.ts• L201-363 packages/…/lifecycle.ts• L156-169

Directory synchronization

Directory synchronization reconciles active WorkOS directory records for organizations with an active SSO and SCIM entitlement. The protected scheduled API selects due organizations, reads their remote directory members, and turns verified active users into product users, organization members, and teammate profile-sync work.

The reconciliation also removes access when a managed directory user leaves. It keeps the organization owner and users retained by another active directory link, while other affected memberships lose sessions and external access credentials. A large removal set is held for operator approval instead of being applied automatically.

Each organization uses a lease and a bounded time budget. The process limits the due batch, paginates remote data, retries failures, and records partial or held results so a slow or unsafe run does not silently claim that the directory is current.

The following flow shows how a remote directory snapshot becomes a guarded organization and lifecycle update.

flowchart LR
    A[Due organization sync] --> B[Authenticated directory-sync API]
    B --> C[Read verified WorkOS organization and directories]
    C --> D[Reconcile active directory users]
    D --> E{Safe change?}
    E -->|Add or retain| F[Provision membership and queue profile sync]
    E -->|Remove| G{Large removal?}
    G -->|Yes| H[Hold for approval]
    G -->|No| I[Remove membership and revoke access]

References: apps/…/route.ts• L14-56 apps/…/directory-sync.ts• L118-149 apps/…/directory-sync.ts• L152-249 apps/…/directory-sync.ts• L275-357 apps/…/directory-sync.ts• L360-537 apps/…/directory-sync.ts• L540-671

Loops owns subscription preferences. The sync carries source consent into the profile and keeps existing global unsubscribes, suppressions, bounces, complaints, and mailing-list removals. A normal profile update does not set subscribed to true or add a contact back to a removed list.

The local loops tooling tests this as a held boundary. It preserves negative consent during profile updates and keeps contacts from entering lifecycle paths when a list or global subscription is no longer active. Historical import and provisioning tooling is maintained outside this repository.

References: packages/…/sync-policy.ts• L15-23 packages/…/sync-policy.ts• L34-69 scripts/…/profile.test.ts• L289-347 scripts/…/README.md• L8

Customer activation

Customer activation measures whether an independent user has reached the first useful product outcome. It turns recording and sharing signals into conditional help rather than sending every message to every user.

Activation signals

The activation view distinguishes a completed cloud video from a pending or failed upload. It also uses the first-view notification marker as a practical signal that a completed video has reached another person. Local-only recordings are outside this sync view.

The newer signal set also suppresses follow-ups while an upload is pending and ignores a recent application notification for a short quiet period. This reduces messages that arrive while the product is still processing or while another product email is already handling the same moment.

Viewer grants and organization visibility defaults are product access controls. They do not by themselves change the activation signals or grant marketing consent. A change that should make direct viewer access affect activation must update the activation source and its journey conditions together.

References: packages/…/activation.ts• L7-29 packages/…/sources.ts• L66-83 emails/onboarding-runtime.md• L13-23 packages/…/schema.ts• L212-228 packages/…/schema.ts• L561-580

Activation follow-ups

The free activation journey uses the signals to select the next useful message. A user without a completed video can receive recording help. A user with a completed but unshared video can receive sharing help. A user who is ready for Pro can receive plan or workflow guidance.

The older free journey uses the simpler capHasVideo and capHasSharedVideo conditions. The free-v2 journey uses capNeedsRecordingHelp, capNeedsSharingHelp, and capReadyForPro, and it is assigned only when the experiment gate is enabled for the configured date boundary. Pending uploads and recent application notifications hold the relevant follow-up until the signal is safe to act on.

References: packages/…/lifecycle.ts• L49-61 packages/…/lifecycle.ts• L102-135 emails/flows.ts• L19-83 emails/onboarding-runtime.md• L5-11 scripts/…/lifecycle.test.ts• L247-262

Campaign email assets

The email library defines the content and audience intent for lifecycle journeys and one-off product campaigns. It keeps copy, shared branding, customer plan variations, flow timing, and audience guards separate so a content change does not silently change enrollment policy.

Lifecycle journeys

The managed journeys cover five lifecycle paths. Loops applies the audience and eligibility filters downstream at every journey entry, so a profile change can stop later delivery after a purchase, invite, unsubscribe, or teammate classification.

JourneyAudienceProduct purpose
Independent free-user onboardingfreeHelp a new independent user record, share, and understand plans.
Customer onboardingcustomerWelcome the customer with plan-aware copy, a repeatable workflow idea, and a feedback request.
Free activation and Pro conversion v2free-v2Test a more signal-based activation path for eligible free users.
Teammate onboardingteammateHelp an invited or SSO user find the workspace and hand off work.
Former customer follow-upformerAsk for feedback after cloud access ends.

Journeys use stable email and step identities. They are not the same as transactional product email: the Loops journeys are lifecycle communication, while authentication, invitations, notifications, billing notices, payment-failure notices, and support messages remain on their existing Resend paths.

References: emails/flows.ts• L19-102 emails/audiences.ts• L1-27 emails/README.md• L7-19 emails/CATALOG.md• L5-23 apps/…/route.ts• L794-881

Transactional invitations

Transactional invitations deliver access to a specific product resource. The video viewer invitation addresses the named email, links to the recording, and states that the recipient does not need to join the owner’s organization; it is not a lifecycle journey or a campaign.

The product stores this access separately from the email asset. A viewer grant ties one email to one video, records who invited the viewer, and can be revoked. Deleting the video also removes its grants. An organization-level private default can override the environment default for new videos, so access policy remains a product decision rather than a marketing decision.

References: packages/…/video-viewer-invite.tsx• L17-63 packages/…/schema.ts• L212-228 packages/…/schema.ts• L561-580 packages/…/video-sharing-default.ts• L7-24 packages/…/0049_jittery_professor_monster.sql• L1-13

Campaign templates

Campaign templates are manually scheduled product announcements. They do not enroll contacts by themselves. Each campaign targets an exact audience, and the free-user campaign also requires promotional eligibility and excludes teammates.

The current templates are:

  • A customer launch announcement for current customers.
  • A noncustomer launch announcement for eligible independent free users.

The templates share the product-update theme but use audience-specific copy. Scheduling requires a fresh sync health check and a separate operational decision because campaigns are not covered by automatic lifecycle timing.

References: emails/campaigns.ts• L1-18 emails/CATALOG.md• L165-172 emails/README.md• L42-54

Email assets and personalization

Marketing email assets are assembled from source definitions. Shared branding supplies the sender, logo, layout, footer, and fallbacks. Customer copy supplies plan-specific welcome text, while profile sync supplies the stored greeting and plan fields.

Custom MJML content requires browser review after export and upload. The catalogue and local checks can verify structure and source relationships, but they cannot prove that the remote rendered email matches the local asset.

References: emails/README.md• L7-23 emails/README.md• L25-40 emails/customer-copy.ts• L1-22 emails/CATALOG.md• L174-189

Lifecycle operations

Lifecycle operations keep synchronization, delivery controls, directory reconciliation, and credential cleanup separate. The local runners can seed and process profile sync work, while scheduled APIs also reconcile managed directories and content, provisioning, verification, and delivery-watchdog tooling lives in the private marketing repository.

Operational runners

The repository’s loops scripts provide operator-facing entry points for queue seeding and bounded synchronization. A seed command reports or applies work for completed signups, while sync.ts --apply invokes the same worker as the scheduled web API. The runner refuses a dry invocation, which prevents an accidental sync from changing contacts without an explicit operator action.

The loops folder does not own campaign content or the full migration and delivery toolchain. The README directs those functions to the private CapSoftware/cap-marketing repository, so changes to those operations must preserve the contracts of the database profile and scheduled sync API.

References: scripts/…/README.md• L1-8 scripts/…/sync.ts• L1-12

Developer storage accounting

Developer storage accounting is a scheduled database operation that charges each active developer app for its stored video duration. It converts chargeable storage into daily micro-credit usage and records the charge with the app’s credit balance.

The protected route sweeps current and recently completed days. It skips deleted apps and already settled accounts. A daily ledger entry and storage snapshot prevent duplicate charges, while an account with insufficient credit remains eligible for a later attempt and can trigger an out-of-credit notice. The run uses bounded pages, parallel account work, and continuation requests so a large account set can finish across several scheduled hops. It also handles missed first-month charges and settles delivery days only after the storage sweep completes. Due automatic top-ups run before the first sweep and after the final sweep.

References: apps/…/route.ts• L15-43 apps/…/route.ts• L47-97 apps/…/route.ts• L106-225 apps/…/route.ts• L237-310 apps/…/route.ts• L313-413 apps/…/route.ts• L433-489 apps/…/developer-pricing.ts• L1-14 packages/…/schema.ts• L1867-2001

Developer delivery metering

Developer delivery metering is a protected scheduled operation that turns infrastructure delivery logs into account usage records. It reads a configured object-storage log source, resolves delivery data to stored accounts, and records method-based usage such as playlist, rendition, MP4, and audio delivery.

The run is bounded by file count and time. It reports work that was recomputed, finalized, deferred, or failed so a later run can continue incomplete metering. If the delivery-log source is not configured, the endpoint returns a successful skipped result instead of changing account state.

The delivery meter shares the scheduled credential boundary with other operational loops. Its output supplies the delivery billing step that the storage sweep settles only after all required storage work is complete.

References: apps/…/route.ts• L23-54 apps/…/route.ts• L56-89 apps/…/route.ts• L91-129

Developer transcript cleanup

Developer transcript cleanup is a protected scheduled operation that closes stale transcript work and removes stale upload data. It returns separate counts for expired work, redispatched work, swept storage, and caption records reconciled after deleted videos.

The endpoint rejects requests without the shared cron credential. It reports cleanup errors as an internal failure rather than presenting a partial successful run as complete. Caption reconciliation also exposes synced and failed counts so operators can see when deleted-video metadata needs further work.

References: apps/…/route.ts• L18-33 apps/…/route.ts• L35-61 apps/…/route.ts• L62-80

Developer upload cleanup

Developer upload cleanup protects object storage from unfinished and unreferenced data. It aborts old multipart uploads, removes files that have no matching infrastructure record, and purges files for deleted or failed developer videos.

The operation is bounded by upload count, concurrency, and time. A large backlog continues on later runs. Any failed abort or purge makes the scheduled request fail, which keeps incomplete cleanup visible to the scheduler instead of treating it as finished.

The following flow shows how one scheduled boundary handles unfinished uploads and video-related storage.

flowchart LR
    A[Authenticated cleanup request] --> B[Abort stale multipart uploads]
    B --> C[Remove unrecorded files]
    C --> D[Purge deleted video files]
    D --> E[Purge failed video files]
    E --> F[Return counts or report failure]

References: apps/…/route.ts• L19-27 apps/…/route.ts• L47-128 apps/…/route.ts• L130-205 apps/…/route.ts• L211-213

Developer video purge

Developer video purge is the focused scheduled operation for closing stalled developer imports and removing files that belong to deleted developer videos. It provides a smaller operational boundary than the combined upload cleanup route when operators need to run or monitor these repairs on their own.

The protected endpoint first reaps old imports that still wait on deleted or unfinished videos. It then purges eligible deleted-video files and returns counts for both activities. Any failed import cleanup or file purge produces an internal failure so unfinished work is not hidden by a successful response.

References: apps/…/route.ts• L14-27 apps/…/route.ts• L30-77 apps/…/developer-video-purge.ts• L60-91 apps/…/infra-video-import.ts• L1290-1346

Delivery safety

The protected health endpoint provides the sync state used by delivery operations. The delivery watchdog is maintained in the private marketing repository rather than in the local loops scripts, so its controls must consume the same health and lifecycle contracts as the scheduled sync.

References: apps/…/route.ts• L14-58 packages/…/health.ts• L18-69 scripts/…/README.md• L8

Activation gates

Production activation is a cutover, not a side effect of deploying the sync code. The team must configure the mailing list and enrollment boundary, use an owned test allowlist, prove account transitions, seed held sync jobs, and then choose when new contacts may enter live journeys.

The local runner requires --apply, the scheduled API requires the cron bearer secret, and runtime configuration requires an explicit enrollment boundary and test allowlist. These separate controls allow profile synchronization tests without allowing contacts to enter live journeys.

References: scripts/…/README.md• L3-6 scripts/…/sync.ts• L5-12 scripts/…/lifecycle.test.ts• L495-527 apps/…/route.ts• L30-59

Credential cleanup

The protected cleanup endpoint removes expired or retained authentication records for agent APIs and MCP access. It runs as a bounded scheduled job, so old authorization codes, idempotency records, completed operations, tokens, unused clients, stale clients without active tokens, and expired registration quotas do not remain in the product database.

The endpoint checks the shared cron credential before it starts. Agent API cleanup is required for a successful run, while an MCP cleanup error is logged and does not prevent the endpoint from returning the agent cleanup result. This keeps routine maintenance separate from customer messaging while using the same scheduled-operations boundary.

MCP access also has a protected live transport boundary. The /api/mcp endpoint accepts requests only from approved origins and the configured issuer, requires a valid bearer token with the caps:read scope, limits request bodies, and does not allow a stateful GET session. It passes the authenticated user identity to the MCP handler and marks responses as non-cacheable. This keeps external agent access tied to an explicit identity and prevents transport responses from becoming shared cached data.

References: apps/…/route.ts• L1-32 apps/…/agent-api-cleanup.ts• L17-103 apps/…/mcp-cleanup.ts• L17-97 apps/…/route.ts• L18-150

Protected data

Shared database cryptography protects values that must be stored in recoverable form, while password handling stores a one-way derived value for later verification. Both paths reject empty input and use a random salt. Encryption also uses a random initialization value and accepts supported key sizes so stored credentials can survive current key formats.

The encryption key is read from server-only configuration and is checked before use. Decryption failure is reported as a failed operation rather than returning partial data. Password checks use a timing-safe comparison after deriving the candidate value, which keeps authentication data separate from recoverable secrets.

References: packages/…/crypto.ts• L3-60 packages/…/crypto.ts• L63-127 packages/…/crypto.ts• L130-194

Change checklist

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

  • Keep audience classification aligned with billing status, license renewal dates, membership ownership, invite state, SSO state, directory-managed membership, and retained teammate history.
  • Keep sign-in email normalization aligned with account lookup, OTP identity, blocked-account checks, and disposable-signup checks.
  • Keep allowed and blocked domain rules distinct: allowlists restrict new users, while blocked entries also invalidate existing sessions.
  • Keep disposable-email screening limited to new unverified accounts and preserve access for verified, paid, or linked users.
  • Keep SSO profile identity, verified organization domains, active connections, and product account links aligned before provisioning membership.
  • Keep directory provisioning and deprovisioning aligned with organization membership, retained directory links, credential revocation, and teammate lifecycle origin.
  • Keep directory-sync leases, refresh intervals, time budgets, retry state, and removal approval state aligned so an incomplete snapshot cannot remove access.
  • Keep checkout metadata and customer identity links aligned with webhook lookup rules for signed-in and guest payments.
  • Keep webhook subscription updates and Loops queue writes aligned so a completed purchase or cancellation cannot leave a stale lifecycle profile.
  • Keep billing dunning messages separate from lifecycle journeys and preserve their event idempotency keys.
  • Keep lifecycle stage names aligned across profile sync, downstream journey guards, and the registered Loops workflows.
  • Keep product events and queue writes in the same transaction when a new event can change audience, eligibility, or teammate-join timing.
  • Keep source activation signals aligned with the conditions used by both free-user journeys and with existing Resend recording notifications.
  • Keep consent merge rules from resubscribing a contact or restoring a removed mailing-list membership.
  • Keep profile fingerprints stable when adding derived fields, and decide whether a new field needs reconciliation for existing contacts.
  • Keep campaign audience filters separate from lifecycle enrollment and check campaign timing against active transactional emails.
  • Keep custom email IDs, flow step keys, variables, fallbacks, and remote resource IDs stable when changing assets.
  • Keep viewer grant uniqueness and revocation behavior aligned with the viewer invitation copy and recording access checks.
  • Keep the private organization override separate from the environment default and from lifecycle audience or consent fields.
  • Keep the external watchdog’s health and journey targets aligned with every registered journey and require manual pause handling for workflows already sending.
  • Keep scheduled cleanup authentication and retention rules aligned with the records that agent API and MCP flows create.
  • Keep MCP origin, issuer, scope, body-size, and cache controls aligned with the clients that use the live transport endpoint.
  • Keep the database encryption key format and protected-value handling aligned with all stored secrets and password verification paths.
  • Keep the developer storage snapshot date, processed state, credit debit, and ledger entry aligned so a daily charge is neither duplicated nor omitted.
  • Keep storage pricing units aligned across video duration, daily micro-credit calculation, account balances, and transaction metadata.
  • Keep storage sweep continuation markers and hop limits aligned with scheduler behavior so a large account set is resumed without skipping or repeating work.
  • Keep storage settlement and delivery-day billing after storage continuation completes, and keep the final-hop condition aligned with the scheduler’s continuation behavior.
  • Keep delivery-log location, delivery method names, account resolution, and metering result states aligned so deferred infrastructure usage is not lost.
  • Keep stale-upload age, abort limits, and continuation reporting aligned so object-storage cleanup works off a bounded backlog.
  • Keep transcript expiry, upload sweeping, and deleted-video caption reconciliation in the same cleanup result contract so operators can distinguish each kind of unfinished work.
  • Keep stalled-import, deleted-video, and failed-video purge results visible as scheduled failures when any cleanup work remains incomplete.

Important failure modes

TriggerConsequenceGuard
A teammate signal is lost during profile classificationAn organization user can enter a promotional customer or free-user journeyRetain teammate history and give teammate evidence priority over paid status
An SSO profile does not match the intended organization or verified domainAn identity can join the wrong organization or create an untrusted membershipMatch the sign-in intent, active connection, product organization, linked account, and verified domain
A directory snapshot is slow or incompleteThe sync can apply a partial view as if it were the full source of membershipUse a deadline, lease, partial result, and retry state before changing access
A directory provider reports a mass departureMany valid organization memberships can be removed at onceHold large removals until a recent operator approval exists
A managed directory user has another active directory linkAccess can be revoked even though another source still grants membershipRetain users with another active link and remove only the departing link
A directory removal targets the organization ownerThe organization can lose its owner or receive an invalid membership changeRetain the owner and skip owner deprovisioning
A blocked email is checked only at new sign-inAn already issued session can continue to access the accountReject the blocked identity during session-token decoding
A disposable-email check treats every matching address as a new accountA verified or paid customer can lose accessApply the filter only to unverified, unpaid, and unlinked accounts
A DNS outage is treated as proof that an email is disposableA provider outage blocks valid signupsTreat resolver failure as not disposable and use a short failure cache
A billing or invite change updates product data but not the sync queueLoops keeps stale audience or eligibility fieldsEnqueue the user in the same transaction as the product change
A checkout webhook cannot map the Stripe customer or session to a product userSubscription state and lifecycle data remain stale after paymentPreserve the session identity, retry unmapped webhook delivery, and create a guest user only for marked guest checkout
A synced email changes or the remote contact disappearsA worker could update or recreate the wrong identityHold the old contact and require identity reconciliation
A source opt-out is treated as a normal subscribed profileA later update can send unwanted marketingPreserve suppression and unsubscribe records and never write subscribed: true during normal sync
Activation sees a pending upload as a completed recordingThe user receives sharing or Pro follow-ups too earlyRequire a completed cloud signal and suppress follow-ups during pending processing
A viewer grant is treated as marketing consentAn invited viewer can receive a lifecycle message without audience or consent checksKeep viewer access grants and marketing profile state separate
A private organization override is ignored when creating a new videoA recording can be more open than the organization allowsResolve the organization setting before falling back to the environment default
A viewer grant is not removed with its videoStale access records can remain after the resource is goneUse the video relationship with cascade deletion
Sync health fails while a workflow is sendingDelivery controls may not stop an already active journeyPause the workflow manually before applying a persistent delivery hold
A custom MJML upload changes body content but not remote metadataSubject, preview, sender, or fallback values can remain staleReview the rendered email and metadata in the Loops UI after upload
A payment failure is sent through the lifecycle pathA billing retry notice can be delayed, duplicated, or sent to the wrong audienceKeep renewal dunning on the transactional email path and use an invoice-attempt idempotency key
The cleanup endpoint has no valid cron credentialScheduled credential cleanup is rejected or fails as a server configuration errorRequire the configured bearer credential and use the protected scheduled route
MCP cleanup fails after agent API cleanup startsSome expired MCP records remain until a later run while the endpoint still reports successInspect the logged cleanup error and monitor the next scheduled run
An MCP request uses an unapproved origin, issuer, scope, or body sizeExternal agent access is rejected before it reaches the product handlerEnforce the live transport boundary and keep responses non-cacheable
The database encryption key is absent or has an unsupported formatRecoverable protected values cannot be encrypted or decryptedValidate the server-only key before deriving the encryption key
A password hash or candidate has an invalid shapeVerification can fail unexpectedly or expose an unsafe comparison pathReject empty input and compare derived values with a timing-safe operation
A developer storage run lacks the cron credentialStorage charges are not applied and the scheduled operation is rejectedRequire the configured bearer secret before reading or changing app data
A daily storage snapshot is already processedThe same app can be charged twice for one daySkip processed snapshots and write the debit and snapshot in one transaction
A developer credit balance is below the daily storage chargeNo debit or completed snapshot is written, so the app remains eligible for a later runUse an atomic balance sufficiency check and reconcile reported processing counts with ledger and snapshot state
A storage sweep reaches its time or hop limitSome accounts remain unprocessed and delivery-day settlement can wait for a continuation that never completesReturn the date and account cursor, schedule the bounded continuation, and settle dependent work only on the final hop
A delivery log source is not configuredInfrastructure delivery usage is skipped and account metering remains unchangedTreat the explicit skipped result as an operational configuration state and monitor it
Delivery logs exceed the file or time boundSome delivery usage remains deferred for a later runUse the bounded meter result and process the reported remainder on the next schedule
A stale multipart upload remains in object storageUnfinished upload parts consume storage and remain outside normal video recordsAbort uploads older than the retention threshold and report remaining backlog
A transcript or developer upload cleanup step failsStale work or files remain while a run may appear completeReturn an internal failure and log the failed cleanup stage
Deleted-video captions cannot be reconciledCaption records can remain out of sync with deleted mediaReturn the failed caption count and monitor the cleanup result for a later repair
A deleted or failed developer video is not purgedObject storage retains data that no longer has a live product useRun the dedicated purge and surface every failed file operation
A stalled import remains active after its video is deleted or stops progressingImport work can remain open and hide incomplete developer-video cleanupReap eligible imports in the protected purge run and fail the schedule when reaping reports an error

Key files

FileWhy to read it
packages/…/sources.tsShows which Cap and license data becomes a lifecycle profile.
packages/…/profile.tsDefines consent, audience, entitlement, teammate, and plan classification.
packages/…/lifecycle.tsDefines enrollment gates, lifecycle stages, activation follow-ups, and retry timing.
packages/…/worker.tsShows the scheduled profile-sync boundary and safe handling of identity or provider failures.
packages/…/queue.tsShows how product changes request durable synchronization work.
packages/…/activation.tsDefines the product signals used for recording and sharing readiness.
packages/…/schema.tsShows the durable user marketing origin, sync queue, directory link, organization sharing default, video viewer grant, and developer storage accounting records.
packages/…/video-sharing-default.tsDefines how an organization’s private default controls the visibility of new videos.
packages/…/0049_jittery_professor_monster.sqlRecords the schema change that adds viewer grants and the organization sharing default.
packages/…/video-viewer-invite.tsxDefines the transactional email that gives a named viewer access to a recording.
packages/…/auth-options.tsConnects sign-in admission, blocked-account session invalidation, SSO membership provisioning, and account creation to the product identity.
packages/…/sso.tsValidates SSO identities and records teammate membership changes that trigger lifecycle sync.
packages/…/domain-utils.tsDefines email normalization and configured allow or block rules.
packages/…/disposable-signup.tsDefines when throwaway-email screening blocks a new Cap account.
packages/…/disposable-email.tsDefines the domain and mail-server checks used by throwaway-email screening.
apps/…/directory-sync.tsReconciles WorkOS directory membership, access removal, leases, retries, and large-removal holds.
apps/…/route.tsDefines the authenticated scheduled boundary for directory reconciliation.
emails/flows.tsDefines lifecycle journey audiences, timing, and conditional messages.
emails/audiences.tsDefines contact properties and the common audience conditions.
emails/campaigns.tsDefines manually scheduled customer and free-user campaign templates.
emails/customer-copy.tsDefines plan-aware customer welcome content.
scripts/…/README.mdGives the current operational boundary between local sync runners and the private marketing tooling.
scripts/…/profile.tsExposes the shared profile classifier to local loops tooling.
scripts/…/sync.tsRuns the same bounded worker as the cron route after explicit operator approval.
apps/…/route.tsStarts an authenticated subscription checkout and preserves product identity for billing completion.
apps/…/route.tsStarts a guest subscription checkout that can later create a product identity.
apps/…/route.tsConverts verified Stripe checkout and subscription events into product billing state and sync work.
apps/…/route.tsDefines the authenticated scheduled sync endpoint.
apps/…/route.tsDefines the authenticated health endpoint used by delivery safety.
apps/…/route.tsDefines the protected daily loop for storage charges, delivery-day settlement, and continuation work.
apps/…/route.tsDefines the protected loop that meters infrastructure delivery logs into account usage.
apps/…/route.tsDefines the protected loop that expires stale transcript work, sweeps uploads, and reconciles deleted-video captions.
apps/…/route.tsDefines the bounded cleanup loop for multipart uploads, unrecorded files, deleted videos, and failed videos.
apps/…/route.tsDefines the protected scheduled boundary for reaping stalled imports and purging files from deleted developer videos.
apps/…/developer-video-purge.tsDefines which deleted developer-video files are ready for purge and how purge completion is recorded.
apps/…/infra-video-import.tsDefines how stalled or deleted-video imports are closed during the purge operation.
apps/…/developer-pricing.tsDefines the shared conversion from stored video minutes to daily micro-credit usage.
apps/…/route.tsDefines the protected scheduled boundary for agent API and MCP record cleanup.
apps/…/agent-api-cleanup.tsDefines retention cleanup for agent API authorization, operation, idempotency, and token records.
apps/…/mcp-cleanup.tsDefines retention cleanup for MCP OAuth records and registration quotas.
apps/…/route.tsDefines the authenticated, origin-limited MCP transport boundary for external agent access.
packages/…/crypto.tsDefines encryption for recoverable secrets and derived-value checks for passwords.