Modular monolith, durable data, realtime operations, and private live/on-demand media pipelines
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
• The existing frontend also serves /portal/chat through Cognito PKCE without the staff shell or /me. Identity resolves one active UserProfile per token; no VIPProfile or Cognito-only access is granted.
• Chat commands use authenticated HTTP. PostgreSQL owns ordered messages, idempotency keys, membership, read watermarks and moderation evidence. Redis carries metadata invalidations and shared limits; no message bodies or file bytes enter Redis.
• AWS KMS wraps a per-conversation AES-256-GCM key. Direct uploads enter a dedicated versioned private S3 quarantine prefix. GuardDuty tags the immutable version; confirmation validates checksum and detected type before attachment availability. Deployment configuration and smoke verification remain required. The explicit CHAT_ATTACHMENT_SCAN_MODE=disabled exception is accepted only for Railway staging. Validated uploads retain ready_unscanned evidence and are publishable/downloadable only while that exception is active; other environments require clean scans and reject disabled configuration. Membership, checksum, format, size and immutable version controls remain enforced. Reconfirmation validates the original frozen version; withdrawing the exception blocks new links while previously signed downloads retain their two-minute expiry.
• 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.
• 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.
• Authorized external completion may explicitly record video_unavailable=true. Delivery atomically completes the request and retains completed_without_video project state and immutable actor/version evidence, without fabricating a final_video, render timestamp or delivery. The upload path still requires a confirmed private final asset; failed uploads keep requests open. The old local-review toggle is replaced by the explicit no-video choice.
Modular monolith
• All About You FBF1-FBF4 controls send all_about_you_fbf to the existing overview endpoint. A new reviewed All About You import captures bounded same-year Consultations A-column headings/dates; no new worker, table or migration. Gold stores private versioned block evidence. Reads intersect dates with one explicit observed block, including recorded post-event weeks. Undated adjustments require a full selected month with uniform program attribution. Missing FBF4 is unavailable; November is never assigned by month or counted twice through totals/reimports.
• All About You larger date ranges calculate the rate from matched confirmed VIP and attendance sums. The overview adds conversion_showed as the explicit eligible denominator; overall Scheduled/Showed retain their selected-period scope. Partial results explain excluded records. This read-time update uses existing Gold and requires no import or worker run.
• The same acquisition import selector also supports Consultations, dataset consultations and mapping consultations.v1. Integrations reads bounded unformatted A:H from yearly Consultations tabs; Sales publishes daily Gold in the existing transaction. The overview serves nullable month/week/day scheduled and net VIP metrics, source/quality metadata and explicit unsupported attribution. Monthly source precedence is established before date filters; no new worker or direct browser spreadsheet access.
• Identity owns immediate Experience VIT redistribution through the existing POST /assignments contract. Optional expected_current_assignment_id and expected_current_vit_id preconditions are compared under the existing capacity transaction lock; stale reviewed ownership is rejected. Replacements close the previous assignment and retain history. The staff workspace composes Program Run rosters and previous-month Engagement snapshots; each confirmed VIP transfer commits separately with existing authorization, capacity checks and audit. No new ledger, worker, automated balancing or enrollment mutation is introduced.
• The acquisition import page selects Registration or All About You before Start import. Authenticated preview accepts dataset registration or all_about_you; source-specific review/publication and retry preserve that choice. All About You reads bounded unformatted A:I ranges from yearly tabs and corrects dates to the worksheet year. The existing Airtable conversion also projects canonical All About You Gold; no new worker. The card serves nullable metrics, source freshness and quality from saved Gold with monthly spreadsheet precedence and explicit unsupported-filter states.
• PostgreSQL owns durable business, audit, and long-running operation progress state
• Authorized Socket.IO snapshots are published only after durable progress changes
• Sales evaluation-framework compilation returns HTTP 503 with safe, actionable OpenAI failure categories, allowlisted provider status/code/request references and retryability. It never forwards raw provider messages, source text or credentials. Confirmed rate-limit and server failures receive at most three total requests with bounded Retry-After delays; quota, access, model, input and ambiguous network failures are not replayed. Increased output-token recovery shares that request budget. The same safe failure message and compilation code are persisted before operation-scoped staff progress is published; already-running source batches settle before terminal failure, so late successes cannot overwrite it.
• Notification inbox writes publish schema-versioned invalidations through Redis Pub/Sub to the authenticated staff recipient room; HTTP remains the recovery path
• Role-aware notification preferences gate each eligible future inbox write before realtime publication
• Delivery, recorder, Engagement, and scheduled jobs emit non-blocking in-process facts; Notifications projects the assigned VIT StaffUser or active admins asynchronously
• Persisted inbox mutations emit a committed fact; the asynchronous realtime bridge handles local Socket.IO and Redis Pub/Sub fan-out
• Notification source facts are best effort across process termination; a future transactional outbox is required for guaranteed recovery
• Attendance calls recorder commands over authenticated HTTP and receives bot, participant, and capacity projections over Socket.IO
• Bot Management is the only editing surface for Delivery-owned ProgramRun Meeting ID assignments and optional configured expected session time; matching occurrences receive the IDs
• Its authorized dashboard projects monitored meeting status, duration anchors, online attendance participants, live camera counts, and active breakout-room participant counts from signed Zoom webhooks over Socket.IO
• A dedicated clinical-data import process runs one Practice Better batch every five minutes under Railway scheduling, independently of VIP and break jobs. The API queues scans and SQL checkpoints resume interrupted imports
• The five-minute clinical process handles explicit source-copy jobs as well as downloads; Clinical owns durable source versions and Integrations owns resumable checkpoints
• The Clinical frontend calls the Identity HTTP composition layer and ClinicalWorkspaceService inside the API. Body observations and summaries save synchronously with revisions; no new worker or realtime PHI is introduced
• 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
• Sales Historical imports uses authorized HTTP history and review snapshots. The mounted staff page advances bounded Airtable capture pages after explicit start/resume; closing it leaves durable checkpoints. Acquisition remains a manual approved spreadsheet capture, with no new worker or provider secrets in the browser
• The existing complete Stripe import also captures Membership Silver and Gold atomically in Sales. Page-limited imports do not project; same-day identical captures are no-ops and corrections append revisions. Authorized /sales/overview/memberships reads saved aggregate Gold independently of Airtable and FBF; no new worker or schedule.
• 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.
• Delivery owns revision-protected SessionOccurrence analysis roster exceptions. Program Run stores per-time VIT priorities, limits and overflow settings. Experience owners are allocated first, then ascending priority with balanced session counts, then overflow. Staff may change session-only VIT priorities, limits and membership, then recalculate suggestions or explicitly redistribute unstarted requests; active/completed work and projects/feedback are preserved. Assignment-change facts publish after commit.
• Integrations resolves recording VIP attendance links and phase through Delivery RecordingAttendanceContextService. Source, local recording date, phase and canonical VIP-name search filter the catalog before pagination; media remains private.
• Clinical versioned summaries own VIP Goals & Feedback Preference and Physical Limitations & Important Conditions. Clinical Records edits them; Studio tabs read the existing authorized Clinical HTTP surface without copying sensitive content to Delivery compositions.
• Integrations owns revision-aware session playback HTTP controls, immutable command-intent outbox snapshots and transactional control audit. Recovery serializes with mutations, retains pending commands until a live streamer lease exists, and validates stop events against the locked revision and fencing token. Passwords remain TTL-only Redis secrets; dead letters contain allowlisted envelope metadata. The isolated C++ Meeting Streamer implements the join/leave foundation; media execution is pending. Simulation stays offline; process-bound authority and observed TTLs fence SDK effects. Historical native-startup evidence is recorded; live lifecycle safety and remaining SDK/security checks are pending. The spike has Henrique's conditional go (2026-08-21); remaining playback/interruption checks belong to the end-to-end story.
• Read-only impersonation (ADR 0070) wraps the original Cognito access JWT with a target StaffUser selector for backend HTTP only. Identity verifies both users on every request and rejects writes. The browser preserves this mode through token refresh, shows a persistent exit banner, discards caches on entry/exit, and disables Socket.IO/chat and external OAuth actions. AuditEntry stores nullable impersonatorStaffId; no new runtime, secret, or independent login session is introduced.
• Delivery exposes POST /program-runs/:id/vips/transfer to staff with program_setup.manage or attendance.roster.manage. It reads the current source roster on the server, ends source memberships and adds missing destination memberships atomically with audit. Cancelled runs and same-run transfers are rejected. Roster mutations serialize through a PostgreSQL transaction advisory lock; existing program.run.vip_removed and program.run.vip_assigned facts publish after commit. Attendance and Session Analysis history remain unchanged.
• Quitter participation review runs inside the existing API and generic notification worker. Notifications supplies the Delivery ConfirmedVipParticipationService read callback to Identity reconcileWithParticipation under the per-VIP lock and reconciles the last 30 days with four concurrent evaluations. Awaited post-commit emitAsync and promisified listeners drain inbox projection before one-shot application shutdown; no new runtime or provider call is introduced.
• PostgreSQL Identity stores exact-cus_ VipQuitterParticipationMonitor episodes, locks current profile/evidence decisions and ignores older scan cutoffs. Notifications holds a separate per-VIP source projection advisory lock, uses Identity getCurrentEpisodeId and expires all older source episodes while preserving current intent and read state. Both transaction lock callbacks must finish bounded local database work within 15 seconds. Inbox writes commit independently before existing Redis invalidations.
• 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.
• The authorized Sales Overview response adds cards.active_ads from the existing Airtable appointment Gold read. Preserved affiliate classifies Facebook Ads and The Fitness Doctor; Sold counts confirmed VIP appointment outcomes, not payments or distinct customers. General UTC date and salesperson/affiliate/package filters apply. Real clicks remain null; the frontend shows a dash without FBF controls or edition comparisons. No new provider call, worker, table, projection or migration; UTM-only attribution is not available in this Gold read.
• 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.
• Private Sessions Only adds a default-false Identity VIPProfile field within the existing monolith and PostgreSQL schema. Integrations owns reviewed current Touchpoint-tab parsing of the explicit PS Only H3 Boolean plus retained source evidence, then uses the synchronous Identity public import contract after Integrations preview. imports.manage authorization, stale-preview compare-and-set and safe completed-action audit guard apply. Engagement reads current eligibility through Identity public profiles for source-linked attendance reports, showing PS Only separately and excluding it from group populations and low/no-attendance indicators. Original attendance evidence, Program Run membership and Not Acc rules stay independent. No runtime, event, worker, topology or media path is added.
• 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.
Recorder control plane
• Each genuine start opens a distinct Integrations-owned finalization lifecycle. Same-meeting target revisions preserve it; only the last authoritative shard exit closes it. Atomic participant claims and stream publication prevent stale close markers, lost late facts and duplicate enqueueing on resumed recordings.
• Zoom finalization request/result envelopes v3 carry finalizationLifecycleId and finalizationRequestId; participant attempt authority also fences same-cycle backfill retries. Worker checks the current closed lifecycle and absence of desired/shard state before processing, uploading and atomically publishing the result; obsolete jobs acknowledge without changing current recording state.
• Integrations trims recorder events in atomic bounded batches after at least 24 hours, preserving unread and pending entries for every consumer group; both API and finalizer groups must exist
• Leases, TTL renewal, and fencing tokens protect recorder ownership
• Recorders retain fenced terminal ownership until Backoffice accepts the event and performs shard and lease cleanup
• Accepted failures allocate a replacement while intent is active or finalize after the last stopping shard
• Finalizer concurrency uses continuously replenished independent slots; one long participant remux cannot hold an otherwise available slot
• Backoffice persists participant capture-start evidence in PostgreSQL before registering the capture in Redis. Delivery's authorized Attendance row projection exposes additive video_status: available, recording, processing or camera_off. The same confirmed, occurrence-scoped Attendance binding resolver associates stored/capturing/finalizing metadata without repeating VIP identity matching; only eligible capture evidence produces recording/processing. Blue Rec is a read-only capture/processing indicator; camera remains the existing editable Boolean and stored media alone qualifies as an available source. Session Analysis analyst allocation reuses this occurrence-scoped recording/processing projection for preview and creation, including an automatic camera Boolean still false while preserving explicit manual camera-off corrections. A request with pending capture and no stored source starts awaiting_vip_video without inventing sourceVideoId or videoSent; the existing stored-recording event attaches confirmed media and promotes it to ready_for_analysis. Camera off without qualifying evidence remains ineligible. Video-state changes refresh allocation preview without changing attendance edit intent; existing roster/capacity/started-work protections and media boundaries remain unchanged. Missing, failed, ambiguous or unrelated captures never imply Rec, and staff camera corrections are preserved. The frontend also classifies an unreviewed candidate with a unique persisted VIP decision above 95% as identified when its only review blocker is an existing manual Attendance fact. Linked VIPs explicitly displays that manual-attendance review conflict; needs_review, protected manual presence and every unresolved-candidate/finalization blocker remain unchanged. Automatic Attendance now qualifies an actual observed meeting join with a unique VIP identity strictly above 95%, without a five-minute threshold or participant leave. Waiting-room or admission-only evidence cannot establish attendance. Closed-interval duration remains factual metadata and can stay zero while connected; it does not gate attendance. The legacy attendance_threshold_seconds input is deprecated and ignored; reviewed decisions and duplicate-VIP protection remain authoritative. Suggestions, ambiguity, duplicate assignments, explicit unlink and staff review never establish this read classification.
• Delivery reuses one positive active attendance for a later joined participant only when a unique VIP identity above 95% agrees with a confirmed candidate for the same internal meeting, occurrence, VIP and exact attendance. The additional candidate records attendance_reused:<attendanceId>; source, status, camera, staff notes, analyst, media and analysis work remain unchanged. Manual absence, invalidation, relocation, shared-device facts, explicit review/unlink and ambiguous competing associations remain protected. Removing or reassigning one entry preserves attendance supported by another valid confirmed same-VIP entry. Active participant/candidate views and finalization blockers omit a waiting-only representation only when its nonempty UUID set is a strict subset of exactly one joined row in the same meeting with compatible candidate ownership. Positive reviewed waiting evidence hides only after the joined candidate confirms the exact same attendance and VIP. Negative review, unlink, conflicts and ambiguous targets remain reviewable; no saved observation or raw Zoom event is deleted. Waiting normalization requires a unique join target. Multiple confirmed candidates feed the existing occurrence-scoped video binding resolver and preserve primary media ownership.
• Projection events that fail five times move to a dead-letter stream only after the copy succeeds
• Connection failures remain durable timeline evidence; a higher desired revision may start a new bot attempt without erasing the prior failure
• An active desired assignment may recover a premature ended projection only when recorder instance, fencing token, and revision remain authoritative
• Unexpected shard exits enter reconnecting while desired state is active; one shard ending cannot terminate a meeting that still owns other shards
• A bot moved into a breakout room stops main-room capture, leaves the Zoom meeting, and reconnects to the configured main room while the SessionOccurrence intent remains active; it never records inside a breakout room
• Repeated commands for the same fenced shard reconcile targets in place; only its current assignment may fail or end that shard
• Zoom meeting start plus any participant join triggers one idempotent ALL-mode request after authorized StaffUser host validation; OBF prefers owner then co-host
• Recorder monitoring and automatic attendance share one resolution: Meeting ID identifies the Program Run, then Zoom start time selects the occurrence inside that run
• Authorized historical linking may explicitly select an attendance-enabled occurrence when its Zoom meeting ID is configured on the Program Run; host and time-window matching are bypassed. It persists ProgramSessionZoomLink evidence, then idempotently reprocesses participant-to-VIP attendance matching
• Normal meeting end and manual stop retain shard ownership until the adapter closes encoders and drains the final upload scan; an accepted stop command is not a completed capture.
• Finalization progress separates stored, failed and still-processing videos in the current lifecycle. Prior playable outputs survive a restart, while metadata compare-and-set fences delayed request/result/failure projections; unavailable Redis authority reports unknown progress rather than success.
• Delivery bulk Attendance confirmation still submits the complete live roster, but each row must declare edited_fields containing only present and/or camera. Empty edit intent is untouched: no Attendance creation, field update or provenance rewrite occurs, and a default false never becomes a manual absence. The transaction merges only explicitly edited fields into current records; camera-only edits cannot create an unknown Attendance. Explicit new presence/absence and actual corrections remain manual and protected, while unedited assignments, incidents, source/media links and existing work remain unchanged. Frontend presence/camera interactions alone establish edit intent; polling and analyst selection do not. Finalization still marks the occurrence checked after existing pending/duration guards. Missing edited_fields fails validation so cached older clients must reload. There is no schema migration or historical rewrite, and qualifying automatic matches remain free to create Attendance for untouched VIPs.
Private media plane
• Media bytes never pass through Redis or the Backoffice API
• Recorder, finalizer, Session Analysis browser capture, and the Delivery renderer exchange media directly with private S3; movement lab browser mode stays local; explicit cloud mode uploads a private clip
• Zoom Live finalization downloads only visual HLS/fMP4 intermediates, remuxes without re-encoding, and stores hasAudio=false; AddPipe and Studio audio flows remain independent
• AddPipe webhooks persist inbox metadata and enqueue a versioned storage request; the finalizer downloads only bounded allowlisted HTTPS sources
• The AddPipe copy is H.264 320x180 at 15 fps with yuv420p, AAC 128 kbit/s, and faststart; Delivery availability waits for confirmed private storage
• Session Analysis resolves AddPipe stable video ids through authenticated private playback and never falls back to the provider URL
• Participant-to-VIP confirmation persists every stable video id on Delivery attendance and enriches Integrations recording metadata
• A stored participant-video fact immediately attempts idempotent attendance and Session Analysis reconciliation; confirmation-time and queue-read reconciliation recover either event order
• Session Analysis requests reuse all attendance video ids whether the request is created before or after finalization; the singular id remains a compatibility primary source
• The existing authorized Integrations Session Analysis project catalog exposes nullable assigned_analyst_vit_id and source_type metadata. Delivery's linked request supplies the current responsible VIT and Live/On-demand source independently of request-list date filters; projects without a surviving request use unambiguous recording source metadata, otherwise retain an unknown source. Recording creators are not inferred as request assignees. All-VIT saved-recording cards display the responsible VIT, and each card identifies Live or OD without exposing provider payloads or media storage details.
• Delivery associates curated Session Analysis projects with one exact VIP request when their nonempty selected stable video ids are a subset of that request's sources; competing overlaps or outside sources require explicit review. Ordered source advisory locks, request/project row locks, current staff authorization and immutable link revisions preserve existing work. Existing request-created and assignment-created facts reconcile projects after commit when requests arrive later; only confirmed same-project private final media completes a linked request, using the existing completion and availability-ended facts. No media bytes, new context, public route or provider contract is introduced.
• Live Recording stores every Studio clip before a project version can queue one idempotent durable render job; Backoffice PostgreSQL alone owns progress, retry, cancellation, and recovery
• An opaque fingerprint of clip order, cuts, assets, duration, and microphone gain blocks duplicate completed renders until a saved clip changes
• Authorized staff download a completed MP4 from the Studio or project card through a short-lived attachment URL; private storage keys remain server-only
• Delivery publishes an authorized per-staff Socket.IO render snapshot only after persisting progress; reconnect reads PostgreSQL and disconnected clients fall back to HTTP polling
• The separately scaled Delivery FFmpeg worker has no database access; it consumes immutable render requests, applies order, cuts, and microphone gain, stores a private MP4, and returns result facts through Redis
• Source-video additions and ordered replacements cross the Integrations recording boundary, retain at least one source, and persist through Delivery optimistic locking
• The movement lab captures a staff-selected browser tab through explicit getDisplayMedia consent and MediaRecorder, then previews and detects movement locally under five-minute/100 MiB limits. Single-view 3D refinement runs MotionBERT-Lite through ONNX Runtime Web WASM and bounded sequence optimization in a cancellable browser worker. Versioned model shards are served as frontend static assets; captured, estimated and refined poses remain separate in browser memory. Browser-mode capture never enters the API, Redis or S3. Legacy staff-owned YouTube import routes and finalizer cleanup remain available but are not called by the lab UI.
• Zoom finalization requires closed HLS playlists and every referenced init/media segment, starts at segment zero, rechecks capture inventory, and compares final duration to the playlist timeline before publication or cleanup. Incomplete captures and duration mismatches remain pending for bounded retry with sanitized reason/duration logs; exhausted retries publish failure and retain intermediates.
• Attempt-scoped final-<id>.mp4 and thumbnail-<id>.jpg objects cannot overwrite another capture cycle or retry attempt. Guarded catalog reconciliation accepts only the current closed lifecycle, and lifecycle finalization retains all source epochs even when legacy cleanup is configured.
• 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.
• SessionAnalysisDraftClipCleanupService runs within the existing Backoffice Delivery process, with bounded batches of 25 per minute and a 16-minute grace period exceeding signed upload lifetime. Durable media tombstones survive restart; failed private S3 deletion remains pending. Runtime identity needs scoped s3:DeleteObject; exact project/asset capture namespaces are validated, no whole prefix is deleted, and no private storage key enters logs or audit. Browser cleanup removes only the deleting staff member's recovery clips and capture checkpoints for that project. Successful deleted tombstones remain eligible for bounded re-deletion after one hour; reserved scan capacity also serves pending work. This removes signed PUTs that began before expiry and finish after the first deletion, without discarding durable deletion intent.
• 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.
Trust boundaries
• Cognito authenticates; StaffUser granular permissions authorize operational routes and matching UI actions, while direct role checks remain only for identity-bound or ownership rules
• ActiveCampaign credentials remain backend-only while Marketing performs reviewed tag reads and replacements
• OAuth connections are stored per Zoom user, allowing multiple staff in one Zoom account; OBF prefers the owner before eligible present co-hosts
• AddPipe redirects, hosts, sizes, durations, and processing time are bounded before media enters the private platform store
• 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.
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
• Delivery appends bounded creationOrigin evidence to new successful analysis_project.created operations: analysis_request, meeting_videos or external_completion. The server derives this method from the invoked creation path; count distinguishes a newly created project from reuse, and history is never rewritten.
• The meeting-video DTO optionally accepts declared entry_point values session_recordings or session_analysis and persists the validated value as entryPoint only for the meeting_videos method. Page declarations never grant access or replace request/source ownership checks. Older clients retain a known method with an unknown page; legacy Audit facts without provenance remain readable and explicitly unidentified under the existing restricted-evidence grant.
Optional cloud motion capture
• Delivery owns MotionCaptureJob in PostgreSQL, staff ownership checks and upload/result signing. Authenticated /motion-captures requests require motion_capture.generate explicitly assigned to the staff user; wildcard access alone is insufficient.
• The private Modal CPU gateway accepts backend proxy credentials and dispatches one L4 GPU worker on demand. No provider credential reaches the browser; no model execution depends on a developer Mac.
• Browser uploads directly to private S3. The GPU reads bounded signed sources and writes a versioned MHR70 skeleton plus a bounded mesh ZIP (faces, per-frame vertices, camera and timestamps) directly to S3. MotionCaptureJob retains an optional meshKey for backward compatibility. Delivery verifies both required artifacts before completion and signs owner-only downloads; media never passes through the API.
• MediaPipe locates one person within the selected full/left/right view; SAM estimates 3D. The frontend maps MHR70 joints to the existing anatomical rig, preserving atlas bone lengths and GPU muscle skinning.
• Start uses an atomic job claim; ambiguous dispatch fails without automatic retry. Polling updates durable completion. Stopping browser checks does not cancel already submitted GPU work.
Transcript review and processing — ADR 0069
• TranscriptWorkspaceModule composes owner services over authenticated /transcripts routes. PostgreSQL transcripts schema stores releases, derived halfvec chunks and leased index jobs; originals/candidates remain in Sales or Clinical.
• A ten-second in-process worker claims durable jobs with SKIP LOCKED, renewed leases and generation fencing. Audited remote batches use approved recipient profiles; local text indexing requires no provider.
• Source changes and revocation remove platform-owned derivatives atomically. External analysis creates schema-validated cited drafts only. Legacy identified Sales analysis/embedding retains its separate expiring approval gate by default; the user-authorized November 4 temporary exception requires exact CONSULTATION_IDENTIFIED_PROCESSING_APPROVALS_ENFORCED=false and DEPLOYMENT_ENVIRONMENT=development. Unset/other values and every non-development deployment enforce the original registry; NODE_ENV cannot enable a bypass. Restore true or remove the flag and reload processes to reactivate enforcement. No approval records or reviewed releases are fabricated, production never bypasses the gate, and existing raw vectors remain excluded. Runtime activation and reactivation are separate operational actions.
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.
• Staff can save optional named Lesson chapter markers through the existing Track draft contract. Delivery freezes the markers in TrackVersion and validates their starts against the selected video clip. Quiz answers and Lesson completion use their existing contracts.
• VIP Home reads the launch product name from the published Service Funnel selected in Initial assessment entry. The authenticated availability read does not create participation. New clients start explicitly, and existing clients keep their pinned TrackVersion.
• The VIP journey overview reads the current activity and completed history from the owned TrackParticipation. Completed activity reads expose Lesson chapter markers from the pinned TrackVersion only after checking authorized history. Playback uses the existing authorized media route, and review never writes progress.
• 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.
• Track schema v2 adds bounded semantic lesson copy and optional supporting sections. Staff with program_setup.view and tracks.content.edit can use the revision-protected content-only HTTP mutation; managers retain structural and publication authority. Delivery merges only lesson copy into its draft, freezes effective editorial content and VIP catalog documentation in new immutable publications, and preserves v1 snapshots and participation pinning. The Lesson editor stores alignment and private library image IDs inside semantic content. Publication pins those library references for archive protection, and Delivery signs only the current authorized lesson’s images for portal rendering. Editing copy and fictional previews never grant portal access or create runtime progress. The Conclusion block freezes selected Badges library image references with the published Track. The authorized owner sees the conclusion and earned badges only after Track execution reaches completion, including on the dashboard badge projection. Optional feedback uses the existing revisioned execution command and stays in TrackProgress, visible to the authorized reviewer. A Dashboard step automatically uses the owner-scoped completion command before client navigation and preserves its continuation for resume. The authorized Track view projects progress.completed and progress.total from the pinned resolved path: common work plus only the selected route, excluding skipped optional work. Unresolved branches return a null total. The same resolved path exposes ordered upcomingActivities id/title/kind metadata for grey non-actionable timeline cards, without changing prerequisite enforcement or media access. When a future decision remains unresolved, upcomingActivities still exposes the known common prefix up to that decision or the next professional review, without disclosing outgoing branches or the common continuation after an unresolved branch. The top lesson trail displays this prefix independently of the nullable overall total; waiting decisions and reviews disclose no future steps. Until the client confirms the final Home guided-tour step, the VIP router checks the current UserProfile-owned initial assessment before admitting portal pages. Only confirmed go_to_dashboard history admits Home; direct URLs, participation-query shortcuts and browser history otherwise resume current execution. The menu, Home/list return shortcuts and Chat stay unavailable, with the logo at the left. The mandatory Home tour targets that logo and unlocks general navigation on final confirmation. Completion is a browser preference scoped by UserProfile and the existing home_tour_reset_token, separate from shown-only tour preferences; it creates no resource authorization, new backend contract or participation write. No staff configuration is required. The owner-scoped activityPosition projection numbers lessons and assessments separately on that resolved path; video quizzes and forms share the assessment sequence, while goal and dashboard handoffs are excluded. Unresolved paths return a null position.
• ADR 0099 records schema v3 frozen video chapters and portalSurface: assessment. Participation-scoped save commands persist required operational-only choices in TrackProgress with request-key/revision protection; chapter answers never prove watching, recording or professional review. Assessment playback reuses private library media and its bounded four-hour grant. Operational question snapshots and the authorized portal projection carry an optional one- or two-column answer layout for Forms and video chapters. Layout does not affect stored answers, decision evaluation or playback authorization. Real health answers remain Clinical-owned; DEV pain/symptom examples require fictional profiles and invented answers. Rollout targets only an explicitly selected cohort with default/off false.
• 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.
• 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. 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.
• The existing authorized current-activity projection optionally exposes lessonSummary and vipDocumentMarkdown from that activity’s pinned frozenEditorial entry. Delivery signs private library images referenced across all semantic sections of the current lesson through the existing organization-scoped image lookup and portal/staff signers. The projection never reads live ProgramAsset catalog copy or future/unassigned activity media, and it does not mutate progress, routes, publication snapshots or authorization rules. Legacy snapshots without frozen editorial retain their existing response.
• 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.
• 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.
• TrackActivity optionally carries showJourneyTrail, a boolean authored per activity and frozen in TrackVersion. The owned current-activity projection preserves this setting; omitted values retain visible paths for older snapshots. VIP Lesson, Quiz, Form, goal and operational screens hide the entire top path only when the current activity explicitly sets false. Welcome skips the path morph for that destination. This display preference does not remove the activity from history or resolved paths and never changes prerequisites, route disclosure, completion or ownership authorization. Structural Track edit and publication permissions remain required; content-only editors cannot change it.
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.
• Anatomy image/GIF records consolidate into SessionAnalysisLibraryAsset with original ids, private object keys, description/region/view metadata and all pending/archive states retained. Legacy anatomy HTTP routes are guarded image-only views over the same canonical catalog; the original anatomy table is a sealed backup with no runtime access. Existing Studio anatomyAssetId and referenceMaterialId values and historical composition snapshots are unchanged; shared archive checks protect those references. Staff with library upload access can change folder and subfolder through PATCH /assets-library/:id/location on an active, ready organization asset. PATCH /assets-library/:id/name edits the title and retains the original upload name for the reserved portal assessment lookups. Both operations preserve asset ids and stored objects. GET /assets-library/:id/playback gives a staff viewer a fresh private, non-cacheable playback grant for one ready asset in their organization.
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. Portal HTTP CORS permits only the configured VIP browser origin and exposes Retry-After. Both HTTPS origins share the tfdportal.com site. The VIP Pages build emits a script and framing policy, and the portal API serves no-store responses with framing denied. API-host-only HttpOnly, Secure, SameSite=Lax cookies identify server-held portal sessions. Active UserProfile authorization and rollout flags remain independent and mandatory.
• Identity uses atomic Redis budgets for authentication by IP, normalized account, active transaction or session family, and an optional short-lived browser cookie. Redis failures fail closed. Cognito transport errors, server errors and throttled refresh remain retriable. Aggregate authentication outcomes use the existing OpenTelemetry metrics pipeline and Grafana alert provisioning, with no request, identity or proof data in metric labels.
• Authorized staff can cancel a pending user invitation. The existing email lock serializes cancellation with acceptance; cancellation clears outstanding proof and appends a durable event. Staff Audit records the completed action. In-flight provisioning and consumed invitations require reconciliation. See docs/operations/vip-authentication-incidents.md for exercises and release gates.
• 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.
• The frontend diagram node groups independent Pages deployments; only staff uses the direct Hosted UI/PKCE edge and Live Analysis Capture. VIP authentication follows the API session boundary described here.
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.
Local movement-lab equipment review
• Development only: browser-selected video bytes pass through the existing Vite/Storybook server at /__local-equipment to a short-lived local Python DINO + MediaPipe subprocess. TFD_LOCAL_EQUIPMENT=1 is required; production build/preview has no inference route. No new deployed service or cross-context contract.
• Loopback peer and localhost Host checks, same-origin/custom-header checks, fixed executable/arguments, 100 MB upload cap, four-second sampled window, one job at a time and a two-minute subprocess deadline bound this local trust boundary. Temporary video/config/result files are removed after success, failure or disconnect; no cloud recipient or durable media store is involved.
• The viewer verifies media SHA-256 and sample timing, rejects stale results after video/view changes, and asks for confirmation. Confirmed equipment applies only within the reviewed interval; per-hand load and support still need review. Bands and shared bars remain unsupported by the current arm calculation.
• The development-only /__local-clean route accepts up to 1 MiB of captured pose JSON (7–81 samples, at most eight seconds) under the same loopback/origin gate. One two-minute native OpenSim 4.6 subprocess uses pinned Gait2392 plus bilateral Arm26 (104 muscles), inferred unilateral heel/toe friction contacts and a symmetric hand-load proxy. Private temporary files are deleted on completion or cancellation. No cloud transfer or production runtime is added.
• The clean research panel requires scale, timing and explicit reference-anatomy assumptions, rejects stale results and withholds muscle estimates when pose, force or moment residuals fail. Percentages describe nominal model force capacity, not measured individual activation. Catch, flight, shoulder-complex biomechanics and atlas color mapping remain unvalidated; anatomical colors are preserved.
• The same local boundary also serves /__local-clean/calibrate: a bounded pose-only reference alignment fits image scale/camera angle on one half-window and checks the other. No measured calibration is inferred. Optional stature and mass scale the native model under explicit assumptions; heel/toe observations constrain foot pose. Calibration changes invalidate prior effort results; individual muscle capacity remains unmeasured.
• Whole-clean review remains browser-orchestrated: sequential bounded pose windows share an inferred image-plane floor, split at occlusion/gaps and preserve missing-estimate intervals. Native IK uses stance evidence; external root balance precedes recruitment. Geometric hand/rack proposals never establish measured contact; unresolved bar-ground/turnover, rack mismatch and joint-limit failures withhold muscle values. No residual actuator is presented as effort, and the full clean remains unvalidated.
• The development-only /__local-sam/analyze route accepts a browser-selected video up to 100 MiB/five minutes under the same loopback/Host/origin/custom-header boundary. One job sequences local Apple MPS + CPU SAM inference and native OpenSim, with fixed pilot profile/crop, 15-minute per-stage deadlines, streamed progress, disconnect cancellation and private temporary-file cleanup. No production route or cloud transfer is added.
• SAM camera translation is preserved and added once before fixed camera/body-basis alignment and reference stature scaling. Metric XYZ targets feed sagittal symmetric native IK/contact/recruitment in bounded windows. Result media hashes bind the response to the selected video; source changes and cancellation invalidate late responses. Unmeasured visibility, contacts, timing and capacity remain explicit assumptions. Rejected intervals have no muscle values; full-body coloring and whole-clean accuracy remain unvalidated.
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. Portal decision logs use bounded reasons and redact private identifiers, proof, PHI, request bodies, private keys and signed URLs. Staff action evidence is maintained in the authorized audit store; 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.
• Complete successful Stripe imports reconcile existing standalone schedule observations by exact schedule and customer identity. Observed non-pending or subscription-bound schedules retain their actual provider status and link; absent still-pending schedules become missing_from_stripe_import without invented cancellation. Partial or failed fetches cannot retire absent schedules. Preserve all rows, provider term dates, plan evidence, staff renewal overrides and break adjustments; capture reconciled ids through the existing MembershipHistoryService before recording import completion. The shared Identity read projection excludes retired, non-pending or bound standalone schedules, including exact same-customer planScheduleId/raw.schedule replacement evidence, from queue selection, generic fallback, prior-membership and financing-completion evidence and Sales eligibility. Ordinary missing real subscriptions retain their existing policy; payment, credits, VIP status and access remain independent.
• Identity owns nullable VipProfile.operationalStatusOverride (active/inactive). Its dedicated audited staff command requires vip_management.manage and updates operational status without changing Stripe snapshots or renewal rules. Subscription upserts lock the exact customer profile before reading the override; both import deactivation paths atomically skip retained statuses and return only changed rows for existing activity facts. Null releases status to the next import. The override establishes neither credit balance/expiry, commercial coverage, payment nor portal access. Canceled contracts remain excluded even when the profile is retained Active.
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 exposes staff-gated /delivery/achievements catalog reads and optimistic writes under existing Program Setup permissions and rollout. Conclusion publishes an ordered, frozen catalog revision and protects its media. On workflow completion, Delivery records the selected badge and source participation once per UserProfile and achievement in the progress transaction. Identity supplies only completed years from the verified linked VIP, when available. Existing owner-authorized Conclusion and Dashboard projections display earned variants and legacy badges.
• 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. The Introduction node stores optional welcome copy; the authenticated assessment-entry GET also projects the published product name, welcome copy and overview titles along the common entry path. Personal goal updates invoke Identity in the completion transaction; the owner-only personal-goal projection supplies VIP Home.
• 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.
• Delivery publishes optional Quiz/Form postSubmission presentation metadata in the existing immutable activity snapshot and owner-authorized current-activity projection: bounded duration, heading/message, ordered hints and hint interval. Backoffice content editing and canvas summaries reuse this configuration. VIP submission runs concurrently with the Robbie presentation and reveals only the refreshed authorized next state after both successful completion and the minimum duration. This is presentation, never a timer-based access rule, additional workflow step, progress ledger, job or server delay. Errors preserve recoverable answers; completed-work resume does not replay the configured pause. Clinical evaluation and professional-review gates remain authoritative.
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.
Consultation import provenance
• Sales owns immutable organization/key-scoped ConsultationImportBatch records. Transcript revisions pin the batch, server import time and created-consultation versus attached-transcript action; historical versions remain filterable.
• Staff list/detail projections expose import history, searchable paginated batches and a separate outcomeConfirmationPending marker. Explicitly selecting an outcome, including Open, confirms it without retranscription or queue work.
• Legacy import metadata stays absent and existing outcomes stay unchanged. Cognito/active StaffUser and read/manage/reprocess grants retain their existing responsibilities; no provider or runtime service is added.
• 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.
• 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.
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