Skip to content

by-carlos/plan-staged-rollout / skills/staged-rollout

staged-rollout

Unverified

Run a large build as many small, resumable sessions by decomposing it into a `.plan/` folder of dependency-ordered stages with an evidence ledger, then executing one stage per fresh session. Use when the user says "this is too big for one session", "plan a staged rollout", or describes a multi-day build that needs cross-session progress tracking.

FileKindSize
SKILL.mdskill md52.3 KB
references/decisions-format.mdmarkdown6.1 KB
references/estimates.mdmarkdown5.5 KB
references/plan-review.mdmarkdown7.4 KB
references/programme-format.mdmarkdown2.8 KB
references/remote-driver.mdmarkdown18.3 KB
references/templates/BRIEF.mdmarkdown3.0 KB
references/templates/LEDGER.mdmarkdown3.3 KB
references/templates/PLAN.mdmarkdown48.0 KB
references/templates/README.mdmarkdown8.2 KB
references/templates/RUNNER.mdmarkdown9.7 KB
references/templates/stage-N.mdmarkdown2.1 KB
references/templates/stage-f-review.mdmarkdown11.2 KB
scripts/artifacts_check.pyscript5.6 KB
scripts/effortlog.pyscript18.0 KB
scripts/estimates.pyscript14.4 KB
scripts/plan_run_local.pyscript31.4 KB
scripts/renumber_stages.pyscript13.2 KB
tests/fixtures/drift-plan/.plan/LEDGER.mdmarkdown1.0 KB
tests/fixtures/drift-plan/.plan/PLAN.mdmarkdown1.7 KB
tests/fixtures/live-plan/.plan/LEDGER.mdmarkdown564 B
tests/fixtures/live-plan/.plan/PLAN.mdmarkdown1.4 KB
tests/fixtures/live-plan/.plan/stage-0-scaffold.mdmarkdown90 B
tests/fixtures/live-plan/.plan/stage-1-build-api.mdmarkdown83 B
tests/fixtures/live-plan/.plan/stage-2-deploy-staging.mdmarkdown87 B
tests/fixtures/live-plan/.plan/stage-3-migrate-data.mdmarkdown97 B
tests/fixtures/live-plan/.plan/stage-4-warm-cache.mdmarkdown84 B
tests/fixtures/live-plan/.plan/stage-5-runbook.mdmarkdown87 B
tests/fixtures/live-plan/.plan/stage-f-review.mdmarkdown81 B
tests/test_artifacts_check.pyscript5.9 KB
tests/test_discovery_bound.pyscript2.3 KB
tests/test_estimates.pyscript10.7 KB
tests/test_plan_run_local.pyscript18.3 KB
tests/test_preflight_ahead.pyscript3.3 KB
tests/test_renumber_stages.pyscript17.0 KB

scripts/effortlog.py

