CtrlK
BlogDocsLog inGet started
Tessl Logo
PluginPublic

gamussa/reels-producer-skill

Write talking-head scripts and produce Instagram reels and YouTube shorts

1.07x
Quality

96%

Does it follow best practices?

Impact

98%

1.07x

Average score across 8 eval scenarios

SecuritybySnyk

Low

Low-risk findings worth noting

Overview
Quality
Evals
Security
Files

plan_schema.pyskills/reel-builder/scripts/

#!/usr/bin/env python3
"""Owner of plan/cut_plan.json: its version, its keys, and every read and write.

Every script that writes a cut plan (build_cut_plan.py, import_timeline.py,
resolve_bridge.py, transitions.py) writes it through write(), which stamps
PLAN_SCHEMA; every script that reads one reads it through load(), which
upgrades an older plan on read and rewrites it (the owner's migration), and
refuses a plan newer than this skill. The agent writes plans by hand too; the
first script that reads such a plan stamps it.

Version history (shape documented in references/state-schema.md "cut_plan.json"):
  1  no schema_version key (every plan before 0.51.0)
  2  the same keys plus "schema_version": 2 — the upgrade only adds the stamp

Usage:
  plan_schema.py check plan/cut_plan.json     validate and upgrade; JSON on stdout

Exit codes: 0 ok; 1 not a usable plan. A failure also explains itself on stderr.
"""

import json
import math
import os
import sys
from pathlib import Path

PLAN_SCHEMA = 2
# Every top-level key a plan may carry, and the type it must have.
TOP_KEYS = {
    "schema_version": int,
    "segments": list,
    "music": str,
    "music_start": (int, float),
    "total_duration": (int, float),
    "bpm": (int, float),
    "vo": dict,
    "audio": str,
    "speech_end": (int, float),
    "fade_out": dict,
    "fps": (int, float, type(None)),
}
SEGMENT_REQUIRED = {"clip": str, "in": (int, float), "duration": (int, float)}


class PlanError(Exception):
    pass


def validate(plan):
    """Errors in a plan, [] when every reader can use it."""
    if not isinstance(plan, dict):
        return ['a cut plan must be a JSON object with a "segments" list']
    errors = []
    for key, kind in TOP_KEYS.items():
        if key in plan and (not isinstance(plan[key], kind) or isinstance(plan[key], bool)):
            errors.append(f"{key} has the wrong type")
    segs = plan.get("segments")
    if not isinstance(segs, list) or not segs:
        errors.append("segments must be a non-empty list")
        return errors
    for n, seg in enumerate(segs):
        if not isinstance(seg, dict):
            errors.append(f"segment {n} must be an object")
            continue
        for key, kind in SEGMENT_REQUIRED.items():
            if not isinstance(seg.get(key), kind) or isinstance(seg.get(key), bool):
                errors.append(
                    f"segment {n}: {key} is required ({'a path' if kind is str else 'seconds'})"
                )
        for key, positive in (("in", False), ("duration", True)):
            v = seg.get(key)
            if (
                isinstance(v, (int, float))
                and not isinstance(v, bool)
                and not (seconds(v) and (v > 0 if positive else v >= 0))
            ):
                errors.append(
                    f"segment {n}: {key} must be finite seconds {'> 0' if positive else '>= 0'}"
                )
    vo = plan.get("vo")
    if isinstance(vo, dict):
        if not isinstance(vo.get("file"), str) or not vo["file"]:
            errors.append("vo.file is required: the voice file's path")
        if "start" in vo and not (seconds(vo["start"]) and vo["start"] >= 0):
            errors.append("vo.start must be seconds >= 0 into the voice file")
        if "words" in vo and not isinstance(vo["words"], str):
            errors.append("vo.words must be a path to the voice's words JSON")
    fade = plan.get("fade_out")
    if isinstance(fade, dict):
        if "seconds" in fade and not (seconds(fade["seconds"]) and fade["seconds"] > 0):
            errors.append("fade_out.seconds must be seconds > 0")
        if "video" in fade and not isinstance(fade["video"], bool):
            errors.append("fade_out.video must be true or false")
    for key in ("speech_end", "music_start"):
        if key in plan and not (seconds(plan[key]) and plan[key] >= 0):
            errors.append(f"{key} must be seconds >= 0")
    if "total_duration" in plan and not (
        seconds(plan["total_duration"]) and plan["total_duration"] > 0
    ):
        errors.append("total_duration must be seconds > 0")
    for key in ("bpm", "fps"):
        v = plan.get(key)
        if isinstance(v, (int, float)) and not isinstance(v, bool) and not (seconds(v) and v > 0):
            errors.append(f"{key} must be a finite number > 0")
    if "audio" in plan and plan["audio"] != "segments":
        errors.append('audio, when set, must be "segments"')
    return errors


def seconds(v):
    """A finite number of seconds (not a bool, NaN or infinity)."""
    return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)


def stamp(plan):
    plan["schema_version"] = PLAN_SCHEMA
    return plan


def write(path, plan):
    """The only way a script writes a plan: stamped, atomically replaced."""
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_name(f"{path.name}.tmp.{os.getpid()}")
    try:
        tmp.write_text(json.dumps(stamp(plan), indent=2) + "\n")
        tmp.replace(path)
    finally:
        tmp.unlink(missing_ok=True)


def load(path):
    """The only way a script reads a plan. An older plan is upgraded and
    rewritten; a newer one is refused. Raises PlanError with what to do."""
    path = Path(path)
    try:
        plan = json.loads(path.read_text())
    except (OSError, json.JSONDecodeError) as err:
        raise PlanError(f"cannot read cut plan {path}: {err}") from None
    if not isinstance(plan, dict):
        raise PlanError(f'{path} is not a cut plan (a JSON object with "segments")')
    version = plan.get("schema_version", 1)
    if version not in (1, PLAN_SCHEMA):
        raise PlanError(
            f"{path} is cut_plan schema_version {version!r}; this skill reads up "
            f"to {PLAN_SCHEMA} — update the skill"
        )
    if version == 1:
        write(path, plan)  # the owner's migration: only the stamp changes
    return plan


def load_or_exit(path):
    """load() for scripts whose contract is sys.exit with a message."""
    try:
        return load(path)
    except PlanError as err:
        sys.exit(str(err))


def main(argv=None):
    import argparse

    ap = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
    )
    ap.add_argument("cmd", choices=("check",))
    ap.add_argument("plan")
    a = ap.parse_args(argv)
    try:
        plan = load(a.plan)
    except PlanError as err:
        print(json.dumps({"ok": False, "error": str(err)}))
        print(f"plan_schema.py check failed: {err}", file=sys.stderr)
        return 1
    errors = validate(plan)
    print(
        json.dumps({"ok": not errors, "errors": errors, "schema_version": plan["schema_version"]})
    )
    for err in errors:
        print(f"plan_schema.py check: {err} — fix it in {a.plan}", file=sys.stderr)
    return 1 if errors else 0


if __name__ == "__main__":
    sys.exit(main())

skills

tile.json