caelum0x d56639a594
Some checks failed
build-images / web (push) Has been cancelled
vision2026-ci / Python SDK resource tests (push) Has been cancelled
build-images / api (push) Has been cancelled
build-images / worker-gpu (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Has been cancelled
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Has been cancelled
codeql / Analyze (javascript-typescript) (push) Has been cancelled
codeql / Analyze (python) (push) Has been cancelled
perf / API hot-path micro-smoke (budgeted) (push) Has been cancelled
perf / Desktop engine crates (release build check) (push) Has been cancelled
vision2026-ci / API phase modules (ruff + pytest) (push) Has been cancelled
vision2026-ci / Alembic upgrade + drift check (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Has been cancelled
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

47 KiB
Raw Permalink Blame History

infra/ + .github/ + docs/ — Cross-Cutting Infrastructure & Documentation IA (Vision 2026)

Scope. This document is the additive build plan for three cross-cutting concerns that no single app owns: (1) a NEW top-level infra/ tree (Terraform, Kubernetes/Helm, GPU render-worker packaging, GPU autoscaling, queue topology, observability, release/deploy orchestration, secrets); (2) the NEW .github/workflows/ CI/CD/security/release automation; and (3) the docs/ information architecture that houses every new spec produced by the other Vision-2026 architecture tracks (apps-*, external, reelforge/*).

Non-goals. This does NOT re-specify what exists: the four docker-compose*.yml stacks, apps/api/Dockerfile{,.generation}, docker/worker-entrypoint.sh, the Celery celery,render,generation queues, app/telemetry/{cost,events,progress,sentry}.py, the Alembic setup, the Neon / R2 / Cloudflare-Pages / EAS targets described in DEPLOYMENT.md, or the external/workers/* image source (owned by external.md). This plan is the deploy, scale, observe, and document layer around all of that.


0. Governing principles (constraints every file below obeys)

  1. infra/ is declarative and environment-parameterized. Every runtime fact (region, replica count, GPU pool size, secret ref) is Terraform variables or Kustomize/Helm values keyed by dev|staging|prod — never hardcoded. No product code imports from infra/; the boundary is images, manifests, and env.
  2. The real-time microdollar wallet stays authoritative. Autoscaling, queue routing, and cost dashboards observe the wallet/ledger; they never become a second source of billing truth. Lago (external/services/lago) is invoicing only.
  3. GPU capacity is the scarce, metered resource. Every render worker is an isolated image (external/workers/<cap>) deployed through infra/render-workers and scaled by infra/gpu-autoscale off queue depth + wallet-holds, never off raw CPU. Warm-pool cost is a first-class SLO.
  4. Success-only billing implies success-only scaling & alerting. Failed / queued / errored provider jobs never debit the wallet (product rule) and are tracked as a distinct SLI so a provider outage does not silently burn GPU budget.
  5. One async GPU job envelope, one telemetry schema. The IN_QUEUE → IN_PROGRESS → COMPLETED/FAILED envelope (from external/workers/_contract) is the only thing the autoscaler, queue router, and OTel spans key off — so a new model is observable and scalable with zero new infra code.
  6. License class gates deployment, not just dispatch. infra/render-workers refuses to build/deploy an image whose source licenses.yaml class is non-commercial/territorial into a commercial pool; it mirrors the catalog router's exclusion at the deploy layer.
  7. Everything ships through .github/. No manual terraform apply, no manual image push, no manual migration. PR-gated plan, protected-branch apply, signed images, SBOMs.
  8. Docs are versioned specs, not prose. Each subsystem gets a spec under a fixed IA with front-matter (status, owner, phase, supersedes) so the dozens of existing docs/reelforge/*.md files become a navigable, dedup'd tree instead of a flat pile.

1. What exists today (do not rebuild)

Path Role Seam this plan targets
docker-compose.reelforge.yml Product stack (db, redis, api, worker, beat, generation-worker, web) Becomes the local/dev profile; infra/ adds staging/prod topology
apps/api/Dockerfile, Dockerfile.generation CPU API image + CUDA generation image Built/pushed/signed by .github/workflows/build-images-*; base layers move to infra/docker
docker/worker-entrypoint.sh Worker bootstrap Reused; extended by infra/queues autoscaled worker manifests
Celery queues celery,render,generation Job routing infra/queues formalizes the topology + adds publish, ingest, film, captions queues
app/telemetry/{cost,events,progress,sentry}.py In-process metrics/cost/Sentry infra/observability scrapes/exports these; OTel collector fans out
alembic.ini + migrations/ Schema migrations infra/deploy/migrations adds the gated pre-deploy migration job
.env.reelforge.example, config.example.toml Config surface infra/secrets + infra/env template these per environment
scripts/reelforge-release-gate.sh, scripts/reelforge_bench.py Release gate + bench Invoked by .github/workflows/release.yml and perf.yml
docs/reelforge/*.md (40+ flat files) Existing plans/specs docs/ IA (section 6) indexes, buckets, and de-dups these
docs/reelforge/vision2026/architecture/{external,apps-desktop}.md Peer architecture tracks This doc is the cross-cutting sibling; section 6 defines where all tracks land

Convention seam: infra/ consumes images produced from external/workers and apps/*, deploys them to Cloudflare (edge/web), Neon (db), Upstash/managed Redis (broker), and RunPod + optional K8s (GPU), and wires OTel → Grafana/Sentry. .github/ is the only actuator. docs/ is the index of record.


2. New top-level layout (the three trees at a glance)

infra/                              # NEW — all deploy/scale/observe IaC & tooling
├── README.md  Makefile  .tool-versions  versions.tf  taskfile.yml
├── terraform/       # cloud resources: Cloudflare, Neon, Redis, RunPod, registry, DNS, WAF
├── k8s/             # Kustomize bases + per-env overlays + Helm charts
├── render-workers/  # GPU worker image build/publish/deploy manifests (consumes external/workers)
├── gpu-autoscale/   # queue-depth/wallet-driven GPU autoscaler + warm-pool controller
├── queues/          # Celery/Redis/KEDA broker topology, routing, DLQ, rate-limits
├── observability/   # OTel collector, Prometheus, Grafana, Loki, Tempo, Sentry, SLOs, alerts
├── deploy/          # release orchestration, blue-green, migration gates, runbooks
├── docker/          # shared base images + hardened runtime layers
├── secrets/         # SOPS/sealed-secrets/Vault policy + env manifests
├── env/             # per-environment declarative env-var + endpoint manifests
├── cdn/             # Cloudflare edge: cache rules, R2 lifecycle, signed-URL, Workers
├── dns/             # zone files + record manifests (source of truth)
├── policy/          # OPA/Conftest guardrails run in CI against plans & manifests
└── scripts/         # cross-cutting operational scripts

.github/                            # EXISTS (SECURITY.md, ISSUE_TEMPLATE) — add workflows
├── workflows/       # NEW — CI, CD, image build, terraform, security, release, docs
├── actions/         # NEW — composite/local actions reused across workflows
├── CODEOWNERS  dependabot.yml  labeler.yml  release-please-config.json
└── pull_request_template.md

docs/                               # EXISTS — impose an IA over the flat pile
├── README.md (nav index)  _meta/  reference/  guides/  runbooks/  adr/
└── reelforge/vision2026/           # architecture/ (exists) + specs/ diagrams/ data/ api/ …

3. infra/ — per-subsystem manifest

3.1 Root governance (infra/)

Path Responsibility
infra/README.md Entry map: what each subdir does, how to run a plan/apply, env matrix
infra/Makefile Thin task aliases (make plan ENV=staging, make deploy, make gpu-scale)
infra/taskfile.yml Task runner mirroring Make for contributors preferring task
infra/.tool-versions Pins terraform, kubectl, helm, kustomize, sops, opa versions
infra/versions.tf Global Terraform + provider version constraints (single source)
infra/ENVIRONMENTS.md Canonical `dev
infra/BOOTSTRAP.md Cold-start runbook: create state backend, registries, first apply
infra/CODEMAP.md Directory-to-owner-to-doc cross reference for this tree

3.2 Terraform (infra/terraform/)

Root-module-per-environment; reusable modules under modules/. Remote state in R2/S3 with lock table.

Path Responsibility
terraform/backend.tf Remote state backend (R2/S3 + DynamoDB-compatible lock) config
terraform/providers.tf Cloudflare, Neon, Upstash, RunPod, AWS(S3), Grafana Cloud providers
terraform/globals.tf Org-wide locals: naming convention, tags, cost-center labels
terraform/envs/dev/main.tf Dev root: composes modules at dev sizing
terraform/envs/dev/{variables,outputs,terraform.tfvars}.tf Dev inputs/outputs/values
terraform/envs/staging/main.tf Staging root (prod-shaped, smaller)
terraform/envs/staging/{variables,outputs,terraform.tfvars}.tf Staging inputs/outputs/values
terraform/envs/prod/main.tf Prod root (HA, multi-region edge)
terraform/envs/prod/{variables,outputs,terraform.tfvars}.tf Prod inputs/outputs/values
terraform/modules/network/main.tf VPC/private networking + peering for GPU/K8s pools
terraform/modules/network/{variables,outputs}.tf Network module I/O
terraform/modules/neon/main.tf Neon project, branches (main/preview), roles, connection strings
terraform/modules/neon/{variables,outputs}.tf Neon module I/O
terraform/modules/redis/main.tf Managed Redis/Upstash: broker + result-backend + rate-limit store
terraform/modules/redis/{variables,outputs}.tf Redis module I/O
terraform/modules/r2/main.tf Cloudflare R2 buckets (assets, renders, uploads, backups) + CORS
terraform/modules/r2/{variables,outputs}.tf R2 module I/O
terraform/modules/cloudflare-pages/main.tf apps/web Pages project + preview bindings + env
terraform/modules/cloudflare-pages/{variables,outputs}.tf Pages module I/O
terraform/modules/cloudflare-dns/main.tf Zone, records, custom-domain reseller CNAMEs
terraform/modules/cloudflare-dns/{variables,outputs}.tf DNS module I/O
terraform/modules/cloudflare-waf/main.tf WAF rules, rate-limit rules, bot mgmt for public API
terraform/modules/cloudflare-waf/{variables,outputs}.tf WAF module I/O
terraform/modules/cloudflare-tunnel/main.tf Zero-trust tunnel to origin API + internal dashboards
terraform/modules/cloudflare-tunnel/{variables,outputs}.tf Tunnel module I/O
terraform/modules/registry/main.tf Container registry (GHCR/ECR) repos + retention + immutability
terraform/modules/registry/{variables,outputs}.tf Registry module I/O
terraform/modules/runpod/main.tf RunPod serverless endpoints per GPU capability + network volumes
terraform/modules/runpod/{variables,outputs}.tf RunPod module I/O
terraform/modules/k8s-cluster/main.tf Optional managed K8s (GPU node pools, CPU pools, autoscaler IAM)
terraform/modules/k8s-cluster/{variables,outputs}.tf K8s cluster module I/O
terraform/modules/object-cdn/main.tf Public render CDN (R2 custom domain + cache)
terraform/modules/object-cdn/{variables,outputs}.tf Object-CDN module I/O
terraform/modules/secrets/main.tf Cloud secret stores + KMS key for SOPS/age
terraform/modules/secrets/{variables,outputs}.tf Secrets module I/O
terraform/modules/observability/main.tf Grafana Cloud stack, Sentry project, log/metric ingestion tokens
terraform/modules/observability/{variables,outputs}.tf Observability module I/O
terraform/modules/billing-lago/main.tf Managed Postgres + service host for external/services/lago
terraform/modules/billing-lago/{variables,outputs}.tf Lago infra I/O
terraform/modules/queue-scaler-iam/main.tf IAM/service-accounts for KEDA + GPU autoscaler
terraform/modules/queue-scaler-iam/{variables,outputs}.tf Scaler IAM I/O
terraform/README.md Module catalog, state layout, apply order, drift policy

3.3 Kubernetes / Helm (infra/k8s/)

Kustomize base + per-env overlays; Helm charts for the app + workers. K8s is the optional self-hosted GPU/CPU path; RunPod serverless is the default GPU path.

Path Responsibility
k8s/README.md When to use K8s vs RunPod vs compose; apply order
k8s/base/kustomization.yaml Aggregates all base manifests
k8s/base/namespace.yaml reelforge namespaces (api, workers, ingest, observability)
k8s/base/api/deployment.yaml FastAPI (app.asgi:app) deployment
k8s/base/api/service.yaml API ClusterIP/service
k8s/base/api/hpa.yaml API horizontal autoscaler (RPS/latency)
k8s/base/api/ingress.yaml Ingress + TLS + Cloudflare origin auth
k8s/base/api/pdb.yaml PodDisruptionBudget for API
k8s/base/worker-cpu/deployment.yaml Celery celery,render,publish,ingest,captions CPU worker
k8s/base/worker-cpu/keda-scaledobject.yaml KEDA scaler off Redis queue depth
k8s/base/worker-gpu/deployment.yaml Celery generation,film GPU worker (node selector + tolerations)
k8s/base/worker-gpu/keda-scaledobject.yaml KEDA scaler off generation/film depth + wallet holds
k8s/base/worker-gpu/runtimeclass.yaml NVIDIA runtime class + GPU resource requests
k8s/base/beat/deployment.yaml Celery beat (singleton, leader-elected)
k8s/base/redis/statefulset.yaml In-cluster Redis fallback (dev/self-host only)
k8s/base/redis/service.yaml Redis service
k8s/base/comfy-runtime/deployment.yaml In-cluster ComfyUI serving pool (from external/workers/comfyui-runtime)
k8s/base/comfy-runtime/service.yaml ComfyUI service + warm-volume mount
k8s/base/migrations/job.yaml Alembic migration Job (pre-deploy gate)
k8s/base/configmap.yaml Non-secret config projected from infra/env
k8s/base/serviceaccounts.yaml Workload identities per component
k8s/base/networkpolicies.yaml Default-deny + explicit allow between tiers
k8s/base/resourcequota.yaml Namespace CPU/GPU/memory quotas
k8s/base/priorityclasses.yaml GPU-job vs API priority classes
k8s/overlays/dev/kustomization.yaml Dev replicas=1, in-cluster redis, no GPU
k8s/overlays/dev/patches/*.yaml Dev-specific resource + image patches
k8s/overlays/staging/kustomization.yaml Staging: managed redis, small GPU pool
k8s/overlays/staging/patches/*.yaml Staging patches (replicas, HPA bounds)
k8s/overlays/prod/kustomization.yaml Prod: HA, multi-AZ, full GPU + warm pool
k8s/overlays/prod/patches/*.yaml Prod patches (PDB, anti-affinity, quotas)
k8s/charts/reelforge-api/Chart.yaml Helm chart metadata for API+workers bundle
k8s/charts/reelforge-api/values.yaml Default chart values
k8s/charts/reelforge-api/values-{staging,prod}.yaml Env value overrides
k8s/charts/reelforge-api/templates/*.yaml Templated deploy/svc/hpa/keda/ingress
k8s/charts/gpu-worker/Chart.yaml Per-capability GPU worker chart (parameterized by cap)
k8s/charts/gpu-worker/values.yaml Defaults: image, GPU count, queue, warm
k8s/charts/gpu-worker/templates/*.yaml GPU deploy + scaler + runtimeclass templates
k8s/addons/keda/*.yaml KEDA operator install pin
k8s/addons/nvidia-device-plugin/*.yaml NVIDIA device plugin + DCGM exporter
k8s/addons/cert-manager/*.yaml TLS issuance
k8s/addons/external-secrets/*.yaml External-Secrets operator wiring to infra/secrets

3.4 Render-worker packaging (infra/render-workers/)

The deploy/publish half of external/workers/* (which owns the image source). One descriptor per capability; a build matrix; a license-gate.

Path Responsibility
render-workers/README.md How a external/workers/<cap> source becomes a deployed endpoint
render-workers/registry.yaml Canonical map: capability → image repo → source path → license class → default pool
render-workers/build-matrix.yaml CI matrix of {capability, cuda, arch} build targets
render-workers/license-gate.py Refuse to publish non-commercial/territorial images to commercial pools (principle 6)
render-workers/publish.py Tag, sign (cosign), push image + attach SBOM/provenance
render-workers/warmpool.yaml Per-capability warm-instance count + idle-TTL budget
render-workers/endpoints/runpod/wan22-t2v.yaml RunPod endpoint descriptor for Wan T2V
render-workers/endpoints/runpod/wan22-i2v.yaml RunPod endpoint for Wan I2V
render-workers/endpoints/runpod/wan22-flf2v.yaml RunPod endpoint for Wan FLF2V keyframe
render-workers/endpoints/runpod/ltx-video.yaml RunPod endpoint for LTX-Video (speed tier)
render-workers/endpoints/runpod/cogvideox.yaml RunPod endpoint for CogVideoX (low-VRAM)
render-workers/endpoints/runpod/framepack.yaml RunPod endpoint for FramePack
render-workers/endpoints/runpod/frame-interp.yaml RunPod endpoint for RIFE/FILM interpolation
render-workers/endpoints/runpod/whisperx.yaml RunPod endpoint for WhisperX align
render-workers/endpoints/runpod/chatterbox.yaml RunPod endpoint for Chatterbox TTS
render-workers/endpoints/runpod/kokoro.yaml RunPod endpoint for Kokoro CPU-draft TTS
render-workers/endpoints/runpod/musetalk.yaml RunPod endpoint for MuseTalk lipsync (realtime tier)
render-workers/endpoints/runpod/latentsync.yaml RunPod endpoint for LatentSync (fidelity tier)
render-workers/endpoints/runpod/infinitetalk.yaml RunPod endpoint for InfiniteTalk long-form
render-workers/endpoints/runpod/mmaudio.yaml RunPod endpoint for MMAudio Foley
render-workers/endpoints/runpod/comfyui-runtime.yaml RunPod endpoint for generic ComfyUI graph pool
render-workers/endpoints/gated/hunyuanvideo.yaml Gated (territorial) endpoint — disabled by default
render-workers/endpoints/gated/coqui-xtts.yaml Gated (NC) endpoint — disabled by default
render-workers/endpoints/gated/f5-tts.yaml Gated (NC) endpoint — disabled by default
render-workers/network-volumes.yaml Warm model-weight volume defs (shared across endpoints)
render-workers/health/probe.py Uniform readiness/smoke probe hitting the async envelope
render-workers/health/canary-jobs.yaml Per-capability canary job specs run post-deploy
render-workers/rollout.py Blue-green endpoint swap with canary gate + drain

3.5 GPU autoscaling (infra/gpu-autoscale/)

Scales GPU capacity off queue depth × wallet-held budget, not CPU — the crown seam that keeps warm-pool cost bounded.

Path Responsibility
gpu-autoscale/README.md Scaling model, inputs (queue depth, wallet holds), outputs (endpoint replicas)
gpu-autoscale/controller/main.py Control loop: poll queue + holds → target replicas per capability
gpu-autoscale/controller/signals.py Read Redis queue depth, in-flight envelope states, wallet holds
gpu-autoscale/controller/policy.py Scale-up/down policy: burst, cooldown, min-warm, max-cap
gpu-autoscale/controller/runpod_client.py Set RunPod endpoint min/max workers
gpu-autoscale/controller/k8s_client.py Patch K8s GPU deployment replicas / KEDA bounds
gpu-autoscale/controller/costguard.py Enforce per-hour GPU spend ceiling; pause scale-up on breach
gpu-autoscale/controller/predictor.py Optional pre-warm from cadence/schedule signals (publishing peaks)
gpu-autoscale/controller/metrics.py Emit scaler decisions + saturation to OTel/Prometheus
gpu-autoscale/config/pools.yaml Per-capability {min-warm, max, target-latency, $/hr cap}
gpu-autoscale/config/schedules.yaml Predictive pre-warm windows by timezone/genre cadence
gpu-autoscale/keda/scaledobject-generation.yaml KEDA Redis scaler for generation queue
gpu-autoscale/keda/scaledobject-film.yaml KEDA Redis scaler for film queue
gpu-autoscale/keda/scaledjob-batch.yaml KEDA ScaledJob for batch clipfarm renders
gpu-autoscale/deploy/controller-deployment.yaml Deploy the autoscale controller
gpu-autoscale/deploy/rbac.yaml Least-priv RBAC for the controller
gpu-autoscale/tests/test_policy.py Unit tests for scale math + cooldown
gpu-autoscale/tests/test_costguard.py Unit tests for spend-ceiling breaker

3.6 Queue topology (infra/queues/)

Formalizes the Celery/Redis topology and the KEDA/rate-limit contracts. Extends the existing celery,render,generation queues with publish,ingest,film,captions,batch.

Path Responsibility
queues/README.md Queue catalog, priorities, ownership, DLQ + retry policy
queues/topology.yaml Canonical queue → {broker, priority, rate-limit, worker-pool, SLA} map
queues/routing.yaml Task-name → queue routing (mirrors Celery task_routes)
queues/redis/redis.conf Broker config (persistence, maxmemory-policy, keyspace)
queues/redis/sentinel.conf HA sentinel config (prod)
queues/redis/acl.conf Per-service Redis ACL users (least priv)
queues/dlq/policy.yaml Dead-letter routing + replay window per queue
queues/dlq/replayer.py Operator tool to inspect/replay/purge DLQ entries
queues/ratelimits/per-provider.yaml Provider concurrency caps feeding the router
queues/ratelimits/per-workspace.yaml Per-workspace/plan job concurrency ceilings
queues/backpressure.py Reject-before-provider signal when a queue exceeds depth SLA
queues/tests/test_routing.py Assert every task maps to exactly one declared queue

3.7 Observability (infra/observability/)

OTel collector fans in app/telemetry/* → Prometheus/Grafana/Loki/Tempo/Sentry. SLOs are first-class; alerts route by subsystem.

Path Responsibility
observability/README.md Telemetry topology, signal catalog, dashboard index
observability/otel/collector.yaml OTel collector pipelines (traces/metrics/logs) + exporters
observability/otel/processors.yaml Attribute/resource processors (workspace, model, queue tags)
observability/otel/sampling.yaml Tail-sampling: keep all errors + slow render spans
observability/prometheus/prometheus.yml Scrape config (api, workers, DCGM GPU, redis, autoscaler)
observability/prometheus/rules/api.yaml API latency/error recording+alert rules
observability/prometheus/rules/render.yaml Render throughput, queue-depth, warm-pool utilization rules
observability/prometheus/rules/gpu.yaml GPU util/memory/temperature (DCGM) rules
observability/prometheus/rules/wallet.yaml Wallet holds vs settled, success-only-billing invariants
observability/prometheus/rules/publishing.yaml Publish success rate, per-platform cap breaches, watermark-guard
observability/prometheus/rules/cost.yaml $/render, GPU $/hr, margin-erosion alerts
observability/grafana/dashboards/api-overview.json API RED dashboard
observability/grafana/dashboards/render-pipeline.json Job-envelope funnel (queued→progress→done/fail)
observability/grafana/dashboards/gpu-fleet.json GPU fleet utilization + warm-pool cost
observability/grafana/dashboards/queues.json Per-queue depth, latency, DLQ
observability/grafana/dashboards/wallet-cost.json Wallet burn, margin, per-model $
observability/grafana/dashboards/publishing.json Cross-platform publish + retention ingestion health
observability/grafana/dashboards/marketplace.json Clipping-campaign view verification + fraud signals
observability/grafana/dashboards/reseller-margin.json Wholesale-vs-retail margin per reseller
observability/grafana/provisioning/{datasources,dashboards}.yaml Grafana provisioning
observability/loki/config.yaml Log aggregation config + retention
observability/loki/pipeline.yaml Log parsing → structured labels (job_id, workspace, model)
observability/tempo/config.yaml Trace store config
observability/sentry/projects.yaml Sentry project/env/DSN mapping (extends telemetry/sentry.py)
observability/sentry/alerts.yaml Sentry issue-alert routing rules
observability/slo/catalog.yaml SLO definitions (api availability, render p95, publish success)
observability/slo/error-budgets.yaml Error-budget policy + burn-rate alert thresholds
observability/alerts/routing.yaml Alertmanager routes (Slack/PagerDuty/email) by severity+team
observability/alerts/templates/*.tmpl Alert message templates
observability/synthetics/checks.yaml Black-box uptime probes (public API, web, render canary)
observability/status-page/config.yaml Public status-page component + incident mapping

3.8 Release / deploy orchestration (infra/deploy/)

Path Responsibility
deploy/README.md Release flow, environments, promotion gates, rollback
deploy/strategy.yaml Blue-green/canary parameters per component
deploy/migrations/plan.py Compute pending Alembic migrations + safety class (online/blocking)
deploy/migrations/gate.py Block deploy if a blocking migration lacks a maintenance window
deploy/migrations/job.yaml Migration Job manifest (reused by K8s + CI)
deploy/promote.py Promote an image digest dev→staging→prod (immutable digests)
deploy/rollback.py Roll an environment back to prior known-good digest
deploy/canary/gate.py Post-deploy canary: error-rate + render-canary + SLO burn gate
deploy/canary/checks.yaml Canary check definitions per component
deploy/release-manifest.schema.json Schema for the signed release manifest (images, migrations, config hash)
deploy/feature-flags/flags.yaml Flag defaults (ties to PostHog) for phased rollout
deploy/runbooks/incident-gpu-saturation.md Runbook: GPU pool saturated / queue backlog
deploy/runbooks/incident-provider-outage.md Runbook: upstream model provider down (success-only billing)
deploy/runbooks/incident-redis-broker.md Runbook: broker degradation / failover
deploy/runbooks/incident-db-migration.md Runbook: failed/stuck migration recovery
deploy/runbooks/incident-wallet-drift.md Runbook: wallet-vs-ledger reconciliation alarm
deploy/runbooks/incident-publish-backlog.md Runbook: scheduler backlog / platform-cap lockout
deploy/runbooks/rollback.md Generic rollback runbook
deploy/runbooks/oncall.md On-call rotation, escalation, severity matrix

3.9 Shared images (infra/docker/)

Path Responsibility
docker/base-python/Dockerfile Hardened Python base (uv, non-root, ffmpeg-libass) shared by api/worker
docker/base-cuda/Dockerfile CUDA runtime base shared by GPU workers
docker/base-node/Dockerfile Node base for apps/web + external/render/*
docker/ffmpeg/Dockerfile Pinned libass-enabled FFmpeg build layer
docker/README.md Base-image lineage + rebuild cadence + CVE-patch policy
docker/hardening/seccomp.json Seccomp profile for runtime containers
docker/hardening/dockerfile-lint.yaml hadolint ruleset enforced in CI

3.10 Secrets & env (infra/secrets/, infra/env/)

Path Responsibility
secrets/README.md Secret model: SOPS/age at rest, External-Secrets at runtime, rotation
secrets/.sops.yaml SOPS creation rules (which keys encrypt which paths)
secrets/dev.enc.yaml Encrypted dev secrets
secrets/staging.enc.yaml Encrypted staging secrets
secrets/prod.enc.yaml Encrypted prod secrets
secrets/external-secrets/*.yaml ExternalSecret CRs mapping cloud store → K8s secrets
secrets/rotation.md Rotation runbook + cadence per secret class (BYOK-Fernet, provider keys)
secrets/schema.yaml Declared required-secret schema (fail-fast validation)
env/README.md How env manifests render into compose/K8s/CI
env/base.yaml Non-secret defaults common to all envs
env/dev.yaml Dev endpoints/flags
env/staging.yaml Staging endpoints/flags
env/prod.yaml Prod endpoints/flags
env/render.py Render env manifests → .env/ConfigMap; validate against secrets/schema.yaml
env/matrix.md Cross-reference of every var → owning subsystem → CONFIG.md section

3.11 Edge / DNS / policy (infra/cdn/, infra/dns/, infra/policy/, infra/scripts/)

Path Responsibility
cdn/cache-rules.yaml Cloudflare cache rules for renders/assets/static
cdn/r2-lifecycle.yaml R2 lifecycle: expire previews, retain paid renders, backups
cdn/signed-url-worker/index.ts Cloudflare Worker issuing signed R2 URLs (watermark-tier aware)
cdn/signed-url-worker/wrangler.toml Worker config/bindings
cdn/reseller-domains.yaml Custom-domain (white-label) routing map
dns/zones/reelforge.app.yaml Primary zone records (source of truth for Terraform)
dns/zones/reseller-template.yaml Per-reseller custom-domain record template
dns/README.md Record ownership + change process
policy/opa/terraform-plan.rego Deny risky TF plans (public buckets, unencrypted, over-cap GPU)
policy/opa/k8s-manifests.rego Deny non-conformant manifests (no limits, privileged, latest tag)
policy/opa/image-provenance.rego Require signed image + SBOM before deploy
policy/conftest.yaml Conftest config wiring rego into CI
policy/README.md Guardrail catalog + waiver process
scripts/plan.sh Wrap terraform plan with env selection + policy check
scripts/apply.sh Gated apply (protected-branch only)
scripts/gpu-scale.sh Manual override for autoscaler (ops break-glass)
scripts/drain-workers.sh Cordon+drain workers for maintenance
scripts/db-backup.sh On-demand Neon branch/backup snapshot
scripts/restore.sh Restore from snapshot into a Neon preview branch
scripts/smoke.sh Post-deploy smoke across api/render/publish canaries

4. .github/ — CI/CD/security/release automation

4.1 Workflows (.github/workflows/)

Path Responsibility
ci-api.yml apps/api lint (ruff), type, pytest+coverage (≥80% gate)
ci-web.yml apps/web lint, typecheck, build, unit/component tests
ci-mobile.yml apps/mobile Expo lint/typecheck/test + EAS build preview
ci-desktop.yml apps/desktop cargo fmt/clippy/test (per apps-desktop.md)
ci-packages.yml packages/{api-contract,sdk-*} build + contract snapshot tests
ci-infra.yml Terraform fmt/validate, tflint, Kustomize/Helm render, OPA/Conftest
contract-check.yml Assert api-contract ↔ generated SDKs ↔ server routes stay in sync
migrations-check.yml Alembic: no drift, reversible, safety-class annotated
build-images-api.yml Build+sign apps/api CPU + generation images, push, SBOM, provenance
build-images-workers.yml Matrix build+sign external/workers/* via render-workers/build-matrix.yaml + license-gate
build-images-node.yml Build apps/web + external/render/* images
deploy-staging.yml On merge to main: promote digests, migrate, deploy staging, canary
deploy-prod.yml On release tag: promote to prod, blue-green, canary gate, rollback-on-fail
terraform-plan.yml PR-scoped terraform plan per env + policy, comment plan
terraform-apply.yml Protected-branch gated terraform apply
gpu-endpoints-sync.yml Reconcile RunPod endpoints from render-workers/endpoints/*
security-codeql.yml CodeQL for py/ts/rust
security-deps.yml Dependency + license scan (pip-audit, npm audit, cargo-audit, license class)
security-images.yml Trivy/grype scan of built images + fail on critical
security-secrets.yml gitleaks/trufflehog secret scan
security-iac.yml tfsec/checkov over Terraform + K8s
perf.yml Nightly scripts/reelforge_bench.py render-throughput regression
e2e.yml Critical-flow E2E (create→publish→measure) against ephemeral env
release.yml release-please: version, changelog, tag, invoke reelforge-release-gate.sh
docs-build.yml Build docs site, validate front-matter + internal links
docs-linkcheck.yml Scheduled dead-link + orphan-doc check across docs/
preview-env.yml Spin ephemeral per-PR env (Neon branch + preview deploy), teardown on close
stale.yml Stale issue/PR hygiene
labeler.yml Path-based PR auto-labeling

4.2 Composite actions & config (.github/actions/, root)

Path Responsibility
actions/setup-python-uv/action.yml Cached uv + Python toolchain setup
actions/setup-node-pnpm/action.yml Cached Node/pnpm setup
actions/setup-terraform/action.yml Pinned terraform + provider cache
actions/build-sign-image/action.yml Buildx + cosign sign + SBOM attach (reused by all image workflows)
actions/deploy-kustomize/action.yml Render+apply an overlay with drift check
actions/canary-gate/action.yml Run deploy/canary/gate.py and fail on breach
actions/notify/action.yml Slack/PagerDuty deploy+alert notification
CODEOWNERS Path → owning team (infra, api, web, docs)
dependabot.yml Update policy for pip/npm/cargo/actions/terraform
labeler.yml Path-glob → label map
release-please-config.json Monorepo release-please components + versioning
pull_request_template.md PR checklist (tests, docs, migration safety, security)

5. Key cross-cutting models & contracts (new)

  • Release manifest (deploy/release-manifest.schema.json): immutable record { app_images{digest}, worker_images{cap→digest}, migrations[], config_hash, terraform_state_serial, signatures[] } — the single artifact promoted across environments; enables digest-pinned rollback.
  • Capability registry (render-workers/registry.yaml): capability → { image_repo, source(external/workers/<cap>), license_class, default_pool, min_warm, gpu, envelope_version } — the join key between external/, the autoscaler, the router, and observability labels.
  • Queue topology (queues/topology.yaml): queue → { broker, priority, rate_limit, worker_pool, sla_seconds, dlq } — consumed by KEDA scalers, backpressure, and Grafana queue dashboards.
  • Scaling signal (gpu-autoscale/config/pools.yaml): target replicas = f(queue_depth, in_flight_holds, min_warm, max, $/hr_cap) — GPU scales on wallet-backed demand, never CPU.
  • SLO catalog (observability/slo/catalog.yaml): api-availability 99.9, render-p95 by tier, publish-success 99, wallet-billing-invariant 100 — drive error-budget burn alerts and the canary gate.
  • Env matrix (env/matrix.md + secrets/schema.yaml): every var declared once, validated fail-fast at boot, cross-linked to CONFIG.md.

6. docs/ information architecture (housing every new spec)

The existing 40+ flat docs/reelforge/*.md files stay as historical/reference, but new Vision-2026 work lands in a fixed tree with front-matter. Peer tracks (external.md, apps-desktop.md) already live under docs/reelforge/vision2026/architecture/; this section defines the full IA and where each remaining spec goes.

docs/
├── README.md                       # top-level nav: how docs are organized, status legend
├── _meta/
│   ├── STYLE.md                    # doc conventions: front-matter, tables, tree diagrams
│   ├── frontmatter.schema.json     # status|owner|phase|supersedes|updated schema (CI-checked)
│   ├── glossary.md                 # shared vocabulary (envelope, hold, markup_policy, warm-pool)
│   ├── doc-index.yaml              # generated index of every doc + status (docs-build.yml)
│   └── redirects.yaml              # old-path → new-path map as flat files migrate
├── reference/                      # stable "how it is" reference (promoted from flat files)
│   ├── config.md                   # ← supersedes/links CONFIG.md
│   ├── data-model.md               # ← links DATA_MODEL.md
│   ├── api.md                      # ← links API.md
│   └── security.md                 # ← links SECURITY_AUDIT.md
├── guides/                         # task-oriented "how to"
│   ├── local-dev.md  deploy.md  add-a-model.md  add-a-queue.md
│   ├── add-a-publish-platform.md  provision-reseller.md  run-a-migration.md
│   └── onboarding.md
├── runbooks/                       # operational (mirrors infra/deploy/runbooks, single source→links)
│   └── README.md                   # index pointing to infra/deploy/runbooks/*
├── adr/                            # Architecture Decision Records (dated, immutable)
│   ├── _TEMPLATE.md
│   ├── 0001-microdollar-wallet-authoritative.md
│   ├── 0002-gpu-autoscale-on-wallet-demand.md
│   ├── 0003-runpod-default-k8s-optional.md
│   ├── 0004-license-gate-at-deploy.md
│   ├── 0005-lago-invoicing-wallet-billing-split.md
│   └── 0006-docs-ia-frontmatter.md
└── reelforge/
    ├── (existing flat *.md — kept; tagged in redirects.yaml)
    └── vision2026/
        ├── README.md               # index of the vision2026 program + phase map
        ├── architecture/           # EXISTS: external.md, apps-desktop.md, infra-docs.md (this) + siblings
        │   ├── apps-api.md         # (peer track) API domain expansion
        │   ├── apps-web.md         # (peer track) web surfaces
        │   ├── apps-mobile.md      # (peer track) mobile surfaces
        │   ├── packages.md         # (peer track) sdk/api-contract
        │   └── overview.md         # system context diagram tying all tracks together
        ├── specs/                  # detailed subsystem specs (one per backlog domain)
        │   ├── templates-engine.md         # genre shot-template engine spec
        │   ├── captions-whisperx.md        # caption microservice + Hormozi presets
        │   ├── film-pipeline.md            # screenplay→shot-list→character-lock→I2V→animatic
        │   ├── publishing-hub.md           # OAuth adapters, scheduler, watermark-safe export
        │   ├── retention-analytics.md      # retention-curve ingestion + A/B orchestration
        │   ├── gateway-provisioning.md     # provisioning keys, markup_policy, plans
        │   ├── billing-lago-bridge.md      # Lago bridge + success-only billing
        │   ├── marketplace-clipping.md     # CPM campaigns, view verification, fraud
        │   ├── affiliate-program.md        # lifetime-recurring affiliate
        │   ├── trend-ingestion.md          # Creative-Center/trending-audio scrapers
        │   ├── async-gpu-envelope.md       # the IN_QUEUE→COMPLETED contract (infra ref)
        │   ├── autoscaling-and-queues.md   # ← this doc's runtime companion spec
        │   └── observability-slo.md        # ← SLO/telemetry spec companion
        ├── data/
        │   ├── erd.md                      # cross-subsystem ERD deltas (additive tables)
        │   └── migrations-plan.md          # ordering/safety of new-table migrations
        ├── api/
        │   ├── openapi-deltas.md           # new endpoint groups (gateway, publishing, marketplace)
        │   └── mcp-tools.md                # new MCP tools (publish/schedule/trend)
        ├── diagrams/
        │   ├── system-context.excalidraw / .svg
        │   ├── render-job-envelope.svg
        │   ├── gpu-autoscale-loop.svg
        │   ├── publishing-loop.svg
        │   └── deploy-pipeline.svg
        ├── phasing/
        │   ├── roadmap.md                  # P1–P5 sequencing across all tracks
        │   └── dependencies.md             # inter-track dependency graph
        └── ops/
            ├── slo-catalog.md              # human-readable mirror of observability/slo/catalog.yaml
            ├── cost-model.md               # GPU $/render, margin, warm-pool budget
            └── capacity-plan.md            # GPU pool sizing per phase
Path Responsibility
docs/README.md Root navigation + status legend for the whole docs tree
docs/_meta/STYLE.md Front-matter + table/tree conventions all specs follow
docs/_meta/frontmatter.schema.json CI-validated doc metadata schema
docs/_meta/doc-index.yaml Generated catalog of every doc + status/owner/phase
docs/_meta/redirects.yaml Maps legacy flat docs/reelforge/*.md → new IA slots
docs/adr/_TEMPLATE.md ADR template (context/decision/consequences)
docs/adr/000X-*.md Immutable decision records (wallet, autoscale, licensing, docs-IA)
docs/reference/*.md Promoted stable references linking existing DATA_MODEL/API/CONFIG/SECURITY
docs/guides/*.md Task guides (local-dev, deploy, add-a-model/queue/platform, reseller)
docs/runbooks/README.md Single index pointing at infra/deploy/runbooks/* (no duplication)
docs/reelforge/vision2026/README.md Program index + phase map across all architecture tracks
docs/reelforge/vision2026/architecture/overview.md System-context doc unifying infra/apps/external tracks
docs/reelforge/vision2026/specs/*.md One spec per new subsystem domain (13 files listed)
docs/reelforge/vision2026/data/*.md Additive ERD + migration-ordering plan
docs/reelforge/vision2026/api/*.md OpenAPI + MCP tool deltas
docs/reelforge/vision2026/diagrams/* Source + exported diagrams
docs/reelforge/vision2026/phasing/*.md Roadmap + cross-track dependency graph
docs/reelforge/vision2026/ops/*.md SLO/cost/capacity operator docs

7. Integration seams into what already exists

New infra/docs surface Existing seam Contract
infra/render-workers/* external/workers/<cap> (source) + app/domains/broll/providers/* (adapter) Consumes image source, publishes signed endpoint the adapter calls
infra/gpu-autoscale/* Redis broker + Celery generation,film queues + wallet holds Reads queue depth + ledger holds; writes RunPod/K8s replica counts
infra/queues/* Existing celery,render,generation + new publish,ingest,film,captions,batch Extends celery_app task_routes; KEDA scales off topology.yaml
infra/observability/otel/* app/telemetry/{cost,events,progress,sentry}.py Scrapes/receives existing metrics; adds resource labels (workspace,model,queue)
infra/observability/rules/wallet.yaml Microdollar ledger Alerts on hold/settle drift + success-only-billing invariant (observe-only)
infra/deploy/migrations/* alembic.ini, migrations/ Adds safety-class gate + pre-deploy Job; never bypasses Alembic
infra/terraform/modules/{r2,neon,redis,cloudflare-pages,runpod} R2/Neon/Redis/Pages/RunPod from DEPLOYMENT.md Codifies the manually-created accounts as IaC (import existing)
infra/terraform/modules/billing-lago external/services/lago Provisions Lago host; wallet stays authoritative (ADR-0005)
infra/secrets/* + infra/env/* .env.reelforge.example, config.toml, Fernet BYOK Templates env per environment; validates required-secret schema at boot
.github/workflows/build-images-* apps/api/Dockerfile{,.generation}, apps/web/Dockerfile, external/workers/* Builds/signs/SBOMs every image; license-gate blocks NC/territorial to commercial pools
.github/workflows/{deploy-staging,deploy-prod}.yml docker-compose.reelforge.yml (dev) → infra/k8s (staging/prod) Compose = local; workflows deploy overlays/charts with canary gate
.github/workflows/release.yml scripts/reelforge-release-gate.sh Release-please invokes the existing gate before tagging
.github/workflows/perf.yml scripts/reelforge_bench.py Nightly render-throughput regression
docs/ IA 40+ existing docs/reelforge/*.md Indexed + redirected, not deleted; new specs land in fixed slots
docs/reelforge/vision2026/architecture/overview.md external.md, apps-desktop.md, this doc The unifying system-context that references all peer tracks

8. Phasing (aligns to the program P1–P5)

Phase Infra/docs shipped Unblocks
P0 — Foundation infra/terraform (import existing R2/Neon/Redis/Pages), infra/docker base images, .github/workflows/{ci-*,build-images-api,security-*}, docs/_meta + IA skeleton + ADR-0001..0006 Reproducible envs + PR-gated CI + docs IA before any new subsystem
P1 — Templates + captions infra/queues (captions queue), render-workers/endpoints/{whisperx,faster-whisper}, observability api+render dashboards, docs/specs/{templates-engine,captions-whisperx}.md Genre templates + Hormozi captions observable & deployed
P2 — Complete the loop infra/queues (publish,ingest), services deploy (postiz/n8n/posthog via terraform + k8s), publishing+retention dashboards+alerts, preview-env workflow, docs/specs/{publishing-hub,retention-analytics,trend-ingestion}.md Publish→measure→regenerate wedge in staging/prod
P3 — Resellable platform terraform/modules/billing-lago, gateway/reseller dashboards, cdn/reseller-domains + custom-domain DNS, cost/margin rules, docs/specs/{gateway-provisioning,billing-lago-bridge}.md + ops/cost-model.md Provisioning keys + markup + white-label live
P4 — Deep film moat render-workers/endpoints/{wan22-*,ltx-video,cogvideox,framepack,frame-interp,mmaudio,musetalk,latentsync,infinitetalk}, gpu-autoscale full controller + warm-pool + costguard + predictor, infra/k8s GPU pools + KEDA, docs/specs/{film-pipeline,async-gpu-envelope,autoscaling-and-queues}.md + ops/capacity-plan.md Full film pipeline at bounded GPU cost
P5 — Compounding acquisition marketplace fraud/view dashboards, affiliate payout infra, services/listmonk, docs/specs/{marketplace-clipping,affiliate-program}.md Clipping marketplace + affiliate + micro-tools
Gated / deferred render-workers/endpoints/gated/{hunyuanvideo,coqui-xtts,f5-tts} Deploy only after territorial/NC review; excluded from commercial pools by default

Bottom line. infra/ becomes four cleanly-separated planes — a provisioning plane (terraform, secrets, env, dns, cdn) that codifies today's hand-created cloud accounts; a runtime plane (k8s, render-workers, gpu-autoscale, queues) that scales GPU capacity off wallet-backed demand through one async envelope; an observability plane (observability, deploy canaries + runbooks) with first-class SLOs and success-only-billing invariants; and a policy/actuation plane (.github/, policy) where every change ships PR-gated, signed, and license-checked. docs/ imposes a front-matter'd IA so the existing flat pile plus every new subsystem spec becomes one navigable, de-duplicated, phase-tagged tree — with architecture/overview.md as the single system-context that ties infra-docs, external, apps-*, and packages together.