View on GitHub
#!/usr/bin/env python3
"""Runaway-spend circuit breaker, and the one-line run record it leaves behind.

Two jobs, deliberately kept in a script rather than in skill prose:

  check  Read *this* session's own transcript, total the current context, and
         say whether it has blown a generous budget for the declared scope.
  log    Append one NDJSON row describing how the run went.
  tally  Append one NDJSON row for a create-issue run: what the gap review
         produced and whether it changed the ticket. Same log, same switch.
  usage  Print this session's actuals -- wall-clock span and summed tokens,
         subagents included -- and the `Actuals:` line a stage's ledger notes
         carry. Reads only; never gated by `CLAUDE_EFFORT_LOG`.

Why a script. A skill could in principle instruct the model to do the same
arithmetic inline, but the session that most needs this check is the one that
has already lost the thread — exactly the session least likely to do careful
bookkeeping. The measurement has to work without the model's cooperation, so
it reads a file and returns a number.

Why the transcript and not a usage tool. `CLAUDE_CODE_SESSION_ID` is always in
the environment and Claude Code always writes `<id>.jsonl` under some
`projects/` directory, so this works identically in an attended desktop session
and an unattended cloud run. A host-provided usage tool does not: it may be
absent from the very unattended runs this exists to stop. Note that the two do
not agree to the token -- they sample at different moments and may account
differently -- so a budget is only meaningful in the unit that `check` reports.

This is a BREAKER, not a classifier. The budgets carry 2-3x headroom over a
healthy run: blowing one means something has gone wrong, not that the work was
merely chunky. Nothing here tries to decide whether a model tier was correct --
that judgement needs many rows and belongs to whatever reads the log later.

Invoke as `python <path>/effortlog.py <subcommand> ...` -- one native command
that behaves identically in PowerShell 5.1, pwsh and git-bash.

Logging is opt-in and silent when off: with `CLAUDE_EFFORT_LOG` unset, `log`
writes nothing and still exits 0. A plugin distributed to other people must
not start appending files to their home directory because it was installed.

Exit codes
----------
  check   0 under budget, 3 over budget (the trip), 2 usage/IO failure
  log     0 written or deliberately skipped, 2 usage/IO failure
  tally   0 written or deliberately skipped, 2 usage/IO failure
  usage   0 printed, 2 no session id, transcript or usage
"""

from __future__ import annotations

import argparse
import json
import os
import sys
from datetime import datetime, timezone
from pathlib import Path

# Generous by design -- see the module docstring. Units are the context total
# that `check` reports, which is NOT interchangeable with a host usage tool's
# figure. Starting values, expected to be revised once the log has rows.
BUDGETS = {
    "XS": 150_000,
    "S": 250_000,
    "M": 400_000,
    "L": 600_000,
    "XL": 800_000,
}
DEFAULT_BUDGET = 400_000  # scopes with no declared size (e.g. a plan stage)

CONTEXT_KEYS = ("input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens")


def fail(message: str) -> "int":
    print(f"effortlog: {message}", file=sys.stderr)
    return 2


def session_id() -> str | None:
    return os.environ.get("CLAUDE_CODE_SESSION_ID") or None


def is_attended() -> bool:
    """Whether a human is watching. The harness states this outright.

    Absent means unattended: the safe reading, since a cloud run that lost the
    variable should still be stopped rather than left to burn.
    """
    return os.environ.get("CLAUDE_CODE_SESSION_ATTENDED", "") == "1"


def profile_roots() -> list[Path]:
    """`~/.claude` plus every `~/.claude-*` profile that holds transcripts."""
    home = Path.home()
    roots = []
    for candidate in [home / ".claude"] + sorted(home.glob(".claude-*")):
        projects = candidate / "projects"
        if projects.is_dir():
            roots.append(projects)
    return roots


def find_transcript(sid: str) -> Path | None:
    """Locate `<sid>.jsonl` by search rather than by rebuilding the slug.

    The project directory name is a mangled form of the working directory, and
    re-deriving that mangling here would be a second implementation of someone
    else's rule -- one that breaks silently the day it changes.
    """
    for projects in profile_roots():
        for path in projects.glob(f"*/{sid}.jsonl"):
            return path
        direct = projects / f"{sid}.jsonl"
        if direct.is_file():
            return direct
    return None


def read_transcript(transcript: Path) -> tuple[int | None, str | None]:
    """Context total and model name, as of the last assistant turn with usage.

    Deliberately the LAST turn's figure, not a sum across turns: context is a
    working-set size, and summing would double-count every cached read.

    The model is taken from the same row rather than from the environment,
    which carries no model variable -- and reading it here means the caller
    cannot misreport what it was actually running on.
    """
    latest_usage = None
    latest_model = None
    with transcript.open(encoding="utf-8", errors="ignore") as handle:
        for line in handle:
            line = line.strip()
            if not line:
                continue
            try:
                row = json.loads(line)
            except ValueError:
                continue
            if row.get("type") != "assistant":
                continue
            message = row.get("message") or {}
            usage = message.get("usage") or {}
            if usage:
                latest_usage = usage
                latest_model = message.get("model") or latest_model
    if latest_usage is None:
        return None, latest_model
    total = sum(int(latest_usage.get(key, 0) or 0) for key in CONTEXT_KEYS)
    return total, latest_model


