Skip to content

armelhbobdad/oh-my-skills / .claude/skills/skf-campaign

skf-campaign

Verified

Campaign orchestration — multi-library skill production with dependency tracking, file-based state, and resume. Use when the user asks to "run a campaign" or "orchestrate skills."

scripts/campaign-deps.py

View on GitHub
# /// script
# requires-python = ">=3.11"
# dependencies = ["pyyaml"]
# ///
"""Campaign Deps — dependency computation and enforcement for campaign skills.

Two modes:
  --compute: topological sort of all skills from depends_on edges
  --check:   verify a single skill's dependencies are satisfied

A Tier A skill may not depend on a Tier B skill: Tier B skills are built in
the batch stage, after the skill loop that builds Tier A skills, so the Tier A
skill could never pass its dependency gate. --compute reports each such edge
in `tier_inversions` and exits 1, so the strategy stage rejects the plan
before any skill is built. That rule and the dangling-reference rule come
from campaign-parse-manifest.py's dependency_problems, the one statement of
both, so Setup and Strategy report the same entries.

At a blocked skill, --check names the status of each unmet dependency and the
headless default: `skip` when every unmet dependency failed or was skipped
(it can never complete in this run), `halt` when one is still pending or
active (an order the loop cannot follow).

CLI:
  uv run campaign-deps.py --compute --state-file <path>
  uv run campaign-deps.py --check --state-file <path> --skill <name>
  uv run campaign-deps.py --check --state-file <path> --skill <name> --force

Output (JSON on stdout):
  --compute:
    {"execution_order": [...], "circular_deps_detected": bool,
     "cycle_participants": [...] | null, "tier_counts": {"A": int, "B": int},
     "tier_inversions": [{"skill": "<Tier A>", "depends_on": "<Tier B>"}]}

  --check:
    {"skill": "name", "ready": bool, "unmet_deps": [...], "forced": bool,
     "unmet_status": {"<dep>": "<status>"}, "default_action": "skip" | "halt" | null}

Exit codes:
  0  success / ready / force-override
  1  circular deps / tier inversion / unmet deps / dangling reference
  2  error (missing file, bad YAML)
"""

from __future__ import annotations

import argparse
import importlib.util
import json
import sys
import heapq
from pathlib import Path
from typing import Any, Dict, List

import yaml

MANIFEST_SCRIPT = Path(__file__).resolve().with_name("campaign-parse-manifest.py")


def _dependency_problems(skills: List[Dict[str, Any]]) -> Dict[str, List[Dict[str, str]]]:
    """campaign-parse-manifest.py's dependency_problems (one rule for Setup and Strategy)."""
    spec = importlib.util.spec_from_file_location("campaign_parse_manifest", MANIFEST_SCRIPT)
    manifest = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(manifest)
    return manifest.dependency_problems(skills)


def _emit_error(message: str, code: str) -> None:
    json.dump({"error": message, "code": code}, sys.stderr)
    sys.stderr.write("\n")


def _load_yaml(path: Path) -> Any:
    with open(path, encoding="utf-8") as f:
        return yaml.safe_load(f)


def _build_skill_map(skills: List[Dict[str, Any]]) -> Dict[str, Dict[str, Any]]:
    return {s["name"]: s for s in skills}


