Skip to content

borghei/Claude-Skills / engineering/human-step-wizard

human-step-wizard

Flagged

Generate an interactive, resumable bash wizard that walks a person through steps only a human can do. Use when a task needs dashboard credentials, DNS or change approval, key rotation, or a manual traffic cutover.

scripts/wizard_generate.py

View on GitHub
#!/usr/bin/env python3
"""Generate an interactive, resumable bash wizard from a human-step spec (JSON).

The spec is validated first (wizard_spec_validate.py, loaded from this folder);
a spec with errors produces no script. The output is a single self-contained
bash file: a header with the spec's data, the shared runtime from
assets/wizard_runtime.sh, and one function per step. Every string from the spec
is emitted as a single-quoted shell literal, so no spec text is ever expanded,
and values the human types are stored with printf -v and never evaluated.

Usage:
  python3 wizard_generate.py --spec ../assets/sample_wizard_spec.json --out cutover-wizard.sh
  python3 wizard_generate.py --spec spec.json --stdout > wizard.sh
  python3 wizard_generate.py --spec spec.json --out wizard.sh --format json

Exit codes:
  0  script written (and bash -n passed, when bash is available)
  1  spec has validation errors, or the generated script failed bash -n
  2  usage error (unreadable spec or runtime, output path problem)
"""

from __future__ import annotations

import argparse
import hashlib
import importlib.util
import json
import shutil
import stat
import subprocess
import sys
from pathlib import Path
from typing import Any, Dict, List

SKILL_DIR = Path(__file__).resolve().parent.parent
RUNTIME = SKILL_DIR / "assets" / "wizard_runtime.sh"
GENERATOR_VERSION = "1.0.0"


def _load_validator() -> Any:
    """Load the sibling validator by path so the skill folder stays self-contained."""
    path = Path(__file__).resolve().parent / "wizard_spec_validate.py"
    spec = importlib.util.spec_from_file_location("wizard_spec_validate", path)
    if spec is None or spec.loader is None:
        raise SystemExit(f"error: cannot load {path}")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


def q(text: Any) -> str:
    """Quote any value as a single bash word with no expansion at all."""
    return "'" + str(text).replace("'", "'\"'\"'") + "'"


def render_step(n: int, step: Dict[str, Any]) -> List[str]:
    """Emit the bash function for one step."""
    out = [f"step_{n}() {{", f"  w_header {n} {q(step['title'])}"]
    if step.get("irreversible"):
        out.append(f"  w_confirm_irreversible {q(step['id'])} {q(step['rollback'])}")
    for idx, line in enumerate(step["instructions"], 1):
        out.append(f"  w_say {q(f'  {idx}. {line}')}")
    if step.get("url"):
        out.append(f"  w_open_url {q(step['url'])}")
    inputs = step.get("inputs") or []
    if step.get("pause", not inputs) or step.get("irreversible"):
        out.append("  w_pause")
    for inp in inputs:
        secret = "1" if inp.get("secret") else "0"
        out.append(f"  w_ask {q(inp['name'])} {q(inp['prompt'])} {q(inp.get('pattern') or '')} {secret}")
        if inp.get("store", "env") == "env":
            out.append(f"  w_store_env {q(inp['name'])}")
    allow_skip = "1" if step.get("allow_skip") else "0"
    for chk in step.get("checks") or []:
        desc = chk.get("description") or chk["command"]
        out.append(f"  w_check {q(desc)} {q(chk['command'])} {allow_skip}")
    out.append("}")
    return out


