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

345 lines
16 KiB
Markdown

# ReelForge — Developer / Contributor Guide
ReelForge is a UGC avatar-reel pipeline forked in-place onto MoneyPrinterTurbo
(MPT). It reuses MPT's `/api/v1` router, config loader, and TTS/compose helpers,
and adds Celery/Redis orchestration, SQLAlchemy 2 + Alembic on Neon/Postgres,
Cloudflare R2 object storage, a HeyGen talking-head provider, an ElevenLabs
`/with-timestamps` timing adapter, a Next.js web app, and an Expo mobile client.
This is the working guide for building, testing, and contributing to that slice.
For runtime setup see [`README.md`](./README.md); for the module/signature spec
see [`INTEGRATION_CONTRACT.md`](./INTEGRATION_CONTRACT.md); for the adversarial
security posture see [`SECURITY_AUDIT.md`](./SECURITY_AUDIT.md).
---
## 1. Repo layout
The fork keeps MPT's tree intact and adds the ReelForge subsystem alongside it.
The directories a contributor actually touches:
| Path | What lives there |
|---|---|
| `apps/api/app/` | The Python backend (FastAPI + Celery). See breakdown below. |
| `apps/web/` | `reelforge-web` — Next.js 15 App Router frontend (Clerk auth, Tailwind). |
| `apps/mobile/` | `reelforge-mobile` — Expo + `expo-router` thin client (upload → create → poll → play). |
| `tests/reelforge/` | The ReelForge pytest suite (3,312 collected tests at the 2026-08-22 snapshot). |
| `tests/golden/` | Golden-acceptance harness: `manifest.yaml` (10 reference jobs) + `acceptance.py` (pure assertions). |
| `migrations/` | Alembic: `env.py`, `script.py.mako`, and `versions/` (48 revisions at the 2026-08-22 snapshot). |
| `docs/reelforge/` | All ReelForge docs (this file, README, ARCHITECTURE, DATA_MODEL, CONFIG, SECURITY_AUDIT, STATUS, …). |
### `app/` internals
| Path | Role |
|---|---|
| `app/asgi.py` | ASGI entrypoint (`uvicorn app.asgi:app`); wires Sentry for the API. |
| `app/router.py` | Mounts the `/api/v1` controllers. |
| `app/controllers/v1/` | HTTP surface: `jobs.py`, `billing.py`, `studio.py`, `brand.py`, `workspaces.py`, `voices.py`, `catalog.py`, `covers.py`, `ideas.py`, `schedule.py`, `social.py`, `notifications.py`, `llm.py`, `me.py`, `video.py`. |
| `app/services/reelforge.py` | Stage functions (`stage_script/tts/avatar/captions/compose/upload`) + the R2 ownership guards. |
| `app/services/{script,tts,avatar,captions,compose,storage,billing}/` | Per-domain provider modules (the pipeline stages). |
| `app/workers/` | `celery_app.py`, `pipeline.py` (stage chain + retry), `tasks.py`, `context.py`. |
| `app/models/db/` | SQLAlchemy models, `base.py` (`get_session`), and `repositories.py` (row-locked money path). |
| `app/core/clerk.py` | Clerk JWT bridge (JWKS-cached `Authorization: Bearer` alongside `x-api-key`). |
| `app/telemetry/` | `sentry.py`, `cost.py` (per-job USD estimators), `events.py`, `progress.py`. |
| `app/config/`, `app/utils/` | Config loader and shared utilities (incl. `file_security.py`). |
---
## 2. Local setup
### The `.venv` light-dependency subset
The hermetic test suite runs against a Python **3.11** virtualenv at `.venv/`.
It carries the subset of `pyproject.toml` needed to import the ReelForge app
modules and drive the tests — FastAPI, SQLAlchemy 2 + Alembic, `boto3`,
`celery[redis]`, `psycopg`, Pydantic, plus the dev group (`pytest==9.1.1`,
`ruff==0.15.21`, `coverage`). The heavy media/ML dependencies MPT pins
(`moviepy`, `streamlit`, `faster-whisper`, `azure-cognitiveservices-speech`) are
**not** required to run `tests/reelforge` — the suite mocks providers and the
real-ffmpeg tests shell out to a system `ffmpeg` rather than a Python codec.
If you provision the venv yourself, the canonical resolver is `uv` against the
committed `uv.lock` (`uv sync`); `pyproject.toml` is the single dependency
source of truth.
### Hermetic test environment variables
The suite never touches a real database or bucket. Point it at an in-memory
SQLite DB and dummy R2 credentials so module import (which reads `R2_*` /
`NEON_DATABASE_URL` at boundary time) succeeds without live infra:
```bash
export NEON_DATABASE_URL='sqlite:///:memory:'
export R2_ACCOUNT_ID=x
export R2_ACCESS_KEY_ID=x
export R2_SECRET_ACCESS_KEY=x
export R2_BUCKET=x
```
> Note: `SELECT ... FOR UPDATE` row locking in the money path is a no-op under
> SQLite — the tests assert the *logical* invariants (no double-spend/refund);
> the lock's DB-level enforcement only holds on the production Neon/Postgres
> backend. See `SECURITY_AUDIT.md` § "Honest limitations".
---
## 3. Running the suite
Full ReelForge suite (`3,312 collected` at the 2026-08-22 snapshot):
```bash
NEON_DATABASE_URL='sqlite:///:memory:' R2_ACCOUNT_ID=x R2_ACCESS_KEY_ID=x \
R2_SECRET_ACCESS_KEY=x R2_BUCKET=x \
.venv/bin/python -m pytest tests/reelforge -q
```
Warnings you can ignore: pre-existing Pydantic v2 `class Config` deprecations
(`app/models/schema.py`) — informational, not failures.
The developer `Makefile.reelforge` wraps the common gates (it prefers `uv run`
when `uv` is on PATH, else the bare tool):
```bash
make -f Makefile.reelforge test # pytest
make -f Makefile.reelforge lint # ruff check app
make -f Makefile.reelforge fmt # ruff check --fix app && ruff format app
make -f Makefile.reelforge migrate # alembic upgrade head
make -f Makefile.reelforge golden # golden gate (see §5)
make -f Makefile.reelforge gate # local pre-push quality gate (see below)
```
### Local quality gate
Hosted GitHub Actions workflows cover build/deploy, security, performance,
release, and the broader app matrix. Run the following local pre-push gate too:
```bash
make -f Makefile.reelforge gate
```
The gate runs, in order: `ruff --select F,E9` against the backend, ReelForge
tests, and migrations; `pytest tests/reelforge`; `alembic upgrade head`; an
`alembic check` for model/migration drift; and the **synthetic** golden
acceptance suite. It always uses the synthetic golden suite, even if live
provider credentials are present, so routine checks never trigger paid renders.
Run `make -f Makefile.reelforge golden` separately when you intend to run the
credential-gated real 10-job render set.
### Lint gate — `ruff --select F,E9`
The blocking lint gate is the pyflakes (`F`) + syntax/runtime-error (`E9`)
subset, run across the backend, tests, and migrations:
```bash
.venv/bin/python -m ruff check --select F,E9 apps/api/app \
apps/api/engine/reelforge_engine tests/reelforge migrations
```
This catches undefined names, unused imports, and syntax errors without
enforcing the full style ruleset. `make -f Makefile.reelforge lint` runs the
broader `ruff check app`; `fmt` auto-fixes and formats.
### Alembic
Migrations live in `migrations/versions/` (48 revision files; current head
`e1f2a3b4c5d6`). Apply and
drift-check against Neon/Postgres:
```bash
.venv/bin/alembic upgrade head # apply to head
.venv/bin/alembic check # assert no model/schema drift
.venv/bin/alembic revision --autogenerate -m "add_x_column" # new migration
```
`alembic.ini` + `migrations/env.py` drive config; the worker does **not** run
migrations at boot (avoids migration races) — apply them out-of-band.
---
## 4. Golden acceptance harness (`tests/golden`)
The golden set encodes the CTO plan §8.1 Definition of Done for a finished reel:
`1080x1920`, H.264 + `+faststart`, ≥ 8 Mbps (real renders), duration window,
caption drift ≤ 50 ms, hook ≤ 2.5 s, avatar/audio duration delta ≤ 150 ms.
Two layers:
- **`tests/golden/acceptance.py`** — *pure* assertion helpers over an ffprobe
JSON dict or a word-timing array: `assert_resolution`, `assert_h264_faststart`,
`assert_min_bitrate`, `assert_duration_window`, `assert_caption_drift`,
`assert_hook_within`, `assert_avatar_audio_delta`, and `moov_precedes_mdat`
(a stdlib-only raw-MP4 scan for faststart, which ffprobe does not surface). No
third-party imports, no subprocess — import-safe on a media-less CI box.
- **`tests/golden/manifest.yaml`** — 10 reference jobs (5 Turkish + 5 English)
across the `pip` / `hook_intro` / `split` layouts, each with an `app_context`,
`prompt`, `language`, `target_duration_s`, `avatar_id`, `voice_name`, and the
per-job thresholds (YAML-anchored `&defaults`).
Two ways to run it, chosen by whether provider keys are present:
```bash
make -f Makefile.reelforge golden
```
- **Synthetic (hermetic default):** `tests/reelforge/test_golden_acceptance.py`
exercises every `acceptance.py` helper (pass + fail cases) plus a `lavfi`-
composed clip and a raw-MP4 faststart check. Always safe on a box with no
provider keys; this is the local pass/fail gate.
- **Real 10-job set:** when `ANTHROPIC_API_KEY`, `ELEVENLABS_API_KEY`, and
`HEYGEN_API_KEY` are all set, the target runs
`REELFORGE_GOLDEN_REAL=1 pytest -m integration ...` which renders real videos
end-to-end and asserts the 8 Mbps + drift/hook/Δ thresholds. Requires a
libass-enabled `ffmpeg`.
---
## 5. Real-ffmpeg integration tests (auto-skip without libass)
Several suites drive a real `ffmpeg`/`ffprobe` instead of mocking the
compositor — e.g. `tests/reelforge/test_compose_integration.py`,
`test_compose_smart.py`, `test_broll_concat.py`, `test_preview.py`,
`test_watermark.py`, `test_turkish_glyphs.py`. They are marked
`@pytest.mark.integration` and **auto-skip** on a machine that lacks the media
stack, so the hermetic suite stays green everywhere.
The skip gate is a module-level `pytestmark`:
```python
_FFMPEG = shutil.which("ffmpeg") or utils.get_ffmpeg_binary()
_REQUIRED_FILTERS = (...) # chromakey/geq/overlay/scale/crop/vstack, ass, ...
def _have_media_stack() -> bool:
return all(ffmpeg_has_filter(f, _FFMPEG) for f in _REQUIRED_FILTERS)
pytestmark = pytest.mark.skipif(
not _have_media_stack(),
reason="ffmpeg/ffprobe with the required filters not available",
)
```
`ffmpeg_has_filter` (`app/services/compose/compose_ffmpeg.py`) probes
`ffmpeg -filters` truthfully. **libass specifically:** caption burn-in needs an
ffmpeg built with `--enable-libass`. `test_compose_integration.py` includes a
preflight — `test_caption_request_without_libass_fails_fast` — asserting that a
caption request on a libass-less ffmpeg raises an actionable
`RuntimeError` matching `"libass"` rather than a cryptic crash; when libass *is*
present the captions burn and produce a real portrait video. So the
integration layer degrades cleanly: fully skipped without ffmpeg, and
fail-fast-with-a-clear-message on partial (libass-less) ffmpeg.
To run them locally you need a system ffmpeg with the required filters:
```bash
ffmpeg -buildconf | grep -- --enable-libass # confirm libass
.venv/bin/python -m pytest tests/reelforge -m integration -q
```
---
## 6. Web & mobile
### `web/` (Next.js 15 App Router)
TypeScript is `strict` with `noUncheckedIndexedAccess` + `noImplicitOverride`
(`web/tsconfig.json`). The type check runs as part of `next build`:
```bash
cd web && npm install
npm run lint # next lint (eslint-config-next)
npm run build # next build — type-checks + produces the production bundle
npm run dev # local dev server
```
### `mobile/` (Expo + expo-router)
```bash
cd mobile && npm install
npm run typecheck # tsc --noEmit
npm run lint # expo lint
npm run ios | android | web # expo start on a target
```
Both apps are `private` workspaces (`reelforge-web` / `reelforge-mobile`) and
talk to the same `/api/v1` surface.
---
## 7. Graph-engineering workflow method
ReelForge was built (and should be extended) with a four-phase
**graph-engineering** loop rather than linear top-to-bottom coding:
1. **Modules** — build each stage as an isolated, independently-testable module
with a pinned signature (script, tts, avatar, captions, compose, storage,
billing). Each has its own unit tests before it is wired to anything.
2. **Integrate** — compose the modules into the end-to-end Celery chain
(`app/workers/pipeline.py`), asserting the cross-module contracts
(`INTEGRATION_CONTRACT.md`) — notably the single-source-of-truth timing
handoff from ElevenLabs alignment to captions and avatar.
3. **Adversarial verify** — a hostile pass over the integrated graph that
actively tries to break invariants, run with **fresh-context verifiers** on
the highest-blast-radius paths: **money/credits**, **auth**, and **payment
webhooks**. A verifier starts with no memory of *why* the code was written so
it re-derives the invariant from scratch. Documented catches
(`STATUS.md` § "Adversarial hardening"): WF3 → 11 defects
(credit/retry TOCTOU, missing `retry_pipeline`, MIME allowlist, ass-path
escaping, monotonic progress, lazy-init race); WF8 → 7 defects in the money
path (Redis-down webhook double-grant TOCTOU, rate-limit key determinism,
§8 duration silent-bypass, publish idempotency, `image_key` ownership).
4. **Anchor** — pin the now-hardened behaviour with regression tests + a
written audit so it cannot silently regress. The security anchor pass over
`app/`, `tests/reelforge/`, `migrations/` is captured in
[`SECURITY_AUDIT.md`](./SECURITY_AUDIT.md); the DoD anchor is the golden set.
When you change any money/auth/webhook code, re-run phase 3 with a
fresh-context reviewer and re-anchor with a regression test named for the
invariant it protects.
---
## 8. Security posture (what to preserve)
The full adversarial audit is in [`SECURITY_AUDIT.md`](./SECURITY_AUDIT.md).
The three invariants a contributor must not break:
**Owner-scoped resources (IDOR / BOLA).** Jobs and brand assets are resolved
through owner-scoped repository lookups. Brand logos are guarded by
`_verify_logo_ownership` (`app/controllers/v1/brand.py`). Every *user-supplied*
R2 key reaching the compositor is guarded by **`_assert_owned_r2_key`**
(`app/services/reelforge.py:235`), which mirrors that guard: a key under the
`jobs/<ref>/` namespace is allowed only when `<ref>` is *this* job or another
job owned by the *same* user (resolved via `JobRepository`); non-`jobs/`
prefixes (e.g. `uploads/<uuid4>`) are user-scoped, non-enumerable namespaces and
short-circuit with zero DB hits (`_key_job_ref`). It **fails closed** — any
unresolvable cross-job reference (no DB, missing rows, transient error) is
rejected with `PermissionError`. It is wired *before* `_download_from_r2` in
`stage_compose` (violation → hard `ReelForgeStageError`) and inside the
best-effort watermark block in `_prepare_watermark` (violation → compose without
the overlay).
**Signature-verified, idempotent webhooks.** The credit-granting webhook path
requires an authentic provider signature: `verify_and_parse_webhook`
(`app/services/billing/creem_client.py`) recomputes HMAC-SHA256 over the **raw**
body with the config webhook secret and compares with `hmac.compare_digest`
(constant-time). A missing/invalid signature raises → 400, grants nothing
(**fail-closed**). Replay is blocked twice: a fast Redis `SETNX
billing:evt:<provider>:<event_id>` (TTL 30d) *and* a durable reason-encoded
ledger idempotency key (`_idempotent_grant`, `app/services/billing/service.py`),
so a duplicate event is a no-op even during a Redis outage.
**Row-locked, atomic money path.** Balance mutations in
`app/models/db/repositories.py` (`debit`/`grant`/`workspace_debit`/
`workspace_grant`) run under `SELECT ... FOR UPDATE` (`with_for_update()`).
Debit happens *before* enqueue and refunds run in isolated sessions, so a failed
enqueue cannot leave credits spent. Job-retry billing is routed to the funding
pool (personal vs workspace SHARED) via the earliest `CreditLedger` row for the
job (audit defect **D1**).
Boundary rules that back these up: the FFmpeg compositor never interpolates
untrusted strings into a shell (argv lists only) and escapes every path handed
to `-filter_complex` (`_escape_ass_filter_path`, `_escape_ffmpeg_concat_path`);
secrets come only from `config.*` / env and a missing webhook secret raises
rather than accepting unsigned events. Do not regress any of these; re-run the
`ruff --select F,E9` gate, the hermetic suite, and (for compositor changes) the
integration + golden gates before opening a PR.