def measure_subagents() -> int | None:
    """Summed context of this session's subagents, or None when it had none.

    Claude Code writes each subagent's transcript under `<sid>/subagents/`
    beside the session's own `<sid>.jsonl`. Each one contributes its last
    turn's figure -- the same unit `read_transcript` reports -- so a bootstrap
    row can carry its review lenses' share without the model adding it up.
    """
    sid = session_id()
    if not sid:
        return None
    transcript = find_transcript(sid)
    if transcript is None:
        return None
    totals = []
    for path in sorted((transcript.parent / sid / "subagents").glob("*.jsonl")):
        total, _ = read_transcript(path)
        if total is not None:
            totals.append(total)
    return sum(totals) if totals else None


USAGE_KEYS = {
    "in": "input_tokens",
    "out": "output_tokens",
    "cache_read": "cache_read_input_tokens",
    "cache_write": "cache_creation_input_tokens",
}


def sum_usage(transcript: Path) -> dict:
    """Running token totals, first and last timestamp of one transcript.

    Unlike `read_transcript`, this is a SUM: it answers "what did this run
    spend", not "how big is the context now". Streaming writes one assistant
    message as several lines that repeat the same usage, so each message id is
    counted once -- summing lines would double or triple the figure.
    """
    tokens = {name: 0 for name in USAGE_KEYS}
    seen: set[str] = set()
    first = last = None
    with transcript.open(encoding="utf-8", errors="ignore") as handle:
        for line in handle:
            line = line.strip()
            if not line:
                continue
            try:
                row = json.loads(line)
            except ValueError:
                continue
            stamp = row.get("timestamp")
            if isinstance(stamp, str):
                first = first or stamp
                last = stamp
            if row.get("type") != "assistant":
                continue
            message = row.get("message") or {}
            usage = message.get("usage") or {}
            if not usage:
                continue
            key = message.get("id") or row.get("uuid")
            if key in seen:
                continue
            if key:
                seen.add(key)
            for name, field in USAGE_KEYS.items():
                tokens[name] += int(usage.get(field, 0) or 0)
    return {"start": first, "finish": last, "tokens": tokens}


def parse_stamp(stamp: str | None) -> datetime | None:
    if not stamp:
        return None
    try:
        return datetime.fromisoformat(stamp.replace("Z", "+00:00"))
    except ValueError:
        return None


def measure_usage() -> dict:
    """This session's actuals: wall-clock span and tokens, subagents included.

    The span runs from the transcript's first timestamp to its last, so it
    includes any time spent waiting on the user -- an estimate leaves that out,
    and a reader comparing the two should know it.
    """
    sid = session_id()
    if not sid:
        raise RuntimeError("CLAUDE_CODE_SESSION_ID is not set")
    transcript = find_transcript(sid)
    if transcript is None:
        raise RuntimeError(f"no transcript found for session {sid}")
    main = sum_usage(transcript)
    subagents = sorted((transcript.parent / sid / "subagents").glob("*.jsonl"))
    tokens = dict(main["tokens"])
    for path in subagents:
        for name, value in sum_usage(path)["tokens"].items():
            tokens[name] += value
    start, finish = parse_stamp(main["start"]), parse_stamp(main["finish"])
    minutes = round((finish - start).total_seconds() / 60) if start and finish else None
    return {
        "start": main["start"],
        "finish": main["finish"],
        "elapsed_minutes": minutes,
        "tokens": tokens,
        "subagents": len(subagents),
        "session_id": sid,
    }


def actuals_line(usage: dict) -> str:
    """The one line `/stage-run` pastes into a ledger notes block.

    Fixed shape, raw integers: `estimates.py report` parses it back, so a
    rounded "3.6k" here would be a number nobody can add up later.
    """
    t = usage["tokens"]
    return (
        f"Actuals: {usage['start']} → {usage['finish']} · "
        f"{usage['elapsed_minutes']} min · "
        f"tokens in={t['in']} out={t['out']} cache_read={t['cache_read']} "
        f"cache_write={t['cache_write']} · subagents={usage['subagents']}"
    )