def render(spec: Dict[str, Any], runtime: str, spec_sha: str) -> str:
    """Assemble the full wizard script."""
    steps = spec["steps"]
    names = sorted({i["name"] for s in steps for i in (s.get("inputs") or [])})
    header = [
        "#!/usr/bin/env bash",
        f"# {spec['title']}".replace("\n", " "),
        f"# Generated by human-step-wizard {GENERATOR_VERSION} from a spec with sha256 {spec_sha[:16]}.",
        "# Regenerate from the spec instead of editing this file by hand.",
        "# Run it in a terminal; re-run to resume. --list shows progress, --help shows options.",
        "set -euo pipefail",
        "",
        f"WIZARD_TITLE={q(spec['title'])}",
        f"WIZARD_SLUG={q(spec['slug'])}",
        'WIZARD_ENV_FILE="${WIZARD_ENV_FILE:-}"',
        f"[ -n \"$WIZARD_ENV_FILE\" ] || WIZARD_ENV_FILE={q(spec.get('env_file', '.env'))}",
        f"WIZARD_VARS={q(' '.join(names))}",
        "WIZARD_STEP_IDS=(" + " ".join(q(s["id"]) for s in steps) + ")",
        "WIZARD_STEP_TITLES=(" + " ".join(q(s["title"]) for s in steps) + ")",
        "",
    ]
    if spec.get("description"):
        header.insert(2, "# " + str(spec["description"]).replace("\n", " ")[:200])
    body: List[str] = []
    for n, step in enumerate(steps, 1):
        body.extend(render_step(n, step))
        body.append("")
    return "\n".join(header) + "\n" + runtime.rstrip() + "\n\n" + "\n".join(body) + 'w_main "$@"\n'


def syntax_check(path: Path) -> Dict[str, Any]:
    """Run bash -n on the output if bash exists."""
    bash = shutil.which("bash")
    if not bash:
        return {"ran": False, "ok": True, "detail": "bash not found; syntax check skipped"}
    res = subprocess.run([bash, "-n", str(path)], capture_output=True, text=True, timeout=20)
    return {"ran": True, "ok": res.returncode == 0, "detail": res.stderr.strip()}


def main() -> None:
    """Entry point."""
    p = argparse.ArgumentParser(description="Generate an interactive bash wizard from a step spec.")
    p.add_argument("--spec", required=True, help="wizard spec JSON")
    target = p.add_mutually_exclusive_group(required=True)
    target.add_argument("--out", help="write the script here (made executable)")
    target.add_argument("--stdout", action="store_true", help="print the script instead of writing a file")
    p.add_argument("--force", action="store_true", help="overwrite --out if it already exists")
    p.add_argument("--format", choices=["text", "json"], default="text", help="summary format (default: text)")
    args = p.parse_args()

    validator = _load_validator()
    spec = validator.load_spec(args.spec)
    report = validator.validate(spec)
    if report["errors"]:
        print(f"error: spec has {len(report['errors'])} validation error(s); no script generated", file=sys.stderr)
        for e in report["errors"]:
            print(f"  - {e}", file=sys.stderr)
        sys.exit(1)
    try:
        runtime = RUNTIME.read_text(encoding="utf-8")
    except OSError as exc:
        print(f"error: cannot read runtime {RUNTIME}: {exc}", file=sys.stderr)
        sys.exit(2)
    raw = Path(args.spec).read_bytes()
    script = render(spec, runtime, hashlib.sha256(raw).hexdigest())
    if args.stdout:
        sys.stdout.write(script)
        sys.exit(0)

    out = Path(args.out)
    if out.exists() and not args.force:
        print(f"error: {out} exists; pass --force to overwrite", file=sys.stderr)
        sys.exit(2)
    try:
        out.parent.mkdir(parents=True, exist_ok=True)
        out.write_text(script, encoding="utf-8")
        out.chmod(out.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP)
    except OSError as exc:
        print(f"error: cannot write {out}: {exc}", file=sys.stderr)
        sys.exit(2)
    check = syntax_check(out)
    summary = {"script": str(out), "steps": report["steps"], "inputs": report["inputs"],
               "irreversible_steps": [s["id"] for s in spec["steps"] if s.get("irreversible")],
               "env_file": spec.get("env_file", ".env"), "lines": script.count("\n"),
               "syntax_check": check, "warnings": report["warnings"]}
    if args.format == "json":
        print(json.dumps(summary, indent=2))
    else:
        print(f"Wrote {out} ({summary['lines']} lines, {summary['steps']} steps)")
        print(f"  captures: {', '.join(summary['inputs']) or 'nothing'} -> {summary['env_file']}")
        if summary["irreversible_steps"]:
            print(f"  typed confirmation before: {', '.join(summary['irreversible_steps'])}")
        print(f"  bash -n: {'ok' if check['ok'] else 'FAILED ' + check['detail']}"
              + ("" if check["ran"] else " (skipped)"))
        for w in summary["warnings"]:
            print(f"  warn: {w}")
        print(f"\nRun it in a terminal: ./{out.name}   (--list for progress, --help for options)")
    sys.exit(0 if check["ok"] else 1)


if __name__ == "__main__":
    main()
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall