videogen/scripts/deploy-preflight.py
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

768 lines
27 KiB
Python
Executable File

#!/usr/bin/env python3
"""Phased deploy readiness preflight for menivor / ReelForge.
Companion to ``apps/api/tools/ops/preflight.py`` (the launch-flag gate wired into
``scripts/reelforge-release-gate.sh``). This script answers a different question:
**"which credential phase is the running system ready for?"** It reads the phased
credential contract from ``docs/runbooks/deploy-credentials.md`` and the
``.env*.example`` templates, checks each required variable is SET and SHAPE-VALID
(not a placeholder), and prints a PASS/FAIL readiness table per phase.
Key-independent by design:
* It validates presence + shape only. It never needs real secret values and it
never prints secret values (only variable names + a redacted reason).
* External calls are OFF by default. ``--check-connectivity`` opts into a DB
ping / Redis ping / R2 HEAD, and even then only for phases already SET.
Exit code:
0 every REQUIRED phase passes and launch flags are coherent
1 a required phase is missing/invalid, or launch flags are incoherent
2 bad usage
Which phases are REQUIRED:
* Phase 0 (infra) and Phase 1 (render) are always required (you cannot deploy a
working render stack without them) — tune with ``--min-phase``.
* Phases 2-4 are required only when their launch flag is enabled (e.g.
``REELFORGE_CHECKOUT_ENABLED=true`` makes Phase 3 required). Otherwise they are
reported as informational readiness, never a hard failure.
Usage:
python3 scripts/deploy-preflight.py # process env
python3 scripts/deploy-preflight.py --env-file .env.reelforge
python3 scripts/deploy-preflight.py --min-phase 2 # also require auth
python3 scripts/deploy-preflight.py --check-connectivity # opt-in live pings
python3 scripts/deploy-preflight.py --json # machine-readable
"""
from __future__ import annotations
import argparse
import os
import re
from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable
from urllib.parse import urlsplit
# ---------------------------------------------------------------------------
# Env loading (no secret values ever leave this process via stdout).
# ---------------------------------------------------------------------------
_KEY = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
# Substrings that mark a value as a template placeholder rather than a real
# credential. Matched case-insensitively. Kept conservative so a genuine secret
# is never rejected; these all come from the repo's .env*.example files/docs.
_PLACEHOLDER_TOKENS: tuple[str, ...] = (
"your-",
"your_",
"changeme",
"change-me",
"placeholder",
"example.com",
"local-dev",
"smoke-test",
"replace_me",
"replaceme",
"xxxx",
"<", # e.g. https://<key>@... or postgres://USER:<pw>@...
"account_id.r2.cloudflarestorage.com", # literal from R2_S3_ENDPOINT template
)
# Exact placeholder values (whole-string match, case-insensitive).
_PLACEHOLDER_EXACT: frozenset[str] = frozenset(
{"x", "todo", "tbd", "none", "null", "changeme", "test", "test-token-key"}
)
def parse_dotenv(path: Path) -> dict[str, str]:
"""Parse a dotenv file into a name->value map. Mirrors cloud-runtime-env.py."""
parsed: dict[str, str] = {}
for raw in path.read_text(encoding="utf-8").splitlines():
line = raw.strip()
if not line or line.startswith("#"):
continue
if line.startswith("export "):
line = line[7:].strip()
key, separator, value = line.partition("=")
key = key.strip()
if not separator or not _KEY.fullmatch(key):
continue
value = value.strip()
if len(value) >= 2 and value[0] == value[-1] and value[0] in {"'", '"'}:
value = value[1:-1]
parsed.setdefault(key, value)
return parsed
def load_env(env_file: Path | None) -> dict[str, str]:
"""Process env wins over the dotenv file (ambient overrides templates)."""
merged: dict[str, str] = {}
if env_file and env_file.is_file():
merged.update(parse_dotenv(env_file))
merged.update(os.environ)
return merged
# ---------------------------------------------------------------------------
# Value helpers.
# ---------------------------------------------------------------------------
def is_placeholder(value: str) -> bool:
low = value.strip().lower()
if low in _PLACEHOLDER_EXACT:
return True
return any(token in low for token in _PLACEHOLDER_TOKENS)
def is_set(value: str | None) -> bool:
return bool(value and value.strip() and not is_placeholder(value))
def first_set(env: dict[str, str], *names: str) -> tuple[str, str] | None:
"""Return (name, value) for the first name that holds a real value."""
for name in names:
value = env.get(name, "")
if is_set(value):
return name, value
return None
# ---------------------------------------------------------------------------
# Shape validators. Each returns None on success or a short reason on failure.
# Reasons never contain the secret value.
# ---------------------------------------------------------------------------
def shape_nonempty(_value: str) -> str | None:
return None # presence already checked upstream
def shape_postgres_url(value: str) -> str | None:
try:
parsed = urlsplit(value)
except ValueError:
return "not a parseable URL"
if parsed.scheme not in {"postgres", "postgresql", "postgresql+psycopg"}:
return "must be a postgres:// / postgresql:// / postgresql+psycopg:// URL"
if not parsed.hostname:
return "URL has no host"
if any(ch.isspace() for ch in value):
return "URL contains whitespace (looks like a psql command, not a URL)"
return None
def shape_https_url(value: str) -> str | None:
try:
parsed = urlsplit(value)
except ValueError:
return "not a parseable URL"
if parsed.scheme != "https":
return "must be an https:// URL"
if not parsed.netloc:
return "URL has no host"
return None
def shape_url(value: str) -> str | None:
try:
parsed = urlsplit(value)
except ValueError:
return "not a parseable URL"
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
return "must be an http(s):// URL with a host"
return None
def shape_port(value: str) -> str | None:
if not value.isdigit() or not (0 < int(value) < 65536):
return "must be a TCP port number (1-65535)"
return None
def shape_int(value: str) -> str | None:
return None if value.lstrip("-").isdigit() else "must be an integer"
def make_prefix_shape(prefix: str, label: str) -> Callable[[str], str | None]:
def _check(value: str) -> str | None:
return (
None
if value.startswith(prefix)
else f"expected {label} (starts with '{prefix}')"
)
return _check
def shape_fernet_key(value: str) -> str | None:
# crypto_tokens.py derives a Fernet key from any non-empty secret, so we only
# require reasonable entropy, not a raw 32-byte urlsafe key.
if len(value.strip()) < 16:
return "should be a long random secret (>=16 chars)"
return None
# ---------------------------------------------------------------------------
# Requirement model.
# ---------------------------------------------------------------------------
@dataclass(frozen=True)
class Requirement:
"""One logical requirement. ``names`` are accepted aliases (first-set wins)."""
names: tuple[str, ...]
label: str
shape: Callable[[str], str | None] = shape_nonempty
optional: bool = False # reported but never fails a phase
def check(self, env: dict[str, str]) -> "CheckResult":
hit = first_set(env, *self.names)
alias = " / ".join(self.names)
if hit is None:
status = "WARN" if self.optional else "FAIL"
return CheckResult(self.label, alias, status, "unset or placeholder")
name, value = hit
reason = self.shape(value)
if reason:
status = "WARN" if self.optional else "FAIL"
return CheckResult(self.label, alias, status, reason, resolved=name)
return CheckResult(self.label, alias, "PASS", "", resolved=name)
@dataclass(frozen=True)
class CheckResult:
label: str
alias: str
status: str # PASS | FAIL | WARN
reason: str
resolved: str = ""
@dataclass(frozen=True)
class Phase:
key: str
title: str
requirements: tuple[Requirement, ...]
# A phase is required when this predicate is true for the given env, OR when
# ``--min-phase`` covers it. Default: never self-required (flag-gated phases).
required_when: Callable[[dict[str, str]], bool] = lambda _env: False
gate_hint: str = ""
# ---------------------------------------------------------------------------
# Launch-flag helpers (kept semantically identical to ops/preflight.py).
# ---------------------------------------------------------------------------
_TRUTHY = {"1", "true", "yes", "on"}
def flag_on(env: dict[str, str], name: str) -> bool:
return env.get(name, "").strip().lower() in _TRUTHY
def checkout_on(env: dict[str, str]) -> bool:
return flag_on(env, "REELFORGE_CHECKOUT_ENABLED")
def publishing_on(env: dict[str, str]) -> bool:
return flag_on(env, "REELFORGE_PUBLISHING_ENABLED")
# ---------------------------------------------------------------------------
# The phase contract (extracted from docs/runbooks/deploy-credentials.md +
# .env.reelforge.example / apps/web/.env.example / apps/mobile/.env.example).
# ---------------------------------------------------------------------------
def build_phases() -> tuple[Phase, ...]:
pk_shape = make_prefix_shape("pk_", "a Clerk publishable key")
sk_shape = make_prefix_shape("sk_", "a Clerk secret key")
phase0 = Phase(
key="0",
title="Infra (Neon + Redis + R2 + CORS + observability)",
gate_hint="always required to deploy a working stack",
requirements=(
Requirement(
("REELFORGE_DATABASE_URL", "NEON_DATABASE_URL", "DATABASE_URL"),
"Neon Postgres pooled URL",
shape_postgres_url,
),
Requirement(
("DATABASE_URL_UNPOOLED",),
"Neon Postgres unpooled URL (migrations)",
shape_postgres_url,
optional=True,
),
Requirement(("REDIS_HOST",), "Redis host"),
Requirement(("REDIS_PORT",), "Redis port", shape_port),
Requirement(("REDIS_DB",), "Redis db index", shape_int, optional=True),
Requirement(
("REDIS_PASSWORD",), "Redis password", optional=True
), # managed Redis may be passwordless on a private network
Requirement(("R2_ACCOUNT_ID",), "R2 account id"),
Requirement(("R2_ACCESS_KEY_ID",), "R2 access key id"),
Requirement(("R2_SECRET_ACCESS_KEY",), "R2 secret access key"),
Requirement(
("REELFORGE_R2_BUCKET_NAME", "R2_BUCKET_NAME", "R2_BUCKET"),
"R2 bucket name",
),
Requirement(("R2_S3_ENDPOINT",), "R2 S3 endpoint", shape_https_url),
Requirement(("R2_PUBLIC_BASE_URL",), "R2 public base URL", shape_url),
Requirement(("CORS_ALLOWED_ORIGINS",), "CORS allowed origins"),
Requirement(
# Hard requirement in the production release gate
# (apps/api/tools/ops/preflight.py --production); kept required
# here so this preflight and that gate never disagree.
("SENTRY_DSN",),
"Sentry DSN (error/perf monitoring)",
shape_https_url,
),
),
required_when=lambda _env: True,
)
phase1 = Phase(
key="1",
title="Render pipeline (Claude + ElevenLabs + HeyGen)",
gate_hint="required for the first real render",
requirements=(
Requirement(("ANTHROPIC_API_KEY",), "Claude (script generation)"),
Requirement(("ELEVENLABS_API_KEY",), "ElevenLabs (TTS timing authority)"),
Requirement(
("HEYGEN_API_KEY",),
"HeyGen (avatar) — or self-host LatentSync/RunPod",
optional=True,
),
Requirement(
("COMFYUI_BASE_URL",),
"ComfyUI base URL (optional B-roll)",
shape_url,
optional=True,
),
Requirement(
("COMFYUI_API_KEY",), "ComfyUI API key (optional B-roll)", optional=True
),
Requirement(
("COMFYUI_DEPLOYMENT_ID",),
"ComfyUI deployment id (optional B-roll)",
optional=True,
),
),
required_when=lambda _env: True,
)
phase2 = Phase(
key="2",
title="Auth (Clerk — web + app)",
gate_hint="required before REELFORGE_SIGNUP_ENABLED=true",
requirements=(
Requirement(
("NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY",),
"Clerk publishable key",
pk_shape,
),
Requirement(("CLERK_SECRET_KEY",), "Clerk secret key", sk_shape),
),
required_when=lambda env: flag_on(env, "REELFORGE_SIGNUP_ENABLED"),
)
phase3 = Phase(
key="3",
title="Payments (checkout rails + RevenueCat)",
gate_hint="required before REELFORGE_CHECKOUT_ENABLED=true",
requirements=(
Requirement(
("__PAYMENT_RAIL__",),
"At least one complete payment rail",
optional=False,
),
),
required_when=checkout_on,
)
phase4 = Phase(
key="4",
title="Direct publish (OAuth + Fernet token key)",
gate_hint="required before REELFORGE_PUBLISHING_ENABLED=true",
requirements=(
Requirement(
("SOCIAL_TOKEN_KEY",),
"Fernet token-encryption key (encrypts OAuth tokens at rest)",
shape_fernet_key,
),
Requirement(
("__PUBLISH_PROVIDER__",),
"At least one publishing OAuth app",
optional=False,
),
),
required_when=publishing_on,
)
return (phase0, phase1, phase2, phase3, phase4)
# Payment rails: a rail is usable only when ALL of its vars are set.
_PAYMENT_RAILS: dict[str, tuple[str, ...]] = {
"stripe": ("STRIPE_SECRET_KEY", "STRIPE_WEBHOOK_SECRET"),
"iyzico": ("IYZICO_API_KEY", "IYZICO_SECRET_KEY"),
"creem": ("CREEM_API_KEY", "CREEM_WEBHOOK_SECRET"),
"polar": ("POLAR_ACCESS_TOKEN", "POLAR_WEBHOOK_SECRET"),
}
# Publishing OAuth providers: a provider is usable when both client id + secret set.
_PUBLISH_PROVIDERS: tuple[str, ...] = ("TIKTOK", "INSTAGRAM", "YOUTUBE")
def evaluate_special(req: Requirement, env: dict[str, str]) -> CheckResult:
"""Handle composite requirements (payment rail / publish provider)."""
name = req.names[0]
if name == "__PAYMENT_RAIL__":
usable = [
rail
for rail, vars_ in _PAYMENT_RAILS.items()
if all(is_set(env.get(v)) for v in vars_)
]
if usable:
return CheckResult(
req.label, "|".join(_PAYMENT_RAILS), "PASS", "", ", ".join(usable)
)
return CheckResult(
req.label,
" | ".join(f"{r}: {'+'.join(v)}" for r, v in _PAYMENT_RAILS.items()),
"FAIL",
"no rail has both API and webhook credentials",
)
if name == "__PUBLISH_PROVIDER__":
usable = [
p
for p in _PUBLISH_PROVIDERS
if is_set(env.get(f"{p}_CLIENT_ID"))
and is_set(env.get(f"{p}_CLIENT_SECRET"))
]
if usable:
return CheckResult(
req.label, "<PROVIDER>_CLIENT_ID/SECRET", "PASS", "", ", ".join(usable)
)
return CheckResult(
req.label,
"TIKTOK/INSTAGRAM/YOUTUBE _CLIENT_ID + _CLIENT_SECRET",
"FAIL",
"no provider has both client id and secret",
)
return req.check(env)
def evaluate_requirement(req: Requirement, env: dict[str, str]) -> CheckResult:
if req.names and req.names[0].startswith("__"):
return evaluate_special(req, env)
return req.check(env)
# ---------------------------------------------------------------------------
# Launch-flag coherence (hard errors + warnings).
# ---------------------------------------------------------------------------
@dataclass
class Coherence:
errors: list[str] = field(default_factory=list)
warnings: list[str] = field(default_factory=list)
def check_launch_coherence(env: dict[str, str]) -> Coherence:
out = Coherence()
mode = env.get("REELFORGE_LAUNCH_MODE", "internal_pilot").strip().lower()
approved = flag_on(env, "REELFORGE_PUBLIC_LAUNCH_APPROVED")
signup = flag_on(env, "REELFORGE_SIGNUP_ENABLED")
checkout = checkout_on(env)
publishing = publishing_on(env)
if mode not in {"internal_pilot", "public"}:
out.errors.append("REELFORGE_LAUNCH_MODE must be internal_pilot or public")
if mode == "public" and not approved:
out.errors.append("public mode requires REELFORGE_PUBLIC_LAUNCH_APPROVED=true")
if (checkout or publishing) and mode != "public":
out.errors.append(
"checkout/publishing may be enabled only in approved public mode"
)
if signup and not (
is_set(env.get("CLERK_SECRET_KEY"))
and is_set(env.get("NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY"))
):
out.errors.append("REELFORGE_SIGNUP_ENABLED=true requires Clerk keys (Phase 2)")
if checkout:
usable = [
r for r, v in _PAYMENT_RAILS.items() if all(is_set(env.get(x)) for x in v)
]
if not usable:
out.errors.append(
"REELFORGE_CHECKOUT_ENABLED=true requires a complete payment rail (Phase 3)"
)
if publishing:
if not is_set(env.get("SOCIAL_TOKEN_KEY")):
out.errors.append(
"REELFORGE_PUBLISHING_ENABLED=true requires SOCIAL_TOKEN_KEY (Fernet key, Phase 4)"
)
providers = [
p
for p in _PUBLISH_PROVIDERS
if is_set(env.get(f"{p}_CLIENT_ID"))
and is_set(env.get(f"{p}_CLIENT_SECRET"))
]
if not providers:
out.errors.append(
"REELFORGE_PUBLISHING_ENABLED=true requires an OAuth app (Phase 4)"
)
if checkout and not signup:
out.warnings.append(
"checkout enabled but signup disabled — buyers cannot authenticate"
)
return out
# ---------------------------------------------------------------------------
# Optional connectivity checks (opt-in only).
# ---------------------------------------------------------------------------
def connectivity_checks(env: dict[str, str]) -> list[CheckResult]:
results: list[CheckResult] = []
db = first_set(env, "REELFORGE_DATABASE_URL", "NEON_DATABASE_URL", "DATABASE_URL")
if db:
results.append(_ping_postgres(db[1]))
if is_set(env.get("REDIS_HOST")):
results.append(_ping_redis(env))
r2 = first_set(env, "R2_S3_ENDPOINT")
if r2:
results.append(_head_r2(env, r2[1]))
return results
def _ping_postgres(url: str) -> CheckResult:
label = "DB connectivity"
try:
import psycopg # type: ignore
dsn = re.sub(r"^postgresql\+psycopg://", "postgresql://", url)
with psycopg.connect(dsn, connect_timeout=5) as conn:
conn.execute("SELECT 1")
return CheckResult(label, "SELECT 1", "PASS", "")
except ModuleNotFoundError:
return CheckResult(label, "psycopg", "WARN", "psycopg not installed; skipped")
except Exception as exc: # noqa: BLE001 - report, do not raise
return CheckResult(label, "SELECT 1", "FAIL", type(exc).__name__)
def _ping_redis(env: dict[str, str]) -> CheckResult:
label = "Redis connectivity"
try:
import redis # type: ignore
client = redis.Redis(
host=env.get("REDIS_HOST", "localhost"),
port=int(env.get("REDIS_PORT", "6379") or 6379),
db=int(env.get("REDIS_DB", "0") or 0),
password=env.get("REDIS_PASSWORD") or None,
socket_connect_timeout=5,
)
client.ping()
return CheckResult(label, "PING", "PASS", "")
except ModuleNotFoundError:
return CheckResult(label, "redis", "WARN", "redis not installed; skipped")
except Exception as exc: # noqa: BLE001
return CheckResult(label, "PING", "FAIL", type(exc).__name__)
def _head_r2(env: dict[str, str], endpoint: str) -> CheckResult:
label = "R2 connectivity"
bucket = first_set(env, "REELFORGE_R2_BUCKET_NAME", "R2_BUCKET_NAME", "R2_BUCKET")
if not bucket:
return CheckResult(label, "HEAD bucket", "WARN", "no bucket name; skipped")
try:
import boto3 # type: ignore
from botocore.config import Config # type: ignore
client = boto3.client(
"s3",
endpoint_url=endpoint,
aws_access_key_id=env.get("R2_ACCESS_KEY_ID"),
aws_secret_access_key=env.get("R2_SECRET_ACCESS_KEY"),
config=Config(connect_timeout=5, retries={"max_attempts": 1}),
)
client.head_bucket(Bucket=bucket[1])
return CheckResult(label, "HEAD bucket", "PASS", "")
except ModuleNotFoundError:
return CheckResult(label, "boto3", "WARN", "boto3 not installed; skipped")
except Exception as exc: # noqa: BLE001
return CheckResult(label, "HEAD bucket", "FAIL", type(exc).__name__)
# ---------------------------------------------------------------------------
# Rendering.
# ---------------------------------------------------------------------------
_ICON = {"PASS": "PASS", "FAIL": "FAIL", "WARN": "WARN"}
def phase_status(results: list[CheckResult]) -> str:
if any(r.status == "FAIL" for r in results):
return "FAIL"
if any(r.status == "WARN" for r in results):
return "PASS (with warnings)"
return "PASS"
def render_text(
phase_rows: list[tuple[Phase, bool, list[CheckResult]]],
coherence: Coherence,
connectivity: list[CheckResult],
) -> None:
print("=" * 78)
print("menivor / ReelForge — deploy readiness preflight")
print("(presence + shape only; secret values are never printed)")
print("=" * 78)
for phase, required, results in phase_rows:
status = phase_status(results)
if not required and status == "FAIL":
status = "PENDING (not required yet; creds not provided)"
tag = "REQUIRED" if required else "optional"
print(f"\nPhase {phase.key} — {phase.title} [{tag}] => {status}")
print(f" ({phase.gate_hint})")
for r in results:
detail = f" — {r.reason}" if r.reason else ""
resolved = f" [{r.resolved}]" if r.resolved and r.status == "PASS" else ""
print(f" {_ICON[r.status]:4} {r.label}{resolved}{detail}")
if r.status != "PASS":
print(f" set: {r.alias}")
print("\n" + "-" * 78)
print("Launch-flag coherence")
if not coherence.errors and not coherence.warnings:
print(" PASS flags are coherent")
for err in coherence.errors:
print(f" FAIL {err}")
for warn in coherence.warnings:
print(f" WARN {warn}")
if connectivity:
print("\n" + "-" * 78)
print("Connectivity (opt-in)")
for r in connectivity:
detail = f" — {r.reason}" if r.reason else ""
print(f" {_ICON[r.status]:4} {r.label}{detail}")
def render_json(
phase_rows: list[tuple[Phase, bool, list[CheckResult]]],
coherence: Coherence,
connectivity: list[CheckResult],
ok: bool,
) -> None:
import json
payload = {
"ok": ok,
"phases": [
{
"phase": phase.key,
"title": phase.title,
"required": required,
"status": phase_status(results),
"checks": [
{
"label": r.label,
"status": r.status,
"reason": r.reason,
"vars": r.alias,
"resolved": r.resolved,
}
for r in results
],
}
for phase, required, results in phase_rows
],
"coherence": {"errors": coherence.errors, "warnings": coherence.warnings},
"connectivity": [
{"label": r.label, "status": r.status, "reason": r.reason}
for r in connectivity
],
}
print(json.dumps(payload, indent=2))
# ---------------------------------------------------------------------------
# Main.
# ---------------------------------------------------------------------------
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--env-file",
type=Path,
default=None,
help="dotenv file to load (process env still wins). Values are never printed.",
)
parser.add_argument(
"--min-phase",
type=int,
default=1,
help="highest phase number required regardless of launch flags (default 1).",
)
parser.add_argument(
"--check-connectivity",
action="store_true",
help="opt into live DB/Redis/R2 checks (off by default; needs drivers).",
)
parser.add_argument("--json", action="store_true", help="machine-readable output")
args = parser.parse_args(argv)
env = load_env(args.env_file)
phases = build_phases()
phase_rows: list[tuple[Phase, bool, list[CheckResult]]] = []
hard_fail = False
for phase in phases:
results = [evaluate_requirement(req, env) for req in phase.requirements]
try:
phase_num = int(phase.key)
except ValueError:
phase_num = 99
required = phase.required_when(env) or phase_num <= args.min_phase
if required and any(r.status == "FAIL" for r in results):
hard_fail = True
phase_rows.append((phase, required, results))
coherence = check_launch_coherence(env)
if coherence.errors:
hard_fail = True
connectivity: list[CheckResult] = []
if args.check_connectivity:
connectivity = connectivity_checks(env)
if any(r.status == "FAIL" for r in connectivity):
hard_fail = True
ok = not hard_fail
if args.json:
render_json(phase_rows, coherence, connectivity, ok)
else:
render_text(phase_rows, coherence, connectivity)
print("\n" + "=" * 78)
if ok:
print("READY: all required phases pass. Proceed with the deploy runbook.")
else:
print("NOT READY: fix the FAIL rows above, then re-run this preflight.")
print("=" * 78)
return 0 if ok else 1
if __name__ == "__main__":
raise SystemExit(main())