def compute(state_file: str) -> int:
    path = Path(state_file)
    if not path.is_file():
        _emit_error(f"State file not found: {state_file}", "STATE_NOT_FOUND")
        return 2

    try:
        state = _load_yaml(path)
    except Exception as exc:
        _emit_error(f"Failed to parse state file: {exc}", "STATE_PARSE_ERROR")
        return 2

    skills = state.get("skills", [])
    if not isinstance(skills, list):
        _emit_error("State file 'skills' is not an array", "INVALID_STATE")
        return 2

    skill_map = _build_skill_map(skills)

    tier_counts = {"A": 0, "B": 0}
    for skill in skill_map.values():
        tier = skill.get("tier")
        if tier in tier_counts:
            tier_counts[tier] += 1

    problems = _dependency_problems(list(skill_map.values()))
    dangling = [
        f"{d['skill']} depends on unknown skill '{d['depends_on']}'"
        for d in problems["dangling_depends_on"]
    ]
    if dangling:
        _emit_error(
            f"Dangling dependency references: {'; '.join(dangling)}",
            "DANGLING_DEPENDENCY",
        )
        return 1

    inversions = problems["tier_inversions"]

    in_degree: Dict[str, int] = {name: 0 for name in skill_map}
    adjacency: Dict[str, List[str]] = {name: [] for name in skill_map}

    for name, skill in skill_map.items():
        for dep in skill.get("depends_on", []) or []:
            adjacency[dep].append(name)
            in_degree[name] += 1

    def _tier_key(n: str) -> tuple[int, str]:
        return (0 if skill_map[n].get("tier") == "A" else 1, n)

    heap: List[tuple[int, str]] = []
    for n in skill_map:
        if in_degree[n] == 0:
            heapq.heappush(heap, _tier_key(n))

    execution_order: List[str] = []

    while heap:
        _, current = heapq.heappop(heap)
        execution_order.append(current)

        for dependent in adjacency[current]:
            in_degree[dependent] -= 1
            if in_degree[dependent] == 0:
                heapq.heappush(heap, _tier_key(dependent))

    if len(execution_order) < len(skill_map):
        cycle_participants = sorted(
            n for n in skill_map if n not in set(execution_order)
        )
        output = {
            "execution_order": execution_order,
            "circular_deps_detected": True,
            "cycle_participants": cycle_participants,
            "tier_counts": tier_counts,
            "tier_inversions": inversions,
        }
        json.dump(output, sys.stdout, separators=(",", ":"))
        sys.stdout.write("\n")
        return 1

    if inversions:
        _emit_error(
            "Tier A skills depend on Tier B skills, which are built after them: "
            + "; ".join(f"{i['skill']} depends on {i['depends_on']}" for i in inversions),
            "TIER_INVERSION",
        )

    output = {
        "execution_order": execution_order,
        "circular_deps_detected": False,
        "cycle_participants": None,
        "tier_counts": tier_counts,
        "tier_inversions": inversions,
    }
    json.dump(output, sys.stdout, separators=(",", ":"))
    sys.stdout.write("\n")
    return 1 if inversions else 0


def check(state_file: str, skill_name: str, force: bool = False) -> int:
    path = Path(state_file)
    if not path.is_file():
        _emit_error(f"State file not found: {state_file}", "STATE_NOT_FOUND")
        return 2

    try:
        state = _load_yaml(path)
    except Exception as exc:
        _emit_error(f"Failed to parse state file: {exc}", "STATE_PARSE_ERROR")
        return 2

    skills = state.get("skills", [])
    if not isinstance(skills, list):
        _emit_error("State file 'skills' is not an array", "INVALID_STATE")
        return 2

    skill_map = _build_skill_map(skills)

    if skill_name not in skill_map:
        _emit_error(f"Skill '{skill_name}' not found in state", "SKILL_NOT_FOUND")
        return 2

    deps = skill_map[skill_name].get("depends_on", []) or []
    unmet: List[str] = []
    for dep in deps:
        if dep not in skill_map:
            _emit_error(
                f"Skill '{skill_name}' depends on unknown skill '{dep}'",
                "DANGLING_DEPENDENCY",
            )
            return 1
        if skill_map[dep].get("status") != "completed":
            unmet.append(dep)

    ready = len(unmet) == 0
    forced = force and not ready
    unmet_status = {dep: skill_map[dep].get("status") for dep in unmet}
    if ready:
        default_action = None
    elif all(status in ("failed", "skipped") for status in unmet_status.values()):
        default_action = "skip"
    else:
        default_action = "halt"

    if forced:
        json.dump(
            {"warning": f"Forcing past unmet dependencies for '{skill_name}'", "unmet": unmet},
            sys.stderr,
        )
        sys.stderr.write("\n")

    output = {
        "skill": skill_name,
        "ready": ready,
        "unmet_deps": unmet,
        "forced": forced,
        "unmet_status": unmet_status,
        "default_action": default_action,
    }
    json.dump(output, sys.stdout, separators=(",", ":"))
    sys.stdout.write("\n")

    if not ready and not force:
        return 1
    return 0


def main() -> int:
    parser = argparse.ArgumentParser(
        description="Campaign dependency computation and enforcement.",
    )
    mode = parser.add_mutually_exclusive_group(required=True)
    mode.add_argument(
        "--compute",
        action="store_true",
        help="Compute execution order via topological sort",
    )
    mode.add_argument(
        "--check",
        action="store_true",
        help="Check if a skill's dependencies are satisfied",
    )
    parser.add_argument("--state-file", required=True, help="Path to _campaign-state.yaml")
    parser.add_argument("--skill", help="Skill name (required for --check)")
    parser.add_argument(
        "--force",
        action="store_true",
        help="Force past dependency check (--check only)",
    )
    args = parser.parse_args()

    if args.check and not args.skill:
        parser.error("--skill is required when using --check")

    if args.compute:
        return compute(args.state_file)
    return check(args.state_file, args.skill, force=args.force)


if __name__ == "__main__":
    raise SystemExit(main())
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 323kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 323kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 323kUpdated Claude CodeCodexVerifiedInstall