Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,15 +86,18 @@ cost, lower thinking for mechanical stages, a larger model at lower
thinking for design work, faster models for long or wide work and one step
up for risk. Claude stages and phase reviews are then built headless by
`plugins/phased-delivery/scripts/claude-build.sh` (`claude -p`), stopped at
a dollar cap: 150k tokens for `small`, 400k for `middle`, 1M for `top`, at
a dollar cap: 150k tokens for `small`, 400k for `middle`, 1M for `top` and `top+`, at
the pair's input price. A stage stopped at its cap is retried one step down
the frontier; one that fails its checks, one step up. Premium models
(output price of $30 or more per million tokens) are used below `top` only
when cheaper than the standard pick and as good, or as the step up past the
last standard pick while their score per unit of cost is within 5% of it;
`top` comes only from a total score of 9 or more. They get $10 per phase; past
that, builds use none. Reviews always run on `top`, and their cost counts
against that budget. The builder may edit files and runs only the commands
`top` comes only from a total score of 9 or more. The most capable pair is
kept for `top+`: a `top` stage with a total of 12 or more or the highest
risk (K2); other `top` stages get the pair one below it, and step up only
when a build fails. They get $10 per phase; past that, builds use none.
Reviews run on `top`, or on `top+` for a phase with a `top+` stage, and
their cost counts against that budget. The builder may edit files and runs only the commands
your project's permission rules allow; set
`CLAUDE_BUILD_PERMISSIONS=bypassPermissions` only when Claude Code already
runs in a sandbox container (the ai-coding sandbox image sets it). Every cap is at least $0.25, since a cheap
Expand Down
2 changes: 1 addition & 1 deletion plugins/phased-delivery/.claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "phased-delivery",
"version": "0.13.0",
"version": "0.15.1",
"description": "Plan work as self-contained phases, then implement it phase by phase.",
"author": {
"name": "Bryan"
Expand Down
3 changes: 3 additions & 0 deletions plugins/phased-delivery/scripts/build-check.py
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,9 @@ def cmd_finish(a):
last = next(h for h in log if any(c.startswith(h) or h.startswith(c) for c in ours))
save(os.path.join(pdir, "phase.json"), with_record(pj, built=last))
plan_check.render_plan(plan_dir)
if subprocess.run(["git", "-C", top, "check-ignore", "-q", rel(top, plan_dir)]).returncode == 0:
print("not committed: git ignores the plan directory") # a plan kept out of the repository
return 0
subject = f"Phase {os.path.basename(pdir)[:2]} {'stopped' if a.stopped else 'built'}: status and notes"
print(git_commit(top, [rel(top, plan_dir)], subject, [f"Phase: {rel(top, pdir)}"] + a.extra_trailer))
return 0
Expand Down
9 changes: 6 additions & 3 deletions plugins/phased-delivery/scripts/claude-build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
#
# PROMPT is a file holding stage-builder.md and its inputs, kept outside
# REPO; its text is passed as the prompt. Claude works in REPO with the
# phased-delivery plugin off. OUTDIR receives report.md (the final
# message), stream.jsonl and stderr.txt.
# phased-delivery plugin off and thinking summarized in the stream (the
# hidden --thinking-display flag; headless runs otherwise leave it empty).
# OUTDIR receives report.md (the final message), stream.jsonl (written as
# the call runs) and stderr.txt.
#
# CLAUDE_BUILD_PERMISSIONS sets the permission mode (default acceptEdits:
# file edits work and commands follow the project's allow rules). A session
Expand All @@ -22,7 +24,7 @@
# seconds without output); 8 the budget was reached; other non-zero: the
# claude exit status. Never commits; the orchestrator does.
set -u
[ $# -eq 6 ] || { sed -n '2,23p' "$0" >&2; exit 2; }
[ $# -eq 6 ] || { sed -n '2,25p' "$0" >&2; exit 2; }
REPO=$1; PROMPT=$2; MODEL=$3; EFFORT=$4; BUDGET=$5; OUT=$6
MODE=${CLAUDE_BUILD_PERMISSIONS:-acceptEdits}
case "$MODE" in
Expand All @@ -38,6 +40,7 @@ TEXT=$(cat "$PROMPT") || exit 2
(cd "$REPO" && exec claude -p "$TEXT" --model "$MODEL" --effort "$EFFORT" \
--max-budget-usd "$BUDGET" \
--settings '{"enabledPlugins":{"phased-delivery@ai-coding-plugins":false}}' \
--thinking-display summarized \
--permission-mode "$MODE" --no-session-persistence \
--output-format stream-json --verbose) \
< /dev/null > "$OUT/stream.jsonl" 2> "$OUT/stderr.txt" &
Expand Down
6 changes: 6 additions & 0 deletions plugins/phased-delivery/scripts/plan-check.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,12 @@ def tier(mb):
return total, t, why


def hardest(mb):
"""A top stage of the most extreme complexity (a total of 12 or more, or risk K2): the one routed to top+."""
total, t, _ = tier(mb)
return t == "top" and (total >= 12 or mb["K"] == 2)


def strings(x, path=""):
if isinstance(x, str):
yield path, x
Expand Down
72 changes: 69 additions & 3 deletions plugins/phased-delivery/scripts/run-phase.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
import subprocess
import sys
import tempfile
import threading
import time
from types import SimpleNamespace

HERE = os.path.dirname(os.path.abspath(__file__))
Expand Down Expand Up @@ -106,6 +108,57 @@ def py(script, *args):
return sh(sys.executable, os.path.join(HERE, script), *args)


def feed(label, event):
"""The live lines for one stream event: thinking, text, tool calls, failed tool results, the result."""
def short(text, n=300):
text = " ".join(str(text).split())
return text if len(text) <= n else text[:n] + "…"
kind, msg = event.get("type"), event.get("message") or {}
blocks = msg.get("content") if isinstance(msg.get("content"), list) else []
lines = []
for b in blocks:
if not isinstance(b, dict):
continue
if kind == "assistant" and b.get("type") == "thinking" and b.get("thinking"):
lines.append(f"thinking: {short(b['thinking'])}")
elif kind == "assistant" and b.get("type") == "text" and b.get("text", "").strip():
lines.append(f"says: {short(b['text'])}")
elif kind == "assistant" and b.get("type") == "tool_use":
args = b.get("input") or {}
what = next((args[k] for k in ("command", "file_path", "pattern", "description", "prompt") if k in args), "")
lines.append(f"{b.get('name')}: {short(what, 160)}")
elif kind == "user" and b.get("type") == "tool_result" and b.get("is_error"):
lines.append(f"tool error: {short(b.get('content'), 160)}")
if kind == "result":
cost = event.get("total_cost_usd")
lines.append(f"result: {event.get('subtype')}" + (f", ${cost:.2f}" if isinstance(cost, (int, float)) else ""))
return [f"[{label}] {x}" for x in lines]


def follow(label, path, done):
"""Print the call's stream to stderr as it is written, until done is set and the file is read to its end."""
while not os.path.exists(path):
if done.wait(0.5) and not os.path.exists(path):
return
with open(path, "rb") as f:
pending = b""
while True:
chunk = f.read()
if not chunk:
if done.is_set():
return
time.sleep(0.5)
continue
*lines, pending = (pending + chunk).split(b"\n")
for line in lines:
try:
event = json.loads(line)
except ValueError:
continue
for x in feed(label, event) if isinstance(event, dict) else []:
print(x, file=sys.stderr, flush=True)


def last(text):
lines = [x for x in text.splitlines() if x.strip()]
return lines[-1].strip() if lines else ""
Expand Down Expand Up @@ -183,8 +236,15 @@ def call(c, label, guide, inputs, pair, keep_briefs):
before = plan_docs(c.plan_dir)
present = plan_files(c.plan_dir)
for _ in range(2): # a stalled call is undone and run once more
print(f"[{label}] {pair['model']} {pair['effort']}, cap ${pair['cap_usd']}; stream: {out}/stream.jsonl",
file=sys.stderr, flush=True)
done = threading.Event()
watcher = threading.Thread(target=follow, args=(label, os.path.join(out, "stream.jsonl"), done), daemon=True)
watcher.start()
r = sh("sh", os.path.join(HERE, "claude-build.sh"), c.top, prompt, pair["model"], pair["effort"],
pair["cap_usd"], out)
done.set()
watcher.join()
if r.returncode != 7:
break
for p, doc in before.items():
Expand Down Expand Up @@ -214,8 +274,11 @@ def record(c, what, pair, res, *flags):
def stage_pair(c, brief, *steps):
"""The stage's routed pair, from its brief's scores and the premium spend."""
spent = must(py("build-check.py", "spend", c.pdir), "spend").stdout.strip()
scores = "".join(f"{k}{brief['model_basis'][k]}" for k in "JFRCKPVS")
return route(c, "--scores", scores, "--premium-spent", spent, *steps)
return route(c, "--scores", scores_of(brief), "--premium-spent", spent, *steps)


def scores_of(brief):
return "".join(f"{k}{brief['model_basis'][k]}" for k in "JFRCKPVS")


def set_findings(c, findings):
Expand Down Expand Up @@ -369,7 +432,10 @@ def review(c, stages):
path = os.path.join(c.pdir, "review.json")
rec = plan_check.read_json(os.path.join(c.pdir, "phase.json"))["record"]
unchecked = [sid for sid, s in stages.items() if not s["brief"]["checks"]]
pair = route(c, "--scores", "J0F0R0C0K0P0V0S0", "--review")
# the phase's hardest stage decides between top and top+
hardest = max((s["brief"]["model_basis"] for s in stages.values()),
key=lambda mb: (plan_check.hardest(mb), plan_check.tier(mb)[0]))
pair = route(c, "--scores", scores_of({"model_basis": hardest}), "--review")
inputs = [f"- Phase folder: `{c.pdir}`", f"- Diff of the phase: `git diff {rec['start_commit']}`",
"- Edits that were present before the phase and are not part of it: "
+ (", ".join(f"`{p}`" for p in rec["preexisting"]) or "none"),
Expand Down
51 changes: 37 additions & 14 deletions plugins/phased-delivery/scripts/select-models.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,10 @@
import sys

# Tier floors: a candidate qualifies if its score is at least this share of
# the best candidate's score; the cheapest qualifying candidate wins.
FLOORS = {"top": 0.97, "middle": 0.85, "small": 0.50}
# the best candidate's score; the cheapest qualifying candidate wins. Only the
# hardest stages (plan-check.py's hardest) and their phases' reviews get top+;
# top is the frontier pair one below it, never below middle+.
FLOORS = {"top+": 0.97, "middle": 0.85, "small": 0.50}
# After a tier picks a candidate, any cheaper candidate scoring within this
# many index points (the index runs 0-100) of the pick is taken instead.
TIE_POINTS = 3.0
Expand All @@ -86,7 +88,7 @@
PROFILES_FILE = "model-profiles.json"
# Tokens a stage may spend, by tier; passed on as a dollar cap at the pair's
# input price.
CAP_TOKENS = {"small": 150000, "middle": 400000, "middle+": 400000, "top": 1000000}
CAP_TOKENS = {"small": 150000, "middle": 400000, "middle+": 400000, "top": 1000000, "top+": 1000000}
# No build's dollar cap is lower than this: at the input price alone a cheap
# model's cap rounds to a cent, below what one headless run costs.
MIN_CAP_USD = 0.25
Expand Down Expand Up @@ -306,10 +308,17 @@ def assign_tiers(scored):
pick = min(above, key=lambda c: (c["score"], c["cost"]))
tiers["middle+"] = prefer_cheaper(pick, above)
else:
tiers["middle+"] = tiers["top"]
tiers["middle+"] = tiers["top+"]
tiers["top"] = below_top_plus(frontier(scored), tiers["top+"], tiers["middle+"])
return best, tiers


def below_top_plus(front, top_plus, middle_plus):
"""top: the frontier pair one below top+'s pick, or middle+'s pick when that scores more."""
lower = [c for c in front if c["score"] < top_plus["score"]] # front is cheapest first
return max(lower[-1:] + [middle_plus], key=lambda c: c["score"])


def money(value):
return "n/a" if value == math.inf else f"{value:.2f}"

Expand Down Expand Up @@ -338,7 +347,7 @@ def render(available, profiles, metric, cost_field, best, tiers, scored, exclude
"| Tier | Model | Effort | Score | Cost | Report row |",
"| --- | --- | --- | --- | --- | --- |",
]
for tier in ["small", "middle", "middle+", "top"]:
for tier in ["small", "middle", "middle+", "top", "top+"]:
c = tiers[tier]
lines.append(f"| {tier} | {c['tool_model']} | {c['effort']} | {c['score']:.1f}"
f" | {money(c['cost'])} | {c['row']['name']} |")
Expand Down Expand Up @@ -481,12 +490,20 @@ def parse_scores(text):
return {text[i]: int(text[i + 1]) for i in range(0, 16, 2)}


def stage_tier(scores):
"""plan-check.py's tier: (total, tier, why) with the model-selection overrides."""
def plan_check():
spec = importlib.util.spec_from_file_location("plan_check", os.path.join(HERE, "plan-check.py"))
plan_check = importlib.util.module_from_spec(spec)
spec.loader.exec_module(plan_check)
return plan_check.tier(scores)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module


def stage_tier(scores):
"""plan-check.py's tier: (total, tier, why), with top+ for its hardest stages."""
checks = plan_check()
total, tier, why = checks.tier(scores)
if checks.hardest(scores):
return total, "top+", "total of 12 or more, or risk K2"
return total, tier, why


def frontier(pool):
Expand All @@ -502,6 +519,8 @@ def meets_floor(front, tier, best):
if tier == "middle+":
bar = frontier_pick(front, "middle", best)["score"]
return [c for c in front if c["score"] > bar]
if tier == "top":
return [c for c in front if c["score"] >= frontier_pick(front, tier, best)["score"]]
return [c for c in front if c["score"] >= FLOORS[tier] * best]


Expand All @@ -514,6 +533,8 @@ def frontier_pick(front, tier, best):
if tier == "middle+":
middle = front.index(frontier_pick(front, "middle", best))
return front[min(middle + 1, len(front) - 1)]
if tier == "top":
return below_top_plus(front, frontier_pick(front, "top+", best), frontier_pick(front, "middle+", best))
meeting = meets_floor(front, tier, best)
if not meeting:
return max(front, key=lambda c: c["score"])
Expand Down Expand Up @@ -544,7 +565,7 @@ def pick_pair(allowed, tier, best, scores, signals, up, down):
if cap and pick is not frontier_pick(frontier(allowed), tier, best):
why.append(f"{'mechanical' if mechanical else 'long or wide'} stage: thinking capped at {cap}")
meeting = meets_floor(front, tier, best)
if signals and scores["K"] >= 1:
if signals and scores["K"] >= 1 and tier not in ("top", "top+"): # top+ already takes K2
short = short or front.index(pick) == last
stepped = front[min(front.index(pick) + 1, last)]
if stepped is not pick:
Expand Down Expand Up @@ -595,8 +616,10 @@ def route_main(args):
if not pool:
print("no selectable pair", file=sys.stderr)
return 4
tier, tier_why = ("top", "phase reviews run on top") if options.review \
else stage_tier(options.scores)[1:]
tier, tier_why = stage_tier(options.scores)[1:]
if options.review: # a review runs on top, or top+ when its scores are the phase's hardest stage's
tier, tier_why = ("top+", "review of a phase with a top+ stage") if tier == "top+" \
else ("top", "reviews run on top")
best = max(c["score"] for c in pool)
over_budget = not options.review and options.premium_spent >= PREMIUM_BUDGET_USD
allowed = [c for c in pool if not c["row"]["premium"]] if over_budget else pool
Expand All @@ -615,7 +638,7 @@ def route_main(args):
print(notes, file=sys.stderr)
return 4
standard = [c for c in allowed if not c["row"]["premium"]]
if tier != "top" and choice["row"]["premium"] and standard:
if tier not in ("top", "top+") and choice["row"]["premium"] and standard:
# Below top a premium pair must beat the standard pick on cost and score,
# unless the standard pairs cannot give a step up the stage asked for:
# the next model up at low thinking beats more thinking on a smaller one.
Expand Down
10 changes: 7 additions & 3 deletions plugins/phased-delivery/skills/implement-in-phases/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,11 @@ works this way is in
Pass each project instruction file (CLAUDE.md, AGENTS.md) with
`--instructions`, and the project's required commit subject annotation
and trailers with the other two options. It prints a report and exits 0
(built), 10 (halted) or 2 (bad usage: fix the command).
(built), 10 (halted) or 2 (bad usage: fix the command). Run it as a
background shell: a phase outlasts a foreground command's time limit,
and the user watches the live feed on its stderr (each call's thinking,
messages and tool calls) in the tool's view of that shell. Do not read
the feed into your own context; wait for the exit and read the report.
2. **On exit 10, answer the halt.** Read `record.halt` in the phase's
`phase.json` (the report prints it too): `step`, `stage`, `reason`,
`detail` and `next`. Do what `next` says, as the table below expands it,
Expand Down Expand Up @@ -124,8 +128,8 @@ Continue to the next phase only when the user says so; a user stop wins.
## Report the models' work

After the last phase is committed, write `work-report.md` in the plan
directory, commit it with the trailer `Phase: <plan directory>`, and give
the user its tables and Reading.
directory, commit it with the trailer `Phase: <plan directory>` (unless git
ignores the plan directory), and give the user its tables and Reading.

1. Generate it, never by hand: `sh scripts/stage-stats.sh <plan start>..HEAD`.
Per model and effort it gives stages, first-try and clean counts, failed
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@ in `record.halt` of the phase's `phase.json`. Exit 2: bad usage. Each run
prints a report: every stage and its status, the review findings and their
outcome, the halt, that Codex is off and, for a built phase,
`stage-stats.sh`'s table. `--work` keeps each call's prompt, output and
`report.md` in a numbered folder (a temporary directory otherwise).
`report.md` in a numbered folder (a temporary directory otherwise). While a
call runs, the driver prints its feed to stderr, each line tagged with the
call (`[build-01.2]`): its thinking summaries, messages, tool calls, failed
tool results and result.

## The parts

Expand Down Expand Up @@ -140,7 +143,9 @@ Each finding's status is kept in `record.findings` of `phase.json`:
`build-check.py finish` checks `review.json` and that every stage has a
commit and none is reopened, records the built commit, re-renders
`phase.md` and `plan.md` and commits the plan directory with a `Phase:`
trailer and each `--extra-trailer`. Its refusal halts `build-error`.
trailer and each `--extra-trailer`; a plan directory git ignores (a plan
kept out of the repository) is left uncommitted. Its refusal halts
`build-error`.

## Premium spend

Expand Down
3 changes: 2 additions & 1 deletion plugins/phased-delivery/skills/plan-in-phases/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,8 @@ since it reads the files as an implementer will, without the planning
session's context. Give it [plan-reviewer.md](plan-reviewer.md) unchanged,
with its inputs filled in; that file holds what counts as a finding, where
to look and the report format. Use the `top` candidate from the plan's
`models.md`.
`models.md`, or `top+` when the plan holds a `top+` stage (a `top` stage
with a total of 12 or more, or K = 2).

The reviewer reports only the finding types plan-reviewer.md lists, each
with evidence, and may recommend going back to change earlier phases, even
Expand Down
Loading
Loading