caelum0x d56639a594
Some checks failed
build-images / web (push) Has been cancelled
vision2026-ci / Python SDK resource tests (push) Has been cancelled
build-images / api (push) Has been cancelled
build-images / worker-gpu (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Has been cancelled
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Has been cancelled
codeql / Analyze (javascript-typescript) (push) Has been cancelled
codeql / Analyze (python) (push) Has been cancelled
perf / API hot-path micro-smoke (budgeted) (push) Has been cancelled
perf / Desktop engine crates (release build check) (push) Has been cancelled
vision2026-ci / API phase modules (ruff + pytest) (push) Has been cancelled
vision2026-ci / Alembic upgrade + drift check (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Has been cancelled
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

913 lines
56 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# ReelForge Vision 2026 — `apps/api` Architecture (Additive)
> **Scope.** This document specifies the **new** FastAPI + Celery + SQLAlchemy work required to
> expand ReelForge from "wallet + catalog + routing + compose + B-roll" into a full
> **creation × clipfarm × publishing × growth** engine. It is strictly **additive**: it assumes
> everything in `CODEBASE_INVENTORY.md` already ships (microdollar wallet, catalog/price_versions,
> OpenRouter-style routing, Fernet BYOK, spend controls, compose FFmpeg pipeline, camera/VFX presets,
> URL→reel ingest, repurpose long→clips, MCP server, EDL editor, publishing/insights **stubs**,
> SDKs). We design what is missing and how it seams into the existing skeleton.
---
## 1. Overview & Design Rules
### 1.1 Where new work lives
New product surface is added as **cohesive domains** under `app/domains/<name>/` — matching the
existing convention: each domain owns `router.py` (thin HTTP), `service.py` (business logic),
`schemas.py` (Pydantic request/response + view builders), `repository.py` (SQLAlchemy data access),
`policy.py` (pure decision functions), and optional `providers/` (external adapters). Cross-domain,
worker-internal engines that are not HTTP-owned live under `app/services/<area>/`. Provider adapters
that participate in the routing engine live under `app/domains/routing/providers/`. New ORM tables
are grouped into new `app/models/db/*.py` modules (never bloating `models.py`). New Celery stages are
added to `app/workers/` as focused task modules registered on the existing `celery_app`.
### 1.2 Invariants preserved (seams into existing systems)
| Existing system | New code MUST | File(s) it touches |
|---|---|---|
| **Microdollar wallet** (`domains/wallet/service.py`) | reserve→settle→release/refund around every provider call; never grant except from a confirmed webhook | `wallet.service` (called, not modified) |
| **Routing engine** (`domains/routing/service.py`) | resolve a route per shot/output; record `UsageRecord`; respect `provider_order/:nitro/:floor/cost-cap` | `routing.service`, `routing.providers.registry` |
| **Catalog + price_versions** (`domains/catalog`) | read `markup_policy`, license class, deprecation metadata; never hardcode price | `catalog.repository`, `catalog.policy` |
| **Spend controls** (`domains/spend`) | check budget cap + BYOK consent at reserve | `spend.policy` |
| **Compose pipeline** (`services/compose`) | emit new render specs (tracks/overlays/loops) the FFmpeg composer consumes | `services/compose/compose_ffmpeg.py` |
| **Job pipeline** (`workers/pipeline.py`, `tasks.py`) | run as append-only `JobEvent` + weighted-progress stages | `telemetry/events`, `telemetry/progress` |
| **Auth** (`core/auth/principal.py`) | resolve principal + workspace scoping on every route | `core.auth.resolve_principal` |
### 1.3 Conventions (match existing)
- All PKs are 32-char uuid hex (`_uuid()`); all timestamps `TIMESTAMP(timezone=True)` server-default `now()`.
- Money is **integer microdollars** end-to-end (`core/money.py`); never floats for money.
- Ledgers/audit tables are **append-only**; materialize running balances for O(1) reads.
- Business failures raise a domain `*Error(status_code, message)` mapped by the thin router to the shared envelope.
- External calls and LLM/transcription rankers are **injectable seams** (Callable/Protocol) so services are testable without network.
- Files 200–400 lines; one responsibility each; import-safe guarded DB blocks so modules `py_compile` before the DB layer exists.
### 1.4 New top-level packages
```
app/
domains/
templates/ # genre shot-template engine (crown jewel)
storyboard/ # screenplay -> shot-list -> first-frame -> animatic
film/ # multi-agent AI-movie orchestration + Narrative Context Protocol
characters/ # Character/Style lock (Soul-ID-like) entities + LoRA training
series/ # clipfarm: episodic series, batch runs, cadence
publishing/ # (expand stub) OAuth connectors + scheduler + retention + A/B
trends/ # trend + sound ingestion and scoring
gateway/ # provisioning keys, markup, tiered plans, reseller, Lago bridge
clipmarket/ # pay-per-view clipping marketplace + affiliate
presets/ # template/preset marketplace (shot templates + ComfyUI graphs)
growth/ # onboarding, micro-tools, A/B hook orchestration, funnels
assets/ # asset library + gameplay B-roll library
moderation/ # safety, watermark-detection, license gating, consent audit
services/
render/ # ComfyUI / render-farm orchestration + unified async GPU envelope
captions/ # (expand) WhisperX two-stage microservice client
audio/ # TTS breadth (Chatterbox/Kokoro/InfiniteTalk), music, MMAudio, ducking
loops/ # seamless-loop + beat-detection + hook-strength predictor
publish/ # (expand) per-platform post builders + watermark-safe re-encode
lago/ # Lago metering/invoicing bridge client
models/db/
templates.py storyboard.py film.py characters.py series.py
publishing.py trends.py gateway.py clipmarket.py presets.py
growth.py assets.py moderation.py render.py events.py
workers/
tasks_film.py tasks_render.py tasks_publish.py tasks_trends.py
tasks_series.py tasks_captions.py tasks_clipmarket.py dag.py
mcp/
tools_publish.py tools_film.py tools_trends.py tools_gateway.py
routing/providers (under domains/routing/providers/)
sora2.py kling.py veo.py runway.py luma.py wan_local.py seedance.py
hunyuan.py cogvideox.py ltx.py suno.py aiva.py musetalk.py latentsync.py
infinitetalk.py flux.py midjourney.py
events/ # internal event bus (outbox + dispatch)
```
---
## 2. Domain: `templates/` — Genre Shot-Template Engine (Phase 1, crown jewel)
Templates are **first-class DB objects**, not one-off tools: a genre template is a versioned graph of
named **segment slots** (Hook / Proof / Payoff / Loop) each mapping to compose tracks with default
durations, transitions, audio layers, and caption presets. The **compiler** binds a template + user
inputs into a concrete compose render-spec that `services/compose` executes.
### `app/domains/templates/`
| Path | Responsibility |
|---|---|
| `__init__.py` | Router export + guarded DB import. |
| `router.py` | `POST /templates` create · `GET /templates` list · `GET /templates/{id}` · `POST /templates/{id}/compile` compile→render-spec · `POST /templates/{id}/instantiate` create a draft reel from a template. |
| `service.py` | Orchestrates compile: load template version, validate slot inputs, resolve caption/audio presets, produce a `RenderSpec`, reserve wallet, dispatch render job. |
| `compiler.py` | Pure template→`RenderSpec` compiler: expand segment slots into timed compose tracks/overlays/transitions. |
| `slots.py` | Segment-slot model (`SlotSpec`: role, t_start/t_end, track bindings, audio layers, caption preset, transition-in/out). |
| `render_spec.py` | `RenderSpec` dataclass the composer consumes (tracks, overlays, captions, audio bus, loop flags, aspect). |
| `validation.py` | Pure input validation per slot (required media, durations sum, aspect, safe-zone). |
| `repository.py` | CRUD for `ShotTemplate`, `ShotTemplateVersion`, `TemplateSlot`, `TemplateInstance`. |
| `schemas.py` | Pydantic DTOs + view builders (`template_view`, `slot_view`, `instance_view`). |
| `policy.py` | Pure defaults: per-genre default durations, tension-bump cadence, CTA placement, min-hook-clearance. |
| `versioning.py` | Immutable version pinning (a compiled instance records the exact template version + preset hashes). |
| `presets/__init__.py` | Registry loader for seeded genre presets. |
| `presets/minecraft_reddit_split.py` | Seed: top~55% narrated Reddit story + bottom~45% parkour, cold-open-first, 5s tension bumps, Part-2 loop CTA. |
| `presets/asmr_loop.py` | Seed: single ~5s seamless loop, trigger-in mid-action, no voice/music, invisible-cut seam. |
| `presets/brainrot_meme.py` | Seed: recurring AI character, 0–1.5s pattern-interrupt, escalating nonsense to signature sound. |
| `presets/anime_beat_edit.py` | Seed: beat-synced montage, hardest frame first, story-beat trims, -2/-3 frame nudge. |
| `presets/movie_recap.py` | Seed: specific-angle narrated recap, hook-in-first-20-30s, Hormozi captions. |
| `presets/fake_podcast.py` | Seed: 2-host mid-convo hook, speaker-cut turns, Mode A lip-sync / Mode B split-screen. |
| `presets/gameplay_story.py` | Seed: any gameplay + narration split-screen, narration-above-mix. |
| `presets/platform_hook_open.py` | Seed: composable 0–5s opener prefix (pattern-interrupt + promise + loop-back). |
| `presets/power_washing_podcast.py` | Seed: cheap fake-podcast variant (B-roll top + captions bottom). |
| `presets/glass_cutting_asmr.py` | Seed: single-trigger ASMR variant, surreal-scale, external-mic audio. |
| `presets/gta_narration.py` | Seed: GTA split-screen narration variant. |
| `presets/trend_audio_remix.py` | Seed: trending-sound-first template (edit muted → relink native sound on upload). |
| `presets/retention_ab_hook_pack.py` | Seed: 1-body/N-hooks A/B experiment template. |
| `seed.py` | Idempotent seeder writing preset registry into `ShotTemplate`/`TemplateSlot` rows (mirrors `catalog/seed_data.py`). |
### `app/models/db/templates.py`
| Table | Responsibility |
|---|---|
| `ShotTemplate` | A named genre template (slug, genre, aspect, description, owner=null for system). |
| `ShotTemplateVersion` | Immutable version (semver, slot graph JSON, default audio/caption preset refs, changelog). |
| `TemplateSlot` | A named segment slot row (role, order, default duration range, track/audio/caption bindings). |
| `TemplateInstance` | A compiled instantiation (template_version_id, user inputs, produced reel/job id, preset hash). |
---
## 3. Domain: `captions/` + `services/captions` + `services/loops` — Caption / Loop / Beat / Hook (Phase 1)
Extends the existing `services/captions` (ass_karaoke, presets, words) with a **WhisperX two-stage**
microservice client and the **Hormozi** style engine, plus new loop/beat/hook analyzers.
### `app/services/captions/` (additions)
| Path | Responsibility |
|---|---|
| `whisperx_client.py` | HTTP client to the WhisperX microservice: `transcribe→align`, returns word-level JSON (±50ms). |
| `whisperx_schema.py` | Typed word/segment/alignment DTOs decoupled from ASS styling. |
| `hormozi.py` | Hormozi preset builder: Montserrat Black ALL CAPS, white base + `#FFD93D` highlight on key noun/verb, outline+shadow, 1–2 words. |
| `keyword_highlight.py` | Pure key-noun/verb detector selecting which word gets the highlight color per segment. |
| `safezone.py` | Per-platform safe-zone sizing (12–20% TikTok / ~9% Shorts, Y=62–65%). |
| `keyword_seo.py` | Caption + on-screen-text + transcript keyword-SEO generator (how users search per platform). |
### `app/services/loops/` (new)
| Path | Responsibility |
|---|---|
| `__init__.py` | Package exports. |
| `loop_finder.py` | Frame-perfect seamless-loop point detector (last-frame≈first-frame, SSIM/optical-flow discontinuity score). |
| `loop_exporter.py` | Produce a validated seamless-loop MP4 for ~5s ASMR; reject if visible discontinuity. |
| `beat_detect.py` | Audio beat detection (onset/tempo) returning beat timestamps. |
| `beat_cut.py` | Snap shot boundaries to beats with configurable -2/-3 frame nudge; "preview 3 template fits". |
| `hook_predictor.py` | Hook-strength predictor scoring first-3s (motion/contrast/text/audio-onset heuristics + optional model) vs 70% threshold. |
| `hook_suggestions.py` | Cold-open rewrite suggestions when hook score is below threshold. |
| `retention_presets.py` | Retention-optimized export preset builder (loop-back last=first frame + keyword burned-in text baked in). |
### `app/domains/captions/` (thin HTTP facade)
| Path | Responsibility |
|---|---|
| `router.py` | `POST /captions/transcribe` · `POST /captions/style` (apply Hormozi/preset) · `POST /captions/hook-score` · `POST /captions/loop-check`. |
| `service.py` | Wires the caption/loop/hook services behind auth + wallet metering (WhisperX GPU seconds). |
| `schemas.py` | Request/response DTOs. |
### `app/models/db/render.py` (shared render/analysis tables — see §11)
| Table | Responsibility |
|---|---|
| `CaptionJob` | A transcription/alignment job (source asset, language, word-json artifact ref). |
| `HookScore` | Persisted hook-strength score per reel/variant (first-3s subscores + verdict). |
---
## 4. Domain: `characters/` — Character/Style Lock (Soul-ID-like, Phase 4 moat)
Reusable **Character** and **Style** entities (reference images + optional Wan 2.2 LoRA + cross-model
identity) auto-injected into every shot's first-frame prompt, reused across projects/episodes.
### `app/domains/characters/`
| Path | Responsibility |
|---|---|
| `router.py` | `POST /characters` · `GET /characters` · `POST /characters/{id}/references` add ref images · `POST /characters/{id}/lora` start LoRA training · `POST /characters/{id}/sheet` generate character sheet · `POST /styles` style-lock CRUD. |
| `service.py` | Character/Style lifecycle; enrolls references, orchestrates sheet + LoRA jobs, exposes identity-injection payload for storyboard. |
| `lora_trainer.py` | LoRA-train orchestration (dispatch to `services/render` Wan 2.2 LoRA workflow on 50+ images). |
| `identity.py` | Pure identity-injection builder: merges ref images + LoRA token + cross-model descriptor into a prompt/asset bundle. |
| `feature_extract.py` | Static+dynamic visual feature extraction (portrait crops, palette, wardrobe) for the character sheet. |
| `sheet.py` | Character-sheet generator (Omni-Reference/Wan-LoRA style multi-pose sheet). |
| `repository.py` | CRUD for `CharacterEntity`, `CharacterReference`, `StyleEntity`, `LoraArtifact`, `IdentityBinding`. |
| `schemas.py` | DTOs + view builders. |
| `policy.py` | Min references, license gating (paying users blocked from non-commercial weights), consent requirement for likeness. |
| `consistency.py` | Cross-shot consistency scorer (identity-embedding cosine drift alarm). |
### `app/models/db/characters.py`
| Table | Responsibility |
|---|---|
| `CharacterEntity` | A reusable character (name, descriptor, owner/workspace, license class). |
| `CharacterReference` | A reference image/asset bound to a character. |
| `StyleEntity` | A reusable style lock (palette, look, ref set). |
| `LoraArtifact` | A trained LoRA (weights ref, base model, trigger token, training job id, license). |
| `IdentityBinding` | Cross-model identity descriptor (Soul-ID-style) per character. |
---
## 5. Domain: `storyboard/` — Screenplay → Shot-List → First-Frame → Animatic (Phase 4)
Reads the **whole script as context before spending credits**, produces a shot-list, per-shot
first-frame stills, and a cheap animatic for pacing review, with per-shot "regenerate only this shot".
### `app/domains/storyboard/`
| Path | Responsibility |
|---|---|
| `router.py` | `POST /storyboard/ingest` screenplay→beats · `POST /storyboard/{id}/shotlist` · `POST /storyboard/{id}/first-frames` · `POST /storyboard/{id}/animatic` · `POST /storyboard/shots/{shot_id}/regenerate` · `POST /storyboard/shots/{shot_id}/motion`. |
| `service.py` | Orchestrates the storyboard pipeline stages; enforces "read whole script first"; per-shot regen without recompiling the project. |
| `ingest.py` | Screenplay/logline ingest → beat sheet (LLM seam) → normalized scene/beat tree. |
| `shotlist.py` | Beat→shot-list generator (~4 scenes / ~22 shots; camera, movement, framing, action, dialogue). |
| `first_frame.py` | Per-shot T2I/I2I first-frame generation, auto-injecting locked character/style refs from `characters.identity`. |
| `animatic.py` | Frames→Video low-cost animatic pass (2–8 keyframes) for pacing approval before premium generation. |
| `motion.py` | Per-shot I2V motion request builder (route to best model, or Wan FLF2V start→end). |
| `regenerate.py` | Pure diff logic: regenerate only off-intent frames / weak-motion shots; preserve approved shots. |
| `repository.py` | CRUD for `Storyboard`, `Scene`, `Shot`, `ShotFrame`, `ShotMotion`. |
| `schemas.py` | DTOs + view builders. |
| `policy.py` | Credit-gating: block generation until shot-list approved; per-shot cost preview. |
### `app/models/db/storyboard.py`
| Table | Responsibility |
|---|---|
| `Storyboard` | A screenplay project (logline, beats JSON, style/character bindings, status). |
| `Scene` | A scene within a storyboard. |
| `Shot` | A shot (camera/movement/framing/action/dialogue, target model hint, status). |
| `ShotFrame` | A generated first-frame still (asset ref, prompt, approved flag, regen count). |
| `ShotMotion` | A generated motion clip for a shot (model used, FLF2V/I2V, interpolation, upscale). |
---
## 6. Domain: `film/` — Multi-Agent AI-Movie Orchestrator + Narrative Context Protocol (Phase 4)
Ports the **ViMax** Director/Screenwriter/Producer/Editor structure and the **Open-AI-Micro-Drama**
4-agent stack; carries a shared **Narrative Context Protocol (NCP)** JSON between stages.
### `app/domains/film/`
| Path | Responsibility |
|---|---|
| `router.py` | `POST /film/projects` · `POST /film/{id}/run` kick the orchestrator · `GET /film/{id}/state` · `POST /film/{id}/stage/{stage}/rerun` · `POST /film/{id}/export` (per-aspect + OTIO/FCPXML). |
| `service.py` | Project lifecycle + orchestrator entrypoint; wallet-metered per shot; resumable from any stage. |
| `orchestrator.py` | The agent DAG driver: sequences Screenwriter→Character→Storyboard→Generation→Voice→Score→Edit→Finish→Distribution. |
| `agents/__init__.py` | Agent registry. |
| `agents/base.py` | `FilmAgent` protocol (`run(ctx: NarrativeContext) -> NarrativeContext`), LLM seam, cost accounting. |
| `agents/director.py` | Director agent: global vision, pacing, cross-shot consistency guard, AutoCameo insertion. |
| `agents/screenwriter.py` | Logline→beat sheet→screenplay + per-character dialogue. |
| `agents/character_extractor.py` | Static+dynamic feature extraction → reusable portraits (delegates to `characters`). |
| `agents/storyboard_artist.py` | First-frame per shot (delegates to `storyboard.first_frame`). |
| `agents/producer.py` | Budget/model selection per shot via routing; queue management; success-only billing. |
| `agents/editor.py` | Stitch/animatic → final edit; beat-cut; transitions. |
| `agents/composer.py` | Score+SFX stage (Suno/AIVA/ElevenLabs Music + MMAudio, auto-duck to shot durations). |
| `agents/voice_director.py` | Per-character dialogue TTS (ElevenLabs v3 / Chatterbox) with expressive tags. |
| `ncp/__init__.py` | Narrative Context Protocol package. |
| `ncp/context.py` | `NarrativeContext` schema (story/character/beat/style/shot JSON) transported between stages. |
| `ncp/store.py` | Persist/load NCP snapshots per stage (resumability + audit of what each agent saw). |
| `ncp/merge.py` | Pure immutable merge of stage outputs into the running context (no in-place mutation). |
| `autocameo.py` | User-photo insertion keeping creator likeness consistent across the narrative (consent-gated). |
| `micro_drama.py` | Serialized short-drama episode preset (ViMax/Micro-Drama structure) reusing locked characters. |
| `export/__init__.py` | Export package. |
| `export/otio.py` | OpenTimelineIO emitter. |
| `export/fcpxml.py` | FCPXML emitter. |
| `export/resolve_mcp.py` | DaVinci Resolve MCP hand-off bridge for power-user finishing. |
| `repository.py` | CRUD for `FilmProject`, `FilmStageRun`, `NarrativeSnapshot`. |
| `schemas.py` | DTOs + view builders. |
| `policy.py` | Stage-gating, per-shot burn preview, license-clean model selection. |
### `app/models/db/film.py`
| Table | Responsibility |
|---|---|
| `FilmProject` | An AI-movie project (title, logline, style/character bindings, status, aspect targets). |
| `FilmStageRun` | One agent-stage execution (stage, agent, input/output NCP refs, cost, status, retries). |
| `NarrativeSnapshot` | An immutable NCP snapshot (context JSON, stage, hash). |
---
## 7. Domain: `series/` — Clipfarm Automation: Series / Batch / Cadence (Phase 5)
Turns one template + a content source into a **recurring channel**: episodic series with persistent
recurring-character identity, batch runs, and a genre-tuned cadence scheduler that feeds the
publishing queue.
### `app/domains/series/`
| Path | Responsibility |
|---|---|
| `router.py` | `POST /series` create · `GET /series/{id}` · `POST /series/{id}/episodes` generate next episode · `POST /series/{id}/batch` batch-generate N · `PUT /series/{id}/cadence` · `POST /series/{id}/pause`. |
| `service.py` | Series lifecycle; spawns per-episode film/template jobs; enforces single-format channel mode. |
| `episode.py` | Per-episode variation generator on a fixed character/style lock (numbered episodes). |
| `batch.py` | Batch run planner (N videos from a source list / trend feed) with per-item wallet reserve. |
| `cadence.py` | Genre-tuned daily-cadence planner (warmed vs new account frequency) feeding the scheduler. |
| `source_feed.py` | Content-source adapters (Reddit/URL/trend feed) → per-episode inputs. |
| `repository.py` | CRUD for `Series`, `SeriesEpisode`, `BatchRun`, `BatchItem`, `CadencePlan`. |
| `schemas.py` | DTOs + view builders. |
| `policy.py` | Cadence caps, self-cannibalization spacing, budget guard for unattended runs. |
### `app/models/db/series.py`
| Table | Responsibility |
|---|---|
| `Series` | A recurring channel (genre, template ref, character/style lock, cadence plan, target platforms). |
| `SeriesEpisode` | An episode (number, source input, produced reel id, publish status). |
| `BatchRun` | A batch generation run (source set, count, status, aggregate cost). |
| `BatchItem` | One item in a batch (input, job id, status, cost). |
| `CadencePlan` | Per-series posting cadence (frequency, timezone, account maturity, spacing). |
---
## 8. Domain: `publishing/` (expand stub) + `services/publish` — Multi-Platform Publishing Hub (Phase 2, the wedge)
Replaces the 5-line stub with a full **multi-account OAuth hub**, self-hosted scheduler, watermark-safe
per-platform export, retention analytics ingestion, closed-loop A/B, and a publishing MCP.
### `app/domains/publishing/`
| Path | Responsibility |
|---|---|
| `router.py` | Compose sub-routers below; keep canonical `/api/v1/publishing/*`. |
| `service.py` | Publish orchestration: pick connection, build platform post, watermark-safe re-encode, enqueue schedule, record result. |
| `schemas.py` | DTOs + view builders (connection, post, schedule, analytics, experiment). |
| `policy.py` | Per-platform daily-cap awareness, foreign-watermark rejection, self-cannibalization spacing, cross-post staggering (≥24h). |
| `repository.py` | CRUD for publishing tables (§8 DB). |
| **connections/** | |
| `connections/router.py` | OAuth connect/disconnect/list endpoints per platform + aggregator. |
| `connections/service.py` | Token lifecycle (encrypted via Fernet), refresh, per-account scoping. |
| `connectors/base.py` | `Publisher` protocol (`publish`, `schedule_supported`, `caps`, `refresh`, `fetch_analytics`). |
| `connectors/tiktok.py` | TikTok Content Posting API adapter (no native scheduling → ReelForge queue; audit-aware). |
| `connectors/instagram.py` | Instagram Graph container+poll 2-step publish; 25–50/24h cap awareness. |
| `connectors/youtube.py` | YouTube Data API upload + Shorts metadata + Test-and-Compare title/thumbnail. |
| `connectors/x.py` | X pay-per-use posting ($0.015/post, $0.20 w/ link) with wallet metering. |
| `connectors/aggregator.py` | Ayrshare/Blotato/Upload-Post aggregator fallback (managed queue) behind the same protocol. |
| `connectors/oauth_flows.py` | Per-platform OAuth handshake helpers (PKCE, scopes, redirect). |
| **scheduler/** | |
| `scheduler/router.py` | Schedule/reschedule/cancel endpoints; list upcoming. |
| `scheduler/service.py` | Self-hosted scheduling queue: timezone-correct enqueue, exponential-backoff retries, per-platform cap enforcement. |
| `scheduler/queue.py` | Durable schedule queue (DB-backed) with claim/lease semantics for the Celery beat worker. |
| `scheduler/best_time.py` | Best-time-to-post optimizer learning from the account's own first-hour performance. |
| `scheduler/cannibalization.py` | Self-cannibalization guard (spacing + throttle when reach-per-post drops). |
| **exportfx/** | |
| `exportfx/watermark_safe.py` | Watermark-safe per-platform re-encoder (unique re-encode, no foreign/ReelForge mark). |
| `exportfx/reencode_presets.py` | Per-platform master presets (bitrate, codec, aspect, loudness). |
| **analytics/** | |
| `analytics/router.py` | `GET /publishing/analytics/{post_id}` retention curve · account rollups. |
| `analytics/ingest.py` | Pull per-second retention, completion, Viewed-vs-Swiped, sends/reach into a unified drop-off graph. |
| `analytics/retention.py` | Retention-curve normalizer + threshold mapping (70–85%→2.2x, >85%→viral, <60%→minimal). |
| **experiments/** | |
| `experiments/router.py` | A/B experiment CRUD + results. |
| `experiments/hook_ab.py` | "1 body, N hooks" generator + auto-schedule across days/accounts. |
| `experiments/winner.py` | Retention-weighted winner selection (completion + avg watch, not vanity); feed winner back into generation prompts. |
| `experiments/yt_test_compare.py` | YouTube Test-and-Compare integration (title/thumbnail by watch-time-per-impression). |
### `app/services/publish/` (post builders — worker-internal)
| Path | Responsibility |
|---|---|
| `post_builder.py` | Build a platform-specific post payload (caption SEO, hashtags, trending-audio relink, cover). |
| `trending_audio.py` | Export-muted → auto-relink the exact native trending sound on upload (trending-audio discovery). |
| `ad_safe_audio.py` | Cross-platform-safe (Meta-compatible) licensed-audio matcher for cross-posting. |
| `cover_frame.py` | Per-platform cover/thumbnail selection. |
### `app/models/db/publishing.py`
| Table | Responsibility |
|---|---|
| `PublishConnection` | An OAuth-connected account (platform, external id, encrypted tokens, scopes, caps). |
| `PublishPost` | A publish attempt (reel id, connection, platform post id, status, watermark-safe master ref). |
| `PublishSchedule` | A scheduled slot (post ref, run_at UTC, retries, backoff, cap-bucket). |
| `RetentionCurve` | Per-post retention samples (per-second array, completion, viewed-vs-swiped, sends/reach). |
| `AbExperiment` | An experiment (body ref, variant list, metric, status). |
| `AbVariant` | A hook variant (variant ref, scheduled slot, measured retention, winner flag). |
---
## 9. Domain: `trends/` — Trend + Sound Ingestion & Scoring (Phase 2)
Cron-driven ingestion of trending hashtags/sounds/creators with a **saturation/decay** score feeding
the template picker and best-time optimizer. ToS-risky scrapers isolated behind adapters; sanctioned
Research API preferred.
### `app/domains/trends/`
| Path | Responsibility |
|---|---|
| `router.py` | `GET /trends` browse scored trends · `GET /trends/sounds` rising sounds · `GET /trends/hashtags` · `POST /trends/attach` attach a sound to a draft. |
| `service.py` | Aggregate snapshots, compute scores, expose trend feed scoped to niche/platform. |
| `scoring.py` | Pure saturation/decay/velocity score (rising-but-not-peaked detection). |
| `sources/base.py` | `TrendSource` protocol (`fetch() -> list[TrendSnapshot]`). |
| `sources/tiktok_api.py` | davidteather/TikTok-Api wrapper adapter (isolated, ToS-flagged). |
| `sources/tiktok_actions_scraper.py` | antiops/ogohogo GitHub-Actions Discovery snapshot ingest. |
| `sources/creative_center.py` | TikTok Creative Center trending ingest. |
| `sources/hashtag_cooccurrence.py` | bellingcat hashtag co-occurrence analysis into the keyword feed. |
| `repository.py` | CRUD for `TrendSnapshot`, `TrendScore`, `TrendingSound`. |
| `schemas.py` | DTOs + view builders. |
| `policy.py` | Source trust/ToS gating, dedupe, snapshot retention window. |
### `app/models/db/trends.py`
| Table | Responsibility |
|---|---|
| `TrendSnapshot` | A raw trend observation (source, platform, entity type, payload, observed_at). |
| `TrendScore` | Materialized score per entity (saturation, velocity, decay, computed_at). |
| `TrendingSound` | A trending native sound (platform id, title, usage curve, ad-safe flag). |
---
## 10. Provider Adapters — Real Video/Audio/Lipsync Models (Phase 1→4, breadth)
New adapters implementing the existing `routing.base.ProviderRegistry` contract (`ProviderRun`,
`NormalizedUsage`, async envelope). They register into `domains/routing/providers/registry.py` and
carry catalog license/deprecation metadata. All GPU/async ones route through the **unified async job
envelope** in `services/render` (§11).
### `app/domains/routing/providers/` (new adapters)
| Path | Responsibility |
|---|---|
| `sora2.py` | Sora 2 T2V/I2V adapter (physics tier) + **deprecation metadata** (sunset 2026-09-24) for auto-migration. |
| `kling.py` | Kling 3.0 adapter (expressive character motion, native audio, 15s sequences). |
| `veo.py` | Veo 3.1 adapter (premium 4K). |
| `runway.py` | Runway Gen-4.5 adapter (temporal control) + Gen-3/Aleph deprecation flags. |
| `luma.py` | Luma Dream Machine adapter. |
| `seedance.py` | Seedance 2.0 adapter (consistency/speed tier). |
| `wan_local.py` | Self-hosted Wan 2.2 adapter via `services/render` ComfyUI (Apache, license-clean default). |
| `wan_flf2v.py` | Wan 2.2 FLF2V start+end keyframe → 81-frame clip + RIFE/FILM 2x + upscale workflow adapter. |
| `hunyuan.py` | HunyuanVideo adapter (Community License — **territorial** flag, gate carefully). |
| `cogvideox.py` | CogVideoX adapter (low-VRAM diffusion tier). |
| `ltx.py` | LTX-Video adapter (Apache speed tier). |
| `flux.py` | FLUX dev/kontext T2I/I2I adapter for first-frames/storyboard. |
| `midjourney.py` | Midjourney Omni-Reference adapter for character-consistent stills (via proxy). |
| `suno.py` | Suno music adapter (score stage). |
| `aiva.py` | AIVA music adapter (score stage). |
| `musetalk.py` | MuseTalk realtime 30fps lipsync (MIT, safe-default tier). |
| `latentsync.py` | LatentSync diffusion lipsync (Apache, best-fidelity/premium tier). |
| `infinitetalk.py` | InfiniteTalk infinite-length multi-speaker avatar (Wan2GP integration) for long-form dialogue. |
| `chatterbox.py` | Chatterbox TTS (MIT, emotion dial, 5s clone) — commercial-safe voice. |
| `kokoro.py` | Kokoro TTS (Apache, CPU draft-narration tier). |
| `_deprecation.py` | Shared model-lifecycle/sunset-date metadata + deprecation-aware routing helper. |
| `_license_class.py` | Shared license-class tags (commercial-safe / non-commercial / territorial) + paying-user hard-exclusion. |
---
## 11. Render / GPU Orchestration — `services/render` + ComfyUI Farm (Phase 1→4)
The **unified async GPU job envelope** (`IN_QUEUE → IN_PROGRESS → COMPLETED`, poll/webhook) with a
warm model pool, versioned ComfyUI workflow registry, and Revideo/Remotion data-driven render layer.
### `app/services/render/`
| Path | Responsibility |
|---|---|
| `__init__.py` | Package exports. |
| `envelope.py` | Unified async GPU job envelope dataclasses + state machine (`IN_QUEUE/IN_PROGRESS/COMPLETED/FAILED`). |
| `job_client.py` | Submit/poll/cancel a render job against a backend; webhook callback verification. |
| `warm_pool.py` | Warm-pool model caching + network-volume warm-start hints across adapters. |
| `backends/base.py` | `RenderBackend` protocol (`submit`, `poll`, `cancel`, `warm`). |
| `backends/worker_comfyui.py` | runpod-workers/worker-comfyui async queue/poll/webhook backend. |
| `backends/comfyui_deploy.py` | BennyKok/comfyui-deploy versioned prod/staging API backend. |
| `backends/viewcomfy.py` | ViewComfy serverless endpoint backend (SSO/S3/ACL, white-label agency endpoints). |
| `backends/runpod.py` | RunPod serverless GPU backend. |
| `backends/replicate.py` | Replicate backend (idle-time billing awareness noted). |
| `backends/fal.py` | Fal backend (no-spend-cap gap covered by our reserve). |
| `workflows/registry.py` | Versioned ComfyUI workflow registry (graphs as pinned artifacts: node commits + weights locked per version). |
| `workflows/schema.py` | Workflow-version DTO (graph hash, node commit set, weight refs, inputs contract). |
| `workflows/wan_i2v.py` | Wan 2.2 I2V workflow definition/binding. |
| `workflows/wan_flf2v.py` | Wan FLF2V start→end + RIFE/FILM interpolation + upscale graph. |
| `workflows/flux_first_frame.py` | FLUX first-frame T2I/I2I graph. |
| `workflows/lora_train_wan.py` | Wan 2.2 LoRA training graph (character lock). |
| `workflows/lipsync_musetalk.py` | MuseTalk lipsync graph. |
| `workflows/lipsync_latentsync.py` | LatentSync lipsync graph. |
| `datadriven/base.py` | `DataDrivenRenderer` protocol (template + props → MP4). |
| `datadriven/revideo.py` | Revideo self-host renderer (primary programmatic-render layer, license-friendly). |
| `datadriven/remotion.py` | Remotion renderer (gated behind paid commercial-license class). |
| `datadriven/preview.py` | Live preview render (React Player) before committing GPU time. |
### `app/models/db/render.py`
| Table | Responsibility |
|---|---|
| `RenderJob` | An async GPU job (backend, workflow version, envelope state, poll cursor, cost, output refs). |
| `WorkflowVersion` | A pinned ComfyUI/render workflow artifact (graph hash, node commits, weight refs). |
| `WarmPoolEntry` | A cached warm model/endpoint (backend, model, last-used, ttl). |
| `CaptionJob` | (see §3) transcription/alignment job. |
| `HookScore` | (see §3) hook-strength score. |
---
## 12. Audio Subsystem — `services/audio` (Phase 4)
Consolidated audio breadth behind injectable seams: dialogue TTS tiers, music, Foley, ducking, and
consent-gated voice cloning that reuses the existing Fernet infra.
### `app/services/audio/`
| Path | Responsibility |
|---|---|
| `dialogue.py` | Per-character dialogue TTS orchestration with expressive tags (ElevenLabs v3 / Chatterbox route). |
| `draft_tts.py` | Kokoro zero-cost CPU draft-narration tier (upgrade to cloud/Chatterbox only on final render). |
| `voice_clone.py` | Consent-gated 5s enrollment voice clone (Chatterbox), encrypted storage + audit trail. |
| `music.py` | Routed Suno/AIVA/ElevenLabs Music generation timed to shot durations. |
| `foley.py` | MMAudio video→Foley/SFX auto-sync per shot. |
| `ducking.py` | Auto-duck music/SFX under dialogue (sidechain gain envelope for compose). |
| `two_host.py` | Two-host fake-podcast dialogue builder (disfluencies: um/laughs/interruptions) + speaker turns. |
| `reddit_narration.py` | Reddit/URL story → multi-voice narration script (comment-mode multi-voice). |
---
## 13. Domain: `gateway/` — Resellable API Platform (Phase 3)
Provisioning/management keys, hybrid margin (`markup_policy`), tiered plans, white-label reseller, and
the Lago bridge — turning the wallet into a resellable platform. Real-time pre-block stays in-house.
### `app/domains/gateway/`
| Path | Responsibility |
|---|---|
| `router.py` | Compose sub-routers; `/api/v1/gateway/*`. |
| `service.py` | Gateway orchestration across keys/plans/margin/reseller. |
| `schemas.py` | DTOs + view builders. |
| `repository.py` | CRUD for gateway tables. |
| `policy.py` | Reject-before-provider spend checks, plan entitlement gating, license-clean routing for paying keys. |
| **keys/** | |
| `keys/router.py` | OpenRouter-style `/gateway/keys` CRUD (create/list/rotate/disable). |
| `keys/service.py` | Per-customer spend-capped sub-key issuance, labels, BYOK-in-limit toggle. |
| `keys/resets.py` | Daily/weekly/monthly midnight-UTC spend-cap reset scheduler. |
| `keys/enforcement.py` | Reject-before-provider limit check integrated into reserve. |
| **plans/** | |
| `plans/catalog.py` | Tiered plan definitions (Free-unlocked-after-$10, Pro, Agency, Enterprise) with req/min + req/day + workspace caps. |
| `plans/entitlements.py` | Plan entitlement resolution (limits, overage rates, per-client caps 10/50). |
| `plans/rate_limits.py` | Published rate-limit enforcement (per-min/per-day) integrated with existing `ratelimit`. |
| `plans/sla.py` | Uptime SLA tracking + credit-back on breach. |
| **margin/** | |
| `margin/markup_policy.py` | Configurable per-output `markup_policy` stored on price_versions (read + apply). |
| `margin/topup_fee.py` | Top-up platform fee (5.5% card / 5% crypto, min-top-up) applied at wallet grant. |
| `margin/byok_fee.py` | BYOK-as-fee escape valve (% of list price above plan allowance). |
| `margin/success_billing.py` | Success-only per-output billing (never debit on provider error/queue/failure). |
| `margin/metering_export.py` | Itemized cost breakdown per key/customer (model, provider, wholesale cost, markup, margin). |
| **reseller/** | |
| `reseller/router.py` | White-label reseller config + margin dashboard endpoints. |
| `reseller/service.py` | Removable branding, custom domain binding, wholesale-vs-retail margin config. |
| `reseller/branding.py` | Per-reseller branding + domain resolution. |
| **lago/** (bridge lives in `services/lago`) | see §14. |
| `deprecation.py` | Deprecation-aware routing metadata surface (auto-migrate callers off sunsetting models). |
### `app/services/lago/`
| Path | Responsibility |
|---|---|
| `client.py` | Lago API client (customers, subscriptions, usage events, invoices). |
| `metering_bridge.py` | Push `UsageRecord`→Lago metered events (keep real-time wallet in-house). |
| `entitlements.py` | Sync Lago entitlements → plan gating. |
| `dunning.py` | Dunning/tax/invoice-status reconciliation from Lago webhooks. |
### `app/models/db/gateway.py`
| Table | Responsibility |
|---|---|
| `ProvisioningKey` | A spend-capped sub-key (label, cap, reset period, BYOK-in-limit flag, parent workspace). |
| `KeyResetLog` | Append-only cap-reset events. |
| `ApiPlan` | A tiered plan (limits, overage rates, workspace caps, SLA). |
| `PlanSubscription` | A customer's plan binding. |
| `MarkupPolicy` | Per-workspace/per-model markup config referenced by price_versions. |
| `ResellerConfig` | White-label reseller (branding, domain, wholesale margin). |
| `SlaCredit` | SLA credit-back entries. |
---
## 14. Domain: `clipmarket/` — Pay-Per-View Clipping Marketplace + Affiliate (Phase 5)
Brands set CPM, clippers submit, views API-verified with 72h approval and viewbot fraud detection;
plus a lifetime-recurring affiliate program beating HeyGen's 12-month cap.
### `app/domains/clipmarket/`
| Path | Responsibility |
|---|---|
| `router.py` | Campaign + submission + payout endpoints. |
| `service.py` | Campaign lifecycle, submission intake, approval, payout computation. |
| `campaigns.py` | Brand campaign model (CPM $1–5, budget, rules, asset kit). |
| `submissions.py` | Clipper submission intake + status (pending/approved/rejected/paid). |
| `verification.py` | API-verified view counting across platforms (72h approval window). |
| `fraud.py` | Viewbot fraud detection (velocity/geo/retention anomaly scoring). |
| `payouts.py` | CPM payout computation + Creem/Stripe payout dispatch. |
| **affiliate/** | |
| `affiliate/router.py` | Affiliate dashboard + deep-link endpoints. |
| `affiliate/service.py` | Lifetime-recurring affiliate attribution + accrual. |
| `affiliate/deeplinks.py` | Deep-link generation + attribution capture. |
| `affiliate/payouts.py` | Recurring affiliate payout (Creem/Stripe) beating 12-month cap. |
| `repository.py` | CRUD for clipmarket tables. |
| `schemas.py` | DTOs + view builders. |
| `policy.py` | Fraud thresholds, approval SLA, minimum payout, self-referral guard. |
### `app/models/db/clipmarket.py`
| Table | Responsibility |
|---|---|
| `ClipCampaign` | A brand campaign (CPM, budget, rules, asset kit, status). |
| `ClipSubmission` | A clipper's submitted clip (campaign, platform post, verified views, status). |
| `ViewVerification` | Append-only verified-view samples per submission. |
| `ClipPayout` | A CPM payout record. |
| `AffiliateAccount` | An affiliate (owner, code, lifetime rate). |
| `AffiliateReferral` | A referred customer + recurring accrual. |
| `AffiliatePayout` | Affiliate payout record. |
---
## 15. Domain: `presets/` — Template / Preset Marketplace (Phase 5)
Creator-facing marketplace exposing shot templates and ComfyUI graphs as shareable, resellable presets
(extends existing `MarketplaceTemplate`).
### `app/domains/presets/`
| Path | Responsibility |
|---|---|
| `router.py` | Browse/publish/purchase/install preset endpoints. |
| `service.py` | Preset publishing (from a shot template or ComfyUI workflow version), purchase→install, revenue share. |
| `packaging.py` | Package a `ShotTemplateVersion` / `WorkflowVersion` into a portable, license-tagged preset artifact. |
| `install.py` | Install a purchased preset into the buyer's template/workflow registry. |
| `revshare.py` | Creator revenue-share accrual on preset sales (wallet credit). |
| `repository.py` | CRUD for `PresetListing`, `PresetPurchase`, `PresetInstall`. |
| `schemas.py` | DTOs + view builders. |
| `policy.py` | License compatibility check, pricing bounds, moderation gate before listing. |
### `app/models/db/presets.py`
| Table | Responsibility |
|---|---|
| `PresetListing` | A published preset (source ref, kind, price, license, creator, ratings link). |
| `PresetPurchase` | A purchase (buyer, listing, price paid, revshare split). |
| `PresetInstall` | An install binding into the buyer's registry. |
---
## 16. Domain: `growth/` — Onboarding, Micro-Tools, Funnels (Phase 5)
Empty-screen-killer onboarding, standalone free micro-tools as top-of-funnel, watermark-on-free viral
loop, and free-tier upgrade triggers. Instrumented for the 3–5 min aha activation funnel.
### `app/domains/growth/`
| Path | Responsibility |
|---|---|
| `router.py` | Onboarding + micro-tool + funnel endpoints. |
| `service.py` | Growth orchestration (onboarding state, trigger unlocks). |
| `onboarding.py` | Empty-screen-killer: preload a finished sample reel + one-tap remix (target 3–5 min to first published clip). |
| `sample_reels.py` | Curated sample-reel catalog for one-tap remix. |
| `upgrade_triggers.py` | Free-forever tier locked-trigger registry (editor, hook-score, no-watermark, multi-aspect, scheduler). |
| `watermark_loop.py` | Watermark-on-free-export badge + short-link injection (removable on upgrade). |
| **microtools/** | |
| `microtools/captioner.py` | Standalone free AI captioner micro-tool (funnels into wallet). |
| `microtools/hook_analyzer.py` | Standalone free hook-score analyzer micro-tool. |
| `microtools/thumbnail.py` | Standalone free thumbnail generator micro-tool. |
| **funnel/** | |
| `funnel/activation.py` | Activation-funnel event emitter (3–5 min aha) → analytics/PostHog. |
| `funnel/expansion.py` | Expansion-loop mechanics for 120%+ NRR (shared workspace credits, seat upgrades, volume tiers). |
| `funnel/sora_migration.py` | Sora-shutdown migration onboarding (route displaced creators to Veo/Kling/Seedance stack). |
| `repository.py` | CRUD for `OnboardingState`, `UpgradeTriggerHit`, `MicroToolRun`. |
| `schemas.py` | DTOs + view builders. |
| `policy.py` | Trigger-unlock rules, free-tier quotas, watermark requirement. |
### `app/models/db/growth.py`
| Table | Responsibility |
|---|---|
| `OnboardingState` | Per-user onboarding progress (steps, time-to-first-clip, activated flag). |
| `UpgradeTriggerHit` | Append-only record of which locked trigger a free user hit (upgrade-intent signal). |
| `MicroToolRun` | A standalone micro-tool invocation (tool, input, output, converted flag). |
---
## 17. Domain: `assets/` — Asset & Gameplay B-Roll Library (Phase 1→2)
Unified asset library with a tagged, loop-annotated gameplay B-roll library (Minecraft parkour, Subway
Surfers, GTA, power-washing) feeding split-screen templates.
### `app/domains/assets/`
| Path | Responsibility |
|---|---|
| `router.py` | Asset CRUD/search + gameplay-library endpoints. |
| `service.py` | Asset lifecycle, tagging, dedupe, storage handoff (R2). |
| `broll_library.py` | Gameplay B-roll library manager (categories, tags, loop metadata, duration). |
| `tagging.py` | Auto-tagging (category, motion intensity, loopability). |
| `crop.py` | Face-aware vertical (9:16) crop util for repurpose/split-screen. |
| `repository.py` | CRUD for `LibraryAsset`, `GameplayClip`, `AssetTag`. |
| `schemas.py` | DTOs + view builders. |
| `policy.py` | License/source gating, storage quota. |
### `app/models/db/assets.py`
| Table | Responsibility |
|---|---|
| `LibraryAsset` | A stored asset (kind, storage ref, owner/workspace, license, tags). |
| `GameplayClip` | A gameplay B-roll clip (category, loop metadata, motion intensity). |
| `AssetTag` | Tag join for search. |
---
## 18. Domain: `moderation/` — Safety, License Gating, Consent Audit (Phase 2, cross-cutting)
Pre-publish and pre-generate safety: watermark detection (avoid foreign marks), NSFW/policy checks,
license-class enforcement, and consent audit for voice/avatar cloning.
### `app/domains/moderation/`
| Path | Responsibility |
|---|---|
| `router.py` | `POST /moderation/check` (asset) · `GET /moderation/consent/{id}` · admin review endpoints. |
| `service.py` | Moderation orchestration (pre-generate + pre-publish gates). |
| `watermark_detect.py` | Foreign-watermark detector (blocks competitor-watermarked media from publish). |
| `nsfw.py` | NSFW/policy classifier seam (route to a safety model). |
| `license_gate.py` | Enforce license class per model (hard-exclude non-commercial weights for paying users). |
| `consent_audit.py` | Voice/avatar clone consent capture + audit trail (reuses Fernet, extends `services/compliance/consent`). |
| `repository.py` | CRUD for `ModerationCheck`, `ConsentAudit`. |
| `schemas.py` | DTOs + view builders. |
| `policy.py` | Thresholds, block/allow decisions, appeal states. |
### `app/models/db/moderation.py`
| Table | Responsibility |
|---|---|
| `ModerationCheck` | A moderation result (asset, checks run, verdict, scores). |
| `ConsentAudit` | Append-only consent record for likeness/voice cloning (subject, scope, evidence ref). |
---
## 19. Events Bus + Job DAG Orchestration (Phase 2, cross-cutting)
An internal **outbox event bus** decouples domains (publish/analytics/growth react to job/publish
events) and a **DAG runner** sequences multi-stage film/series pipelines on top of the existing Celery
pipeline.
### `app/events/`
| Path | Responsibility |
|---|---|
| `__init__.py` | Package exports. |
| `bus.py` | In-process event bus + subscriber registry (`emit`, `subscribe`). |
| `outbox.py` | Transactional outbox writer (events persisted in the same tx as domain writes). |
| `dispatcher.py` | Outbox drain → Celery/webhook fan-out (at-least-once, dedupe by event id). |
| `types.py` | Canonical event schemas (`JobCompleted`, `PublishSucceeded`, `RetentionIngested`, `WinnerSelected`, `KeySpendExceeded`, ...). |
| `handlers/publish_on_render.py` | On `JobCompleted` for a scheduled reel → enqueue publish. |
| `handlers/analytics_on_publish.py` | On `PublishSucceeded` → schedule retention-curve ingestion. |
| `handlers/regenerate_on_winner.py` | On `WinnerSelected` → feed winning hook back into generation. |
| `handlers/notify_on_spend.py` | On `KeySpendExceeded` → notify + throttle. |
### `app/models/db/events.py`
| Table | Responsibility |
|---|---|
| `OutboxEvent` | Transactional outbox row (type, payload, status, dedupe key, published_at). |
| `EventSubscription` | Internal-handler subscription registry (optional dynamic subs). |
### `app/workers/dag.py`
| Path | Responsibility |
|---|---|
| `workers/dag.py` | Job DAG runner: build a stage dependency graph (storyboard→motion→stitch→voice→score→finish→publish), dispatch ready stages, aggregate weighted progress. |
---
## 20. Workers — New Celery Task Modules (Phase 1→5)
All register on the existing `celery_app`; each is a thin retry-aware wrapper around a pure stage
function, reporting append-only `JobEvent` + weighted progress (matching `workers/tasks.py`).
| Path | Responsibility |
|---|---|
| `workers/tasks_render.py` | Async GPU render stages (submit→poll→collect) via `services/render` envelope. |
| `workers/tasks_film.py` | Film pipeline stages (screenwriter/character/storyboard/generation/voice/score/edit/finish). |
| `workers/tasks_captions.py` | WhisperX transcribe→align stage + Hormozi styling. |
| `workers/tasks_publish.py` | Scheduled publish worker (claim schedule queue, call connector, record result, backoff). |
| `workers/tasks_trends.py` | Trend ingestion cron worker (fetch sources → snapshots → scores). |
| `workers/tasks_series.py` | Series cadence worker (spawn next episode / batch items on schedule). |
| `workers/tasks_clipmarket.py` | View-verification + fraud-scan cron for clip submissions. |
| `workers/tasks_gateway.py` | Key spend-cap reset cron + Lago metering push. |
| `workers/beat_schedule.py` | Celery-beat schedule declarations for all cron workers (trend/publish/reset/series). |
---
## 21. MCP — New Agent Tools (Phase 2→3)
Extend `mcp/tools.py` (dispatch) with grouped tool modules so external AI agents can create, publish,
analyze, and provision under the same wallet/spend guards.
| Path | Responsibility |
|---|---|
| `mcp/tools_film.py` | Tools: `create_film`, `run_shotlist`, `regenerate_shot`, `export_otio`. |
| `mcp/tools_publish.py` | Tools: `schedule_post`, `list_analytics`, `start_hook_ab`, `get_winner`. |
| `mcp/tools_trends.py` | Tools: `browse_trends`, `attach_sound`. |
| `mcp/tools_gateway.py` | Tools: `create_provisioning_key`, `set_markup`, `usage_export`. |
| `mcp/tools_templates.py` | Tools: `list_templates`, `instantiate_template`, `compile_template`. |
---
## 22. Key Data Models Summary (new tables by module)
| Module | New tables |
|---|---|
| `templates.py` | ShotTemplate, ShotTemplateVersion, TemplateSlot, TemplateInstance |
| `storyboard.py` | Storyboard, Scene, Shot, ShotFrame, ShotMotion |
| `film.py` | FilmProject, FilmStageRun, NarrativeSnapshot |
| `characters.py` | CharacterEntity, CharacterReference, StyleEntity, LoraArtifact, IdentityBinding |
| `series.py` | Series, SeriesEpisode, BatchRun, BatchItem, CadencePlan |
| `publishing.py` | PublishConnection, PublishPost, PublishSchedule, RetentionCurve, AbExperiment, AbVariant |
| `trends.py` | TrendSnapshot, TrendScore, TrendingSound |
| `render.py` | RenderJob, WorkflowVersion, WarmPoolEntry, CaptionJob, HookScore |
| `gateway.py` | ProvisioningKey, KeyResetLog, ApiPlan, PlanSubscription, MarkupPolicy, ResellerConfig, SlaCredit |
| `clipmarket.py` | ClipCampaign, ClipSubmission, ViewVerification, ClipPayout, AffiliateAccount, AffiliateReferral, AffiliatePayout |
| `presets.py` | PresetListing, PresetPurchase, PresetInstall |
| `growth.py` | OnboardingState, UpgradeTriggerHit, MicroToolRun |
| `assets.py` | LibraryAsset, GameplayClip, AssetTag |
| `moderation.py` | ModerationCheck, ConsentAudit |
| `events.py` | OutboxEvent, EventSubscription |
All new tables follow existing conventions: uuid-hex PKs, tz-aware timestamps, append-only ledgers/audit,
workspace scoping FK to `Workspace`, and integer-microdollar money columns.
---
## 23. Key API Surface Summary (new prefixes under `/api/v1`)
| Prefix | Domain |
|---|---|
| `/templates/*` | Genre shot-template engine |
| `/captions/*` | WhisperX + Hormozi + hook/loop checks |
| `/characters/*`, `/styles/*` | Character/style lock |
| `/storyboard/*` | Screenplay→shotlist→frames→animatic |
| `/film/*` | AI-movie orchestrator + export |
| `/series/*` | Clipfarm series/batch/cadence |
| `/publishing/*` (+ `/connections`, `/scheduler`, `/analytics`, `/experiments`) | Publishing hub |
| `/trends/*` | Trend + sound feed |
| `/gateway/*` (+ `/keys`, `/plans`, `/reseller`) | Resellable API platform |
| `/clipmarket/*`, `/affiliate/*` | Clipping marketplace + affiliate |
| `/presets/*` | Preset marketplace |
| `/growth/*` (+ `/microtools`) | Onboarding + funnels |
| `/assets/*` | Asset + gameplay library |
| `/moderation/*` | Safety + consent |
Each new domain router is included in `app/router.py` following the existing `include_router` pattern
(one commented line per domain explaining its seam).
---
## 24. Phasing (matches digest build sequencing)
| Phase | Ships | Primary new modules |
|---|---|---|
| **1 — Fastest ROI** | Shot-template engine + caption/loop/hook + genre presets (reuses compose) | `templates/`, `services/captions` additions, `services/loops`, `assets/` (gameplay library), a few real provider adapters (`wan_local`, `flux`, `chatterbox`, `kokoro`) + `services/render` envelope |
| **2 — The Wedge** | Publishing hub + scheduler + retention analytics + closed-loop A/B + trends + events bus | `publishing/` (full), `services/publish`, `trends/`, `events/`, `moderation/`, `workers/tasks_publish/trends`, `mcp/tools_publish` |
| **3 — Resellable Platform** | Provisioning keys + markup + tiered plans + reseller + Lago | `gateway/`, `services/lago`, `workers/tasks_gateway`, `mcp/tools_gateway` |
| **4 — Deep Moat** | Film pipeline + character lock + storyboard + audio breadth + render farm | `film/`, `characters/`, `storyboard/`, `services/audio`, remaining provider adapters (sora2/kling/veo/runway/luma/seedance/hunyuan/cogvideox/ltx/musetalk/latentsync/infinitetalk/suno/aiva/wan_flf2v), `workers/tasks_film/render`, `dag.py` |
| **5 — Compounding Acquisition** | Clipping marketplace + affiliate + preset marketplace + growth/onboarding | `clipmarket/`, `presets/`, `growth/`, `series/` (clipfarm), `workers/tasks_series/clipmarket` |
---
## 25. Integration Seams (explicit)
1. **Wallet** — every generative/publish/render entrypoint calls `WalletService.reserve` before a
provider call and `settle`/`release` after; success-only billing lives in `gateway/margin/success_billing.py`
and is invoked from `workers/tasks_render.py` completion.
2. **Routing** — all new provider adapters register in `routing/providers/registry.py`; `film/agents/producer.py`
and `storyboard/motion.py` call `RoutingService.resolve` per shot/output; `_deprecation.py` + `_license_class.py`
extend routing policy, not replace it.
3. **Catalog** — `gateway/margin/markup_policy.py` reads/writes `PriceVersion.markup_policy`; per-model burn
preview reads active prices via `catalog.repository`.
4. **Compose** — `templates/render_spec.py` and `services/loops/retention_presets.py` emit specs the existing
`services/compose/compose_ffmpeg.py` consumes (new track/overlay/loop fields added, no rewrite).
5. **Workers/telemetry** — new task modules emit through `telemetry/events.record_event` +
`telemetry/progress.compute_progress`; DAG runner sits above the existing `workers/pipeline.py`.
6. **Auth/workspaces** — every router resolves `core.auth.resolve_principal` and scopes to `Workspace`;
provisioning keys resolve to a workspace with a spend cap.
7. **Events** — domains write to `events/outbox.py` in the same DB tx; `events/dispatcher.py` fans out to the
new Celery workers and existing external `webhook_subscriptions`.
8. **Compliance/consent** — `moderation/consent_audit.py` and `audio/voice_clone.py` extend the existing
`services/compliance/consent` + Fernet crypto, not fork it.
---
## 26. Testing Strategy (per rules: 80%+, TDD)
- **Unit**: pure modules (`templates/compiler.py`, `loops/loop_finder.py`, `trends/scoring.py`,
`publishing/scheduler/cannibalization.py`, `gateway/margin/*`, `film/ncp/merge.py`) tested with
injected seams — no network. Target the pure decision functions first (RED→GREEN).
- **Integration**: domain services against a test DB session (reserve/settle around a mocked provider run;
schedule-queue claim/lease; outbox drain; success-only-billing on simulated provider error).
- **Provider adapters**: contract tests against the `RenderBackend`/`Publisher`/`ProviderRegistry`
protocols with recorded fixtures; async-envelope state-machine tests.
- **E2E (critical flows)**: template→compile→render→publish→retention-ingest→winner-regenerate; and
film screenplay→shotlist→animatic→generate→export.
- Test files mirror the tree under `apps/api/tests/` (e.g. `tests/domains/templates/test_compiler.py`).
</content>
</invoke>