def cmd_usage(args: argparse.Namespace) -> int:
    try:
        usage = measure_usage()
    except RuntimeError as exc:
        return fail(str(exc))
    usage["line"] = actuals_line(usage)
    if hasattr(sys.stdout, "reconfigure"):
        sys.stdout.reconfigure(encoding="utf-8")
    print(json.dumps(usage, indent=2, ensure_ascii=False))
    return 0


def measure() -> tuple[int, str | None]:
    sid = session_id()
    if not sid:
        raise RuntimeError("CLAUDE_CODE_SESSION_ID is not set")
    transcript = find_transcript(sid)
    if transcript is None:
        raise RuntimeError(f"no transcript found for session {sid}")
    total, model = read_transcript(transcript)
    if total is None:
        raise RuntimeError(f"no assistant usage recorded yet in {transcript}")
    return total, model


def cmd_check(args: argparse.Namespace) -> int:
    try:
        total, _ = measure()
    except RuntimeError as exc:
        return fail(str(exc))

    if args.budget is not None:
        budget = args.budget
    elif args.size:
        budget = BUDGETS.get(args.size.upper(), DEFAULT_BUDGET)
    else:
        budget = DEFAULT_BUDGET

    over = total > budget
    print(
        f"context={total} budget={budget} "
        f"attended={'yes' if is_attended() else 'no'} "
        f"verdict={'OVER' if over else 'ok'}"
    )
    if over:
        action = "warn and continue" if is_attended() else "STOP and report"
        print(f"effortlog: over budget -- {action}", file=sys.stderr)
        return 3
    return 0


def cmd_log(args: argparse.Namespace) -> int:
    destination = os.environ.get("CLAUDE_EFFORT_LOG")
    if not destination:
        print("effortlog: CLAUDE_EFFORT_LOG unset, nothing logged")
        return 0

    try:
        total, model = measure()
    except RuntimeError:
        # A record without a measurement still beats no record at all.
        total, model = None, None
    try:
        usage = measure_usage()
    except (RuntimeError, OSError):
        usage = {}

    row = {
        "ts": datetime.now(timezone.utc).isoformat(timespec="seconds"),
        "source": args.source,
        "repo": args.repo,
        "target": args.target,
        "estimated_tier": args.estimated_tier,
        "actual_model": args.model or model,
        "actual_effort": os.environ.get("CLAUDE_EFFORT"),
        "size": args.size,
        "estimate": args.estimate,
        "elapsed_minutes": usage.get("elapsed_minutes"),
        "tokens": usage.get("tokens"),
        "context_tokens": total,
        "subagent_tokens": measure_subagents(),
        "tripped": bool(args.tripped),
        "attended": is_attended(),
        "outcome": args.outcome,
        "note": args.note,
        "session_id": session_id(),
    }

    return append_row(Path(destination), row)


def append_row(path: Path, row: dict) -> int:
    try:
        path.parent.mkdir(parents=True, exist_ok=True)
        with path.open("a", encoding="utf-8", newline="\n") as handle:
            handle.write(json.dumps(row, ensure_ascii=True) + "\n")
    except OSError as exc:
        return fail(f"could not append to {path}: {exc}")

    print(f"effortlog: appended to {path}")
    return 0


def read_json(path: Path) -> dict | None:
    """The file's object, or None when it does not exist. A file that exists
    but cannot be read raises, so a corrupt run record is reported, not hidden."""
    if not path.is_file():
        return None
    data = json.loads(path.read_text(encoding="utf-8"))
    if not isinstance(data, dict):
        raise ValueError(f"{path.name} is not a JSON object")
    return data


