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
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.
557 lines
39 KiB
Markdown
557 lines
39 KiB
Markdown
# Menivor — Deep Enterprise Architecture
|
||
|
||
> **Status:** Planning document. This file describes intent and target structure. It does **not**
|
||
> override [`docs/reelforge/CURRENT_STATE.md`](./reelforge/CURRENT_STATE.md) or the live code.
|
||
> Measured baselines below were taken from the checked-out tree on 2026-08-24.
|
||
>
|
||
> **Naming:** *Menivor* is the product/brand. Many internal paths, Makefiles, and docs still use
|
||
> the original `reelforge` codename — treat `reelforge` and `menivor` as synonyms throughout.
|
||
>
|
||
> **2026-08-27 capability update:** The measured counts below remain the
|
||
> 2026-08-24 baseline, but Prism now persists owner-scoped provider handles in
|
||
> SQLite for restart-safe polling. API submit/poll/detail/timeline, web, mobile,
|
||
> and desktop now use one resumable generation DTO containing terminal error,
|
||
> held/actual/effective cost, correlation/provider ids, executor kind, Identity
|
||
> Lock binding, and nullable signed settlement evidence. The desktop local
|
||
> runtime projects its jobs into that DTO with `execution.kind=desktop_local`
|
||
> and never fabricates a charge or receipt.
|
||
|
||
Menivor is the flagship **demand feeder** in the Railyard portfolio: an AI UGC video generator
|
||
that turns a screen recording + a text prompt into a viral, vertical 1080×1920 reel with an
|
||
AI-written hook script, AI voice, a lip-synced avatar presenter, and CapCut-style karaoke
|
||
captions — optionally auto-published to TikTok / Instagram / YouTube Shorts. After the Railyard
|
||
extraction, Menivor = `apps/{api, web, mobile, desktop, prism-media-gateway}`, and it *consumes*
|
||
the shared rail (Mint settlement, Relay model gateway, Passport character consistency, Prism
|
||
media) across a hard network boundary.
|
||
|
||
---
|
||
|
||
## 1. What Menivor is + current state per app
|
||
|
||
### 1.1 The product in one paragraph
|
||
|
||
The core value loop is a five-stage render pipeline expressed as a Celery `chord`:
|
||
|
||
```
|
||
screen_recording.mp4 + prompt + language(tr|en) + avatar + voice
|
||
→ SCRIPT (Claude via litellm, structured JSON hooks)
|
||
→ TTS (ElevenLabs /with-timestamps — the single timing authority)
|
||
→ { AVATAR (HeyGen v2 / self-hosted LatentSync-RunPod) ‖ CAPTIONS (ASS karaoke, libass) }
|
||
→ COMPOSE (pure FFmpeg: chroma PiP + 3 layouts, hw-accel)
|
||
→ 1080×1920 MP4 (→ optional direct publish)
|
||
```
|
||
|
||
Around that core, Menivor has already grown into a full creator platform: a SPARK idea engine
|
||
fed by a Hook Performance Loop, creator analytics/BI, a template marketplace with win-score
|
||
ranking and remix trees, OAuth direct-publish, watermarked public share pages, creator
|
||
profiles + follow graph + leaderboards, public API keys with quotas, team workspaces, and a
|
||
studio suite (brand voice cloning, watermark, thumbnail generator, notifications, scheduled
|
||
publishing, AI captions/hashtags).
|
||
|
||
Menivor is built on top of MoneyPrinterTurbo (MIT) — it reused MPT's pipeline/state machine and
|
||
LLM/TTS plumbing and extended it into a production, SaaS-ready service.
|
||
|
||
### 1.2 Measured baseline (this is the honest maturity signal)
|
||
|
||
| App | Language / Stack | Source files | Source LOC | Maturity |
|
||
|---|---|---:|---:|---|
|
||
| **api** | Python 3.11 · FastAPI · Celery + Redis · SQLAlchemy 2 · Alembic | **812 `.py`** (2,002 total files) | **~170,074** | **Production-grade / mature.** 44 domains, 70 table mappings, 48 migrations, 247 OpenAPI paths / 281 operations, 3,308 passing tests. |
|
||
| **web** | Next.js 15 · React · TS · Tailwind · OpenNext/Cloudflare | **624 `.ts/.tsx`** | **~73,552** | **Broad but uneven.** 64 App-Router route groups, ~21 `src/features` slices, ~37 component groups, 83 web tests. Surface-complete, depth varies per route. |
|
||
| **mobile** | Expo · React Native · expo-router · TS | **328 `.ts/.tsx`** | **~50,446** | **Mid.** 11 feature slices, tab/capture/job/creator routers. Real capture→generate→job→media flow; not all web features mirrored. |
|
||
| **desktop** | Rust · GPUI · FFmpeg · 31 workspace crates | **99 `.rs`** | **~17,328** | **Early-mid, ambitious.** Clean command/reducer/worker architecture and a deep crate lattice (`rf-render-*`, `rf-compose`, `rf-ffmpeg`, `rf-encode`, `rf-capture`…), but most render crates are scaffold/skeleton depth. |
|
||
| **prism-media-gateway** | Python · FastAPI (standalone) | **7 `.py`** | **~567** | **Runnable durable slice.** 4 endpoints (`/v1/models`, `/v1/media/generations`, `/v1/generation`, `/healthz`), fail-closed auth, BYOK, shared Menivor adapters, and owner-scoped SQLite provider-handle recovery. Mint settlement remains owned by Menivor; arbitrage is later work. |
|
||
| **Total** | | **~1,870 source files** | **~311,967 LOC** | |
|
||
|
||
**Honest read of "real vs in-flight":**
|
||
|
||
- **api — real:** the render pipeline (`app/workers/pipeline.py` + `tasks.py` chord), wallet with
|
||
live Mint client (`domains/wallet/mint_client.py`), the media gateway with ~10 real
|
||
image/video provider adapters (`domains/gateway/`, `domains/routing/providers/`), canon +
|
||
characters consistency (`domains/canon`, `domains/characters`), billing, publishing, identity,
|
||
workspaces, RBAC/audit. This is a genuine, tested backend.
|
||
- **api — in-flight:** the `app/controllers/v1/` layer is an explicitly transitional transport
|
||
adapter shim being folded into domains (`domains/OWNERSHIP.md`); `domains/legacy` is
|
||
contained compatibility only; some domains (`community`, `compliance`, `creator`, `render`)
|
||
are thin router-only stubs whose logic still lives in `app/services/`.
|
||
- **web — in-flight:** several `app/*-lab` routes (hook-lab, trend-lab, retention-lab,
|
||
effects-lab, workflows-lab, filtergraph) are exploratory surfaces, not hardened flows.
|
||
- **mobile — in-flight:** feature parity with web is partial by design (creator-path focus).
|
||
- **desktop — in-flight:** the "render farm" crate lattice is mostly interface-depth; real
|
||
local GPU render is not yet the primary path (desktop currently submits jobs to the API).
|
||
- **prism — durable local slice:** runnable with restart-safe owner-scoped jobs;
|
||
multi-replica storage and standalone wallet ownership are not claimed.
|
||
|
||
The load-bearing division in api is **domain services vs the legacy `services/` + `controllers/`
|
||
shim**: the enterprise target (§2.1) is to complete the migration so `app/router.py` composes
|
||
domains only and `controllers/` / `services/` disappear.
|
||
|
||
---
|
||
|
||
## 2. Target enterprise structure per app
|
||
|
||
Design rules applied to every app: many small files (200–400 LOC typical, 800 hard max);
|
||
organize by feature/domain, not by type; one writer per artifact; clients talk only to
|
||
`/api/v1` through the generated contract (`packages/api-contract`) — never import backend code.
|
||
|
||
### 2.1 `apps/api` — FastAPI + Celery backend (target: domain-pure, ~1,100–1,400 files)
|
||
|
||
Complete the `controllers/` + `services/` → `domains/` migration so every domain is a self-
|
||
contained vertical slice with the **same five-file spine**:
|
||
|
||
```
|
||
app/domains/<domain>/
|
||
router.py # FastAPI transport only (validation, auth dep, envelope)
|
||
service.py # business logic, pure-ish, no FastAPI imports
|
||
repository.py # SQLAlchemy persistence (Repository pattern)
|
||
schemas.py # Pydantic request/response models
|
||
workflows.py # Celery orchestration / multi-step (where the domain owns jobs)
|
||
__init__.py
|
||
```
|
||
|
||
Target domain map (existing 44 domains, grouped into bounded contexts; new/renamed in **bold**):
|
||
|
||
```
|
||
app/
|
||
asgi.py bootstrap.py router.py # composition root: domains only
|
||
core/ # config, di container, errors, envelope, pagination, security primitives
|
||
platform/ # cross-cutting: storage(R2), cache, ratelimit, telemetry, audit, rbac, idempotency
|
||
domains/
|
||
# ── Generation bounded context (the pipeline) ──────────────────────────
|
||
reels/ # the core reel job aggregate: create, wallet_bridge, state
|
||
render/ # render orchestration + executor (fold in services/render/*)
|
||
script/ speak/ # SCRIPT stage (Claude) + voice/TTS (ElevenLabs) — promote from services/
|
||
captions/ # ASS karaoke authoring (thin today → full domain)
|
||
compose/ # FFmpeg composition domain (promote from services/compose)
|
||
avatar/ # **lift-sync avatar stage** (HeyGen / LatentSync-RunPod)
|
||
broll/ # AI B-roll generation + providers + workflows
|
||
film/ storyboard/ stories/ series/ motion/ clipping/ repurpose/ editor/
|
||
# ── Media & routing bounded context ────────────────────────────────────
|
||
gateway/ # unified /images + /videos media gateway + media_catalog + usage
|
||
routing/ # provider registry + policy + license_class + ~20 adapters
|
||
catalog/ # model catalog, presets, policy, seed data
|
||
byok/ # bring-your-own-key credentials (never persisted plaintext)
|
||
# ── Money bounded context ──────────────────────────────────────────────
|
||
wallet/ # Mint-settlement rail client + local micro-ledger fallback
|
||
billing/ spend/ # Stripe + iyzico credits, subscriptions, invoices, cost guard
|
||
clipmarket/ affiliate/ # payouts, commissions, referrals
|
||
# ── Identity & tenancy ─────────────────────────────────────────────────
|
||
identity/ # auth, SSO, SCIM, security policy, me
|
||
workspaces/ # multi-seat, RBAC (pycasbin), audit trail, invites/roles
|
||
developer/ # public API keys, webhooks, quotas
|
||
# ── Content, catalog & consistency ─────────────────────────────────────
|
||
canon/ characters/ # Passport-backed character consistency (identity_key content hash)
|
||
templates/ # marketplace: publish/clone/rate/remix trees + win-score
|
||
content/ creator/ community/ # brand, voices, profiles, follow graph, boards, share
|
||
# ── Distribution & insight ─────────────────────────────────────────────
|
||
publishing/ # OAuth connect + TikTok/IG/Shorts publish + schedule + calendar
|
||
trends/ growth/ insights/ ingest/ # SPARK ideas, hook-loop, analytics/BI, trends
|
||
compliance/ observability/ # policy, moderation, health, metrics
|
||
legacy/ # SHRINKING: contained MPT compat only, no new capability
|
||
workers/
|
||
celery_app.py context.py pipeline.py # the chord DAG assembly (canonical)
|
||
tasks/ # split monolithic tasks.py by stage:
|
||
script.py tts.py avatar.py captions.py compose.py upload.py series.py
|
||
verifiers/ # NEW: separate-context stage verifiers (§3.2)
|
||
models/db/ # 70 table mappings → keep per-context files; add characters/canon/gateway
|
||
mcp/ # MCP server surface (agent tool exposure)
|
||
telemetry/ events/ # event bus emitters (eventbus-types contract)
|
||
```
|
||
|
||
Enterprise additions the current tree lacks: `workers/verifiers/` (per-stage graders, §3.2),
|
||
a first-class `avatar/` domain (today folded in services), and finishing the `controllers/` +
|
||
`services/` teardown so the OWNERSHIP.md "canonical owner direction" column is fully realized.
|
||
|
||
### 2.2 `apps/web` — Next.js 15 creator workspace (target: ~700–850 files)
|
||
|
||
Keep the App-Router route groups as thin route shells; push all logic into `src/features/*`
|
||
vertical slices (already the established pattern — extend it to full coverage of the 64 routes).
|
||
|
||
```
|
||
apps/web/
|
||
app/ # route shells only (RSC + layout + loading/error)
|
||
(marketing)/ # public site
|
||
(app)/ # authed shell — group the 60 product routes
|
||
create/ new/ jobs/ render/ editor/ studio/ # generation
|
||
broll/ broll-library/ film/ motion/ characters/ avatars/ voices/ # assets
|
||
templates/ marketplace/ blueprints/ presets/ kit/ # marketplace
|
||
wallet/ billing/ spend/ usage/ # money
|
||
publish/ scheduled/ calendar/ connections/ # distribution
|
||
trends/ ideas/ insights/ performance/ leaderboard/ # insight
|
||
creators/ team/ agency/ brand/ referral/ # social/agency
|
||
developer/ models/ model-governance/ admin/ status/ # platform
|
||
*-lab/ # experimental (gate behind flags)
|
||
r/ # public watermarked share view
|
||
src/
|
||
features/<slice>/ # ~21 → ~40 slices, each:
|
||
components/ hooks/ api/ schemas/ state/ index.ts
|
||
shared/
|
||
api-client/ # generated SDK wrapper (packages/sdk-typescript)
|
||
auth/ billing/ media/ ui/ hooks/ lib/ config/ telemetry/
|
||
components/ui/ # design-system primitives (shadcn-style)
|
||
editor-bff/ editor-module/ # the timeline editor (keep isolated; heaviest surface)
|
||
middleware.ts # auth + tenant routing
|
||
```
|
||
|
||
Enterprise discipline: every route imports from exactly one feature slice; cross-feature reuse
|
||
goes through `shared/`; no `fetch` outside `shared/api-client`; contract types come from
|
||
`packages/api-contract` (generated, never hand-written).
|
||
|
||
### 2.3 `apps/mobile` — Expo creator client (target: ~450–550 files)
|
||
|
||
```
|
||
apps/mobile/
|
||
app/ # expo-router file routes (thin)
|
||
(tabs)/ capture/ job/ creator/ # + add: wallet/ publish/ templates/ trends/ insights/
|
||
src/
|
||
features/<slice>/ # 11 → ~18 slices, mirror api domains that matter on mobile:
|
||
reel-create/ reel-compose/ speak-studio/ broll-studio/ film-studio/
|
||
clip-market/ clipfarm-console/ jobs-library/ wallet-publish/ trends-feed/ experiments/
|
||
# + creator-profile/ notifications/ scheduled-publish/ character-passport/
|
||
<each>: components/ hooks/ api/ screens/ state/ index.ts
|
||
shared/
|
||
auth/ api/ billing/ media/ product/ lifecycle/ hooks/
|
||
capture/ # NEW: native screen/camera capture + upload handshake
|
||
offline/ # NEW: queue + resumable upload for flaky mobile networks
|
||
```
|
||
|
||
Mobile's north star is the **capture→generate→publish** loop with the same presign → R2 PUT →
|
||
ownership-register handshake as web/desktop, plus native capture and offline resilience that web
|
||
does not need.
|
||
|
||
### 2.4 `apps/desktop` — Rust/GPUI local render farm (target: ~250–350 files across ~35 crates)
|
||
|
||
The desktop app is where Menivor can do **local GPU render** (its enterprise differentiator).
|
||
The 31-crate lattice is the right shape; enterprise scale means giving each render crate real
|
||
depth and adding a distributed local render-farm layer.
|
||
|
||
```
|
||
apps/desktop/
|
||
src/ # GPUI app shell (command → reducer → worker)
|
||
app.rs main.rs
|
||
ui/ (shell, create, preview, media, library, components, settings, theme)
|
||
api/ config/ security/ domain/ workspace/ media/ telemetry/
|
||
crates/ # the render-farm workspace
|
||
# ── render core ───────────────────────────────────────────────────────
|
||
rf-render-core/ # DAG model of the pipeline, stage contracts
|
||
rf-render/ rf-render-cmd/ # render driver + CLI entrypoint
|
||
rf-compose/ rf-ffmpeg/ rf-encode/ # FFmpeg composition + encode (the heavy metal)
|
||
rf-captions/ rf-audio/ rf-effects/ rf-shots/ # per-stage crates
|
||
rf-capture/ # native screen capture
|
||
rf-hardware/ # **GPU/hw probe + capability negotiation** (deepen)
|
||
# ── farm & orchestration (the enterprise layer to build out) ──────────
|
||
rf-jobs/ rf-runtime/ rf-workflows/ rf-plan/ rf-preflight/
|
||
rf-render-farm/ # NEW: multi-node local render scheduling + work-steal
|
||
rf-sync/ # asset sync w/ R2 + resumable transfer
|
||
rf-provider/ rf-gateway/ # Prism/media-gateway client
|
||
rf-project/ rf-assets/ rf-comfy/ # project model, asset store, ComfyUI bridge
|
||
rf-clipfarm/ rf-trends/ rf-growth/ rf-insights/ # feature crates
|
||
rf-plugins/ rf-devproto/ rf-theme/ rf-testkit/
|
||
```
|
||
|
||
Enterprise gap to close: `rf-render-farm` (distributed local render + queue), real depth in
|
||
`rf-compose`/`rf-ffmpeg`/`rf-encode`/`rf-hardware`, and a clean split between "submit to cloud
|
||
API" and "render locally" modes selected by `rf-preflight` capability detection.
|
||
|
||
### 2.5 `apps/prism-media-gateway` — media gateway (target Sx1+: ~35–60 files)
|
||
|
||
Prism today is a compact durable SQLite slice. The enterprise target is a
|
||
multi-replica, wallet-settling media gateway with the same external contract:
|
||
|
||
```
|
||
apps/prism-media-gateway/prism_gateway/
|
||
app.py # FastAPI composition
|
||
auth.py # fail-closed key auth (SHA-256), BYOK passthrough
|
||
api/
|
||
models.py # GET /v1/models
|
||
generations.py # POST /v1/media/generations
|
||
generation.py # GET /v1/generation (poll)
|
||
health.py admin.py # /healthz + owner cost readback
|
||
routing/
|
||
catalog.py policy.py fallback.py # equivalent-model failover (consented)
|
||
adapters/ # image/video upstream adapters (share provider-adapter-kit)
|
||
billing/
|
||
wallet.py # NEW Sx1: Mint hold → settle → void (currently absent)
|
||
cost.py arbitrage.py # exact-cost readback + margin accounting
|
||
jobs/
|
||
store.py # extract existing durable SQLite port; add shared-store adapter
|
||
poller.py # async video polling
|
||
models.py config.py telemetry.py
|
||
tests/
|
||
```
|
||
|
||
Prism should converge with api's `domains/gateway` — ideally sharing `packages/provider-adapter-kit`
|
||
so there is one adapter implementation, two deployment surfaces (embedded in api, standalone as Prism).
|
||
|
||
### 2.6 OSS foundations — what to fork / build-on per app
|
||
|
||
Menivor's founding principle (from `THIRD_PARTY_NOTICES.md` and
|
||
`docs/reelforge/VENDORED-OSS.md`) is **adopt proven permissive OSS, port it into product source
|
||
with notices retained, and hard-exclude GPL/AGPL/no-license code** from the distributed tree
|
||
(`apps/api`, `apps/desktop`). The two foundations already ported are both MIT: **MoneyPrinterTurbo**
|
||
(the api backend + pipeline) and **OpenCut** (the web timeline editor). This section is the
|
||
forward-looking build-vs-reuse map per app, with the license risk called out explicitly.
|
||
|
||
**License-risk rule (grounded in the exclusions already made):** because `apps/desktop` is a
|
||
*distributed* binary and `apps/api` is proprietary, any GPL/AGPL code linked into them forces
|
||
open-sourcing. `elebumm/RedditVideoMakerBot` (GPL-3.0) and `Anil-matcha/...` (no LICENSE) were
|
||
already excluded for exactly this reason. The same test gates every new adoption below.
|
||
|
||
| App | Adopt / build-on | License | Fit | Reuse vs build |
|
||
|---|---|---|---|---|
|
||
| **api (pipeline)** | **MoneyPrinterTurbo** (already ported) | MIT | script→tts→subtitle→compose state machine, LLM/TTS plumbing | **Reused** — the backbone; extend, don't replace |
|
||
| api (clipping) | SaarD00/AI-Youtube-Shorts-Generator (ported) | MIT | long→short auto-clip orchestration | **Reused** into `domains/clipping` |
|
||
| api (trends) | davidteather/TikTok-Api, bellingcat/tiktok-hashtag-analysis (ported) | MIT | trends/sounds/hashtag pull + analysis | **Reused**, ToS-gated behind consent + allowlists |
|
||
| api (LLM/TTS I/O) | **litellm** | MIT | one interface over Claude + provider fan-out | **Reused** (already the script-stage client) |
|
||
| api (media models) | ComfyUI (`external/`) | **GPL-3.0 ⚠** | node-graph media generation | **Reference-only** — must stay a *separate service* behind an HTTP boundary (`rf-comfy`/`comfyui-deploy` pattern); NEVER linked into `apps/api` source |
|
||
| api (video diffusion) | Wan 2.2 (`external/Wan2.2`, `Wan2GP`) | Apache-2.0 | self-hosted text/image→video (Tier B) | **Build-on** — permissive, safe to port; already have a `wan_*` adapter family in `routing/providers` |
|
||
| api (video diffusion) | HunyuanVideo (`external/hyvideo`), VideoTuna, VideoX-Fun | **Non-OSI / mixed ⚠** | alt video backbones | **Reference / BYO-weights only** — Hunyuan uses a restrictive community license; do not assume Apache terms. Verify per-repo before porting |
|
||
| api (lip-sync avatar) | **LatentSync** (self-hosted, RunPod Tier B) | Apache-2.0 (verify weights) | lip-synced avatar when HeyGen SaaS is not used | **Build-on** — the documented self-host path; wrap as a provider adapter |
|
||
| **web** | **Next.js 15** | MIT | App-Router creator workspace | **Reused** (foundation) |
|
||
| web (editor) | **OpenCut** (already ported → `editor-module`) | MIT | timeline/NLE editor | **Reused** — the heaviest surface; keep isolated |
|
||
| web (UI) | Tailwind + shadcn/ui + Radix | MIT | design system primitives | **Reused** (`components/ui`) |
|
||
| web (deploy) | OpenNext / Cloudflare Workers | MIT/Apache-2.0 | edge deployment (`open-next.config.ts`, `wrangler.jsonc`) | **Reused** |
|
||
| **mobile** | **Expo + React Native** | MIT | capture→generate client | **Reused** (foundation) |
|
||
| mobile (nav) | expo-router | MIT | file-based routing | **Reused** |
|
||
| **desktop** | **GPUI** (Zed) | Apache-2.0 | native render workspace shell | **Reused** — Apache crate is safe even for a distributed binary (unlike GPL Zed app) |
|
||
| desktop (media) | **FFmpeg / libass** | **LGPL-2.1+ (⚠ GPL if built `--enable-gpl`)** | compose/encode/caption burn-in | **Reused with care** — dynamic-link LGPL build; **avoid `--enable-gpl` codecs (x264/x265) statically** in the distributed binary or the whole app goes GPL. Prefer LGPL-clean encoders or system FFmpeg |
|
||
| desktop (ML in Rust) | candle, mistral.rs, rig | Apache-2.0 / MIT | optional local inference in `rf-provider` | **Build-on** — permissive; shared with the Relay stack |
|
||
| **prism** | provider-adapter-kit + FastAPI | MIT/Apache-2.0 | media gateway | **Build** on the shared adapter kit (converge with `domains/gateway`) |
|
||
| **all — auth** | **Clerk** (proprietary SaaS, not OSS) | Commercial | auth/orgs/sessions across web/mobile | **Adopt as a service** — no license risk (SaaS), but a vendor dependency; keep behind `shared/auth` so it is swappable |
|
||
|
||
**SaaS providers (not OSS, no license risk — vendor-dependency risk instead):** Claude (script),
|
||
ElevenLabs (TTS + voice clone — the timing authority), HeyGen (avatar Tier A), Stripe + iyzico
|
||
(payments), Sentry (errors), Neon (Postgres), Cloudflare R2. Each is fail-closed and names its
|
||
missing env var at startup; keep each behind an adapter so it is replaceable.
|
||
|
||
**What Menivor consumes from Railyard's Apache platform (the most important reuse of all):**
|
||
Menivor does **not** rebuild model routing, wallet settlement, character identity, or media
|
||
generation from scratch — it consumes them from the sibling Railyard products over the network
|
||
(full detail in §5). The Railyard rail is itself built on permissive OSS: **Relay** is the
|
||
maintained **TensorZero** fork (Apache-2.0) plus rig / mistral.rs / candle; **Helicone ai-gateway
|
||
(GPL) was deliberately excluded**. So Menivor's model-rail, wallet, Passport, and Prism
|
||
dependencies are Apache/MIT-clean end to end. Build-vs-reuse verdict for these four: **always
|
||
reuse the rail, never fork it into Menivor** — forking would duplicate the settlement spine and
|
||
break the "one rail carries the money" invariant.
|
||
|
||
---
|
||
|
||
## 3. Graph engineering
|
||
|
||
Applying `~/.claude/skills/graph-engineering`: a **knowledge graph** (what Menivor remembers)
|
||
and a **task graph** (how Menivor's pipeline executes). Both carry **time + provenance** on every
|
||
edge, decided at modeling time (retrofitting provenance after fusion is impossible).
|
||
|
||
### 3.1 Menivor domain knowledge graph
|
||
|
||
Property-graph representation (the skill's default for products). Entities map ~1:1 onto the 70
|
||
SQLAlchemy tables; edges are the queries the platform actually runs.
|
||
|
||
**Competency questions this graph must answer** (the spec + test suite):
|
||
|
||
1. Which templates did a user fork, and what were the reel outcomes of the forks? (remix + win-score)
|
||
2. Which avatar/voice/character combination produced the highest-performing reels for a workspace?
|
||
3. For a given reel, exactly which providers were called, at what cost, settled on which wallet hold?
|
||
4. Which characters are *canon-locked*, and which published reels violate the canon hash?
|
||
5. What did a credit get spent on, transitively (job → stage → provider call → Mint settlement)?
|
||
6. Which hooks (from the Hook Performance Loop) actually win, ranked by self-reported outcome?
|
||
|
||
**Entities** (canonical-form rule: UUID primary identity; display names are aliases):
|
||
|
||
```yaml
|
||
entities:
|
||
User: {desc: authenticated creator/operator, ex: [usr_…]}
|
||
Workspace: {desc: multi-seat tenant, ex: [ws_…]}
|
||
Job: {desc: one pipeline run (reel/broll/film), ex: [job_…]} # the central aggregate
|
||
Reel: {desc: rendered 9:16 MP4 artifact, ex: [reel_…]}
|
||
Stage: {desc: pipeline stage instance script|tts|avatar|captions|compose|upload}
|
||
Template: {desc: reusable job config, publishable/forkable}
|
||
Avatar: {desc: presenter identity (HeyGen/LatentSync)}
|
||
Voice: {desc: TTS voice / cloned brand voice (ElevenLabs)}
|
||
Character: {desc: consistent identity, LoRA/identity_key} # Passport-backed
|
||
Canon: {desc: locked character/style version + canon_hash}
|
||
Provider: {desc: upstream model vendor call (Claude/ElevenLabs/HeyGen/Kling/Veo…)}
|
||
MediaJob: {desc: gateway image/video generation}
|
||
Publish: {desc: a distribution to TikTok/IG/Shorts}
|
||
Connection: {desc: OAuth social account (Fernet-encrypted token)}
|
||
Credit: {desc: purchased balance unit}
|
||
Wallet: {desc: microdollar balance + Mint account}
|
||
Settlement: {desc: a Mint hold→capture/release event}
|
||
HookOutcome: {desc: self-reported reel performance signal → win-score}
|
||
events:
|
||
Settlement: {trigger: reserve/capture/release, args: [wallet, job, hold_micros, actual_micros, at]}
|
||
Publish: {trigger: publish success/fail, args: [reel, connection, platform, at, status]}
|
||
Fork: {trigger: template clone, args: [parent_template, child_template, user, at]}
|
||
```
|
||
|
||
**Edges** (precise verbs, domain→range, every edge carries `{since/at, source, confidence}`):
|
||
|
||
```
|
||
(User)-[MEMBER_OF {role, since}]->(Workspace)
|
||
(Workspace)-[OWNS]->(Job) ; (Job)-[PRODUCED]->(Reel)
|
||
(Job)-[HAS_STAGE {order}]->(Stage) ; (Stage)-[CALLED {cost_micros, at}]->(Provider)
|
||
(Job)-[USED_AVATAR]->(Avatar) ; (Job)-[USED_VOICE]->(Voice) ; (Job)-[BOUND_TO]->(Character)
|
||
(Character)-[LOCKED_BY]->(Canon) ; (Reel)-[VIOLATES|CONFORMS_TO {canon_hash}]->(Canon)
|
||
(Job)-[INSTANTIATES]->(Template) ; (Template)-[FORKED_FROM {at}]->(Template) # remix tree
|
||
(Reel)-[PUBLISHED_VIA {platform, at}]->(Connection)
|
||
(Reel)-[REPORTED {win_score, at}]->(HookOutcome) ; (HookOutcome)-[RANKS]->(Template)
|
||
(Job)-[DEBITED {micros, reason}]->(Wallet) ; (Wallet)-[SETTLED_ON {hold_id}]->(Settlement)
|
||
(Settlement)-[ON_RAIL]->(Mint) # network boundary → Railyard
|
||
(User)-[FOLLOWS {since}]->(User) ; (User)-[RATED {stars, at}]->(Template)
|
||
```
|
||
|
||
**Provenance discipline (grounded in the code):** the `Settlement` edges mirror the real
|
||
`mint_client` semantics (reserve on create, capture measured actual on success, release on
|
||
failure; amounts are bare integer microdollars). `Canon` conformance edges mirror
|
||
`domains/canon` binding + `identity_key` content hash. The **Fork** and **HookOutcome→Template**
|
||
edges are the remix-tree + win-score ranking already in `domains/templates` + `domains/growth`.
|
||
|
||
**Serving it (GraphRAG for the SPARK idea engine):** the Hook Performance Loop is exactly the
|
||
graph-as-memory pattern — after each reel, extract the `HookOutcome`, fuse into the graph, and at
|
||
idea-generation time retrieve *paths* (`Template -FORKED_FROM-> … -REPORTED-> win_score`) rather
|
||
than dumping rows. Contradiction handling: a template's win-score changes over time; keep both
|
||
with timestamps, prefer newer at retrieval (facts change, the graph records the change).
|
||
|
||
### 3.2 The render pipeline task graph (the diamond, with verifier + human gates)
|
||
|
||
The code already implements the diamond (`workers/pipeline.py`): a Celery `chord` where
|
||
`group(avatar, captions)` fan out from `tts` and `compose` is the fan-in callback. Enterprise
|
||
target adds a **separate-context verifier** and **human gates on irreversible edges**.
|
||
|
||
```
|
||
┌─ AVATAR (HeyGen / LatentSync) ─┐
|
||
SCRIPT ──▶ TTS ──────────────┤ ├──▶ COMPOSE ──▶ [verify] ──▶ UPLOAD
|
||
(Claude) (ElevenLabs = └─ CAPTIONS (ASS karaoke) ───────┘ (FFmpeg) │ (publish)
|
||
single timing │
|
||
authority) ◄─ fan-out reads ONLY tts (real edge) │
|
||
▼
|
||
┌──────────────────┐
|
||
┌─ wallet.reserve (Mint hold, pre-flight) ── HUMAN/POLICY GATE ────────┤ separate-context │
|
||
│ │ VERIFIERS: │
|
||
│ on success: wallet.capture(actual) on failure: wallet.release │ • duration/AV │
|
||
└──────────────────────────────────────────────────────────────────────┤ sync correct? │
|
||
│ • captions match │
|
||
HUMAN GATE (irreversible edges): PUBLISH → TikTok/IG/Shorts, │ tts timestamps?│
|
||
REFUND, credit PURCHASE │ • canon conforms?│
|
||
└──────────────────┘
|
||
```
|
||
|
||
**Fake-edge audit (the skill's zero-cost first optimization):** avatar and captions both read
|
||
*only* `tts` output (`_SEED_REQUIREMENTS` in `pipeline.py` confirms both need
|
||
`audio_key/audio_url/audio_duration/words`) — so they genuinely parallelize; there is no fake
|
||
edge between them. `upload` is correctly appended only when the job requests ≥1 publish platform.
|
||
|
||
**Verifier separation (the non-negotiable node to add):** today compose→upload is direct.
|
||
Enterprise target inserts `workers/verifiers/` grading in a *separate context* with diverse
|
||
questions: (a) *is it correct?* — output duration = tts duration, AV in sync; (b) *is it
|
||
faithful?* — burned captions match the ElevenLabs word timestamps; (c) *is it compliant?* —
|
||
canon hash conforms, moderation passes. A model grading its own compose step misses its own
|
||
mistakes.
|
||
|
||
**The stop rule applied:** only `{avatar ‖ captions}` split (they never read each other). Everything
|
||
else — script→tts→compose→upload — is sequential and stays one owner, because each step needs the
|
||
full upstream picture. This is exactly what the code does; do not over-parallelize it.
|
||
|
||
**Human gates (put them where a mistake is expensive to undo):**
|
||
- **Wallet reserve** — policy/pre-flight gate before spend (already: `wallet_bridge` +
|
||
`cost_guard`).
|
||
- **Publish** — irreversible (a bad reel on the creator's TikTok). Gate before `stage_upload`.
|
||
- **Refund / credit purchase / template payout** — money leaving; Mint settlement + audit.
|
||
|
||
**Publish / monetization flow (a second task graph):**
|
||
|
||
```
|
||
Reel ──▶ [HUMAN GATE: approve publish] ──▶ resolve Connection (OAuth, Fernet-decrypt token)
|
||
──▶ platform adapter (TikTok/IG/Shorts) ──▶ Publish event ──▶ HookOutcome ingest
|
||
──▶ (Template win-score update) ──▶ feeds SPARK idea engine (graph-as-memory loop)
|
||
|
||
Monetization: Job ─reserve→ Mint hold ─(success)→ capture actual ─→ Ledgerline settlement
|
||
Clipmarket/affiliate ─→ payout ─→ Mint transfer ─→ receipt (AITP-402)
|
||
```
|
||
|
||
**Guardrails (from the skill):** every retry loop has a max round count (`pipeline.py` already
|
||
resumes at `failed_stage` or falls back to full re-run); one writer per artifact (each stage owns
|
||
its R2 key — `audio_key`, `avatar_key`, `ass_key`, `final_key`); routing lives in written steps
|
||
(the `REELFORGE_DAG` const), the model fills stages not the plan; hard cap on provider retries.
|
||
|
||
---
|
||
|
||
## 4. Scale reality
|
||
|
||
### 4.1 Current vs target file/LOC estimates
|
||
|
||
| App | Now (source files / LOC) | Target (files / LOC) | Primary growth driver |
|
||
|---|---|---|---|
|
||
| api | 812 / ~170K | ~1,100–1,400 / ~230K | finish domains migration, split `tasks.py`, add verifiers, first-class `avatar` |
|
||
| web | 624 / ~74K | ~750–850 / ~110K | full feature-slice coverage of 64 routes, harden `*-lab` surfaces, editor depth |
|
||
| mobile | 328 / ~50K | ~450–550 / ~80K | web-parity slices, native capture + offline queue |
|
||
| desktop | 99 / ~17K | ~250–350 / ~55K | real render-farm crates (`rf-render-farm`, deep compose/ffmpeg/encode/hardware) |
|
||
| prism | 7 / ~0.6K | ~35–60 / ~6K | durable jobs, Mint wallet settle, shared adapter kit, arbitrage |
|
||
| **Total** | **~1,870 / ~312K** | **~2,600–3,200 / ~480K** | |
|
||
|
||
(api's 2,002 *total* files incl. tests/fixtures/`__pycache__` is the true footprint; source `.py`
|
||
is 812 — that is the baseline to reason about.)
|
||
|
||
### 4.2 Done-ladder (per app, "when is it enterprise-done")
|
||
|
||
**L0 Seed** → **L1 Runnable slice** → **L2 Domain-pure & tested** → **L3 Multi-tenant hardened**
|
||
→ **L4 Enterprise (SLOs, verifier gates, observability, DR)**.
|
||
|
||
| App | Now | To reach L4 |
|
||
|---|---|---|
|
||
| api | **L3** | delete `controllers/` + `services/` shim; add `workers/verifiers/`; publish SLOs (success-only-billing already tracked); DR runbook |
|
||
| web | **L2–L3** | full slice coverage; flag-gate `*-lab`; a11y + Core Web Vitals budgets; contract-typed everywhere |
|
||
| mobile | **L2** | web-parity slices; offline/resumable upload; app-store review pass; native capture |
|
||
| desktop | **L1–L2** | build `rf-render-farm`; real local GPU render path; signed/notarized packaging |
|
||
| prism | **L1** | durable job store; Mint hold/settle/void; shared adapter kit; cost/health leaderboard |
|
||
|
||
---
|
||
|
||
## 5. Interop with Railyard (how Menivor consumes the rail)
|
||
|
||
Menivor is a **feeder** (per `docs/ROADMAP-SPINE.md`: "Relay, ReelForge, Prism are feeders — they
|
||
originate spend and route it onto the rail"). Every integration is a **network boundary** — no
|
||
client or feeder imports another product's code; they speak HTTP contracts and settle in
|
||
microdollars.
|
||
|
||
| Rail service | What Menivor consumes it for | Concrete integration in the code | Boundary contract |
|
||
|---|---|---|---|
|
||
| **Mint** (settlement spine — the durable asset) | Wallet holds + capture/release for every paid job | `domains/wallet/mint_client.py` — real `httpx` client to `mint-server /v1`; reserve on create, capture measured actual on success, release on failure. **ReelForge micros *are* Mint micros — no conversion.** Config-gated: `MINT_SERVER_URL` unset ⇒ falls back to local micro-ledger unchanged | Mint AP1 holds→capture/release; status codes 402/409/422/403 pass through; transport failure → clean 502 |
|
||
| **Relay** (OpenAI-compatible model gateway) | Routing LLM/inference spend onto the rail | `domains/routing/` (registry + policy + `license_class` + ~20 provider adapters) is the ReelForge-side of the model rail; Relay is the shared proxy Vend meters | OpenAI-shaped `/v1/chat/completions`; optional fail-closed Mint settlement |
|
||
| **Passport / Identity Lock** (character consistency) | Bind an exact locked identity version and its signed payment proof to generated media | `domains/gateway/identity_lock_client.py` resolves owner + provider conditioning + locked digest; `media_gateway.py` reserves/captures on Mint, commits the signed receipt before idempotent `/attest`, and exposes the binding through API/web/mobile/desktop contracts. Current production slice is video-only. | passport id + version + content digest + deterministic generation record + Mint receipt |
|
||
| **Prism** (media gateway) | Image/video generation with equivalent-model failover + BYOK | `domains/gateway/media_gateway.py` owns wallet settlement while standalone Prism durably owns provider handles. Both currently execute the reviewed Menivor adapters; extraction into `packages/provider-adapter-kit` remains the clean-boundary goal. | OpenAI-shaped `/v1/media/generations` + `/v1/generation` poll; microdollar cost cap; canonical resumable Menivor generation DTO at the product boundary |
|
||
| **Vend / Ledgerline / Abacus / Turnstile** (downstream of the rail) | Metering, revenue/COGS settlement, budget enforcement, AITP-402 paywall | Menivor's per-stage provider costs (`Stage -CALLED {cost_micros}-> Provider`) feed Ledgerline margin accounting; wallet settlements land as Vend/Mint ops | AITP-402; idempotent request-level settlement |
|
||
|
||
**The money path, end to end (network hops in bold):**
|
||
|
||
```
|
||
web/mobile/desktop ──/api/v1──▶ apps/api (reel job)
|
||
├─ wallet.reserve ──HTTP──▶ **Mint** (hold quoted max) [pre-flight gate]
|
||
├─ script stage ────HTTP──▶ Claude via litellm (or **Relay**) [Stage CALLED Provider]
|
||
├─ tts / avatar / media ─HTTP─▶ ElevenLabs / HeyGen / **Prism** gateway [Stage CALLED Provider]
|
||
├─ on success: wallet.capture(actual) ──HTTP──▶ **Mint** (→ Ledgerline COGS/margin)
|
||
└─ on failure: wallet.release ──────────HTTP──▶ **Mint** (no debit ever emitted)
|
||
```
|
||
|
||
For an identity-bound media job, the success branch is stricter: Menivor first
|
||
persists the signed Mint capture receipt, then attests the exact locked Passport
|
||
version and output. A crash between those operations resumes attestation from
|
||
the stored receipt and never captures a second time.
|
||
|
||
The invariant to preserve across the boundary (already enforced in `media_gateway.py`):
|
||
**a failed job emits the job counter but NEVER a wallet debit** — success-only billing. Any
|
||
enterprise change to the pipeline must keep that SLO intact, because it is what makes Menivor a
|
||
trustworthy feeder for the rail.
|
||
|
||
---
|
||
|
||
## Appendix — provenance of every number
|
||
|
||
All counts measured 2026-08-24 from the checked-out tree:
|
||
`find apps/<app> -name '*.py|*.ts|*.tsx|*.rs' | wc -l` and `… | xargs cat | wc -l`; api totals
|
||
cross-checked against `docs/reelforge/CURRENT_STATE.md` (247 paths / 281 ops, 70 tables, 48
|
||
migrations, 3,308 tests). Domain list from `apps/api/app/domains/`. Pipeline shape from
|
||
`apps/api/app/workers/pipeline.py`. Rail semantics from `apps/api/app/domains/wallet/mint_client.py`,
|
||
`domains/gateway/media_gateway.py`, `domains/canon/service.py`, and `docs/ROADMAP-SPINE.md`.
|
||
</content>
|
||
</invoke>
|