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

228 lines
12 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 — Architecture Restructure Plan (Domain-Driven)
> A CTO/architect plan to fix the repo's real structural debt: move from MPT's
> flat **layer-by-type** layout to **domain-by-domain vertical slices**, and
> shatter the god-files. Companion to [`ARCHITECTURE.md`](./ARCHITECTURE.md)
> (current) and [`ARCHITECTURE_NEXT.md`](./ARCHITECTURE_NEXT.md) (runtime target).
> Written 2026-08-13 against the real tree.
---
## 0. Honest reality check (before we act on assumptions)
Two premises in the request don't survive contact with the numbers — and one is
dead right. As your CTO I'd rather correct the map than march to the wrong target.
**"We have very few files / minimal frontend + backend."** Measured:
| Area | Files | Note |
|---|---|---|
| Backend `app/*.py` | **131** | + **79** test files = 210 Python files |
| Web `.ts/.tsx` | **246** | 175 components, 30 routed pages |
| Mobile `.ts/.tsx` | **147** | 22 screens, 115 components |
| **Total source** | **~600 files, ~50k backend LOC** | |
That is **not** a minimal codebase — it's a mid-size product. The *perception* of
"few files" comes from a real problem: there are only **8 top-level `app/` folders**
and one of them (`app/services/`, **74 files**) is a flat dumping ground, so the
structure *looks* shallow from the outside even though the content is deep.
**"Each directory should have 400–500 files."** This one I'd push back on. File
count per folder is **not** a quality metric — cohesion and coupling are.
400–500 files in one directory is itself an anti-pattern (it's what `app/services/`
is *becoming*). The right target is **10–30 cohesive files per domain module**.
Good news: decomposing the god-files (below) *naturally* takes us from ~600 to
~900+ files — more, smaller, well-named files — without inventing busywork.
**"The structure is wrong."** ✅ **Correct, and it's the highest-value refactor on
the board.** The repo inherited MoneyPrinterTurbo's **layer-by-type** layout
(`controllers/`, `models/`, `services/` all flat). Everything from analytics to
avatars to billing to marketplace lives side-by-side in one `services/` folder,
and the data layer is two monster files. That's the debt worth paying.
---
## 1. The real structural debt
### 1a. `app/services/` is a 74-file flat namespace
Analytics, avatar, billing, captions, compose, marketplace, community, publishing,
TTS, AI — all flat siblings. To understand "the reels domain" you grep across 74
files. No module boundaries, so no enforced dependency direction.
### 1b. Twelve god-files break your own 800-line rule
Your global standard is *200–400 typical, 800 max*. Twelve files blow past it:
| Lines | File | Why it's a problem |
|---|---|---|
| **3666** | `app/models/schema.py` | *Every* feature appends Pydantic models here → the #1 merge/​workflow-race bottleneck |
| **2961** | `app/models/db/repositories.py` | Same — every domain's repository in one file |
| 1829 | `app/services/voice.py` | TTS + clone + timing all in one |
| 1767 | `app/controllers/v1/jobs.py` | The job controller does everything |
| 1434 | `app/services/reelforge.py` | Pipeline orchestration + all stage glue |
| 1372 | `app/services/video.py` | Legacy MPT render path |
| 1355 | `app/services/compose/compose_ffmpeg.py` | Whole compose graph |
| 1309 | `app/services/task.py` | Legacy MPT task engine |
| 1211 | `app/models/db/models.py` | All 22 tables in one file |
| 988 | `app/services/material.py` | MPT stock path (Phase-5e: slated for deletion) |
| 976 | `app/services/llm.py` | All LLM prompts + client |
| 920 | `app/services/billing/service.py` | 4 providers' dispatch |
### 1c. This directly caused the pain we've felt all session
Every feature workflow had to **serialize** its edits to `schema.py` + `router.py`
+ `repositories.py` because they're single shared files — that's why "the API
agent is the single owner of schema.py/router.py" appears in every workflow. **A
domain layout removes that bottleneck**: each domain owns its own `schemas.py` /
`repository.py` / `router.py`, so N features can be built fully in parallel with
zero shared-file contention. The refactor pays for itself in build throughput.
---
## 2. Target architecture — domain-driven vertical slices
Honoring your naming intent (`core`, `reels`, `videos`, `photos`, `ai`, `analytics`,
domain-by-domain), the target:
```
app/
├─ core/ # cross-cutting foundation (no domain logic)
│ ├─ config/ # pydantic settings (was app/config)
│ ├─ db/ # engine, session, Base, mixins (was models/db/base)
│ ├─ security/ # auth (verify_token), api-key hash, crypto_tokens
│ ├─ errors/ # HttpException, error envelope
│ ├─ telemetry/ # sentry, cost, tracing (was app/telemetry)
│ ├─ ratelimit/ cache/ # ratelimit.py, cache_manager.py, state.py
│ └─ http/ # utils.get_response envelope, new_router
├─ platform/ # infra adapters (talk to the outside world)
│ ├─ storage/ # R2 (was services/storage)
│ ├─ queue/ # celery_app, context (was app/workers plumbing)
│ ├─ ffmpeg/ # shared ffprobe/ffmpeg runners
│ └─ llm/ # litellm client (prompts live in domains/ai)
├─ domains/ # ← the product, one folder per bounded context
│ ├─ reels/ # THE pipeline: params, orchestration, stages, retry
│ │ ├─ models.py schemas.py repository.py service.py router.py
│ │ └─ stages/{script,tts,avatar,captions,compose,upload}.py
│ ├─ videos/ # compose graph, render, effects, editing/silence_cut
│ ├─ photos/ # covers, thumbnails, watermark (Pillow)
│ ├─ voice/ # elevenlabs, timestamps, voice_clone (split voice.py)
│ ├─ avatar/ # heygen, latentsync_runpod
│ ├─ captions/ # ass_karaoke, words, presets
│ ├─ ai/ # script/ugc, llm prompts, ideas/spark, translate, twelvelabs
│ ├─ media/ # broll, material_cache, music, bgm, sonilo
│ ├─ marketplace/ # listings, remix, ratings, templates
│ ├─ analytics/ # analytics, insights, hook_performance
│ ├─ community/ # creators, follows, share, referrals, notifications
│ ├─ publishing/ # oauth connect, publishers, scheduler, webhooks, upload_post
│ ├─ billing/ # stripe/iyzico/creem/polar, credits, quotas, plans
│ └─ workspaces/ # teams, members, shared pool
└─ api/ # thin aggregation: mounts every domains/*/router.py
```
**Rules the layout enforces:**
- **Dependency direction:** `domains/ → platform/ → core/`. Domains never import
each other's internals — only public `service.py` functions (or events). A
linter/import-check test guards this.
- **Co-location:** a domain's models, schemas, repository, service, router, and
tests live together. "Where does marketplace live?" → one folder.
- **`core/` and `platform/` hold zero product logic** — swap R2 for S3, or Celery
for another broker, without touching a domain.
---
## 3. God-file decomposition (the mechanical win)
The two monsters map cleanly onto the domains and **kill the workflow-race
bottleneck**:
| God-file | Becomes |
|---|---|
| `models/schema.py` (3666) | `domains/*/schemas.py` — each domain's request/response models |
| `models/db/repositories.py` (2961) | `domains/*/repository.py` |
| `models/db/models.py` (1211) | `domains/*/models.py` (tables) + `core/db` shared mixins |
| `controllers/v1/jobs.py` (1767) | `domains/reels/router.py` + stage handlers |
| `services/reelforge.py` (1434) | `domains/reels/service.py` + `stages/*` |
| `services/voice.py` (1829) | `domains/voice/{service,elevenlabs,clone,timing}.py` |
| `services/video.py` + `task.py` (legacy MPT) | quarantine → delete once reels path fully owns render |
| `router.py` (flat include list) | `api/` mounts `domains/*/router.py` |
After this, **no single file is edited by more than one domain**, so the "single
owner of schema.py/router.py" serialization in every workflow disappears.
---
## 4. Migration strategy — incremental, tests stay green
A big-bang move of a **1709-test green** codebase is how you lose a week to import
hell. Do it as a **strangler**, one domain per PR, green after each:
1. **Scaffold** `app/core/`, `app/platform/`, `app/domains/` with `__init__.py`.
2. **Per domain (repeatable recipe):**
a. Create `domains/<x>/` and **move** its service/repo/model/schema/router files in.
b. Leave **import shims** at the old paths: `from app.domains.x.service import *`
(+ a `warnings.warn(DeprecationWarning)`). Nothing else breaks.
c. Update imports *inside* the moved files to the new paths.
d. Run the full suite — **must stay 1709 green** — + `alembic check` (moving a
table's class must not change the migration graph; keep `__tablename__`).
e. Commit. One reviewable PR per domain.
3. **Sweep** call sites off the shims domain-by-domain; delete each shim when its
last importer is gone.
4. **Enforce** with an import-linter contract test (`domains → platform → core`,
no cross-domain internal imports) so the structure can't rot back.
5. **Delete** the quarantined legacy MPT files (`video.py`, `task.py`, `material.py`
stock path — already Phase-5e-flagged) once `reels` fully owns render.
**Ordering (low-risk → high-value):** `core/` + `platform/` scaffold → leaf domains
with few cross-deps (`photos`, `captions`, `analytics`, `community`) → mid
(`marketplace`, `billing`, `publishing`, `voice`, `avatar`) → **`reels` last** (it
touches everything). Schema/repository shatter happens *as each domain moves*, not
as a separate mega-PR.
**Guardrails:** no `alembic` head/revision changes (pure code move); `__tablename__`
and column defs byte-identical; suite green + ruff clean per PR; import-linter test
added early so violations fail the local gate.
---
## 5. On "400–500 files per folder"
Reframed as the actual goal: **small, cohesive, single-responsibility files inside
clear domain boundaries.** The decomposition takes us from ~600 → ~900+ files
(schema.py alone becomes ~15 domain schema files; repositories.py ~15; each domain
gains explicit `router.py`/`service.py`/`repository.py`). That's the healthy kind
of "more files" — driven by cohesion, not a quota. A folder with 400 files would be
the same anti-pattern we're leaving behind.
---
## 6. Frontend depth (the "minimal frontend" note)
246 web + 147 mobile files isn't minimal, but the *web* app can mirror this
domain split for the same navigability win: today `web/components/` is 175 flat-ish
files. Target `web/{features,components,lib}/` with a `features/<domain>/`
(components + hooks + api-slice) per product area, matching the backend domains.
Same strangler approach; lower risk than the backend (no DB/migration coupling).
Mobile likewise groups `components/<domain>/`. This is a **fast-follow** after the
backend domains land, not a prerequisite.
---
## 7. What this unlocks
- **Parallel builds with zero shared-file races** — the biggest day-to-day win;
N domain workflows run fully concurrent (no more single-owner schema/router).
- **Enforced architecture** — dependency direction is testable, not tribal.
- **Faster onboarding + navigation** — one folder per bounded context.
- **Legacy deletion** — the strangler gives a clean seam to drop MPT's
`video.py`/`task.py`/stock-`material.py` once `reels` owns the render path.
**Cost/risk:** ~3–5 focused PRs of pure code movement, each kept green; near-zero
runtime risk (no behavior change, no migration change) if the shim discipline
holds. **Recommend scheduling this as Phase 8.5 — after the current in-flight
feature (auto-tighten) lands, before the next big feature wave** — so subsequent
features are *authored directly in the new structure* instead of being migrated later.
---
*Plan as of 2026-08-13, grounded in the real tree (~600 source files, 12 god-files
>800 lines, flat `services/` of 74). No code moved yet — this is the map. Execution
is a strangler migration, one domain per green PR, guarded by an import-linter test.*