Business ownership, public contracts, in-process events, projections, and isolated boundaries
Guided views
Explore this system
Step through curated paths without changing the source diagram.
Beat
Next
ReadyChapter 01 / 01
Guided chapter
Diagram guideExplore this system
Inspecting compiled semantics
E ExportT ThemeS Style0 Reset+ Zoom in- Zoom outEsc Close
Find a node
⌕/
No matching nodes
Semantic passport
Verified source
Authored reach
Route probeChoose a start node
Pick two semantic nodes on the diagram
Choose the source, then the destination. Direction matters.
Semantic lensCompare system roles
Choose up to two semantic kinds. One reveals its real traffic; two compare only direct authored relationships.
Choose a kind to inspect its nodes and touching relationships.
Semantic radar
Building overview
Click nodeDrag to pan
Secure communications
• Communications owns durable direct/group/client conversations in the chat schema. Identity exposes PortalIdentityService for unique active UserProfile resolution. VIPProfile alone grants no chat access.
• Communications publishes chat.message.sent after commit; Notifications receives staff recipient ids only and respects conversation muting. Realtime broadcasts metadata invalidations, while history and commands remain authenticated HTTP.
• Internal VIP, Program Run, session and analysis references contain only typed ids. Receivers open existing independently authorized business screens; client conversations cannot carry these internal references.
• Identity persists PortalAccessAttempt only after verified VIP Cognito authentication is denied. Records aggregate by pool and subject, never passwords or raw claims. Admin/manager staff revalidate the exact enabled Cognito identity and explicitly grant UserProfile access and/or link an existing VIP in a version-checked serializable transaction. Existing email/subject owners and VIP links cannot be replaced. Completed decisions publish the sanitized identity.vip_access.login_reviewed Audit fact after commit; failed logins are not staff audit entries. See docs/architecture/vip-login-access-review.md.
• Identity owns the Home guided-tour reset as a UI assistance preference on UserProfile.accessibilityPreferences.homeTourResetToken. Admin/manager staff POST /vip-access/:id/home-tour/reset for one non-archived account; an atomic JSON-field update preserves other preferences and records the completed identity.vip_access.home_tour_reset audit fact. The cookie-authenticated /portal/me projection exposes only home_tour_reset_token. Home appends this non-secret generation to the existing account-scoped local tour key, preserving prior first-visit behavior until reset and replaying once per browser/generation after identity refresh. This changes no authentication, enrollment, assessment answers or Track progress and adds no runtime or event transport.
Synchronous communication
• All About You import additionally reads same-year Consultations A1:A1502 block evidence through the existing Integrations adapter. Explicit FBF N - Week M headings and inherited weeks define observed ranges and post-event markers, never quarters or Zoom tab attribution. Sales retains versioned evidence in campaign dimensions and private Gold sourceEvidence; reviewed publication hashes include mapping changes. The optional all_about_you_fbf overview query filters only that card. Missing attribution is unavailable; worksheet-year correction, monthly source precedence and idempotent source keys remain authoritative.
• The Sales overview All About You contract exposes conversion_showed, the attendance denominator matched to confirmed became_vip contributions. Incomplete spreadsheet months and unknown Airtable outcomes no longer block other eligible records; excluded groups produce partial quality and an explicit basis warning. Source ownership, monthly provider precedence and undated-adjustment boundaries remain unchanged.
• Consultations follows the existing Integrations-to-Sales aggregate adapter boundary. Sales owns consultations campaign Silver, SalesConsultationMetricsGold and the Gold-only overview read composition with provider-keyed Airtable appointments. Both import paths commit Silver and Gold together. A versioned Bronze replay runs once before API and cron startup without provider reads. Sales owns its durable page checkpoint and completion marker; completed versions skip restart work. Incremental imports share the mapper and atomic Silver/Gold writer, checking current source hashes and rule versions under row locks. Published spreadsheet coverage takes monthly priority before date or attribution filters; unsupported dimensions and absent counts remain explicit. The manual import catalog, retry and publication preserve the consultations dataset independently from Registration and All About You.
• Business modules consume another context only through its explicit public contract
• All About You crosses the existing Integrations-to-Sales adapter boundary as approved aggregate cells, with worksheet-year correction and original date evidence. Sales owns separate aggregate/individual Silver and canonical SalesAllAboutYouGold. Spreadsheet coverage has monthly priority over Airtable before date/dimension filters. Undated adjustments require a complete month; unavailable attribution or conflicting VIP counts remain explicit. The overview exposes card-specific quality, nullable metrics and source freshness; private lineage never crosses to the browser.
• Composition roots may wire modules; internals remain private
• The public SubscriptionRenewalsService.listRenewingBetween read supplies the complete UTC upcoming-month Slack digest and matched-VIP subscription-ending facts using the same effective dates, package details and selection as the UI. The financials-authorized renewal queue projects one representative subscription per VIP before filtering and pagination, excluding canceled representatives, VIP Free and internal emails. VIP-scoped reads preserve complete subscription history and expose current VIP profile status independently of subscription selection; start dates and late-start state reuse VIP/CRM ownership and existing confirmation permissions. VIP-list dates distinguish confirmed effective service start from the earliest recorded positive paid invoice matched by exact customer id. Financials-authorized next-contract reads include applied pause days once and preserve manual operational overrides. Service-duration presentation excludes overlapping enabled pauses and stops at known cancellation; missing evidence stays unknown
• VIP/CRM VipNotesService consumes ClinicalNotesService through clinical/public.ts; both contexts recheck their own grants
• The merged notes feed queries only readable kinds, orders by createdAt/id DESC, and binds its opaque cursor to VIP plus readable scope
• VipNotesController fixes scope to /vip-profiles/:vipId/notes, resolves the active StaffUser, and exposes no feed filters beyond pagination
• Marketing reads and replaces ActiveCampaign tags through the Integrations public contract
• Delivery may retain a provider URL as review evidence, but analysis resolves stable technical video ids through Integrations; private S3 keys never cross
• Spreadsheet imports hand reviewed Program Run VIP matches and explicit exclusions from Integrations to Delivery; Delivery remains the owner of Program Run membership
• Registration metrics cross from Integrations to Sales as allowlisted normalized records. Workbook title metadata identifies programs and editions from zoom-fbf-N-monthYY; worksheet names are authoritative over internal tags. Annual counts and explicit affiliate totals stay in their original monthly grain, with reviewed worksheet associations on campaign dimensions. Publication atomically writes Silver and Gold. Dashboard reads stored totals only, exposing shared edition scope and reporting-period dates separately from confirmed program campaigns. The legacy FBF Campaigns mapping remains optional; Zoom time-series quantities are not imported as registrations.
• Practice Better clients, tags and session notes remain Integrations-owned staging; explicit clinical read access protects the Imports workspace and an explicit second stage copies uniquely matched source records through the Clinical public service
• Integrations resolves unique existing VIPs and active staff authorization through Identity public services, then calls ClinicalSourceImportService; no raw Clinical models cross back
• Identity resolves active staff and existing VIPs for ClinicalWorkspaceService; Clinical owns summary and body-map revisions, explicit grants and content-free access audit. The UI reads exact-VIP video catalogs through the existing Integrations HTTP contract
• Clinical exposes an explicitly authorized, VIP-scoped YouTube catalog from current copied note revisions. The frontend opens an official privacy-enhanced YouTube iframe only on staff selection; only a validated video id and origin referrer cross to YouTube, never VIP identifiers or note content. Existing recording permissions remain separate
• Historical Sales reads use the Integrations public adapter for allowlisted Airtable pages; Sales owns leased checkpoints, immutable source versions and row validation. Missing records are retained for review; metric publication stays blocked
• Sales owns immutable metric-review revisions and sanitized decision pages for manual acquisition imports. Staff confirmation pins review id/hash; publication rechecks the active baseline and atomically supersedes changed facts with the selected FBF, All About You or Consultations projection. Missing metrics remain active for review; Airtable metric publication and legacy cutover remain blocked
• Sales owns organization-scoped import history and revision-checked cancel/retry routes. GET historical-imports/sources and the manual start page expose Registration, All About You and Consultations spreadsheet datasets. Existing Airtable historical reads retain review/resume/cancel and blocked publication; new-capture/restart controls are absent. Individual Airtable All About You and Consultations keep the configured Sales Overview cron; All About You conversion also writes canonical Gold
• Sales Overview shares inclusive UTC date bounds across cards. Membership keeps immutable snapshot and interval comparison rules. FBF Gold v4 keeps annual registration and ad counts, and uses annual affiliate counts when present. Confirmed February and May 2026 editions may use the unique-labelled H totals from the 2026 Affiliate registrations worksheet as reported counts, never deduplicated people or sums of weekly cells. Business-confirmed reporting mappings are 2024 February FBF1, May FBF2, July FBF3 and November FBF4; 2025 February FBF1, May FBF2, August FBF3 and November FBF4; 2026 February FBF1 and May FBF2. Same-year Consultations blocks supply other unambiguous associations, including August 2026 FBF3. Zoom worksheet names have no role. Reporting periods are not actual event dates. Reviewed publication preserves source lineage and replaces associations without duplicating counts. Different annual and weekly-unique affiliate definitions suppress incompatible comparisons. Missing values remain null and display as unavailable. No new worker, table or migration.
• Acquisition precision errors expose only approved metric labels, worksheet/cell references and decimal value/unit/scale evidence. Integrations converts percentage ratios without binary division artifacts; Sales retains immutable old captures and requires an explicit new capture for corrected values
• The complete existing Stripe import calls Sales MembershipHistoryService. Identity MembershipEvidenceService supplies sanitized VIP coverage and active pauses; Engagement supplies the last completed UTC week. Sales atomically versions daily MembershipCapture, per-VIP Silver and aggregate Gold, serving authorized /sales/overview/memberships with exact 30-day comparisons only when evidence is complete. No new worker, direct cross-context table reads or manual publication flow.
• Delivery exposes GET /vip-session-history to the VIP drawer under attendance.view. The paginated read combines current live and on-demand attendance with sessions within ProgramRunVip membership intervals; session dates and timezones remain Delivery-owned. Identity activity history is not the attendance source of truth.
• Delivery owns occurrence-scoped joined_by_mistake reviews through the attendance.manage candidate endpoint. A reviewed accidental join has no VIP or attendance link and does not block attendance finalization or Session Analysis assignment. Unlink restores needs_review; meeting reprocessing preserves human reviews. Existing manual attendance, analyses, and attendance supported by another candidate remain protected.
• Studio access: Identity authorizes video deletion and recovery through session_recordings.delete, inherited by administrators and separately grantable to non-admin staff; session_recordings.manage alone does not grant deletion. Delivery allows session_analysis.edit_own to soft-delete only an owned draft with no final render, checking ownership and draft state again in the write. The Integrations project catalog exposes the creating StaffUser id for accurate action visibility.
• Attendance opens the Integrations-owned recording blacklist through authenticated HTTP. attendance.view or recorder_operations.view lists all organization-scoped excluded names; attendance.manage or recorder_operations.manage adds or removes entries. Removal allows future recording without rewriting attendance. Video-source reads expose has_audio metadata so Studio can disable source audio controls for video-only media.
• Identity owns read-only staff impersonation (ADR 0070). Every HTTP request verifies the original Cognito JWT and current administrator authority, resolves an active target, and applies only target permissions and ownership. GET/HEAD are allowed; writes are rejected before controllers. Audit records the viewed StaffUser and verified original administrator; no credentials enter evidence.
• Identity owns separate temporary StaffUser permissions and expiration. Only permanent admins may grant or revoke them through staff updates; RolesGuard checks expiry on every action and /me exposes the separate grant for frontend authorization. Temporary wildcard access retains explicit-grant protections and never permits temporary-access delegation.
• Delivery owns explicit shared-device attendance evidence and pair-scoped video associations for independent VIP analyses. External completion either retains a confirmed private final_video or explicitly records completed_without_video when staff marks the video unavailable; the chosen evidence and request completion commit together. Integrations participant identity and Automatic Attendance matching remain unchanged.
• Engagement exposes VipDropoutRiskReadModule and VipDropoutRiskQuery through its narrow engagement/read-public.ts facade for Identity VIP/CRM and subscription renewal reads. The read facade excludes Engagement controllers and Identity module wiring to prevent circular barrel initialization; cross-context tests consume public contracts.
• Quitter participation review uses public contracts only: Notifications supplies Delivery ConfirmedVipParticipationService.findFirstParticipation as a callback to Identity VipQuitterParticipationMonitorService.reconcileWithParticipation. The per-VIP lock encloses the Delivery read, current profile validation and monitor persistence; older evaluation cutoffs cannot undo a newer observation. Delivery retains attendance ownership; VIP/CRM retains current status and monitoring episodes.
• Delivery returns confirmed positive live participation dated by SessionOccurrence.scheduledAt and confirmed on-demand participation dated by the original upload availableAt. Pending, invalidated, absent, cancelled and future live records are excluded; confirmed uploads may be linked to a future occurrence.
• Engagement classifies missed live attendance as break only when an enabled Identity break covers the occurrence local date, with the return date excluded. Attended, late and on-demand participation remain factual presence. Silver and both Gold projections receive the same classification; source Delivery attendance is unchanged. Report session labels and calendar weekdays use the Program Run IANA timezone, never raw UTC clock labels.
• Delivery adds a versioned experience_vit progression mode: the pinned active Experience VIT recommends, then the membership Director approves before existing transition scheduling. Identity experienceContext supplies assignment id and eligible linked reviewer through its public facade under the assignment capacity lock. Ownership changes or loss of access block pending reviews until explicit revision-checked Director reassignment, including an authorized substitute. Reassignment preserves prior recommendation evidence and requires a fresh recommendation. Existing director/pt_vote snapshots and final decisions retain their semantics; no automatic grants, enrollment changes, new table or worker are introduced.
• Home operational widgets compose existing authorized Delivery attendance/session reads and Identity VIT labels and Delivery Program Run labels without a new context or ledger. The Session Analysis list adds inclusive created_from/created_to filters while preserving soft deletion and analyst ownership scope. Daily workload groups creation-day requests by current VIT; attendance totals deduplicate Live and On-demand VIPs within each occurrence. Bounded period/cycle history preserves source drilldown scope; incomplete reads fail instead of publishing partial totals.
• Identity exports sanitized renewalForecastEvidence through SubscriptionRenewalsService: exact-customer queue selection, effective dates, package rules and source freshness. Sales atomically captures immutable Renewal Bronze, dated customer Silver and daily expected-count Gold after the existing successful complete VIP import chain; page-limited or failed imports do not publish. Authorized /sales/overview/renewals reads latest Gold for UTC quarters and date intersections. Completed quarters and unverified realized/conversion outcomes remain null. Unsupported attribution returns unavailable. Manual changes appear after the next full import; capture/source freshness are separate. No provider access on dashboard reads, direct cross-context table reads, new worker, money or inferred renewal-cycle completion. The standalone capture CLI consumes Sales RenewalHistoryService.forLocalCapture; Sales consumes Identity SubscriptionRenewalsService.forLocalRead. Repositories are assembled inside their owning contexts without initializing provider clients or worker schedules. PR2 stages 1–10 now implement the local operational cohort pipeline: Identity exports allowlisted plan/status/date/correction evidence for all stored contracts, including predecessors. Sales preserves original Expected due quarters, compares fresh observations for unique effective successors, technical plan changes and full operational-term rollover, and excludes installments, pauses, date corrections, future schedules and ambiguous/missing evidence. A one-per-cycle outcome plus journal handles effective successor cancellation, support replacement and subsequent term admission without duplicate realization. Cancellations of completed historical terms or unrelated predecessors do not erase a valid successor. Local snapshots, cycle/outcome updates, events, daily Expected/Realized/unknown Gold and publication metadata commit atomically under the existing advisory lock; stale, older, page-limited or shrinking sources cannot supersede published Gold. Legacy queue replay retains provenance/candidates without inventing missing old plan references or erasing rich evidence. Public-factory CLIs and the existing complete-import capture path read local data only, with no new timer/provider call. Authorized overview reads indexed published cohort Gold and computes conversion from summed counts in the same due-date range. Before cohort publication it retains the separate PR1 forecast scope. Conversion uses confirmed Realized divided by available Expected in the selected due-date range, including partial historical cohorts and positive confirmed subtotals with unresolved outcomes. Missing Realized or zero Expected remains unavailable; known zero remains distinct. Plain count labels and quality warnings explain the available-cycle scope. The existing Figma card shows operational cycle units, history/quality notes and stale/retry states. History is partial and full-refund detection requires unavailable local refund evidence; no payment confirmation is asserted. Renewal accuracy v2 persists mapped plan terms and schedule references while retaining staff overrides and incomplete-phase provenance. Identity owns StripeSubscriptionImportCompletion, written only after a successful unlimited source import; its public renewalCycleEvidence supplies bounded completion metadata to Sales. Fresh matching completion permits legitimate source-count reductions, while missing contracts remain unknown rather than canceled. Stable future schedules are assessed pending, exact-customer schedule activation is linked by schedule id, and activation alone does not realize a cycle. The local bounded sales-renewals:reconstruct CLI defaults to read-only preview; explicit apply atomically preserves observations, admits or matches immutable Expected cycles, confirms validated historical full-term/successor outcomes with provenance and original due attribution, appends journal evidence and publishes Gold. Existing cycles and realized/reversed outcomes are deduplicated; historical candidates are not automatically promoted. Reconstructed historical cohorts retain incomplete-denominator metadata and original evidence. Conversion describes only confirmed Realized relative to available Expected; it does not assert complete historical coverage. Explicitly named one-month plans require a complete one-installment calendar term; annual monthly installments retain annual semantics. Calendar anchors preserve month-end and leap-day boundaries. Reconstruction also prepares the next Expected term for each current effective contract. Scheduled successors require an exact customer/schedule link and a unique previous contract; retained rich observations and legacy Expected Bronze remain separate evidence sources so incomplete recent observations cannot hide preserved ownership. No new provider calls, worker, payment claim or automatic refund detection is introduced. Historical rule v2 reads bounded Sales forecast Bronze as of the observation cutoff and restores omitted past Expected cycles with their original due and observation dates. Exact schedule/customer links require a complete effective operational term and prior commercial membership or replacement-plan evidence; first sales, financing phases and ambiguous cases stay unresolved. Preview and locked apply use the same archive rules. A realized-term attribution key prevents one successor from fulfilling multiple reconstructed cycles, and existing realized/reversed outcomes stay protected. Earlier VIP participation dates are not contract corrections; explicit canceledAt supports effective predecessor evidence and late-import cancellation reversal. No schema migration or provider call is added.
• VIP profile POST/PATCH accepts an optional reviewed vip_experience_assignment. Identity commits profile fields and Responsible VIT replacement/removal in the existing application transaction under the assignment capacity lock. Assignment services retain vit_management.manage authorization, capacity rules, durable history and after-commit facts; unchanged owners bypass assignment writes and capacity checks. Stale review snapshots and capacity conflicts roll back both profile and assignment state. Profile-photo uploads remain a separate media operation.
• Identity owns VIPProfile.privateSessionsOnly, default false, and supplies the current bounded eligibility flag through its public attendance-report profile contract. Integrations imports the reviewed current Touchpoint PS Only H3 Boolean through the Identity public import contract after Integrations preview, retaining source evidence. Apply requires imports.manage and rejects a stale preview through compare-and-set; safe completed-action audit records the setting change. Engagement reads current eligibility for source-linked month/week/day/session and VIT reports: PS Only VIPs remain visible with a separate count while group-session populations and low/no-attendance indicators exclude them. Actual attendance evidence, Program Run membership and independent Not Acc rules remain authoritative and unchanged.
• The Integrations Session Analysis catalog reads bounded authorized cursor pages through Delivery's public project facade, then hydrates only those candidates. Owner-or-delivered visibility is enforced before pagination; current request assignee or creator VIT, VIP name and session-date filters are applied within the bounded page and may yield sparse pages with a continuation cursor. The backoffice appends pages on scroll without eagerly fetching every project's editing aggregate. Render polling and realtime recovery keep their existing authorized global snapshot contract.
• Delivery's SessionAnalysis request read projection exposes has_draft_clips using one parameterized batch over active draft live_recording projects and confirmed same-project/same-organization studio_clip assets referenced by composition.settings.liveClips. Empty drafts, original source videos and composition blocks alone do not remove a request from the analysis queue. Queue and Studio next navigation skip ongoing requests with saved clips; View all open retains them. Archiving a draft releases its occupancy, while other active draft clips and completed/cancelled request history remain authoritative. No lifecycle reset or new completion event is introduced.
• Explicit DELETE delete_clips=true is restricted to unfinished drafts without active render work or protected final/delivery evidence. Delivery atomically archives the project, clears saved clip references, appends draft_clips_deleted version/actor evidence and tombstones only project-owned studio_clip/presenter_video/voiceover media as deletion_pending. Source recordings, shared library assets and completed exports are preserved. Upload/confirm and render creation serialize on project/request/source state so late operations cannot resurrect deleted work.
• Current MVP completion policy: the first successful final render automatically completes the linked open SessionAnalysis Request after confirming same-project/same-organization private final media. Manual start, submitted feedback and VIP delivery are not prerequisites for this automatic path. Waiting live and on-demand requests retain verified source/VIP identity and active linked project-author/global staff authorization; a confirmed independent project need not have the request's assigned analyst as author. The existing idempotent transition preserves the first completedAt and never reopens cancelled work; queued/processing/failed/cancelled renders do not qualify.
• Immutable completed render jobs retain confirmed final-video evidence independently of the current project export pointer. Autosaving a newer revision while rendering cannot strand its request open or attach an old export to the newer revision. Delivery accepts a current confirmed final or resolves the earliest confirmed completed-job final, verifies same-project/organization ownership, and completes the owning request without mutating the newer revision's final pointer.
• The existing render result consumer periodically scans bounded completed-job batches whose active linked requests remain open. Keyset/round-robin continuation and isolated per-candidate failure prevent old unresolved candidates from starving later work. Recovery persists the idempotent request transition before publishing the existing authorized render projection so queue and workload views refresh. No new runtime, Redis stream, event type or ledger is introduced.
• API-only ActiveCampaign tag dates: Integrations owns ActiveCampaignTagFact, ActiveCampaignTagImportRun and ActiveCampaignTagObservation. Isolated manual CLI persists paginated current-association cdate evidence, checkpoints and fenced account leases; no schedules, provider writes, HTTP route or historical removal inference.
• ActiveCampaignTagDatesService resolves exact provider contact IDs through import-owned ActiveCampaignSnapshotLookup and current Identity ActiveCampaignProfileReferenceService. Account attestation is mandatory for matching; legacy matchedBy email remains existing_import_reference. Duplicate/shared/deleted references stay unresolved; no profile foreign key freezes ownership into source facts.
• Tag-date imports compare UTC instants without insignificant fractional zeros while retaining all original evidence. Coverage distinguishes page_limit partials from failed imports with bounded safe reason codes. The public tagDateFailureReport projection exposes only failed status, a safe code and optional generated run UUID; reason writes remain generation/lease-fenced, and failed runs can resume.
Event communication
• MVP events are past-tense facts dispatched in process
• Owning modules persist durable state before events or realtime publication
• AddPipe media uses dedicated Redis request/result streams as infrastructure; Integrations emits on_demand.video.available only after private storage is durable
• Live Zoom and on-demand AddPipe use one normalized participant blacklist; a VIT decision blocks the same name in both media paths
• The availability fact preserves the provider's original availableAt so Delivery chooses the first strictly later scheduled occurrence. Runs with sessionGenerationStartDate accept automatic uploads from the preceding local calendar day onward; explicit relocations override this window and older reviews remain preserved.
• Identity, Delivery, Sales, Integrations, Engagement, and scheduled jobs emit typed past-tense facts without importing Notifications. Ordinary dispatch does not await inbox work; Quitter monitoring awaits its post-commit promisified dispatch so scheduled recovery drains before shutdown.
• Staff-triggered Session Analysis assignment facts carry the acting StaffUser id; batch request creation emits one past-tense fact per assigned VIT with that batch's created-request count, and Notifications refreshes one consolidated inbox item
• Non-blocking Notifications listeners resolve direct StaffUser, assigned VIT, salesperson, and VIP-linked recipients independently
• New VIT forms and spreadsheet provisioning copy the approved creation permission preset into StaffUser.permissions; role vit remains grant-free at runtime, and delegation checks still prevent grants beyond the creator access
• Notification preferences: active StaffUsers read and update only their own /me subscriptions without administrative grants; admin read/list requires staff_users:read and admin updates require staff_users:update
• Notifications applies active-recipient eligibility, mandatory rules, persisted per-staff overrides, then catalog defaults; staff-access changes are always enabled
• Assignment, due-date, attendance attention/incident, subscription-ending, consultation-processing, and VIP-break facts use stable per-target dedupe keys. Weekly renewal digests use the public effective-renewal queue, project once per staff/UTC Monday week, require financials:read and effective subscription, and link to the matched 90-day queue
• In-process notification source facts are best effort across process termination; guaranteed recovery requires a future transactional outbox
• Notifications emits notification.projection.committed only after its inbox write; an asynchronous bridge publishes notification.projection.changed locally and through Redis to authorized staff rooms
• Internal and Clinical note lifecycle facts carry identifiers and revision only; Clinical timeline rows and counts require the explicit read grant
• A linked Zoom meeting requests recorder bots after any participant joins when an authorized StaffUser host is present; per-user OAuth enables owner-first OBF with co-host fallback
• Integrations may supersede an ended pre-session opening of at most two minutes with the same room reopened within the session window. A serializable transaction uses Delivery AutomaticAttendanceService.detachPreparationMeeting to reject consolidated attendance or reviews and detach only unreviewed proposals; existing recorder intent or media blocks automatic replacement. Superseded classification and replacement evidence prevent late events from restoring the old link. Authorized attendance link-conflict snapshots expose a guarded retry, and recorder reconciliation runs after commit with staff OAuth checks intact
• Delivery owns monitored Meeting IDs and their optional expected session time on ProgramRun; Bot Management selects only configured run time slots and propagates IDs to matching occurrences
• The recorder dashboard combines durable attendance presence, signed Zoom breakout-room membership events, and short-lived recorder camera snapshots only after each owning state change persists
• VIP/CRM revalidates current quitter/inactive status, legacy prefixes and deletion under a transaction lock, then persists VipQuitterParticipationMonitor before vip.quitter.participation.identified or .resolved. Awaited emitAsync publication after commit and promisified listeners drain this inbox projection before the one-shot worker closes. Recent participation does not prove historical Quitter status.
• Notifications projects identity.vip_quitter.participation_detected to active administrators only, enabled and configurable by default. One per-user/VIP/episode dedupe key preserves read state on replay. withSourceProjectionLock serializes handlers; Identity getCurrentEpisodeId and expireBySourceEntityPrefix remove all older source episodes before/after fan-out while preserving current intent. The generic worker reconciles the last 30 days; both 15-second lock callbacks perform bounded local database work only.
Current alignment risks
• VIP/CRM and VIT operations still live partially inside the Identity source module
• Dashed relationships are planned or policy-level boundaries, not guaranteed runtime calls
Sensitive boundaries
• Clinical content stays isolated and exposes only required operational summaries
• Realtime transports authorized projections and never becomes a source of truth
• Attendance consumes authorized recorder status and capacity projections; durable attendance remains owned by Delivery
• Integrations owns provider media metadata and the shared Zoom/AddPipe participant blacklist; Delivery owns candidates, pending review, atomic occurrence-scoped linking, relocation, and explicit analysis
• Registration workbook credentials and raw cells stay outside frontend and Sales contracts; only masked identity and aggregate reconciliation are exposed; the manual preview resolves two exact affiliate-tab aliases to one stable historical identity and returns HTTP 400 for missing or ambiguous required tabs
• Clinical owns the experimental movement lab browser workspace: explicit tab-sharing consent creates a temporary local clip, preview and movement detection stay in memory, and no Clinical or Delivery record is written. Integrations retains legacy staff-scoped YouTube import routes, unused by the lab UI.
Audit P0 and P1 coverage
• Identity, Clinical, Sales, Delivery and Integrations retain their state; Audit receives bounded facts through the synchronous public contract
• Staff/RBAC, Clinical and attendance/evidence changes commit with Audit. Private media and sensitive VIP concessions await durable evidence before disclosure
• Integrations owns MediaDeletionJob: committed intent blocks playback, leased bounded retries remove private objects, completion and Audit commit together; terminal failure has an authorized repair path
• Audit HTTP queries use explicit independent read, restricted-metadata and export grants, server organization scope and validated unsigned pagination; every page reapplies authorization and query limits. No Audit secret is required. Retention is held without automatic purge or receipt expiry
• P1 adds manual VIP changes, VIT assignment decisions, Program Run creation, manual attendance and named soft archives; existing video decisions retain one P0 fact and owner histories remain independent
• Staff Audit UI uses the canonical query contract; no Identity StaffAuditLog. Breaks, follow-ups, analysis and run changes retain owner transactions and publish timeline facts after commit.
Transcript reuse — ADR 0069
• Shared Transcript Processing runs inside the monolith. Source authorities and assessment owners register public ports; original/candidate content stays in owner schemas.
• Sales owns commercial sources/assessments; Clinical owns private transcripts and VIP review; Delivery owns PrivateConsultation schedules and VIT quality assessments.
• Owners invoke the lifecycle contract inside source corrections. After-commit release/index/revocation/supersession facts contain identifiers only. See tfd-transcript-reuse for detailed boundaries.
Message template catalog
• Notifications owns MessageTemplate catalog records for email, SMS and WhatsApp, with string channel identifiers and a validated capability registry.
• Settings exposes Message Templates beside Notification Settings. Active StaffUser access and independent message_templates:read/manage grants authorize every route.
• Templates use draft, active and archived states, revision-checked updates, declared variables, visual email authoring and sanitized sample previews. Completed-action audit contains safe metadata only; the catalog does not enqueue outbound messages.
• Notifications also owns revisioned EmailSignature profiles. A template may select one active profile or none; each profile supplies its own optional header and footer. A bounded declarative schema permits approved logos, plain text and HTTPS links.
• One composer builds template/VIP previews and HTML/text delivery. Reviewed signature id/name/revision and composed content freeze in EmailDelivery; enqueue locks and rechecks the active signature. Only the configured public asset origin may load images in the sandboxed preview.
Track authoring — ADR 0083
• Delivery owns TrackDefinition drafts and append-only TrackVersion publications. Nested stages, decisions, routes and training profiles share one typed definition between Structure and Flow.
• Clinical owns immutable TrackQuestionnaireVersion health questions/rules. Identity adapters require explicit Clinical grants; Delivery resolves only approved identity/outcome codes through the synchronous Clinical public facade.
• Publication freezes safe video and exact whole-class Program version references. Catalog/media archival is guarded under dependency locks. Program Runs, existing on-demand attendance and recording processes retain their ownership.
• Delivery now owns TrackParticipation pinned to a published TrackVersion and append-only VipDirectionAction evidence. The direction queue composes existing ProgramRunVip links with a narrow Identity public projection of active VIPs, breaks and experience assignments. VIP execution and camera capture are implemented by ADR 0086. ADR 0085 adds Delivery-owned immutable progression policy versions, participation-scoped reviews, PT votes and append-only actions. Identity exposes scoped Platinum/Diamond Director and active linked VIT eligibility through ProgressionIdentityService. Review windows use persisted timestamps and server-clock checks; no scheduler is needed. Director confirmation preserves a destination; ADR 0086 schedules and applies the effective participation transfer. ADR 0086 adds Delivery-owned ProgressionTransition, TrackProgress, TrackExecutionAction and TrackRecording. A bounded poll in the existing monolith applies due Director-authorized transfers under roster locks and publishes existing participation facts after commit. Active UserProfile ownership gates progressive portal activities and private media. Clinical portalForm/portalSave own TrackQuestionnaireResponse and immutable submitted clinical answers, returning route outcomes only. Browser media uploads directly to private S3 and is frozen through an ETag-conditional internal copy; no API media bytes or new runtime service.
• ADR 0091 reserves VIP Journey for the composed lifecycle of TrackParticipation and ProgramRunVip, without a duplicate ledger. Track entities map to existing Journey tables and columns; immutable snapshots, legacy progression discriminators and LaunchDarkly keys remain stable. Programs remain reusable and independent of Tracks.
• Engagement owns the staff attendance-report summary and week-detail HTTP reads. The summary HTTP read combines year-scoped materialized snapshots with current confirmed OnDemandAttendance through the Delivery public AttendanceReportRunsQuery facade (listReportOnDemandFacts); Identity supplies minimal report profiles and Not Acc exclusions. The bounded public read exposes linked occurrence, phase/cycle, local scheduled date, VIP and analyst metadata only, never private media. Reopened/deleted on-demand attendance and deleted linked occurrences are excluded; later session/run cancellation preserves confirmed history. Engagement replaces old native on-demand copies in memory, preserves durable imported/history facts, and counts Live plus On-demand once per VIP/occurrence while retaining On-demand as a subset. Phase/cycle and actual Program Run-local calendar month constrain every summary; cross-month weeks are clipped for drilldown and exports, and unrelated aggregate snapshots cannot fill a missing phase/month. GET /catalog supplies compact run/VIT lookups; GET /details returns selected-week evidence and minimal identities. Existing membership, Not Acc and HTTP authorization remain required. Referenced Delivery session ids resolve missing phase/cycle metadata. The same public facade exposes compact runTimezones metadata for source-referenced historical, cancelled or archived Program Runs, including runs absent from the active catalog. Both saved and native evidence use that canonical run timezone; optional session localDate keeps detail labels aligned. Current membership never invents a historical phase. Existing generated/imported period-fact and engagement-snapshot detail JSON persists optional nullable reportingPhaseKey metadata through one shared normalizer. An original nonblank phase id plus a complete normalized Phase1/Phase2 name maps to phase_1/phase_2; custom source phases stay distinct and original raw phase ids/names, cycles and source/occurrence identities remain intact. Legacy reads and native On-demand use the same helper. Materialized report trees group Phase 1 then Phase 2 without combining source cycles or changing their monthly metrics. Internal cycle partitions retain the original phase id; only ambiguous derived month-view keys receive a source-phase qualifier, preserving existing unique links. A bounded preview-default maintenance CLI annotates historical derived JSON only on explicit compare-and-set apply. Native On-demand remains a request-only projection; no source/template/manual-attendance rewrite, schema migration, new event, ledger or runtime is introduced.
• Service Funnel question contracts add checkbox selections and ordered rankings (bounded string arrays), rating/opinion scales (bounded integers), and long text with optional prompt descriptions. Delivery validates current-activity answers and published option membership; routing uses explicit contains/first_equals predicates and rejects overlapping automatic outcomes. Existing snapshots and identity/prerequisite checks remain unchanged. Backoffice direct video upload reuses the private Assets library upload/confirm contract and resolves a stable ProgramAsset before applying the step; no signed URL is stored in the workflow and no new runtime service is introduced. Quiz/Form answer options may additionally pin organization-scoped image library ids, aligned with answer labels. Video activities may pin an optional thumbnailAssetId; reset clears the override and authorized playback uses an ephemeral signed thumbnailUrl as its poster. Publication validates and retains these image dependencies; authorized current-activity execution resolves short-lived image URLs without persisting them in snapshots. Backoffice playback rehearsal pauses and collects ephemeral answers locally without recording client completion.
• ADR 0083 connected-workflow amendment: schema 4 TrackVersion freezes an entry stage and per-output destination references. Quiz/Form finite-answer ports or existing checkpoint outcomes connect to stage ids or explicit Finish; Lessons keep one continuation. Delivery validates acyclicity, reachability, answer availability and complete connections, then preview and owned progressive execution traverse the same pinned graph after activity/recording/review gates. Connected operational Decision stages can group all/any response conditions in priority order and provide an explicit default route. Delivery uses the same first-match evaluator in authorized execution and the staff fictional decision test through Track preview. Existing route activities and Clinical outcomes retain their contracts; schemas 1–3 remain ordered. No second progress ledger, new runtime, event or context boundary is introduced.
• Schema 4 optionally stores bounded per-node canvas coordinates in workflow.positions. Revision-checked draft saves and immutable publications preserve this editorial layout; execution and authorization ignore coordinates. Missing positions use automatic layout and deleted blocks lose their saved coordinates.
• ADR 0107 adds explicit scoped staff restart/version-replacement commands. Delivery supersedes the prior TrackParticipation, preserving its pinned snapshot, answers, media and Clinical references, and creates a new owner-scoped cycle. Reset starts empty; published-version replacement preserves compatible answers, completions and recording provenance within one TrackDefinition; revision/request fences reject stale commands and duplicate resets. Delivery-owned TrackExecutionEvent records distinguish bounded advisory portal observations from confirmed execution actions; neither telemetry nor playback progress proves completion. Staff operational response/history reads preserve Clinical isolation. The user-approved November 10 amendment to ADR 0102 grants active administrator/global StaffUsers all resolved Service Funnel executions through Identity canManageAllTracks, including unlinked clients and unassigned participations; non-global reviewer assignment and Director membership scope remain required. No new runtime, provider or cross-context event is added.
• Identity's completed-action audit sanitizer accepts the current track resource label alongside historical journey records; sanitized reset/version-change staff facts remain recorded without response bodies.
• The Conclusion block may pin an optional organization-scoped private library image, including a badge image, as workflow.conclusion.imageAssetId (UUID or null). Publication validates active/ready image ownership and retains the dependency under existing archive protection; immutable TrackVersion snapshots never store private keys or signed URLs. Only the completed owner-authorized portal projection returns the short-lived conclusion.imageUrl. Completed Home/Conclusion may fall back to the first earned badge already returned in that same conclusion; no global Track image, new award, progress mutation, database migration or runtime is introduced. Older snapshots remain compatible.
• Delivery retains submitted conclusion feedback in the existing TrackProgress state when staff replace a Service Funnel publication, even when conclusion copy, artwork, feedback visibility or remaining requirements change. A full reset starts with no feedback. Authorized execution reads may recover legacy feedback only through a unique, evidenced version-replacement chain with the same UserProfile owner, TrackDefinition and original VIP context, decreasing cycle numbers and superseded predecessors. Recovery requires the unique replacement link, stops at reset or missing provenance, rejects invalid saved feedback, and fails closed at the bounded 100-link limit. GET does not write recovered state; the portal keeps its existing feedbackSubmitted boolean without returning rating or comment. This is an internal Delivery state/projection correction, with no new feedback ledger, model, event, public response shape, runtime component or cross-context boundary.
• November 12 VIP visual parity: the owned execution projection adds sessionProgress with a resolved lesson-only denominator, separate from aggregate completion and assessment position. Curated Back Fix artwork and source durations are keyed by imported ProgramAsset ids, with explicit authored covers taking precedence. Portal renders current and resolved future activities, filters dashboard handoffs from the visual timeline and confirms form responses before submission processing. Existing ownership, routing, frozen snapshots and completion evidence remain authoritative; no new ledger, provider, event, database schema or runtime is introduced.
• Delivery video activities may optionally freeze presentation.videoWidth (narrow or wide). Video Quizzes alone may freeze consultationInvitation with integer startMs/endMs inside a hosted video clip. Editor, fictional preview and owned portal execution show the invitation within that interval without pausing playback or requiring an answer; Lessons and Forms cannot own this timed item. Existing explicit presentation.consultationEnabled Quiz flags retain their legacy interval when no timed item exists, without rewriting pinned publications. One width section replaces duplicated authoring controls. Ownership, decisions, completion requirements and media authorization remain unchanged.
• Service Funnel Forms and Video Quizzes may freeze optionPoints aligned with choice/checkbox answer labels: each is a nonnegative integer up to 1000000. Connected priority Decision score conditions explicitly select scored questionIds from common steps encountered on every path, compare their sum with equals/gte/lte and retain first-match/default behavior. Delivery derives the sum from valid answers in completed, encountered activities; skipped answers contribute zero and checkbox selections contribute each selected option once. Staff fictional testing and owner-authorized execution share this evaluator. No independently incremented total, Clinical rule change, migration or publication rewrite is introduced.
Server-side feature flags — ADR 0087
• FeatureFlagsModule is technical infrastructure in the monolith. One server-only LaunchDarkly Node SDK evaluates typed Booleans with 3 s startup and 750 ms decision limits; unavailable/error values return false. Optional isolated Redis persistence retains last-known rules across restarts; persisted rules have no freshness TTL.
• Canonical provider flags are chat, journeys, vip-progression, movement-lab, create-subscription and phase-team-communications, each with false default/off values. Billing groups renewal and creation screens without changing Identity/Integrations ownership. VIT type/roles are excluded at routes and API; create-subscription additionally gates creation with financials:manage. A no-store GET /me/features composes active StaffUser authorization with each flag. The expanded VIP table and shared-view GET/POST endpoints are generally available with vip_management.view; vip-expanded-table is a permission-derived response compatibility field, never provider-evaluated. Movement lab requires Clinical read access and gates its navigation, direct page and YouTube import endpoints; other Clinical screens and shared motion capture remain independent. journey-reviews is a derived compatibility response field: journeys plus explicit client-review eligibility or progression.read with Director authority; Delivery still enforces assigned participation or VIP membership scope. It is never a separate provider evaluation or legacy fallback.
• Tracks covers authoring, the staff Clinical questionnaire catalog, execution reviews and private playback, and Track-specific direction/progression surfaces. VIP progression covers policies, votes, reviews and transitions. Track-linked progression snapshots and commands require both flags. The direction queue still counts real participation coverage; Program Run and VIT operations remain available independently. Planned-transition and applied-progression history projections follow VIP progression; Track involvement requires both flags even for a Program destination. Filtering projections never changes real participation coverage.
• The initial staff pilot targets server-derived isAdmin=true: StaffUser admin type or admin/super_admin role. This private Boolean is the only added context attribute; browser input cannot set it. Admin targeting releases availability, never Director/PT authority, membership scope or a force-on bypass. Identity and Clinical use the public core evaluator without importing the staff adapter back into Identity.
• Scheduled progression transitions pause while the required authorizing-staff flags are false, retaining scheduled state and prior decisions. Resumption rechecks current Director authority, membership, source continuity and destination rules. Server-local emergency disabling overrides provider and cached true values; no work or completion evidence is fabricated.
• Contexts use trusted staff UUID/kind plus private isAdmin; future VIP evaluation uses active UserProfile UUID/kind. Email, names, clinical content and secrets are excluded. Evaluation count/latency labels contain no UUIDs and are not unique exposures or A/B samples. Existing Grafana/OpenTofu definitions require live export/query validation; future VIP experiments need actual served/rendered exposure and attributed outcomes.
• The server-evaluated chat flag defaults/off to false. Active staff and portal identities require independent trusted staff/vip cohort evaluation before chat HTTP, attachments or UI access. Staff sockets recheck availability every 10 seconds and before each recipient projection; message notification projections, inbox lists and unread counts exclude disabled recipients without deleting durable state. Identity exposes independent /portal/me for VIP Journey, separate from gated /portal/chat/me.
• Local-only exception: the explicit start:local launcher supplies TFD_LOCAL_DEVELOPMENT=true with NODE_ENV=development; deployment/CI markers reject this mode. The API binds to 127.0.0.1 and enables valid-context flags without LaunchDarkly. Emergency disable, authentication, RBAC and ownership still apply. Published runtimes retain provider evaluation and fail-closed defaults.
Manual VIP email — ADR 0088
• Notifications owns EmailDelivery with the frozen active MessageTemplate revision, rendered content and reviewed sender/recipient. NotificationEvent carries emailDeliveryId only; EmailDeliveryFeedback and EmailSuppression retain normalized results and permanent-bounce/complaint blocks.
• Saved VIP email HTTP requires active StaffUser, vip_management.view and independent vip_email:send/read. Identity VipEmailRecipientsService resolves the exact internal profile and operational VIP id through its public facade; the worker rechecks deletion and unchanged recipient without importing Identity tables.
• The generic Notifications worker remains a channel-isolated durable fallback for Slack and leased/fenced email work. Amazon SESv2 sends one recipient with maxAttempts 1 and tfd_email_delivery_id correlation. An unresolved started send becomes uncertain rather than automatically resending; only definitive throttling uses bounded retries.
• After durable enqueue commits, an individual reviewed VIP email immediately attempts only its own delivery through the existing fenced EmailDispatcherService and returns the stored status. An identical request keeps the same delivery and cannot bypass scheduled retry time, duplicate a provider attempt, or drain unrelated mail.
• The existing Backoffice API owns an email-only composition-root pass in email-delivery-runtime.service.ts, registered only in AppModule. With EMAIL_DELIVERY_ENABLED=true it starts at bootstrap and checks every five seconds, without overlapping local passes, for approved due cycle schedules and queued email dispatch. Campaigns become visible only after their transaction commits; future due times, 60/120-second retry waits, expired-claim recovery and uncertain-send protections remain authoritative. The pass uses existing Notifications public services, stops with the API, and logs only sanitized failure codes. Slack, digests and the generic worker schedule are unchanged; no separate process, context, broker or email cron is created.
• Amazon SNS feedback must match the configured topic and verified signature using bounded allowlisted HTTPS certificates without redirects. Durable normalized feedback is correlated to provider message plus delivery id; permanent bounce/complaint suppresses current and future queued sends. Server delivery is not inbox/read proof. No CommunicationLog, Engagement fact or new runtime is created; real sender/DNS/AWS setup and deployment remain prerequisites.
• Notifications also owns revisioned EmailSignature profiles. A template may select one active profile or none; each profile supplies its own optional header and footer. A bounded declarative schema permits approved logos, plain text and HTTPS links.
• One composer builds template/VIP previews and HTML/text delivery. Reviewed signature id/name/revision and composed content freeze in EmailDelivery; enqueue locks and rechecks the active signature. Only the configured public asset origin may load images in the sandboxed preview.
• Signature authoring also exposes POST /email-signatures/:id/send-test, requiring an active administrator (StaffUser.userType=admin). A confirmation names the current StaffUser email; the server alone selects that recipient and checks the confirmed address and saved non-archived signature revision. A staff-scoped idempotency key and serialized one-minute limit atomically create EmailDelivery and a minimal email.signature_test.requested outbox fact. Test deliveries have recipientStaffUserId equal to the requesting actor, null vipProfileId/templateId, frozen sample content and signature, and no campaign. The existing fenced dispatcher immediately claims only that delivery, revalidates the active administrator address through Identity public contracts, and preserves SES/SNS feedback, suppression and uncertain-send protections. The API email-only pass and generic worker recover remaining queued work; no VIP record or separately deployed runtime is created. Administrator self-tests bypass the exact-recipient list through their separately authorized policy. The endpoint and dispatcher recheck administrator status; the global enabled flag, sender/SES/SNS configuration, recipient validity and suppression remain required. Other delivery uses its configured recipient policy, including the development-only current registered-VIP option.
Phase team communications — ADR 0090
• Identity publicly supplies bounded stable-VIP contact, status, membership, active-break and normalized shared-mailbox facts. Delivery publicly supplies current run/session audiences, cycle timelines and reviewed group/completion evidence; placement age is never completion.
• Delivery owns CommunicationRosterReview, PhaseTeachingPlanItem and PhaseResourceHandoff. Classification corrections preserve reason, actor/time, revision and append-only history. Teaching plans reuse ProgramAsset VIP document links; VIT guidance and temporary access URLs are not email resources.
• Notifications owns EmailCampaign, CycleEmailSchedule and StaffCommunicationTask. A reviewed campaign revalidates bounded bulk owner projections and atomically freezes private per-VIP EmailDelivery plus minimal NotificationEvent work under stable idempotency and template/signature locks. Cancellation affects queued work only.
• The existing notification worker activates no drafts automatically. Explicitly approved future cycle schedules use run timezone/calendar offsets, reevaluate due recipients and move changed or overdue intent to needs_review. Late joiners are considered at due time; historical catch-up requires a manual review.
• Calendar reads authorized staff tasks; due inbox notifications deduplicate by task/revision and never imply completion. Accepted frozen resource email reconciles idempotent Delivery handoff evidence. No new runtime, media path, VIP portal contract or graduation authority is introduced; existing Director progression governance remains authoritative.
• The false-default phase-team-communications flag gates staff navigation, Calendar reminders and all campaign/team HTTP routes without granting RBAC. Notifications rechecks each stored authorizing actor before due work; disabled schedules/reminders retain intent and revisions. Already queued email dispatch and accepted handoff reconciliation continue.
• Staff navigation exposes separate Communications, Session groups, Teaching plans and Team tasks modules. The session_leader role grants only dashboard.view plus dedicated phase_communications/phase_roster/phase_teaching/phase_tasks read-write capabilities. Each adapter and scheduled command enforces its own capability; the same feature flag gates all four. No dashboard shortcuts or indicators are added.
Personalized video prescriptions
• Delivery owns PrescriptionExercise, VideoPrescription and immutable PrescriptionRenderJob snapshots. Demonstrations reference the existing private SessionAnalysisLibraryAsset; approval freezes no VIP clinical content and changing an exercise requires reapproval. Historical export snapshots pin the source range, cue and dose. Shared library archive blocks all exercise and render dependencies.
• The false-default video-prescriptions LaunchDarkly key gates staff menus and every prescription/catalog/private media HTTP endpoint. video_prescriptions.view is independent from edit_own/manage; author ownership or a separate manager grant protects all prescription access. program_setup.manage protects catalog maintenance and loop approval. Cognito and active StaffUser remain required.
• The existing tfd-session-analysis-renderer also consumes dedicated tfd:prescriptions:render-commands and produces render-results using separate consumer groups and prescription.render message types. It normalizes approved private source intervals, repeats at original speed for the exact timed dose, adds silent audio, countdown/preparation/rest scenes, and writes validated private H.264/AAC 720p MP4. No SessionAnalysis request/project, attendance, portal or recorder state is created.
• PostgreSQL owns draft revision, immutable render snapshot, retry/progress/cancellation and final review. Core reconciliation recovers unpublished and abandoned jobs; attempt ids fence stale results and private output paths. Worker TTL leases renew during rendering and stop work when ownership cannot be proven. Only the monolith mutates database state; neither Redis nor the API carries media bytes.
• Staff explicitly review the exact final MP4 before authenticated short-lived download. A downloaded prescription never proves VIP delivery or completion. Existing reviewed earlier versions remain accessible after a later draft changes. Enabling the flag requires a validated deployment of the renderer contract and configured private storage; no provider flag or deployment is changed by repository implementation.
VIP access and authentication emails
• Identity provisions and pins VIP access in a separate Cognito pool with mail suppressed. An explicit invitation converts FORCE_CHANGE_PASSWORD using an unshared random permanent credential kept only in request memory, then AdminResetUserPassword sends a one-time password link. The CustomMessage_ForgotPassword Lambda uses non-sensitive purpose metadata and calls Notifications with purpose only. Notifications owns revision-pinned templates; invitations require auth_url without separate code or username fields. The adapter inserts the URI-encoded provider email locally; Cognito substitutes the recovery code and sends through SES. The custom VIP form removes the fragment on load and submits the chosen password through the BFF to ConfirmForgotPassword. Only successful verified authentication of the pinned subject conditionally activates invited UserProfile access; disabled access remains denied.
VIP development hosting and authentication boundary
• The independent VIP React/Vite app is hosted on the development-only Cloudflare Pages project tfd-vip-dev at https://dev.vip.tfdportal.com, built from develop. Its public assets contain only the HTTPS development API origin, never Cognito tokens, client secrets or service tokens.
• Browser requests go directly to https://dev.api.tfdportal.com/portal/* with credentials. Explicit CORS permits the VIP origin; both HTTPS origins share the tfdportal.com site. API-host-only HttpOnly, Secure, SameSite=Lax cookies identify server-held portal sessions. Active UserProfile authorization and rollout flags remain independent and mandatory.
• PORTAL_FRONTEND_URL is the canonical HTTPS origin for invitation activation and password-reset links and sensitive form-origin checks. The existing VIP client callback uses /auth/callback for legacy social BFF behavior; no VIP Hosted UI is added. Staff-host, staff Cognito pool and production deployment settings are unchanged.
Standalone portal accounts
• Identity allows privileged staff to create UserProfile with a null VIP link, a required name and a unique sign-in email. The exact Cognito subject is provisioned by the backend with mail suppressed, never supplied by the browser. Existing invitation links, verified activation and password reset remain. ADR 0096 allows limited sessions for inactive/disabled application profiles while business resources remain restricted. Optional vip_id is explicit in staff and /portal/me response contracts. Non-null VIP links retain uniqueness; multiple standalone identities do not conflict on NULL. No VIPProfile, enrollment, clinical access or program ownership is fabricated. Delivery portal routes independently require a linked VIP and existing ownership/prerequisite rules.
• Privileged staff can later attach a non-archived VIP to the existing unlinked account through PATCH /vip-access/:id/vip. A transaction conditionally changes only a null vipId; same-target retries are idempotent and the partial unique index prevents duplicate VIP claims. Different existing or concurrent links are never reassigned. Cognito subject, email, status, password and invitation remain unchanged; ADR 0096 revision fencing invalidates prior BFF sessions on an effective link; no provider call, new identity, email or enrollment is created. Completed links append sanitized identity.vip_access.vip_linked evidence containing only the account and technical VIP identifiers. Subsequent authorized identity reads use the stored link under normal program ownership rules.
• An explicit VIP correction endpoint requires the expected current VIP and account update timestamp plus the target VIP. Its compare-and-set transaction changes only vipId; the existing partial unique index prevents claiming another account’s VIP. Concurrent stale corrections fail closed and same-target retries do not emit another correction audit fact. Privileged staff review old/new VIP names before confirming. Cognito identity, sign-in email, profile fields, status, password and invitations remain unchanged; ADR 0096 revision fencing invalidates prior BFF sessions on an effective correction, with no provider call, email or new account. Technical fromVipId/vipId audit evidence preserves the correction. VIP program, enrollment and clinical records are not moved; subsequent authorization follows the corrected identity link under existing ownership rules.
• ADR 0109: Identity owns standalone UserProfile account fields, PortalPersonalGoal, private PortalAccountAvatar metadata, PortalEmailChange and sanitized status events. Linked VIP equivalents remain synchronized; imports cannot replace governed identity. My Account uses PATCH /portal/me/account/personal-statement with accountVersion, distinct from the existing versionless /portal/me/personal-goal compatibility route; both update the same PortalPersonalGoal. The portal /me projects avatar id/API URL; owner/staff authorization precedes 60-second private S3 access. Native email changes use password reverification, a single new-address proof (old-mailbox access is not required; legacy old proof links are rejected) and a durable applying/uncertain fence, provider observation and authorization-revision revocation. Social/linked identities are blocked. Notifications auth-public reuses pinned settings for two email-change templates: new-address proof and a completion notice sent to both addresses; Settings separately exposes template bindings and read-only permission-protected request monitoring. An API-started bounded recovery poller observes provider outcomes without blindly repeating a mutation. PORTAL_EMAIL_CHANGE_ENABLED defaults false until live provider/inbox homologation; no new deployment or WebSocket command surface is added.
VIP authorization policy — shared session foundation implemented
• ADR 0096 separates BFF authentication from portal resource authorization. Steps 1–2 implement the protected-route inventory, bounded Identity public actor and safe /portal/me expiry/access metadata. Inactive/disabled limited sessions and a minimal unlinked/limited content gate are implemented in steps 3–4; steps 5–6 now implement full browser lifecycle recovery. Steps 3–4 now migrate active-only admission and Bearer business controllers to limited BFF sessions and resource eligibility; invited activation and provider verification remain unchanged.
• All protected portal routes and aliases, nested resources, questionnaire adapters, uploads, confirmations, attachments and playback require a trusted Identity public actor and owning-context authorization. Auth exceptions are explicitly enumerated. No client vipId, StaffUser RolesGuard or Cognito group grants portal business access. Cross-VIP resources and unknown resources have indistinguishable external responses.
• Implemented session foundation: existing Redis runtime stores established sessions and one-time PKCE/invitation transactions under dedicated tfd:portal:auth:v1 keys with fixed expiry. Redis TIME establishes the immutable 12-hour deadline. A PostgreSQL UserProfile portalAuthorizationRevision and transaction-bound trigger fence all effective VIP binding, subject and deletion changes across replicas. Refresh uses a bounded owned lease and versioned compare-and-set; logout consumes before provider revocation. Profile/status edits do not revoke sessions. Cookie rejection cannot fall back to Bearer at /portal/me; Steps 3–4 remove Bearer-only compatibility and migrate every business controller/alias. No idle timeout or new runtime service is added; steps 5–6 implement absolute browser expiry.
• VIP realtime remains outside this increment and existing staff gateways grant no VIP access. New private-media authorization rechecks eligibility; existing signed recording playback (300 seconds) and Chat downloads (120 seconds) retain bounded residual validity. No immediate revocation of issued links or buffered bytes is claimed. See docs/adr/0096-vip-portal-sessions-separate-authentication-from-resource-authorization.md and docs/superpowers/plans/2026-10-19-vip-portal-authorization-and-absolute-session-expiry.md.
• Storage failure returns a sanitized unavailable response without a process-local session fallback. Ordinary session requests resolve the pinned profile id/subject/revision and never adopt accounts by email. See docs/operations/vip-portal-session-storage.md for secret custody, migration order, restore fencing and real PostgreSQL/Redis tests; docs/architecture/vip-portal-protected-surface.md enumerates every current route, alias, auth exception, frontend route and media signer gap.
• Verified existing inactive/disabled UserProfiles may establish BFF sessions and read /portal/me without a denied-login attempt or status activation. Active unlinked accounts remain limited. Invited activation and provider verification stay pinned; missing/deleted/conflicting identities fail closed. /portal/me always returns the immutable BFF deadline with private/no-store metadata; Bearer-only portal access is removed, including legacy Backoffice portal consumers.
• Identity exports a bounded PortalResourceActor or an explicitly selected client-resource PortalReadActor after current status, current optional VIP binding and durable authorization revision checks. A Nest adapter keeps token-custody services private while imported guards resolve correctly in consuming modules. Delivery retains participation/route/prerequisite/clinical checkpoint and nested recording authorization; Chat admits active UserProfiles without requiring VIP and retains typed UserProfile conversation/attachment membership, exact portal realtime rooms, and the independent chat feature flag. Staff RBAC and Cognito groups never authorize a portal resource.
• Delivery separately evaluates the stable journeys provider flag for the trusted VIP UserProfile UUID; Chat retains its independent chat flag. Unsafe portal HTTP methods require the exact PORTAL_FRONTEND_URL Origin, including auth setup and logout. Origin checks are independent of CORS. Owner Forbidden/NotFound denials share a structured Resource unavailable response; limited-account and flag denials retain non-enumerating codes. Logs contain bounded reasons and trusted identity references only, never request bodies, PHI, tokens, private keys or signed URLs; no failed staff audit rows are created.
• The dedicated VIP frontend blocks its existing static/demo screens for newly resolved limited accounts and shows one explanation/sign-out action. Steps 5–6 implement automatic absolute browser expiry, response recovery, cross-tab state and work/cache preservation. VIP realtime and inactivity controls stay excluded. Real PostgreSQL/Redis HTTP tests cover every business route/alias, restricted identities, cross-VIP parent and nested-media substitution, CSRF and flag independence. See docs/architecture/vip-portal-protected-surface.md and docs/operations/vip-portal-session-storage.md.
• Identity exposes withResourceTransaction: shared UserProfile row locking and current revision/binding/status validation precede unsafe portal owner work. Effective binding/status changes serialize with the owning application transaction; stale writers fail before side effects. Same-target retries and transaction rollback preserve the durable revision policy.
• Delivery, Clinical and Chat use the existing application transaction client. Contexts keep ownership queries and aggregate concurrency decisions; Chat publishes message facts only after the outer commit. Existing transaction timeout is 15 seconds. No new context, service or VIP realtime transport is introduced.
• The dedicated VIP frontend separates authenticated limited, expired, recoverable-error and logout-pending states. The immutable server deadline drives timers and focus/resume checks, with conservative server Date clock correction. Offline recovery never extends the deadline. Profile restriction rechecks /portal/me; resource/flag denial does not end the session.
• Account generations cancel pending requests and reject late response bodies; logout clears media, memory drafts and registered account caches. Goal/assessment drafts survive temporary recovery only within one identity/binding/session. Cross-tab messages carry secret-free logout/change metadata; failed server logout blocks sign-in and retries on focus, reconnect or explicit action. No inactivity timeout or warning is added.
Bounded portal media and validated denial/logoff matrix — ADR 0096 steps 7–8
• Every business handler, including GET media, now uses the existing Identity resource transaction with current status/binding/revision checks and a shared UserProfile row lock. Before result delivery and database commit, a private adapter rechecks the authoritative Redis session without another Cognito refresh. Expiry/logout/revocation discards results and rolls back database work; an external copy or previously issued URL cannot be retroactively withdrawn.
• Delivery private lesson playback uses a dedicated 300-second portal signer; staff editor playback retains 900 seconds. Practice playback remains 300 seconds; Chat downloads remain 120 seconds. Practice upload grants last 600 seconds and Chat uploads 300 seconds; confirmation requires a new protected owner check. Published YouTube/direct HTTPS references are existing public catalog sources, not private per-VIP or expiring portal grants. Source validation excludes credentials/signed query data.
• Real PostgreSQL/Redis HTTP tests cover positive two-VIP reads/writes/media, all aliases, nested substitutions, limited/invited/missing/deleted identities, provider outage, revocation/expiry, archived private assets, independent flags/prerequisites, playback-result discard and confirmation rollback. Real SDK presigning with ephemeral synthetic credentials verifies bounded URL metadata without live AWS calls.
• Real Chromium drives the dedicated VIP frontend using a controlled HttpOnly-cookie BFF boundary under TEST_ENV=dev and allowed hosts. Tests cover direct limited routes, 12-hour expiry after activity/reload, sleep/resume, two tabs, account B draft isolation, delayed account A responses, offline recovery, failed logout across reload and media source cleanup. No staff tokens, real providers, persisted auth state, screenshots, traces, video or fixed sleeps. No new runtime, ingress, inactivity controls or VIP realtime.
Repository release readiness — ADR 0096 step 9
• Steps 1–9 are implemented and locally validated in the repository. ADR status, protected-route and denial contracts, private/public media bounds, recovery notes, validation evidence and staff system updates are current. The release handoff records migration order, expected re-login, existing-address cohort rollout, provider smoke requirements and forward recovery; it does not authorize deployment.
• Application Validation preserves exact candidate checkout, existing required-check names, daily/manual/production full validation and non-cancellation. VIP Platform adds development type/lint/environment checks and full-run build/unit/controlled Chromium validation. Portal Authorization adds full-run disposable loopback PostgreSQL/Redis integration with one Prisma generation and no production secrets or application migrations. Workflow YAML/actionlint and CI policy tests pass locally; no remote candidate CI execution is asserted.
• External deployment readiness remains conditional: GitHub rules could not be inspected because gh is unauthenticated; Railway Wait for CI, Cloudflare deployment ordering, live Cognito/cookie/Redis/media settings, cohort targeting and application migration are unverified. Repository workflow definitions are not evidence of those external gates. Production continues through the existing release/prod to main draft PR and main-to-develop sync policy.
• No new ingress, parallel application lane, runtime service, VIP realtime or inactivity timeout is introduced. See docs/operations/vip-portal-release-readiness.md and docs/operations/vip-portal-authorization-validation.md for evidence, pending deployment prerequisites and the exact local-versus-live validation limits.
Explicit VIP session continuation — ADR 0097
• ADR 0097 amends the original-login immutable deadline from ADR 0096 for selected portal-session-renewal cohorts, off/default false. A server warning defaults to 30 minutes before period expiry (PORTAL_SESSION_EXPIRY_WARNING_MINUTES, integer 1–719). Only an explicit Stay signed in command can start another 12-hour period; activity, page reload, polling and automatic Cognito refresh cannot. No inactivity timer or VIP realtime is introduced.
• Identity owns POST /portal/auth/session/renew: exact Origin, current HttpOnly credential, expected generation, warning-window eligibility, server-only trusted UserProfile cohort and provider/profile/subject/VIP/revision revalidation. Valid limited/unlinked sessions may continue without gaining business access. JSON exposes safe scope/generation/server-time/warning metadata only; rotated credentials remain Set-Cookie and tokens stay server-side.
• New v2 credentials separate the family selector from an independently random rotating secret. One authoritative v2 Redis family record, its provider-refresh lease and five-second attempt throttle share a Cluster hash slot. Owned-lease/version/credential CAS rotates one period atomically and cannot recreate logout/expired/revoked state. Retired proofs permit logout only for 30 seconds, never reads or renewal; stale guards never clear a newer cookie. V1 records keep fixed expiry until next login, with no new database migration.
• The existing portal-themed Radix/shadcn dialog offers Sign out now and Stay signed in, with keyboard focus, mobile button targets, pending and inline retry states. Same-family renewal preserves the page, media and memory-only answers by stable scope; request-generation fencing rejects stale results independently of account cleanup. Secret-free cross-tab events trigger authorized metadata rechecks; concurrent confirmations converge to one period and logout wins.
• Real PostgreSQL/Redis tests, controlled-clock components and real Chromium cover config/window/cohort rules, restricted identities, repeated and competing rotations, provider/lease/expiry/binding/logout races, form preservation and multiple tabs. Synthetic desktop/mobile crops verify the existing UI language. Existing CI jobs execute the extended matrices with bounded Node heaps. No live provider flag/configuration or deployment was changed. No token storage in browsers, new ingress or runtime service was added.
• A renewable family whose local deadline appears expired closes content and rechecks the current shared cookie before destructive logout. Suspended tabs may miss renewal messages; authoritative newer generations recover the same work instead of ending a renewed period. Unavailable verification keeps content closed with retry, while confirmed invalidation hints peers to revalidate. The recheck never grants another period.
Renewal evidence and current annual cycles
• Identity preserves recurring unit amount, normalized currency and price status for future schedule snapshots using the existing subscription normalization. Known zero remains zero; unknown amount remains unavailable; non-USD prices retain their currency without a USD amount. The recurring amount is separate from the total of the payment plan.
• The shared renewal projection uses basis current_cycle only for an actual, non-schedule active/trialing/past_due contract with a known positive recurring price, a known annual 12-month package and yearly billing cadence. The original subscription start must be known, and the imported current-period start must be at least its first anniversary and no later than the explicit evaluation instant.
• The imported period must prove a complete 12-month cycle after removing the recorded break offset from its end: either a directly clamped annual interval or an interval aligned to the original contract anniversaries. This is evidence of the imported current cycle, never a clock-based roll-forward. Recorded break days affect the projected renewal once.
• A service-delay anchor applies only when the effective participation civil day is later than the VIP's original startDate civil day and the effective timestamp is later than the commercial contract start. Equal original/effective profile days are a baseline, so the commercial contract supplies the renewal basis and its Phoenix day without changing saved profile dates. Missing original-profile start evidence retains the previous fallback. This shared guard also applies to complete annual installment terms and verified explicit one-month terms. A qualifying delayed participation anchor advances only when the otherwise qualifying annual provider period aligns exactly to original subscription anniversaries. Apply its whole annual-cycle count from the original service date with leap-day clamping, capped by both the observed provider cycle and the latest break-adjusted service anniversary actually started at explicit asOf. Keep basis effective_start and literal saved-day authority. Non-aligned or invalid cycle evidence retains the existing service-start baseline; stale evidence cannot advance beyond its observed cycle and the clock alone never adds cycles. A selected paid-row manual override remains exact and recorded break days apply once. Invalid, short, monthly-installment, future, missing, inactive, unknown-price and zero-price evidence cannot establish current_cycle. A separately verified pending annual schedule may use its own scheduled start. Provider, contract and participation dates remain unchanged.
• Sales consumes the corrected due date and basis through the existing public evidence facade. Existing Expected baselines and original due attribution remain immutable; a date correction requires the existing amendment path and does not prove a Realized renewal or payment. No database schema, boundary, event or runtime is added.
• Automatic renewal eligibility excludes a known-zero recurring row when it has no positive complete plan, even if that row has a manual override. Unknown price is not zero. An introductory zero-priced phase backed by a positive complete plan remains eligible. Excluded rows remain in contract history and renewalCycleEvidence; exclusion neither deactivates a VIP nor changes provider state. For a new VIP profile, import selection prefers a commercial contract over a known-zero placeholder only within the same coverage class. Known-zero-only and unknown-price sources retain their existing import behavior, and already saved participation dates remain untouched. This general source-selection rule uses exact provider-customer ownership, never a case-specific correction or an inferred payment or participation-date origin.
• Monthly multi-payment annual-membership financing is excluded from automatic selection only when an explicit future yearly successor with a known positive unit amount or verified positive complete plan starts on or after the finite financing-plan end and no later than the later of the projected membership end or one calendar month after the financing-plan end. The earliest eligible future candidate must itself satisfy the positive yearly successor and start-window guards, independently of source order. A later qualifying contract cannot promote an earlier unsupported candidate or suppress active financing. A manual override or positive local break adjustment preserves that row. A future financed membership is also preserved when a recognized prior commercial membership started by evaluation and its calculated term ends no later than the financed start; active financing can still yield to its annual successor. Without a qualifying successor the annual-membership projection remains; an installment start alone does not prove renewal. Unknown-price standalone rows remain eligible, but cannot displace financing without that positive successor evidence.
• A complete 12-month plan aligned to the original contract anchor supports annual membership duration independently of quarterly cadence, preserving the quarterly classification kind. Without complete term evidence, quarterly membership duration remains a Product decision; the existing three-month runtime projection stays unchanged. Existing monthly-named annual memberships, including Few Months names, remain recognized; explicit one-month, quarterly and semi-annual names require their own term evidence. Outside the verified pending-annual path, ordinary non-financing future transitions require earlier business-eligible history that has started by evaluation; canceled or paused history can qualify without proof of payment or a completed membership term. A future financed membership instead requires a recognized prior membership with a known positive unit amount or verified positive complete plan whose calculated term ends no later than the financed start. A started zero placeholder supports its separate replacement transition but never proves a paid or completed membership.
• Returning from a started zero placeholder uses the next non-financing commercial start and that row's break offset once. The same pure projector supplies API selection, VIP summary/commercial date, reminders, forecast and Sales evidence. Paid-row manual overrides remain exact; zero-row overrides cannot restore automatic eligibility. Every contract observation remains available to cycle evidence and original Expected cohorts retain their attribution; selecting a new date proves neither payment nor Realized renewal.
• A verified pending annual provider schedule uses basis future_contract, labeled Scheduled membership start: provider-schedule provenance, not_started, scheduled or future_confirmed status, operationally inactive, no canceledAt, yearly cadence and annual classification excluding quarterly and semi-annual classifications, plus a verified positive complete phase plan of exactly 12 calendar months anchored to its own subscription/current-period start and one installment; an approximate installment count is allowed. Its own start plus its own break offset once supplies the date, with the selected-row manual override exact and no started-history requirement. An eligible active contract still wins; otherwise the earliest eligible pending annual start retains chronological priority over later futures, including same-day or overdue pending starts. Pending provider status preserves this scheduled date until activation or cancellation is imported; the clock alone never adds 12 months. VIP participation start remains separate and unchanged; an effective-start conflict does not establish whether that profile value was manual or imported. This schedule evidence proves neither payment nor Sales Realized, and original Expected cohorts remain immutable.
• Identity defines RENEWAL_CALENDAR_TIME_ZONE as America/Phoenix, the confirmed Arizona renewal calendar, without rewriting original instants. Public row day fields and calendar metadata distinguish provider-derived bases, which use Phoenix days, from manual_override and effective_start, which preserve the literal UTC day of staff civil-date intent. A participation day later than the original VIP start day retains effective_start authority and its saved literal day; an equal-day profile baseline uses the commercial contract and provider-derived Phoenix calendar instead. This distinction preserves saved profile values, exact overrides and granted break days, without inferring historical date provenance or repairing profiles. API/UI rows and VIP upcoming days consume these day fields. Date-only filters, statuses, counters, overdue decisions, day windows and reminders use the same calendar policy; legacy explicit-instant filters keep their existing contract. Sales receives dueDay and calendar metadata for future admissions while original Expected cohorts and due attribution remain immutable. The calendar correction proves neither payment nor Realized renewal; no browser or host timezone supplies the business day.
Facebook email confirmation — ADR 0098
• Identity owns PortalEmailChallenge and PortalEmailConfirmation for the dedicated VIP pool and exact Facebook subject. The authenticated callback records the provider email separately as unconfirmed contact and automatically requests one email. A 15-minute HttpOnly pending cookie references only Redis-held login tokens and grants no portal business access.
• Notifications auth-public.ts delivers an HTML confirmation button and plain-text URL through existing SES sender, environment and suppression controls. Only authenticated contact proof uses a narrow transactional recipient policy, like invitations, without generic campaign/test allowlists. A random 256-bit single-use link expires in ten minutes. PostgreSQL stores only its SHA-256 digest and browser-session digest; the URL fragment is removed from browser history and never logged. Resends supersede old challenges under existing cooldown and hourly limits. Failed sends preserve pending work without automatic retry.
• Origin-checked, IP-limited POST confirmation may run on another browser/device. Atomic token consumption, local contact proof and staff-attempt contact/revision update grant no session, account, VIP link or Cognito email_verified change. Explicit continuation requires the original pending cookie, live matching Facebook identity and local proof; another browser signs in again. Missing/invited subjects await staff review; existing inactive/disabled subjects retain only ADR 0096 limited sessions. Legacy code POST remains for in-flight clients. Redis/provider failures fail closed while preserving recoverable work.
Public event registration — ADR 0100
• Integrations owns public-event contacts, opaque browser recognition, fenced PostgreSQL jobs and provider presence. Authorized staff POST persists each event's normalized Zoom link and meeting ID; shared S2S credentials stay in the environment. PUT remains compatible; personal join links remain ephemeral. No visitor CRM or portal identity is provisioned.
• A separate S2S signing secret selects the public-event route; the shared Zoom inbox commits independent public work and an original-route receipt so arrival order cannot suppress dispatch. Exact meeting UUID and joined occurrence evidence stay separate from Delivery attendance.
• Existing AWS public pages use approved Origin/JSON/custom-header requests and host-only HttpOnly cookies; proxy and same-site environment validation remain pending. LaunchDarkly public-events defaults off; accepted work keeps recovering. A designated local test slug may override availability only in development; emergency disabling, event policy/windows, staff authorization and real Zoom verification remain required.
Active unlinked portal reads — ADR 0101
• Identity authorizes only marked GET handlers with an active PortalReadActor whose VIP binding may be null. Guard and shared-row transaction recheck the current profile/revision/binding; the final authoritative session check discards stale, expired or revoked results. Inactive, disabled and invited profiles remain restricted; cookie-only sessions never fall back to staff Bearer identities.
• Delivery returns an empty Track list without a participation query for unlinked clients on tracks/paths/journeys aliases. Existing Tracks feature flags remain required. Common assessment media signs only fixed ready organization-scoped Back Fix assets under the existing four-hour TTL; issued URLs retain their bounded residual validity.
• VIP assessment shows preparation and one Back to home action when no participation exists, deferring media/details/playback/commands until a participation is selected. Identity or binding scope changes reload the assessment. All other personal resources and writes retain linked actors, owner and prerequisite checks. No pre-VIP progress ledger, enrollment, Backoffice UI, event, host or runtime service is introduced.
Historical Track ownership preparation — superseded by final pre-production schema
• Accepted target: Delivery TrackParticipation belongs to a stable Identity UserProfile reference, with optional original VIP context. One current user per VIP and one VIP per user; historical corrections/deleted profiles never silently transfer client ownership or clinical/attendance evidence. TrackProgress, versions, physical Journey names, immutable publications and media keys remain one preserved history.
• Historical staged mapping and later NOT NULL finalization are superseded by the compatible recovery contract. Older unresolved records are retained but unavailable for execution/review; new writes require explicit UserProfile ownership under NOT VALID checks. The current contract is the ADR 0102 recovery amendment and rollout runbook.
• ProgramRunVip, live sessions, operational on-demand and other VIP-based Clinical aggregates retain their VIP contracts. User-only Track ownership, configured explicit start and assigned review are implemented and tested. Application environment deployment, content/reviewer configuration and feature activation remain operational actions, with no automatic test-data deletion.
User-owned Track execution and compatible owner storage — ADR 0102
• Delivery owns the Achievements catalog, child badge rules and durable user-scoped grants. Identity exposes only completed years as of the award for the verified linked VIP. The first grant source is Service Funnel completion. Portal surfaces reuse the existing owner-authorized read boundary.
• Compatible owner storage preserves older unresolved userProfileId rows in physical Delivery JourneyParticipation and Clinical JourneyQuestionnaireResponse. NOT VALID required-owner CHECKs enforce all new/updated writes. The rejected finalization is corrected to a no-op; versioned migration 20261029160000_preserve_older_track_owners aligns both failed-finalization and previously successful databases without owner inference or data deletion. Assigned owner and every original VIP context remain immutable.
• Delivery exposes granular-permission client assignment/closure under existing program_setup.manage and Tracks rollout controls; the Backoffice user directory selects an existing account, published TrackVersion, training profile and reason without provisioning or activation. VIP direction and scheduled Track destinations resolve the unique user before creation/source closure/roster mutation. ProgramRunVip and live/operational on-demand stay VIP-based. November 16 assignment amendment: reviewer allocation is optional for every manual client assignment, including professional-review funnels; non-global review still requires the assigned authorized reviewer and checkpoints never auto-complete. VIP Users supports explicit selection of up to 100 accounts across pages and choosing one published version. The browser sends the existing independently authorized, fenced and idempotent per-user assignment commands sequentially, retains each request key on retry, reports partial results and retries only failed accounts. Existing open cycles are rejected rather than closed, reset or version-replaced implicitly; account lifecycle and ownership remain unchanged.
• Explicit client-owned Track methods derive a trusted active UserProfile from the cookie session, retain Identity row/revision/binding and final Redis-session fences, and validate immutable participation ownership before progress, Clinical, upload or playback access. General Tracks never query VIP attendance/upcoming projections. Clinical retains subject-bound immutable submitted answers; actual recording uploader and media TTLs remain unchanged. Sessions and VIP Journey keep strict VIP guards. Under the November 10 ADR 0060 amendment, portal Chat instead admits active UserProfiles with optional VIP binding through the client-resource actor, including realtime admission and periodic reauthorization; the independent chat flag and exact typed conversation/attachment membership remain required. The Responsible VIT shortcut is empty without a linked VIP, while authorized staff-created client conversations remain available.
• Delivery PortalTrackEntry pins an explicitly configured published assessment version with optimistic revision and the existing physical configuration key. Assessment entry is the UI, implementation and HTTP client terminology, and only assessment-entry HTTP routes are exposed. Published welcome snapshot values remain readable without rewriting immutable versions. Entering Assessment resolves owned work or automatically issues the idempotent assessment-entry/start POST for active authenticated clients, including clients without VIP. GET/login remain read-only. The resulting normal Track participation uses the same pinned video, chapter questions, answers and completion engine as manual assignment. There is no independent preview player or extra Start button; Play is explicit and replies resume playback. Optional checkpoint images use a separate authenticated images GET independent of the legacy fixed video. Roster locks, durable keys and saved work remain authoritative after entry is disabled. Version, progress, original context and ownerless older records are preserved.
• Default reviewer assignment is optional at assessment start; a revoked default grant leaves new participation unassigned. Under the user-approved November 10 amendment to ADR 0102, Identity projects active administrator/global StaffUser authority through canManageAllTracks. Administrators inherit tracks.client.review and can list, review, play execution recordings and control all resolved Service Funnel executions, including general unlinked clients and unassigned participations. Non-global reviewers still require an explicit grant and current assignment; non-global VIP Directors retain membership scope. Portal UserProfile ownership, original-context quarantine, completion prerequisites and independent Clinical permissions remain unchanged. No commercial entitlement engine, new runtime service or extra progress ledger. Required new-write checks and nullable older-owner storage are validated in disposable tests; application environment recovery/configuration remains pending.
• Step 9 regression corrects staff capability eligibility: explicit tracks.client.review and Track management permissions participate in the existing journeys rollout; journey-reviews remains a derived capability, not a new provider key. Active program_setup.manage governs Delivery client assignment/configuration without hardcoded role restrictions; Identity account provisioning/directory policies remain independent. Browser, real PostgreSQL/Redis HTTP and broad domain regression validate new client flows and unchanged VIP live/on-demand operations using synthetic fixtures. No real-data mapping or deployment is performed.
• All 212 migrations install on a clean disposable PostgreSQL 17/pgvector database. Real Prisma CLI recovery/repeat tests preserve older participation, questionnaire answers and progress while rejecting new ownerless writes. Application execution, media, review queues and staff closure exclude or reject unresolved owners. API startup still requires one controlled resolve --rolled-back for an existing P3009 using the corrected release; no automatic migration-history clearing hook or application environment mutation is introduced. Other Clinical/VIP live/on-demand ownership remains unchanged.
Manual historical GA4 reporting import
• Integrations owns read-only Google Analytics Admin/Data access and five PostgreSQL models: GoogleAnalyticsSource, GoogleAnalyticsReportDefinition, GoogleAnalyticsImportRun, GoogleAnalyticsImportPartition and GoogleAnalyticsReportRow. Foreign keys connect source/definition/run to daily partitions and observations. These are private aggregate provider facts, separate from raw events, VIP identity, Clinical, attendance, Sales and Engagement.
• A dedicated manual CLI accepts private configuration files or GA_IMPORT_CONFIG_JSON, and read-only Google credential files or named environment secrets. Credentials never enter plans or logs. Undated development configuration defaults to the previous complete property-local month; validated explicit start/end date arguments support later ranges. Production requires an explicit window. Destination host/port/database and target guards remain required; database run/partition history preserves coverage and failure evidence without receipt files. Preflight and cleanup do not load Google credentials. No application workers, automatic migrations, tracking changes, HTTP routes, schedules, realtime or business events are introduced.
• Property/spec/local-date uniqueness and database-clock leases fence staging and atomic generation activation. Exact original metric strings/types are preserved. Named dimension, metric and metric-type JSON objects replace positional arrays; immutable definitions explain each report grain. Restrict-delete provenance relations, query indexes and private migration backup preserve evidence.
• The retained baseline v1 uses exact allowlists. Explicit marketing v2 preserves original selected reporting values for later cleaning, without rejecting unfamiliar business labels. Thirteen separate grains cover overview, acquisition, content, events, technology, landing pages/campaigns, campaign actions, geography/language, custom event details, video, ecommerce overview and items. Unsupported reports and source restrictions remain explicit; no identity, clinical or full-query URL fields are selected.
• Active rows retain committed spec history. Current rows choose the highest committed report version and latest commit per property/report/day; failed replacements preserve prior snapshots and successful empty snapshots suppress older rows. Flat SQL family views expose named numeric columns without business classification, cross-property deduplication or inferred bookings/payments. Five-request batches, one-use bounded caches, grouped running checkpoints and bounded cleanup retain independent report pagination/fences. See docs/operations/google-analytics-structured-import.md.
Portal user invitations — ADR 0103
• Identity owns PortalInvitation and append-only PortalInvitationEvent, with per-email/actor transaction locks, request idempotency, immutable recipient and a hashed 256-bit bearer token. Staff use /settings/portal-invitations with portal_invitations:manage. Existing local/provider accounts block sends. Default validity is seven days (168 hours), configurable via PORTAL_INVITATION_TTL_HOURS; expiration is authoritative without a cron and reissue supersedes the old token. No VIP or enrollment is inferred.
• Public POST /portal/auth/user-invitation/inspect, /verification and /accept require exact portal Origin plus shared Redis traffic limits. A fixed-email OTP, hashed HttpOnly browser proof, bounded lifetime/resends/guesses and an atomic provisioning claim precede Cognito creation. Native verified subject/email must match before UserProfile invited-to-active and invitation consumption commit. Lost commit results are reconciled before compensating only a proven newly created unbound subject; uncertain creation/cleanup stays needs_review. The portal strips URL fragments and never persists secrets in browser storage.
• Notifications exposes a leaf auth-public invitation mail facade: a manually selected active MessageTemplate revision and optional signature render transient secret-bearing SES messages, without a regular EmailDelivery snapshot/outbox or a new runtime. VIP Users Email configuration binds Portal account invitation separately from legacy Cognito auth settings. Staff-issued invitations and their fixed-recipient proof codes bypass recipient allowlists, retaining enabled sending, valid sender/tracking configuration, address validation and suppression checks. Other email recipient policies remain unchanged. SES acceptance, failure and uncertainty are durable operational facts; no inbox receipt is inferred. StaffAuditLog adds an explicitly validated recipient email snapshot, fixed reason and correlation for completed sends only. Secrets and bodies never enter logs, audit or history. See docs/operations/portal-user-invitations.md.
• The November 4 amendment adds POST /portal/auth/user-invitation/confirm under the existing Origin and shared traffic guards. Identity validates the token, code and HttpOnly cookie under the invitation lock and shared expiry/attempt budget before VIP Platform reveals name/password fields. Confirmation never provisions, consumes or extends proof, creates a session or issues another credential. Final acceptance revalidates and atomically claims the same proof. The November 5 visual correction reuses the VIP Portal split photo/purple glass layout, white fields, shared visibility checkbox and dark actions; responsive invitation forms scroll without shrinking text; password policy remains twelve characters with uppercase, lowercase, number and symbol. No migration, environment variable or Notifications transport change is introduced.
• The verification-code email has a separate revisioned template binding in the existing Notifications PortalInvitationEmailSettings row portal-user-invitation-verification. Identity exposes GET/PATCH /portal-invitations/verification-template under message_templates:manage, recording existing sanitized configuration audit with resource verification-template and version only. Notifications requires visible verification_code, optional verification_validity_minutes, current template/signature revisions and no enabled buttons or markers. Identity passes the newly persisted proof deadline; rounded-up display minutes never extend expiry. Only an absent binding uses the original built-in copy. Rendered code/body remain transient; the fixed recipient, proof, resend, suppression and activation policies are unchanged. No migration, new runtime or env is introduced; publish API before Backoffice frontend.
• ADR 0105 adds native portal password recovery using the existing Cognito one-hour reset link and Password reset template binding, optional auth_validity_minutes=60, shared Redis IP/account limits and exact verified subject/email checks. A per-profile reset fence plus durable UserProfile authorization revision closes old BFF sessions; verified native password login heals uncertain provider outcomes. Reset never provisions, activates or signs in. Notifications uses its existing auth-public facade and settings table for a separate static portal-password-changed template. Dispatch and notice are best-effort without a new worker/outbox. VIP Portal strips fragments, respects Retry-After and offers normal sign-in. No new migration or env; live provider/inbox/CDN checks remain separate. See docs/operations/portal-password-recovery.md.
• ADR 0108 supersedes mandatory OTP with server-owned link-only policy; dormant verification endpoints reject requests while disabled. Identity records invitation_link_verified and retains fixed recipient, expiry, claim, conflict and compensation controls. Activation uses an application transaction with a Notifications auth-public enqueue callback; Notifications owns the unique PortalWelcomeDelivery intent, recipient/name and delivery leases. Existing API/worker processes poll it; aborted preparation retries, unknown sends remain uncertain, definitive rejection retries are bounded. The manual portal-welcome template requires a normal portal_url button, never a credential. Backoffice shows Account access and Password recovery, hides dormant code/provider-purpose controls and preserves legacy first access collapsed. A dedicated permission-protected retry for failed delivery records secret-free completed audit. Migration 20261109120000 precedes coordinated API/worker/frontend release. See docs/operations/portal-invitation-welcome.md.
Optional email action buttons — ADR 0104
• Notifications reserves button_enabled, button_label and button_url for email-only action controls. Variable definitions may persist default_value only for these controls; fictional examples never become live defaults. The existing template DTO/JSON and revisioned editor expose these saved values without a migration or new runtime. Explicit generic send values can override declared controls.
• Absent/false buttons return the existing body unchanged, preserving exact no-button HTML, signature layout and spacing. Enabled buttons require bounded plain text and a literal HTTPS URL or one declared non-button destination variable. The shared renderer appends trusted purple (#7D06D0) anchor/table markup after sanitized content, before optional signature composition, without allowing arbitrary body CSS. Preview, text fallback and delivery use the same result; reviewed delivery snapshots remain immutable.
• Portal invitations require button_url to reference the server-owned invitation_url; existing first-access/password-reset email binds to auth_url and preserves Cognito placeholders. No personal URL is persisted in a signature/default and no token enters audit. Default-off compatibility, unsafe destinations, variable aliases, provider placeholders and editor persistence are tested; real email-client appearance remains an operational verification. See docs/operations/email-action-buttons.md.
• The November 4 amendment adds up to five content.action_buttons entries (id, enabled, label, url), each positioned by exactly one standalone {{action_button:<id>}} paragraph. The generic {{action_button}} positions the legacy action; absent markers preserve its append behavior. Disabled paragraphs disappear. DTO/editor validation rejects duplicate, unknown, inline and subject markers. A per-render sentinel protects configured placement from variable-value injection before trusted HTML rendering. Invitation/auth require the expected personal link and allow supplemental named HTTPS actions. No new table, runtime or event is introduced; deploy API/worker before frontend and rebind revised templates.
• The Backoffice staff shell keeps admitted editors mounted after 15 minutes of inactivity or HTTP authentication expiry. A paused session blocks new authenticated requests and auxiliary realtime connections while an accessible renewal dialog/banner preserves local unsaved work. The previous clear-and-redirect idle behavior is superseded. This changes presentation and browser control within the existing Hosted UI + PKCE authentication model, never backend permission enforcement or VIP cookie sessions.
• Explicit renewal shares a bounded refresh attempt and revalidates Cognito subject plus active effective StaffUser through /me before adopting candidate credentials. The original actor and viewed staff identity must match; refreshed permissions apply without silently discarding an admitted editor. Epoch checks reject delayed requests, replay and renewal results across interactive recovery, logout or workspace replacement. Network failures preserve recoverable credentials, terminal rejection discards only unusable tokens, and interactive recovery never automatically resubmits the failed business save.
• When new sign-in is required, an explicitly opened same-origin popup uses the existing /auth/callback and PKCE. The original tab stays on its editor. Bounded nonce, exact origin/source, callback and tab-scoped state checks allow only the initiating opener to read candidate tokens from the returned popup sessionStorage; completion messages contain no credentials. Blocked/closed/timed-out windows, account mismatch and revoked access preserve original work and offer retry. No tokens enter localStorage/BroadcastChannel, and no new backend service, durable store, draft persistence or event is introduced.
• The recording picker calls read-only POST /session-analysis-projects/from-meeting-videos/preview before submission. Integrations validates stored-video metadata and one resolved VIP, then calls Delivery through its public facade with stable video ids. Delivery composes current Experience VIT from the Identity public current vip_experience Assignment projection, request-assigned analyst, and only the current author's existing project id. No provider payload, private media location or other author's composition enters this projection.
• For the same VIP and request/source context, creation reuses the active current author's existing Studio project, preserving sources and composition. Another active linked VIT may explicitly confirm an independent project with confirm_additional_analysis=true even when the request is assigned to someone else. The server revalidates source/request identity and author eligibility under the existing transaction locks; confirmation never transfers request assignment, Experience VIT ownership or another author's work. Different sessions for one VIP remain independent contexts. Direct request-queue creation retains assigned-analyst/global authorization, while active authors may resume their own existing live project after reassignment.
• The confirmation dialog names the Experience VIT and assigned analyst, distinguishes opening saved work from creating a personal project, and supports retry or cancel without losing the recording selection. Preview is read-only and is not authorization evidence for a later write. Existing project editing remains author/global-editor scoped. The first confirmed final keeps the linked request's existing idempotent completion policy; waiting-video verification accepts its active linked VIT project author after exact VIP/source/request and private final-media checks without requiring that author to equal the request's assigned analyst.
ActiveCampaign contact coverage and recovery
• Identity storage retains import-owned ActiveCampaignContactSnapshot and the account-scoped ActiveCampaignContactImportState checkpoint. Historical scans resume by ordered provider IDs; incremental scans freeze lower/upper time boundaries. A leased owner commits snapshot data and checkpoint advancement in one PostgreSQL transaction, and only a completed scan advances the watermark. Targeted imports never move that checkpoint. Incomplete provider reads fail without replacing stored fields.
• Before VIP projection import, a targeted coverage repair resolves the existing Stripe customer and source subscription to an exact provider email lookup. It imports complete labeled contact snapshots and compare-and-set patches only contact notes; no VIP rows, top-level identity, subscriptions, Clinical answers or portal access are created or replaced. Missing sources, multiple provider contacts, invalid identifiers and concurrent changes retain review evidence visible through the existing authorized expanded-list projection.
• The approved duplicate-contact-data policy copies one provider contact into distinct VIP profiles sharing an email with explicit shared-email evidence. It never merges identities or attributes email-only onboarding/Clinical answers to an individual. Existing contact references are retained; conflicting replacement proposals stay in review. The isolated maintenance bootstrap starts no business consumers.
VIP playback requirements, review metrics and favorite achievements
• Delivery freezes optional per-video videoCompletion requirements in TrackVersion. Omission preserves manual completion; minimum_watch requires an integer 1–100 percent and monitored internal media. TrackVideoWatch stores merged distinct playback intervals per participation/activity with a fenced browser session, monotonic sequence and server-clock-bounded observations. Seeking, disconnected time and replays never add duplicate credit. Completion independently enforces the pinned minimum in the owning backend. Client playback evidence does not prove attention, practice submission, review or live attendance.
• Owner-authorized POST /portal/tracks/:id/lessons/:activityId/watch accepts only the current eligible video and returns saved watch percentage without incrementing execution revision. Delivery staff GET /delivery/track-execution/:id/summary rechecks each included cycle against existing review authority, aggregates up to 500 recent same-owner/Track/original-VIP cycles, and leaves unmeasured viewing and unavailable consultation scheduling unknown. No provider payload, media bytes or cross-context database access is introduced.
• Delivery ProfileBadgeSelection stores up to three explicit profile selections per UserProfile, keyed by earned awardId or an owned completed legacy badge id and ordered by selectedAt then badgeId. POST /portal/tracks/badges/profile validates the owned earned collection and serializes add/remove/count checks with an owner-scoped transaction advisory lock; retries are idempotent and a fourth selection is rejected without replacement. Earned collection and conclusion projections include isProfileBadge and profileBadgePosition. Migration preserves the prior explicit favorite; the legacy favorite route retains single-selection replacement semantics under the same lock. The header overlaps selected badges beside the avatar, with independent subtle float/glow and a browser-only 30-second front-to-back queue animation; reduced motion disables float and rotation, and hover/focus pauses cycling. Profile actions are available wherever earned badges appear. No award, progress, media grant or Identity authorization changes. Completed-step links remain read-only and pass through the existing owned-history APIs during onboarding. Confirmed Quiz answers exit before playback resumes. Consultation celebration is prepared but dormant until a scheduling integration supplies an authenticated persisted confirmation.
• Delivery includes pinned presentation and an optional thumbnailUrl in the owner-authorized completed-activity HTTP projection. Review reuses the published width and resolves the pinned image to a short-lived portal URL, or uses curated artwork for legacy videos without a thumbnail override. Playback still uses the existing authorized route. Visible completed path entries open the authorized review.
• Owner-authorized video playback can include bounded English WebVTT for eligible private or direct HTTPS videos. The common assessment response uses the same library caption lookup under its existing authenticated access. The browser attaches the text as a local track, and YouTube embeds use provider controls.
• DEV Track playback can select approved byte-identical original MP4s from a bounded private activation manifest. The existing catalog key remains the source of captions and the fallback playback. Published snapshots, staff media and production playback keep their current resolution paths.
Portal device and password security
• Identity owns GET /portal/me/security, GET /portal/me/sessions, DELETE /portal/me/sessions/:sessionReference and the existing POST /portal/me/password. Cookie authentication, exact Origin, active UserProfile, the shared Identity transaction and final session fence apply; VIP binding is optional and inactive/disabled exceptions are unchanged.
• Only an authoritative native Cognito account may change its password. Trusted login provenance and current pool identity exclude social and linked/federated accounts. The shared 12–128 character policy rejects whitespace; current-password proof, best-effort notification and uncertain-outcome handling remain inside the BFF. Authenticated change preserves other sessions; forgotten-password recovery retains ADR 0105 revocation.
• Redis remains the session authority. A bounded per-UserProfile derived catalog contains at most 100 public family references and expiry scores, exposes pages up to 25 rows and shows the current family first. Device/browser/OS are normalized from bounded User-Agent parsing, never raw headers. Approximate five-minute activity updates never extend absolute expiry. Indexes never recreate credentials.
• Remote sign-out atomically validates stored ownership, rejects the requesting family and deletes only the target family, with a same-slot secret-free 12-hour retry receipt. The stable public reference survives cookie rotation; refresh/renewal CAS cannot revive deletion. Cognito targeted refresh-token revocation follows local invalidation. No GlobalSignOut, identity-wide revision, new service or realtime command is used; cross-slot catalog cleanup remains derived.
• Legacy families register on authenticated use without global scans. legacy_sessions_may_be_missing marks the first 12-hour catalog window; the UI avoids claiming a complete single-session list then. Shared Redis failure remains fail-closed. Existing signed-media residual validity and backup/restore fencing are unchanged. See ADR 0097 amendment and docs/operations/portal-device-security.md.
Architecture diagram • Built with Archify • Create yours ↗ • Hover to trace • R route • Click to focus • +/− zoom • M radar • [/] views • P play story • T theme • E export