videogen/docs/reelforge/ARCHITECTURE_NEXT.md
caelum0x d56639a594
Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

25 KiB
Raw Permalink Blame History

ReelForge — Target Architecture (Next-Gen)

The forward architecture ReelForge builds toward, on two parallel tracks:

  1. Runtime scaling (§1–5, the track ROADMAP_V2.md sequences): Redis-backed shared state, priority Celery queues, a GPU warm-pool worker tier for LatentSync, an event/webhook bus, and a BI/cost pipeline off job_events.
  2. The 10-epic enterprise platform (§6, the track PRODUCT_BLUEPRINT.md sequences): Access/Governance, Identity/SSO, Billing, API-platform, Compliance, Observability, Notifications, Flags, Orchestration, and BI — each forked from a verified MIT/Apache foundation (RESEARCH_ENTERPRISE_OSS.md). Epics 1–2 are DONE and in the committed tree; Epic 3 (Billing) is in progress; 4–10 are target.

The product runs three client surfaces — web (Next.js 15), mobile (Expo), and desktop (native Rust/GPUI, §7) — on one FastAPI backend, and ships with a one-command runnable full stack (docker-compose.full.yml, §7). Committed reality as of head f1a2b3c4d5e6 (~24 migrations), suite 1986 passed / 4 skipped (python -m pytest tests/reelforge).

Companion to ARCHITECTURE.md (current topology). Where they differ, that doc is today, this doc is target.


1. Why the architecture must evolve

Today every process is stateless-except-for-two-in-memory-caveats, every provider call is a blocking poll inside a worker slot, and there is one flat render queue. That is fine for a single API replica and a handful of concurrent jobs. It breaks in four specific, predictable ways at scale:

  1. In-memory OAuth CSRF store → connect flow breaks behind >1 API replica.
  2. Blocking HeyGen/RunPod polls (8s/5s loops, 1800s timeout) → one in-flight render pins one render-queue slot for up to 30 minutes; throughput is gated by provider latency, not CPU/GPU.
  3. No priority tiers → a bulk batch starves a paid interactive job.
  4. QueuePool × N workers → Neon connection ceiling breached under chord fan-out.

The target architecture removes all four, and adds the two systems the margin/AI thesis needs: a GPU warm-pool tier (the $1→$0.20 lever) and a BI/cost pipeline that turns the already-recorded job_events.cost_usd into a margin decision surface.


2. Target topology (Mermaid)

