videogen/docs/reelforge/API_DIRECTORY_ARCHITECTURE_PLAN.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

612 lines
41 KiB
Markdown

# ReelForge API directory architecture plan
> **Scope:** `apps/api/**` only. This is the authoritative directory-by-directory
> ownership plan for the backend, workers, engine, assets, runtime storage, and
> operator tools.
> **Meaning of “use every file”:** every source or asset must have an explicit
> disposition: **production API**, **worker-only**, **GPU-engine-only**,
> **immutable asset**, **operator tool**, **compatibility adapter**,
> **evaluation-only**, or **generated/ignored**. It does **not** mean every
> legacy route, model experiment, training utility, or demo is started in the
> public API process.
## 1. Runtime topology and import rules
```text
apps/api/app/asgi.py CPU API request process
│
├── app/router.py → app/domains/* → app/services/* → DB/R2/Redis
│
└── app/workers/celery_app.py
├── celery queue script / light work / maintenance
├── render queue avatar / captions / FFmpeg / editor
└── generation queue B-roll / GPU engine only
│
└── apps/api/engine/*
apps/api/assets/* read-only mounted product assets
apps/api/runtime/storage/* writable mounted temporary data
apps/api/tools/* explicit operator/evaluation commands
```
| Process | May import | Must never import or mount as public API |
| --- | --- | --- |
| API request container | `app`, domain services, R2/Redis/DB clients, lightweight asset inventory | `engine` model stacks, `app/generation` app, Gradio demos, training datasets |
| Standard worker | domain services, light providers, assets | CUDA-only engine modules unless a task is explicitly routed to generation |
| Render worker | compose/editor/avatar/caption services, assets, R2 | arbitrary engine WebUI/routes |
| Generation worker | `engine`, B-roll/provider adapters, runtime storage, R2 | public authentication/router assembly, wallet transaction reimplementation |
| Operator workstation/CI | `tools/ops`, manifest checks, approved evaluation tools | production user traffic or secrets in source |
## 2. Top-level `apps/api` files and directories
| Path | Role | Runtime owner | Required disposition |
| --- | --- | --- | --- |
| `pyproject.toml` | API Python dependencies/entrypoints | all Python deployables | split CPU/GPU extras over time; pin lock-compatible versions |
| `Dockerfile` | API/standard/render base image | API, standard, render worker | no engine weight/model dependency layer |
| `Dockerfile.generation` | GPU generation image | generation worker only | engine dependencies, CUDA, no public port |
| `README.md` | backend developer contract | all contributors | keep paths, queues, contract commands current |
| `app/` | product application | API/workers | domain-owned product logic |
| `engine/` | GPU inference capability | generation worker only | private typed engine facade, not HTTP surface |
| `assets/` | immutable product files | API/workers read-only | manifests/license checks and content catalog |
| `runtime/storage/` | mutable temporary work data | workers/API as needed | volume only; never source control content |
| `tools/` | operator/evaluation harnesses | operator/CI | explicit commands, never ASGI-mounted |
| `.ruff_cache/`, `__pycache__/` | generated caches | none | ignored; never runtime dependency or commit target |
## 3. `app/` application architecture
### 3.1 Root files
| File | Responsibility | Must call | Must not do |
| --- | --- | --- | --- |
| `app/__init__.py` | package/version identity | — | startup side effects |
| `asgi.py` | FastAPI lifecycle, middleware, `/healthz`, `/readyz`, CORS, exception mapping | `bootstrap`, root router, health, telemetry | provider calls, direct engine import, business transactions |
| `router.py` | compose domain routers only | `domains/*`, capabilities/launch | controller/business/provider logic |
| `bootstrap.py` | resolve backend/engine/assets/runtime paths; create runtime dirs | filesystem only | request auth, DB, provider SDKs |
### 3.2 `app/config/`
```text
config/__init__.py public configuration import boundary
config/config.py TOML + environment precedence and fail-closed defaults
```
`config.py` is the only source for runtime setting resolution. It owns all
environment overrides for providers, R2, Neon, Redis, Sentry, launch gates, and
payment rails. New features add typed accessors/settings sections here; domain
modules consume configuration but never read ad hoc environment variables except
the narrow bootstrap path overrides.
### 3.3 `app/core/`
| Files | Ownership |
| --- | --- |
| `auth/principal.py`, `clerk.py` | normalize Clerk/API key caller into one principal; domains authorize it |
| `idempotency.py` | reusable reservation/replay primitives for all create commands |
| `capabilities/router.py`, `capabilities/service.py` | authenticated client feature/model/runtime capability document |
| `launch/policy.py`, `launch/router.py` | fail-closed signup/checkout/publish gates and public safe status |
| `observability/correlation.py` | correlation ID ingress/egress and worker propagation |
| `product_inventory.py` | safe engine/assets/runtime/tool availability summary; no engine model import |
Future core additions belong here only when used across domains: `errors.py`,
transaction helper, event envelope, and policy evaluator. Feature-specific logic
does not go into `core`.
### 3.4 `app/platform/`
```text
platform/storage/r2.py canonical R2/S3 client, presign, healthcheck
platform/queue/ planned: dispatch/routing primitives
platform/cache/ planned: Redis locks, state, rate policy base
platform/media/ planned: ffmpeg/ffprobe wrapper
platform/providers/ planned: common provider adapter and catalog client base
```
`platform/storage/r2.py` is the active canonical storage module. The legacy
`services/storage/r2.py` remains an exact import compatibility alias until all
callers migrate. New code uses only `platform/*` modules for infrastructure.
### 3.5 `app/models/`
| File | Role | Migration direction |
| --- | --- | --- |
| `schema.py` | cross-route Pydantic DTO compatibility collection | move new domain DTOs to `domains/<name>/schemas.py`; re-export while clients migrate |
| `const.py` | states, queue/pipeline constants | split domain constants where ownership is clear |
| `exception.py` | stable API error/envelope mapping | retain globally |
| `llm_provider.py` | legacy/model provider registry | become catalog adapter input, not client selectable directly |
| `db/base.py` | SQLAlchemy engine/session | shared platform persistence boundary |
| `db/models.py` | existing ORM tables | incrementally split modules by domain but preserve Alembic table identity |
| `db/repositories.py` | existing query/locking layer | move repositories behind domain public modules; retain aliases temporarily |
No client DTO, price, wallet field, or provider credential should be introduced
only in the giant `schema.py`/`models.py` files after the catalog/wallet domains
exist. Add it in its domain and expose additive compatibility imports.
## 4. Domain and controller migration map
### 4.1 Canonical domain folders
Every domain follows this internal shape as it is migrated:
```text
domains/<domain>/
├── __init__.py public imports only
├── router.py HTTP → schema/service mapping
├── schemas.py request/response models
├── repository.py DB queries/locked writes
├── service.py transaction + business behavior
├── policy.py pure access/cost/retry decisions
└── providers/ only for outbound provider protocols
```
| Domain | Routes/files it absorbs | Worker connection |
| --- | --- | --- |
| `reels` | `controllers/v1/jobs.py`, relevant studio reel actions, `services/reelforge.py` | reel DAG stages |
| `broll` | `broll_studio.py`, B-roll portions of `services/broll.py`/`broll_gen/*` | generation queue |
| `media` | upload/presign/file access, `preview.py`, artifact access | upload/R2 only |
| `editor` | editor export services and media mutations | render queue |
| `catalog` | `catalog.py`, templates/music/model-profile catalog | read-only + quote generation |
| `wallet` | future wallet ledger/reserve/settlement | create pre-dispatch + terminal settlement |
| `billing` | `billing.py`, `subscriptions.py`, `invoices.py`, `usage.py` | payment webhooks/reconciliation |
| `routing` | future provider/model selection, `llm_provider.py` bridge | all provider jobs |
| `publishing` | `studio.py`, `connections.py`, `schedule.py`, `calendar.py`, `social.py` | publish/scheduled jobs |
| `identity` | `me.py`, `sso.py`, `scim.py`, `security_policy.py` | auth/provisioning |
| `workspaces` | `workspaces.py`, `rbac.py`, `audit.py` | shared-credit/workspace policy |
| `creator` | `brand.py`, `voices.py`, `creators.py`, `notifications.py`, `performance.py` | creator assets/events |
| `content` | `ideas.py`, `covers.py`, social copy/caption catalog | generation helpers |
| `community` | `marketplace.py`, `share.py`, referral/profile surfaces | public-safe views |
| `developer` | `api_keys.py`, `developer.py`, `webhooks_admin.py` | outbound event delivery |
| `insights` | `analytics.py` | read models/rollups |
| `compliance` | `compliance.py`, `admin_compliance.py`, `admin.py` | retention/erasure maintenance |
| `legacy` | `video.py`, `llm.py` | contained only; no new product features |
### 4.2 Controller files that remain during migration
`controllers/base.py`, `controllers/v1/base.py`, `controllers/ping.py`, and
`controllers/manager/*` are transport/legacy helpers. They must not gain new
ReelForge domain behavior. Each `controllers/v1/<feature>.py` becomes a thin
compatibility adapter that imports its domain router/service until clients have
moved; root routing already composes domains, never controllers directly.
`controllers/v1/pilot.py` and `controllers/v1/jobs.py` are compatibility
aliases around `core/capabilities` and `domains/reels`; avoid duplicate policy
implementations.
## 5. `app/services/` complete disposition
Services are currently a mixed legacy/shared layer. Their future role is shown
below; this prevents deleting useful capabilities while eliminating ownership
ambiguity.
| Service file/group | Destination owner | Production role |
| --- | --- | --- |
| `reelforge.py`, `cost_guard.py`, `job_idempotency.py`, `task_artifacts.py` | reels | reel stage orchestration, admission and recovery |
| `script/ugc.py`, `llm.py`, `translate.py`, `transcribe.py`, `subtitle.py` | reels/content/routing | script/language/subtitle stages |
| `tts/*`, `voice.py`, `avatar/*` | creator + reels/routing | voice/avatar provider adapters and stage work |
| `captions/*`, `compose/*`, `editing/*`, `cover.py`, `preview.py` | editor/reels/media | rendering/editing/preview |
| `broll.py`, `broll_gen/*` | broll | B-roll suggestions, provider job semantics, adapters |
| `bgm.py`, `bgm_ai.py`, `music.py`, `elevenlabs_music.py`, `sonilo.py` | content/reels/routing | music catalog and stage provider calls |
| `billing/*`, `subscriptions.py`, `invoicing.py`, `metering.py`, `entitlements.py` | billing + future wallet | verified payments/subscriptions/usage; wallet settlement becomes canonical spend path |
| `oauth_connect.py`, `crypto_tokens.py`, `publish.py`, `publishers/*`, `scheduler.py`, `calendar.py`, `upload_post.py` | publishing | encrypted OAuth, direct publish, schedules |
| `workspaces.py`, `rbac.py`, `audit.py`, `apikey_quota.py`, `security_policy.py`, `sso.py`, `scim.py` | workspace/identity/developer | access/governance |
| `analytics.py`, `insights.py`, `hook_performance.py`, `creators.py`, `referrals.py`, `marketplace.py`, `share.py`, `ideas.py`, `notifications.py`, `templates.py` | insights/creator/content/community | user/business features |
| `compliance/*`, `admin.py` | compliance | consent, export, erasure, retention, staff operations |
| `health.py`, `ratelimit.py`, `state.py`, `cache_manager.py`, `task.py`, `webhooks.py`, `webhook_subscriptions.py` | platform/core | shared operations; move by infrastructure responsibility |
| `material.py`, `material_cache.py`, `twelvelabs.py`, `video.py`, `webui_task.py`, `version_checker.py` | legacy/evaluation or content | retain only with explicit product owner; no hidden public flow |
| `storage/r2.py` | platform storage alias | no new behavior; delete only after import migration |
Every service invocation from a router should eventually become
`domain.router → domain.service → domain.repository/platform provider`, never
router → unrelated `services/*` direct calls.
## 6. Workers and telemetry
### 6.1 `app/workers/`
| File | Mandatory role |
| --- | --- |
| `celery_app.py` | queue names, task routing, retry defaults, beat schedule; no business decisions |
| `context.py` | immutable/merge-safe job context and correlation propagation |
| `pipeline.py` | reel DAG dependency graph and stage dispatch only |
| `tasks.py` | thin retry-aware task wrappers; delegate to domain service/engine facade |
| `__init__.py` | package marker only |
Future split: `reel_pipeline.py`, `generation_pipeline.py`, `editor_pipeline.py`,
and `maintenance.py`. Existing task names stay as aliases during deployment
migration so queued jobs survive worker rollout.
### 6.2 `app/telemetry/`
`events.py` writes job/audit events, `progress.py` computes monotonic stage
progress, `cost.py` records normalized provider cost, and `sentry.py` initializes
process telemetry. All API/worker/client events carry correlation ID. Telemetry
may fail open for a render, but it must never silently drop a wallet settlement
or provider usage record—those are domain persistence transactions.
## 7. `app/generation/` disposition
```text
generation/app.py, config.py, dependencies.py
generation/routers/*
generation/schemas/*
generation/tasks/*
```
This is the inherited Pixelle/internal generation application. It has useful
implementation code for clips, frames, images, LLM, TTS, resources, files, and
tasks, but it is **not mounted by `app/asgi.py`**.
Plan for every file here:
1. Extract reusable pure functions behind `engine/reelforge_engine` or a
product domain provider adapter.
2. Keep its routers accessible only to explicit local/evaluation tooling while
migration is active; never proxy public client traffic to them.
3. Map `routers/clip.py` and `tasks/*` to generation-worker pipeline adapters;
map files/resources/template access to `assets` and `platform/storage`.
4. Move public request schemas into catalog/B-roll/media/reel domain schemas.
5. When all callable behavior is extracted, leave a documented compatibility
launcher or remove it in a separately approved cleanup—not a silent delete.
## 8. `engine/` complete architecture
### 8.1 Engine root files
| Files | Role/disposition |
| --- | --- |
| `reelforge_engine/contracts.py`, `registry.py`, `runtime.py`, `pipelines/managed_video.py` | **active private product facade**: typed request/result, allowlisted pipeline, four-layer runtime profile |
| `inference.py`, `hunyuan.py`, `vace_*`, `framepack_utils.py`, `clip_vision.py`, `dit_common.py` | GPU inference implementations; admit one at a time through product pipeline adapters/manifests |
| `service.py`, `registry.py`, `bucket_tools.py`, `memory.py`, `thread_utils.py`, `tts_voices.py`, `llm_presets.py` | legacy engine support; wrap only needed functions in facade, otherwise evaluation-only |
| `hf_login.py` | operator model-fetch utility only; never API request path or repository secret source |
| `pyproject.toml` | GPU dependency boundary; used only by generation image |
| `README.md` | engine contract and supported/pending capability inventory |
### 8.2 Engine directories
| Directory | What it contains | Product use plan |
| --- | --- | --- |
| `acceleration/` | checkpointing, distributed communication, shardformer | GPU-only model optimization; `product_runtime.py` advertises policy; enable per approved pipeline only |
| `pipelines/` | standard/custom/asset/linear/LTX/diffusion orchestration | private implementations; `managed-video` is product facade; expose selected capabilities through catalog only |
| `k_diffusion/` | samplers/wrappers | GPU sampling internals; no client parameters beyond reviewed quality profile |
| `models/` | Wan/LTX/Hunyuan/VAE/text/transformer implementations | model wrappers, not customer-visible checkpoints; approved weight/model map only |
| `annotators/` | depth, pose, mask, face, subject, segmentation, preprocessing | future B-roll/control-image preprocessing service; run in generation queue with consent/input policy |
| `prompts/` | narration/style/image/video/title prompt templates | curated server prompt assets; route through content/routing service with versioning |
| `config/` and `configs/` | engine config loader/schema and static preprocess/diffusion config | generation worker config only; translate selected values into immutable job snapshot |
| `datasets/` | dataloaders, video readers, samplers, transforms | offline evaluation/training/model QA only, never product request container |
| `schedulers/` | RF scheduling algorithms | generation worker pipeline internal; gate via model profile |
| `services/` and `services/api_services/` | legacy media/LLM/TTS/video/frame orchestration | extract direct provider calls into `app/platform/providers`; preserve only worker bridge until migrated |
| `utils/` | tensor/config/sampling/workflow/training helpers | use by engine only; `utils/train.py` is offline training, not deployed runtime |
The required rule is **not every engine file loads in every job**. It is that
each has an intentional, documented call path or evaluation/offline role; none
is orphaned or accidentally exposed.
## 9. `assets/` and `runtime/`
### 9.1 Immutable assets
| Path | Product owner/use |
| --- | --- |
| `assets/resource/fonts/*` + OFL notices | caption/cover render font catalog; license retained |
| `assets/resource/hooks/en.yaml`, `tr.yaml` | script UGC few-shot hook templates |
| `assets/resource/voices.yaml` | reviewed voice catalog; provider IDs only after workspace approval |
| `assets/bgm/default.mp3`, `resource/songs/*` | curated music/default fallback; catalog metadata and license review required |
| `assets/templates/<resolution>/*.html` | legacy/curated visual templates; migrate metadata to content catalog, render server-side only |
| `assets/workflows/manifests/*.yaml` | source/weights/license/approval authority for dispatch eligibility |
| `assets/workflows/runninghub/*.json` | candidate upstream workflow references; dispatch only with approved manifest |
| `assets/workflows/selfhost/*.json` | self-hosted workflow graphs; same immutable manifest requirement |
| `assets/resource/public/index.html` | legacy static resource; keep isolated from authenticated product pages or remove after separate review |
Assets are read-only in containers. New user uploads go to R2 through media
domain ownership, never into `assets/`.
### 9.2 Mutable runtime storage
```text
runtime/storage/
├── data/ temporary downloaded/provider inputs, generated local data
├── output/ transient renders/clips before R2 re-host
└── temp/ secure scratch files, removed after task completion
```
`bootstrap.ensure_runtime_directories()` and readiness own this layout. Workers
must clean task-scoped scratch output after successful R2 persistence or terminal
failure. Nothing under runtime becomes a client URL; results are registered as
assets/jobs and served using R2 signed URLs.
## 10. `tools/` and operational commands
| Tool | Disposition |
| --- | --- |
| `check_architecture_boundaries.py` | required local/CI architecture and manifest gate |
| `tools/ops/preflight.py` | production config/launch gate; never prints secrets |
| `tools/ops/deploy_smoke.py` | post-deploy health/ready/launch verification |
| `tools/ops/smoke.py` | hermetic in-process API route smoke |
| `tools/ops/seed.py` | local/dev demo seed only; forbidden production command |
| `tools/ops/cli.py` | legacy/operator CLI; refactor to call API/domain service, not duplicate behavior |
| `tools/ops/web.Dockerfile*` | local full-stack web harness only |
| `tools/gradio/*`, `tools/gradios/*` | GPU/model evaluation demos; no public auth, no production deployment, no client dependency |
The operator release path is: manifest/license review → `preflight.py` →
migrate → deploy API/workers → `deploy_smoke.py` → real provider golden jobs →
enable the next launch flag. Tools cannot alter wallet balances or provider
catalog approval without an audited domain command.
## 11. Build, deployment, and cleanup sequence
1. Keep CPU and generation Docker images separate; make engine imports fail in
CPU containers by construction.
2. Turn legacy controller/service paths into compatibility aliases one domain at
a time; preserve routes and queued task names.
3. Add catalog/wallet/routing domains before opening variable model pricing.
4. Classify every engine implementation as approved pipeline, evaluation-only,
or offline training. Add a manifest before enabling dispatch.
5. Add asset metadata/license records; do not treat a JSON workflow or MP3 as
automatically licensed/approved because it exists in the tree.
6. Move runtime cleanup/reconciliation into maintenance worker tasks.
7. Remove generated caches from the working tree and enforce `.gitignore`; do
not delete legacy sources until their call graph and compatibility window are
explicitly closed.
## 12. Architecture acceptance criteria
- API request process never imports a GPU model stack.
- Every public path is owned by a domain; controllers are adapters only.
- Every provider call goes through one adapter and records correlation/usage.
- Every file under `engine`, `assets`, `runtime`, and `tools` has one of the
explicit dispositions in this document.
- Candidate workflows and Gradio/Gradios demos cannot be reached by clients.
- Assets, runtime files, and R2 objects have separate immutable/mutable/owned
lifecycles.
- No client or operator tool bypasses API authorization, wallet reservation,
media ownership, or job state transitions.
## 13. Complete entry/exit contract for the requested API roots
This section makes the ownership boundary executable. An inbound dependency may
call a directory only through its stated entry point; it may receive only the
stated output. This stops the web, mobile, desktop, an old controller, or a
Celery task from reaching into arbitrary Python modules.
| Requested directory | Sole entry point | Inputs | Outputs | Consumers | Forbidden consumer |
| --- | --- | --- | --- | --- | --- |
| `app/` | ASGI router or a named domain service | authenticated HTTP command/query or worker context | stable API envelope, domain result, domain event | web, mobile, desktop, workers | GPU workflow/UI directly |
| `assets/` | catalog/asset manifest reader | approved asset ID/version | read-only template, prompt, font, music, workflow metadata | render/generation workers | direct client filesystem path |
| `engine/` | `engine.reelforge_engine` facade | immutable generation job snapshot | typed engine result, artifact paths, engine metrics | generation worker only | ASGI router, browser/mobile/desktop |
| `runtime/` | task-scoped runtime workspace helper | job ID and signed/local input | temporary paths only | workers | API response/client |
| `tools/` | documented CLI module or CI command | explicit operator arguments/config | report, smoke result, or local fixture | CI/operator | application router or production client |
The one sanctioned vertical path is:
```text
client → /api/v1 domain router → domain service/policy → repository + wallet
→ queue message with immutable JobSnapshot → generation worker
→ engine.reelforge_engine → runtime task directory → R2
→ domain state/event → signed result URL returned to client
```
## 14. `app/` leaf-directory ownership map
| Directory/files | Canonical responsibility | Calls allowed | Migration rule |
| --- | --- | --- | --- |
| `config/{__init__,config}.py` | validated runtime settings, secret references, deployment modes | all backend processes | never read feature environment variables elsewhere |
| `controllers/{base,ping,manager/*}` | transport utilities, ping, legacy memory/Redis helpers | ASGI only | no feature business logic |
| `controllers/v1/*.py` | compatibility HTTP adapters for every existing v1 path | matching `domains/*` public API | retain response/path compatibility; add no new implementation |
| `core/auth`, `core/clerk.py` | request/API-key/Clerk identity to principal | routers/policies | no provider-specific user logic |
| `core/idempotency.py` | reusable command replay/lock rule | all state-creating domain services | wallet/job commands must use it |
| `core/capabilities/*`, `core/product_inventory.py` | client-safe availability/catalog capability view | authenticated clients | report only, never launch workloads |
| `core/launch/*` | launch mode and feature admission gates | public routers | fail closed before dispatch/payment/publish |
| `core/observability/*` | correlation propagation | ASGI/workers/providers | never make billing data best-effort |
| `domains/*` | authoritative product behavior | routers, workers through service interfaces | each gets schema/service/repository/policy incrementally |
| `domains/broll/{providers,workflows}.py` | B-roll provider selection and approved-workflow lookup | B-roll service/worker | `services/broll_gen/*` becomes compatibility only |
| `domains/editor/{schemas,service,workflows}.py` | editing request, deterministic edit policy, approved composition graph | editor/reel worker | never run FFmpeg in ASGI |
| `domains/media/{schemas,repository,service}.py` | upload, ownership, artifact metadata and signed access | all media-producing domains | R2 calls only via platform storage |
| `domains/reels/{schemas,policy}.py` | stable reel command/result and admission/retry/cost policy | jobs/reel service | worker stages do not redesign public schema |
| `generation/{app,config,dependencies}.py` | isolated legacy generation bootstrap | explicit local evaluation only | never mounted by ReelForge ASGI |
| `generation/routers/*` | legacy clip/content/files/frame/image/LLM/resources/tasks/TTS/video handlers | legacy app only | extract calls into domains/engine facade; preserve temporarily |
| `generation/schemas/*` | legacy transport DTOs | legacy app only | replace with domain or engine contracts |
| `generation/tasks/{manager,models}.py` | legacy task manager/state | generation-worker compatibility bridge | migrate terminal state to jobs/reels/B-roll domain |
| `models/{schema,const,exception,llm_provider}.py` | shared compatibility DTOs/constants/errors/provider bridge | domains/adapters | new types live in owning domain |
| `models/db/{base,models,repositories}.py` | DB session, existing table models, repositories | domain repositories | preserve table identity while splitting modules |
| `platform/storage/r2.py` | only R2/presign/health client | media/domain repositories | legacy `services/storage/r2.py` is alias |
| `services/*` | existing implementation inventory | domain services while migrated | no router reaches it directly |
| `telemetry/{events,progress,cost,sentry}.py` | append-only job telemetry/process reporting | ASGI/workers | ledger/payment writes remain transactional domains |
| `utils/{file_security,logging_utils,utils}.py` | shared safe parsing/log formatting/general pure helpers | backend only | no hidden provider or database work |
| `workers/{celery_app,context,pipeline,tasks}.py` | route work, carry immutable context, task wrappers | domain services + engine facade | cannot contain customer pricing/authorization policy |
### 14.1 Controller-to-domain completion order
The controller files are not discarded. Each remains an alias until its named
domain owns the command. This is the exact map for the current tree:
| Controller group | Domain public surface |
| --- | --- |
| `jobs`, `studio`, `broll_studio` | reels, B-roll, editor, media |
| `catalog`, `llm`, `video`, `covers`, `voices`, `brand`, `ideas` | catalog, routing, content, creator |
| `billing`, `subscriptions`, `invoices`, `usage` | wallet/billing |
| `connections`, `schedule`, `calendar`, `social` | publishing |
| `me`, `sso`, `scim`, `security_policy` | identity |
| `workspaces`, `rbac`, `audit` | workspaces |
| `analytics`, `performance` | insights |
| `marketplace`, `share` | community |
| `api_keys`, `developer`, `webhooks_admin` | developer |
| `compliance`, `admin_compliance`, `admin` | compliance |
| `pilot` | capabilities + launch |
| `notifications`, `creators` | creator/community notifications |
| `base`, `ping` | platform transport only |
## 15. Exact `engine/` module plan
All engine code is Python-private and is installed only into
`Dockerfile.generation`. `reelforge_engine` is the firewall between product
jobs and research/inference code.
### 15.1 The engine facade and root modules
| Paths | Role in the final system |
| --- | --- |
| `reelforge_engine/contracts.py` | versioned `GenerationJobSnapshot`, approved profile, progress and result DTOs; input to all engine runs |
| `reelforge_engine/registry.py` | map catalog model/profile IDs to an approved adapter; reject unapproved model/checkpoint values |
| `reelforge_engine/runtime.py` | build lightweight runtime profile from acceleration/pipeline/sampler/model layers; emit metrics |
| `reelforge_engine/__init__.py` | the only stable import surface for workers |
| `inference.py`, `hunyuan.py`, `vace_wan_inference.py`, `vace_ltx_inference.py` | model-family adapters invoked only after registry selection |
| `vace_pipeline.py`, `vace_preproccess.py`, `framepack_utils.py`, `clip_vision.py`, `dit_common.py` | family-specific preprocessing/inference internals; never route/API DTOs |
| `registry.py`, `service.py`, `bucket_tools.py`, `memory.py`, `thread_utils.py` | legacy helpers; wrap in facade or designate evaluation-only after call graph audit |
| `llm_presets.py`, `tts_voices.py` | server-side defaults; migrate user-selectable values to catalog/creator domains |
| `hf_login.py` | explicit model-cache provisioning tool; remove from job/runtime import graph |
### 15.2 `engine/acceleration/`
| File | Approved responsibility | Input → output |
| --- | --- | --- |
| `checkpoint.py` | checkpoint/activation-memory policy | approved model + profile → load/offload plan |
| `communications.py` | distributed worker communication primitives | rank/group → tensor/object exchange |
| `parallel_states.py` | process/device parallel state | worker topology → deterministic parallel configuration |
| `product_runtime.py` | reports enabled acceleration policy to facade | profile → serializable runtime metadata |
| `__init__.py` | explicit exports only | — |
No router, normal Celery worker, or client chooses device count, sharding, or
checkpointing. Those come from deployment/profile configuration held in the job
snapshot.
### 15.3 `engine/annotators/`
| Files | Product capability | Required guard |
| --- | --- | --- |
| `canvas.py`, `composition.py`, `layout.py`, `frameref.py` | composition/control-reference preparation | uploaded asset ownership and input retention rule |
| `depth.py`, `flow.py`, `gray.py`, `pose.py`, `scribble.py` | motion/structure conditioning | only profiles that declare the control input |
| `face.py`, `subject.py`, `salient.py`, `ram.py`, `gdino.py` | face/subject/object discovery | synthetic-media/biometric policy; do not store derived data by default |
| `mask.py`, `maskaug.py`, `sam.py`, `sam2.py`, `inpainting.py`, `outpainting.py` | segmentation and regional edit masks | asset consent, task-scoped scratch cleanup |
| `prompt_extend.py` | controlled prompt enrichment | prompt policy/routing service audit event |
| `common.py`, `utils.py`, `__init__.py` | pure shared annotation helpers/exports | no provider, DB, or HTTP calls |
These are not automatically enabled simply because the code exists. The
catalog profile declares which annotator chain runs and the B-roll/editor
policy verifies that each needed input is present and authorized.
### 15.4 `engine/config/` and `engine/configs/`
| Files | Responsibility |
| --- | --- |
| `config/loader.py` | load approved engine configuration from an immutable image/manifest, not a user file path |
| `config/manager.py` | merge deployment defaults with selected profile then freeze a job snapshot |
| `config/schema.py` | validate hardware/model/sampling fields and reject unknowns |
| `configs/common_preproccess.py`, `composition_preprocess.py`, `image_preproccess.py`, `prompt_preprocess.py`, `video_preproccess.py` | named preprocessing recipes referenced by a profile; pure, versioned, no HTTP/DB work |
| each `__init__.py` | narrow exports only |
The double spelling `preproccess` is kept for import compatibility. New files
use `preprocess`; aliases are removed only during a major internal engine
version migration.
### 15.5 `engine/datasets/`
| Files | Disposition |
| --- | --- |
| `aspect.py`, `bucket.py`, `sampler.py`, `parallel.py`, `pin_memory_cache.py` | offline training/evaluation batching and memory tuning |
| `dataloader.py`, `datasets.py`, `read_video.py`, `video_transforms.py` | offline data ingestion/transforms; may be reused by an explicit golden-set runner but never public jobs |
| `utils.py`, `__init__.py` | offline helper/export boundary |
These files must be packaged in a separate `engine-eval` image/extra. They are
not a request-time user-upload pipeline; production uploads are owned by media
and processed by approved annotator/pipeline adapters.
### 15.6 `engine/k_diffusion/`, `models/`, and `schedulers/`
| Paths | Role |
| --- | --- |
| `k_diffusion/uni_pc_fm.py`, `wrapper.py` | sampler implementation and model adaptation used by reviewed profile only |
| `k_diffusion/product_runtime.py` | sampler/runtime capability metadata for the facade |
| `models/hunyuan_video_packed.py` | Hunyuan packed-model wrapper |
| `models/media.py`, `progress.py`, `storyboard.py` | engine-local media/result/progress/storyboard structures; translate at facade boundary |
| `models/product_runtime.py` | model-family availability metadata |
| `schedulers/rf.py` | rectified-flow schedule algorithm; selected by profile, not client parameter |
| all `__init__.py` | narrow import exports |
### 15.7 `engine/pipelines/`
| File | Final responsibility |
| --- | --- |
| `base.py` | pipeline protocol: prepare → run → collect → clean up |
| `standard.py`, `custom.py`, `linear.py` | internal execution styles; enabled only by registry profile |
| `asset_based.py` | image/video/control-asset conditioning pipeline; media ownership check is done before it is called |
| `k_diffusion_hunyuan.py`, `pipeline_ltx_video.py` | specific approved model-family pipeline implementations |
| `crf_compressor.py` | post-process/compression policy; artifact metadata records codec/bitrate |
| `product_runtime.py` | pipeline capability metadata, without importing heavyweight optional modules |
| `__init__.py` | lazy imports and narrow exports so API images never load model code |
### 15.8 `engine/prompts/`
| Files | Final responsibility |
| --- | --- |
| `asset_script_generation.py`, `content_narration.py`, `topic_narration.py` | versioned script/narration prompt recipes |
| `image_generation.py`, `video_generation.py`, `style_conversion.py` | model-input prompt recipes selected by catalog profile |
| `title_generation.py` | title/copy prompt recipe |
| `__init__.py` | prompt registry export |
Prompt recipes receive validated domain fields and return a versioned prompt
artifact. They do not call an LLM themselves: outbound LLM calls belong in the
routing/provider layer so cost, safety, and retries are recorded.
### 15.9 `engine/services/`
| Files | Required disposition |
| --- | --- |
| `api_asset_analysis.py`, `api_media.py` | legacy bridge only; replace outbound API calls with domain/media service calls |
| `comfy_base_service.py` | Comfy workflow execution primitive behind B-roll provider adapter |
| `frame_html.py`, `frame_processor.py` | worker-only template/frame transform; join editor render pipeline |
| `history_manager.py`, `persistence.py` | engine run diagnostic/temporary history only; canonical job state stays in domains/repositories |
| `image_analysis.py`, `video_analysis.py` | generation/evaluation analysis stages; results are task-scoped unless explicitly persisted as user artifact |
| `llm_service.py`, `tts_service.py` | compatibility bridges; replace with platform provider adapters/creator services to centralize wallet usage |
| `media.py`, `video.py` | worker-only media transform primitives; no signed URL/auth logic |
| `__init__.py` | narrow exports |
### 15.10 `engine/utils/`
| Files | Final disposition |
| --- | --- |
| `cai.py`, `ckpt.py`, `config.py`, `diffusers_config_mapping.py`, `optimizer.py`, `torch_utils.py`, `skip_layer_strategy.py` | model loading/performance internals in generation image |
| `inference.py`, `sampling.py` | generation-only inference/sampling helpers |
| `content_generators.py`, `llm_util.py`, `prompt_enhance_utils.py`, `prompt_helper.py`, `prompt_refine.py`, `template_util.py`, `tts_util.py` | pure compatibility helpers; provider invocation must be moved out to routing adapters |
| `logger.py`, `misc.py`, `os_util.py` | local engine diagnostics/general utility; must not log prompts/credentials unredacted |
| `workflow_util.py` | validates/loads an approved asset workflow by manifest ID, never arbitrary JSON from request |
| `train.py` | offline training only; excluded from generation production image if it is not needed for serving |
| `__init__.py` | narrow exports |
## 16. Asset, runtime, and tool file contracts
| Files/directories | Owner and delivery rule |
| --- | --- |
| `assets/bgm/default.mp3`, `assets/resource/songs/output*.mp3` | content catalog records each filename, duration, checksum, rights territory and approval. The renderer receives an asset ID, not a source path. |
| `assets/resource/fonts/*` and `OFL-*.txt` | editor font registry maps safe font IDs to files and preserves licenses. Add licenses/rights records for non-OFL fonts before enabling them. |
| `assets/resource/hooks/{en,tr}.yaml` | versioned script-hook source; content service selects locale and records recipe version in reel metadata. |
| `assets/resource/voices.yaml` and `services/data/azure_voices.json` | creator/catalog import source; never expose provider voice IDs that are not enabled for a workspace/region. |
| `assets/resource/public/index.html` | legacy local static diagnostic only; not mounted as product landing/auth content. |
| `assets/templates/{1080x1080,1080x1920,1920x1080}/*.html` | immutable template source. Catalog exposes only approved templates and editor worker renders after sanitizing user fields. |
| `assets/workflows/{manifests,runninghub,selfhost}/*` | manifest is the approval authority. A raw JSON graph is inert until manifest, license, tested revision, provider target, cost profile and kill switch are present. |
| `runtime/storage/.gitkeep` | retains only directory in git. At runtime create `data/<job>`, `temp/<job>`, `output/<job>`; lifecycle task deletes them after R2 transfer/failure reconciliation. |
| `tools/check_architecture_boundaries.py` | CI-required import/path rule check. |
| `tools/ops/{preflight,deploy_smoke,smoke}.py` | deployment admissibility, post-deploy verification, hermetic route check. |
| `tools/ops/{cli,seed}.py` | explicit operator/local commands; `seed.py` never deploys to production. |
| `tools/ops/web.Dockerfile*` | local operational web harness only, not an additional customer-facing frontend. |
| `tools/gradio/{app,progress_bar}.py`, `tools/gradios/vace_*_demo.py` | engineering model demos. Bind locally/private network only and never share authentication, database mutation, or customer artifact URLs with public traffic. |
## 17. Directory-by-directory build sequence
1. Freeze `app/config`, `core`, `platform/storage`, models DB base, telemetry,
runtime workspace ownership, and worker context first. These are the shared
cross-domain foundation.
2. Finish `media`, `reels`, `B-roll`, and `editor` domains—the only path used
by web, mobile, and Rust desktop for upload → generate → poll → preview →
attach.
3. Move each listed `controllers/v1` file behind its domain adapter while
retaining the exact legacy URL/envelope until clients stop using it.
4. Make `reelforge_engine` the only worker-to-engine import. Put every model,
annotator, sampler and pipeline behind a manifest-backed registry profile.
5. Separate engine serving extras from `datasets`/`utils/train.py` evaluation
extras; make every `tools/gradio*` surface private.
6. Import all assets into a catalog manifest with checksums, license/approval
state and feature/model linkage; only then allow the catalog to advertise
them to clients.
7. Build wallet/catalog/routing before variable-provider public purchasing;
provider adapters consume a reservation and emit actual usage for settlement.