def project_of(draft: dict | None) -> str | None:
    """`owner/repo` for GitHub, `site/KEY` for Jira, from the draft's target."""
    target = (draft or {}).get("target") or {}
    if target.get("repo"):
        return target["repo"]
    if target.get("project"):
        return "/".join(part for part in (target.get("site"), target["project"]) if part)
    return None


def cmd_tally(args: argparse.Namespace) -> int:
    destination = os.environ.get("CLAUDE_EFFORT_LOG")
    if not destination:
        print("effortlog: CLAUDE_EFFORT_LOG unset, nothing logged")
        return 0

    work = Path(args.work)
    try:
        draft = read_json(work / "draft.json")
        filtered = read_json(work / "review-filtered.json")
        skipped = read_json(work / "review-skipped.json")
    except (OSError, ValueError) as exc:
        return fail(f"could not read the run folder {work}: {exc}")

    questions = (filtered or {}).get("questions") or []
    nits = (filtered or {}).get("nits") or []
    review = "ran" if filtered is not None else "skipped" if skipped is not None else "none"
    row = {
        "ts": datetime.now(timezone.utc).isoformat(timespec="seconds"),
        "source": "create-issue",
        "project": project_of(draft),
        "ticket": args.ticket or "not posted",
        "review": review,
        "skip_reason": (skipped or {}).get("reason"),
        "blockers": int((filtered or {}).get("blockers") or 0),
        "gaps": sum(1 for q in questions if q.get("severity") == "gap"),
        "questions_asked": len(questions),
        "nits_applied": len(nits),
        "gaps_dropped": len((filtered or {}).get("gaps_dropped") or []),
        "gate": args.gate,
        "changed_text": bool(nits) or bool(args.answers_edited),
        "session_id": session_id(),
    }
    return append_row(Path(destination), row)


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(prog="effortlog.py")
    subparsers = parser.add_subparsers(dest="command", required=True)

    check = subparsers.add_parser("check", help="context total vs a scope budget")
    check.add_argument("--size", help="XS|S|M|L|XL; omitted uses the default budget")
    check.add_argument("--budget", type=int, help="explicit token budget, overrides --size")
    check.set_defaults(func=cmd_check)

    log = subparsers.add_parser("log", help="append one run record")
    log.add_argument("--source", required=True, choices=["work-issue", "stage-run", "plan-stages"])
    log.add_argument("--repo", help="owner/repo")
    log.add_argument("--target", help="issue number, <plan-slug>/S<n>, or <plan-slug> for a bootstrap")
    log.add_argument("--estimated-tier", dest="estimated_tier", help="the Effort the run was launched on")
    log.add_argument("--model", help="override; by default read from the transcript")
    log.add_argument("--size", help="declared scope, when there is one")
    log.add_argument("--estimate", help="the stage's estimate from the index, e.g. 1-2h")
    log.add_argument(
        "--outcome",
        help="merged | pr-open | abandoned | stage-done | stage-blocked | plan-scaffolded",
    )
    log.add_argument("--tripped", action="store_true", help="the breaker fired during this run")
    log.add_argument("--note", help="one free-text line for a human reading this later")
    log.set_defaults(func=cmd_log)

    usage = subparsers.add_parser("usage", help="this session's elapsed time and token totals")
    usage.set_defaults(func=cmd_usage)

    tally = subparsers.add_parser("tally", help="append one create-issue gap-review row")
    tally.add_argument("--work", required=True, help="the run's work folder")
    tally.add_argument("--gate", required=True, choices=["posted", "edited-first", "not-posted", "dry-run"])
    tally.add_argument("--ticket", help="key or number of the posted ticket; omitted means not posted")
    tally.add_argument(
        "--answers-edited",
        dest="answers_edited",
        action="store_true",
        help="an answered question changed the draft (applied nits are counted from the review itself)",
    )
    tally.set_defaults(func=cmd_tally)

    return parser


def main(argv: list[str] | None = None) -> int:
    args = build_parser().parse_args(argv)
    return args.func(args)


if __name__ == "__main__":
    sys.exit(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