flowchart TB
    subgraph Edge["Public edge (Cloudflare Tunnel — codified)"]
        LB[Load balancer / ingress]
    end

    subgraph API["API tier (N replicas, stateless)"]
        A1[FastAPI app.asgi<br/>/v1/jobs + Idempotency-Key<br/>/healthz /readyz<br/>/v1/callbacks/*<br/>/public/r/&#123;token&#125;]
    end

    subgraph Redis["Redis (shared state plane)"]
        RS[OAuth CSRF store<br/>fail-CLOSED SET NX EX]
        RL[Rate limiter<br/>fail-open]
        IDL[Idempotency short-lock]
        BR[Celery broker<br/>priority queues]
        RB[Result backend<br/>result_expires]
    end

    subgraph PG["Neon Postgres"]
        PGB[PgBouncer<br/>transaction pool → runtime]
        DIR[Direct DSN → Alembic]
    end

    subgraph Workers["Worker tiers"]
        WI[render_interactive<br/>NullPool, high prio]
        WB[render_bulk<br/>NullPool, low prio]
        WP[poll/reconcile queue<br/>low concurrency]
        WBEAT[beat: due-publish,<br/>token-refresh sweep,<br/>metrics ingest]
    end

    subgraph GPU["GPU warm-pool tier (RunPod Serverless)"]
        WPCTL[warmpool.py controller<br/>min-ready floor, autoscale by depth]
        LSW[LatentSync workers<br/>flashboot, executionTime capture]
    end

    subgraph Providers["External seams (config-selected live clients)"]
        HG[HeyGen Tier-A]
        EL[ElevenLabs]
        SOC[TikTok / IG / YT<br/>live OAuth + upload]
        BILL[Stripe / iyzico / Creem / Polar]
    end

    subgraph Data["Storage + BI"]
        R2[(Cloudflare R2<br/>+ replication/backup)]
        JE[(job_events<br/>cost_usd, duration_ms, meta.provider)]
        MARGIN[margin.py aggregate<br/>revenue vs COGS per tier/day]
    end

    subgraph Bus["Event / webhook bus"]
        DISP[webhook_dispatch.py<br/>job.completed / publish.* / performance.ingested]
        SUBS[(webhook_subscriptions<br/>+ deliveries)]
    end

    LB --> A1
    A1 --> RS & RL & IDL & BR
    A1 --> PGB
    PGB --> DIR
    BR --> WI & WB & WP
    WBEAT --> BR
    WI & WB --> HG & EL
    WI & WB --> WPCTL
    WPCTL --> LSW
    WI & WB --> PGB
    SOC -->|signed callback| A1
    LSW -->|signed callback| A1
    HG -->|signed callback| A1
    WP -->|reconcile overdue| HG & LSW & SOC
    WI & WB --> R2
    WI & WB --> JE
    JE --> MARGIN
    WI & WB --> DISP
    DISP --> SUBS
    A1 --> BILL --> RB

Key deltas vs today: the CSRF store and idempotency lock move into the shared Redis plane; the single render queue splits into render_interactive / render_bulk / poll; workers switch to NullPool and route through PgBouncer; provider completion arrives via signed callbacks with a reconcile poller as safety net; a GPU warm-pool tier fronts LatentSync; and job_events feeds a margin aggregate + an event bus fans domain events to webhook subscribers.


3. Module / file changes per subsystem

3.1 Shared state plane (Phase 8: A+CC, B)

  • New app/services/state_store.py — StateStore protocol (issue/consume) + RedisStateStore (SET key NX EX <ttl> on issue, atomic GETDEL/Lua on consume for single-use). Reuses the Redis client factory pattern from app/services/ratelimit.py.
  • Change app/services/oauth_connect.py — export make_state_store() returning RedisStateStore when Redis config resolves, else the existing in-memory SingleUseStateStore (tests only). Fail-CLOSED on Redis outage (unlike the fail-open rate limiter).
  • Change app/controllers/v1/connections.py:114 — build _STATE_STORE via the factory; issue() (line 347) and consume() (line 397) contracts unchanged.
  • New app/services/oauth_state_store.py companion + Celery-beat refresh_expiring_tokens in app/workers/ walking SocialAccount rows near token_expires_at.
  • New idempotency_keys table (Alembic) + IdempotencyRepository.get_or_create; wired into app/domains/reels/router.py::create_job before the debit→enqueue block, guarded by a Redis NX short-lock (reuse the state-store primitive). Returns 200 + replayed=true on match, 409 on fingerprint mismatch.
  • Config oauth_state_ttl_s (default 600) in config.app + .env.reelforge.example.

3.2 Async provider completion (Phase 9: C)

  • New app/controllers/v1/avatar_callbacks.py — POST /v1/callbacks/heygen, /v1/callbacks/runpod; verify signature/shared-secret via app/services/webhooks.py SSRF/verification helpers; look up job, re-enter the chord.
  • Change app/services/avatar/heygen.py + latentsync_runpod.py — split blocking wait()/poll into submit() (returns provider job id, persisted on JobContext) + a resume path; pass callback_url / RunPod webhook config.
  • Change app/workers/pipeline.py — stage_avatar resumes from callback instead of blocking; build_retry_chain chord fan-in intact.
  • New poll queue + reconcile beat task sweeping overdue provider jobs → clean-fail/refund path.

3.3 Priority queues + backpressure + DLQ (Phase 9: E)

  • Change app/workers/celery_app.py task_routes — render_interactive vs render_bulk (+ broker priority); single interactive jobs high, batch fan-out low. Broaden autoretry_for beyond ConnectionError to transient HTTP 5xx with capped backoff; final failure → DLQ → existing _refund_debit (jobs.py:639).
  • Change create_job — admission control: 429 + Retry-After above a Redis high-water mark, refunding any debit taken.

3.4 Neon pooling (Phase 8: D)

  • Change app/models/db/base.py create_engine (line 86) — poolclass=NullPool under Celery via REELFORGE_DB_POOL=null; keep QueuePool for the API. Disable pooled prepared statements.
  • Config pooled (PgBouncer, transaction mode) DSN for runtime vs direct DSN for Alembic (transaction pooling breaks some DDL/prepared-statement paths).
  • Docs connection budget replicas × pool + workers × worker_pool ≤ Neon ceiling in DEPLOYMENT.md + ARCHITECTURE.md; add a soak/load harness.

3.5 GPU warm-pool + cost-aware router (Phase 9: U)

  • New app/services/avatar/warmpool.py — reads RunPod health()/queue metrics, sets min/max workers from pending Tier-B depth in Redis.
  • New app/services/avatar/router.py — select_provider(params, cfg); default latentsync, escalate to heygen on quality_tier=='premium' or Tier-B unavailability; wired into stage_avatar (reelforge.py ~681–712) + jobs.py:531 behind the injectable client seam. On Tier-B hard failure, fall back to Tier-A exactly once (no double debit).
  • Change latentsync_runpod.py wait() — read body['executionTime'] (GPU-ms billed) into the return dict; add [runpod] warm-pool keys (min_workers, idle_timeout, flashboot).
  • New estimate_avatar_cost_from_runpod(execution_ms, usd_per_gpu_hour) in app/telemetry/cost.py; record_cost(meta={'provider':'latentsync','gpu_ms':...}).
  • New docker-compose.gpu.yml / Dockerfile.gpu with warm-pool floor as config.

3.6 Cost guardrails + credit economics (Phase 8: X, Phase 10: Z)

  • New app/services/billing/guardrails.py — estimate_job_cost + enforce_budget → allow|downgrade|reject; called in create_job before debit/enqueue; mid-pipeline hard cap in the avatar stage aborts to clean failed via the refund path. [billing] max_job_cost_usd, downgrade_threshold_usd in config.
  • New app/services/billing/credit_cost.py — credits_for(params, measured_or_estimated); the debit call site uses it instead of a flat 1, preserving debit-on-success + refund-on-failure exactly.
  • New app/services/billing/reconcile.py — periodic estimated-vs-billed diff → variance JobEvent.

3.7 BI / cost pipeline (Phase 9: Y)

  • New app/services/margin.py — gross_margin(session, cutoff) joining CreditLedger positive deltas (→ plan price) against SUM(job_events.cost_usd), per meta.provider tier and per day, reusing _percentile/_bucket_by_day/_window_start from analytics.py.
  • New app/controllers/v1/admin_margin.py — GET /v1/admin/margin behind an admin guard (cross-tenant boundary, unlike per-user analytics.py).

3.8 Event / webhook bus (Phase 11: EE) + live distribution (Phase 9: AA / 10: BB)

  • New WebhookSubscription + WebhookDelivery models; app/controllers/v1/webhooks.py CRUD; app/services/webhook_dispatch.py mapping domain events → subscriptions → existing deliver_webhook (HMAC + SSRF-hardened, already built).
  • New app/services/oauth_clients/live.py (LiveOAuthClient) + app/services/publishers/{instagram,youtube}.py
    • app/services/publishers/clients/* live uploaders; SocialPost model storing external_post_id/permalink.
  • New app/services/platform_metrics/* per-provider fetchers + source column on JobPerformance
    • Celery-beat ingest_platform_metrics.
  • New public share: app/services/share.py, app/controllers/v1/share.py (GET /public/r/{token}), watermarked preview variant via existing compose_ffmpeg watermark builders, Next.js web/app/r/[token]/page.tsx.
  • New health: app/controllers/v1/health.py (/healthz, /readyz checking Redis+DB+R2); OTEL app/telemetry/tracing.py init alongside Sentry in asgi.py + celery_app.py.

4. In-memory / mock seam → production replacement

Current seam Where Today Production replacement Phase
OAuth CSRF SingleUseStateStore connections.py:114, oauth_connect.py:181 in-process set(), no TTL Redis SET NX EX single-use, fail-CLOSED (state_store.py) 8 (A+CC)
Job creation dedupe jobs.py::create_job none (double-debit risk) idempotency_keys table + Redis NX short-lock 8 (B)
Rate limiter ratelimit.py already Redis-backed, fail-open unchanged (keep fail-open) —
Per-key monthly quota apikey_quota.py already DB-backed (ApiKeyUsageRepository) unchanged; feeds metered billing (W) —
Avatar completion heygen.py, latentsync_runpod.py blocking 8s/5s poll, 1800s timeout, pins a slot submit() + signed callback + reconcile poller 9 (C)
Celery queue celery_app.py one flat render queue, no priority/DLQ render_interactive/render_bulk/poll + DLQ + backpressure 9 (E)
DB pool models/db/base.py QueuePool × N workers → Neon ceiling PgBouncer runtime + NullPool workers + direct-DSN Alembic 8 (D)
Avatar provider choice reelforge.py:129, jobs.py:531 hardcoded heygen router.py cost/SLA policy + warm-pool 9 (U)
RunPod cost cost.py static per-minute constant measured executionTime GPU-ms → record_cost 9 (U)
OAuth token exchange/refresh oauth_connect._DEFAULT_CLIENT raises OAuthConfigError (fail-closed) LiveOAuthClient (TikTok v2 / Graph / Google) 9 (AA)
Publishers publishers/tiktok.py (stub only) one one-line stub, no IG/YT live VideoUploadClient per provider + SocialPost.external_post_id 9 (AA)
Hook performance data hook_performance.py, JobPerformance 100% creator-entered (self-report) platform_metrics/* ingest, source='platform' overrides manual 10 (BB)
Billing billing/{stripe,iyzico,creem,polar}_client.py SDK/HTTP guarded, none live live recurring/metered SKUs (Stripe clean, others partial) 10 (V/W)
Observability Sentry wired, NO-OP w/o DSN; no tracing; no probes error capture only OTEL traces + /healthz//readyz + make bench p95 8/9 (G)
Quality checks tests/golden/acceptance.py (test-only) thresholds run in synthetic suite only shared app/services/quality/checks.py imported by tests + runtime 9 (L)

5. Margin math — the path to ≤$0.30 / 60s

The whole unit-economics thesis is the avatar stage. Everything else (LLM script, TTS, encode, R2) is already cents. Illustrative per-60s-video figures (replace with measured executionTime once U is live):

Lever Tier-A (HeyGen, today) Tier-B (LatentSync warm-pool, target)
Avatar render $0.75/min → **$0.75** GPU-seconds billed: ~40–80 GPU-s at $0.0004–0.0006/GPU-s → **$0.02–0.05**
Cold-start tax n/a (managed) eliminated by warm-pool min_workers > 0 (else +tens of s, +$)
TTS (ElevenLabs, ~150 words) ~$0.05 ~$0.05
LLM script (Claude) ~$0.01–0.03 ~$0.01–0.03
Encode (FFmpeg, own CPU) ~$0.01 ~$0.01
R2 storage/egress (7-day) ~$0.01 ~$0.01
COGS / 60s ~$0.83–0.85 ~$0.10–0.16 → guardrail ceiling $0.30

The four levers, in build order:

  1. Route to Tier-B by default (U, router.py). Default latentsync, escalate to HeyGen only on a premium flag or Tier-B failure. This is the single biggest step — it swaps a ~$0.75 line for a ~$0.03 line.
  2. Warm-pool floor (U, warmpool.py). min_workers > 0 removes the cold-start tax that would otherwise blow both p95 (DoD §2) and the per-job GPU bill; tune floor vs idle-GPU cost against utilization.
  3. Measured cost, not constants (U, cost.py). Capture RunPod executionTime GPU-ms so COGS is a number in job_events, and the Y dashboard/Z reconciliation catch drift before the invoice.
  4. Guardrails + differential credit (X, Z). enforce_budget caps any single render at max_job_cost_usd (auto-downgrade or reject), and credits_for charges premium/long renders more so retail price tracks COGS instead of the flat "1 credit = 1 video."

Constraints that keep this honest: LatentSync quality/drift is only mock-verified today — a blind default-to-B could ship worse videos, so U ships paired with a golden-set A/B against the ±0.15s avatar/audio gate before flipping the default. Warm-pool idle GPU erodes margin at low utilization, so the floor is config-driven and depth-scaled. And the Tier-A fallback must escalate only on hard failure or a double-render pays both providers.

Target end state: default renders land ~$0.10–0.16/60s COGS with a hard $0.30 guardrail ceiling, against a ~$1.99 retail credit — a healthy gross margin with premium (HeyGen) as a monetizable upsell, all measured live via executionTime → job_events → margin.py, not assumed.


6. The enterprise platform layer (10-epic program)

Runs in parallel with the runtime-scaling track above and shares its substrates (the Redis plane, the append-only event/audit sink, the Celery ops queues). Each epic is forked from a verified MIT/Apache/BSD OSS foundation and wrapped behind a FastAPI adapter + Protocol seam — never a copyleft datastore duplicated into Neon. The full file plan is PRODUCT_BLUEPRINT.md; the epic → foundation licensing rationale is RESEARCH_ENTERPRISE_OSS.md.

Substrate-first order (per RESEARCH §5): flags (8) → telemetry (6) → admin console (refine) mount before the value epics, so every later surface is flag-gated and instrumented for free.

# Epic OSS foundation (license) Status
1 Access & Governance (RBAC + audit + admin console) pycasbin (Apache-2.0) + refine (MIT) ✅ DONE
2 Identity / SSO / SCIM / MFA python3-saml (MIT) + SCIM 2.0 ✅ DONE
3 Billing platform OpenMeter (Apache-2.0) + Kill Bill (Apache-2.0) 🔵 in progress
4 API platform + SDKs + webhooks Svix (MIT) + Scalar (MIT) + Fern / openapi-generator (Apache-2.0) ⚪ target
5 Compliance (GDPR / retention) Neon append-only + Cerbos/OpenFGA decision logs (Apache-2.0) ⚪ target
6 Observability OpenTelemetry (Apache-2.0) → VictoriaMetrics / SigNoz ⚪ target
7 Notifications (multi-channel) Novu (MIT) + apprise (BSD-2) fallback ⚪ target
8 Feature flags / experiments OpenFeature (Apache-2.0) + Flagsmith (BSD-3) / flagd ⚪ target
9 Workflow orchestration Temporal (MIT) / Hatchet (MIT) ⚪ target
10 BI / analytics pipeline Cube (Apache-2.0) + PostHog (MIT) ⚪ target

6.1 Epic 1 — Access & Governance ✅ (committed)

A pycasbin (casbin==1.43.0, Apache-2.0) in-process RBAC decision engine + tenant-isolation gate enforces workspace roles (owner/admin/editor/viewer); an append-only audit_log table is the immutable sink; User.is_staff marks the platform admin who reaches the cross-tenant surfaces. Code: app/services/{rbac,audit,admin}.py + app/controllers/v1/{rbac,audit,admin}.py. Endpoints (verified): GET /me/permissions, GET/PUT /me/workspaces/{id}/members[/{user_id}/role], GET /me/workspaces/{id}/audit, and the staff surfaces GET /admin/users|workspaces|jobs + POST /admin/impersonate. Tables landed in e5f2a9c74b13 (users.is_staff, audit_log). The UI is a refine admin console (@refinedev/core + @refinedev/nextjs-router, MIT) under web/app/admin. The ReBAC graduation seam (Cerbos/OpenFGA decision logs feeding Epic 5) stays behind the same enforcement interface and is target, not built.

6.2 Epic 2 — Identity / SSO / SCIM ✅ (committed)

SAML 2.0 SSO (via python3-saml, MIT — optional dep, imports as onelogin.saml2, behind a validator seam so the suite stays green without it), a SCIM 2.0 directory-sync surface, and a per-workspace security policy engine. Code: app/services/{sso,scim,security_policy}.py + app/controllers/v1/{sso,scim}.py. Endpoints (verified): GET /sso/{ws}/login|metadata, POST /sso/{ws}/acs, tenant config .../me/workspaces/{ws}/sso; SCIM GET/POST/PUT/PATCH/DELETE /scim/v2/{ws}/Users|Groups guarded by hashed tokens managed at .../me/workspaces/{ws}/scim/tokens[/{token_id}]. Tables landed in f1a2b3c4d5e6 (current head): sso_connections, scim_tokens, security_policies, external_identities. scim2-filter-parser (MIT) is an optional filter-parsing dep. This is the enterprise entry gate; a live IdP (Okta/Entra/ Google) is the account-gate for full round-trip verification.

6.3 Epics 3–10 — target, each on its verified foundation

  • Epic 3 · Billing (in progress). OpenMeter (Apache-2.0) real-time metering + credit burn-down, paired with Kill Bill (Apache-2.0) for full invoicing/dunning, behind a FastAPI adapter emitting CloudEvents from the render workers. Lands services/metering/* + services/billing/{entitlements, invoices,dunning,killbill_client}.py + controllers/v1/{metering,entitlements,invoices}.py. This is where the credit-cost / margin guardrails of §3.6/§5 graduate from single-render controls into a metered SKU — the runtime-scaling and enterprise tracks converge here. (Describe as in-progress; internals are being written by a concurrent workflow — no invented tables here.)
  • Epic 4 · API platform. Svix (MIT) outbound-webhook engine (HMAC/retries/replay, reusing our Postgres+Redis) — the production home for the §3.8 webhook bus — plus Scalar (MIT) replacing Swagger UI on FastAPI and Fern / openapi-generator (Apache-2.0) SDKs generated in the local gate.
  • Epic 5 · Compliance. Neon append-only audit (already the Epic 1 sink) + Cerbos/OpenFGA (Apache-2.0) PDP decision logs; GDPR export/retention/consent services. No live credential needed — verifiable against Neon + mocks.
  • Epic 6 · Observability. OpenTelemetry (Apache-2.0) auto-instrumenting FastAPI + Celery via instrument_app()/instrument_worker(), exported through a Collector in the base stack to VictoriaMetrics / SigNoz (MIT-way around AGPL Grafana). Delivers the /healthz·/readyz·p95 goals noted in §3.8/§4.
  • Epic 7 · Notifications. Novu (MIT core) multi-channel + inbox, with apprise (BSD-2) as the no-service embeddable fallback; maps Clerk orgs → subscribers.
  • Epic 8 · Feature flags. OpenFeature (Apache-2.0) abstraction in both apps, backed by Flagsmith (BSD-3) or flagd (Apache-2.0, flags-as-code) — the kill-switch/rollout layer every later epic rides.
  • Epic 9 · Orchestration. Temporal (MIT) / Hatchet (MIT) Postgres-backed durable DAGs; the render pipeline ports off Celery gradually behind the FastAPI adapter boundary (a natural successor to the §3.2 async-completion + §3.3 priority-queue work).
  • Epic 10 · BI. Cube (Apache-2.0) headless semantic layer with a multi-tenant security context for embedded per-customer dashboards, plus PostHog (MIT core) product analytics — the productized successor to the §3.7 margin.py aggregate.

License discipline (non-negotiable): only MIT / Apache-2.0 / permissive-BSD are forked into source; AGPL/GPL/BSL/SSPL/Elastic/Fair-Core/MPL and any ee/ dir are self-host-behind-a-clean-API-boundary or reference-only. Every pick above was license-verified — see RESEARCH_ENTERPRISE_OSS.md §4.


7. Client surfaces + runnable full stack

Three clients, one backend. All heavy lifting (script → tts → {avatar ∥ captions} → compose → upload) stays server-side; each client is a thin surface over the same /v1 API.

  • apps/web/ — Next.js 15 App Router: the primary end-user studio and the refine admin console (apps/web/app/admin).
  • apps/mobile/ — Expo Router: the high-value self-serve subset (create/jobs/analytics/connections); heavy authoring/ops stay web-only.
  • apps/desktop/ — native Rust + GPUI. It selects native recordings, presigns and uploads them to R2, submits /jobs and canonical B-roll requests, polls on a background worker, and previews results without reimplementing the pipeline. API credentials live only in macOS Keychain, Windows Credential Manager, or Linux Secret Service. The former Electron source is migration reference under apps/desktop/electron-legacy and is not an active runtime or workspace member.

Also shipped since these docs were first written and part of the committed baseline this target builds on: the editing polish stage (app/services/editing/{silence_cut,auto_zoom,motion,matting}.py — opt-in Job.params pre-compose passes wired through reelforge.py) and publishing calendar (app/services/calendar.py + controllers/v1/calendar.py over ScheduledPublish, GET/POST/… /me/calendar[/{schedule_id}]).

Run harness. docker-compose.full.yml brings up the whole stack in one command (postgres + redis + migrate + api + worker + beat + web), orchestrated via Makefile.dev. ops/smoke.py is an in-process ASGI smoke test — boots the real app.asgi:app behind a Starlette TestClient over in-memory SQLite (no live Postgres/Redis/R2) to prove routing, the response envelope, and the auth gate wire up end-to-end (currently PASS).


Target architecture as of 2026-08-13, written against committed head f1a2b3c4d5e6 (~24 migrations, suite 1986 passed / 4 skipped). §1–5 (runtime scaling) sequence in ROADMAP_V2.md; §6 (enterprise, Epics 1–2 DONE / 3 in progress / 4–10 target) sequences in PRODUCT_BLUEPRINT.md on the foundations in RESEARCH_ENTERPRISE_OSS.md. Nothing beyond the seams marked committed is built.