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
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.16.0",
"version": "0.17.0",
"description": "Plan work as self-contained phases, then implement it phase by phase.",
"author": {
"name": "Bryan"
Expand Down
47 changes: 36 additions & 11 deletions plugins/phased-delivery/scripts/build-check.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,12 @@
re-rendered from the records. --repo defaults to the current directory.

start validates phase.json and the stage files and writes HEAD and the
paths already modified into phase.json's record (kept as is when
set: resume). Exit 1 on invalid JSON or a stage's file already
modified.
paths already modified into phase.json's record. On resume (HEAD
already set) it adds the paths modified since, other than stage
files and the plan's, so the driver never restores them. Exit 5
when the only problem is a brief changed without a higher
revision; exit 1 on other invalid JSON or, on the first start, a
stage's file already modified.
can-try exit 1 when the stage already has a non-error attempt on the pair
at the brief's current revision.
record logs an attempt and gates a build: no uncommitted path outside the
Expand All @@ -35,7 +38,10 @@
accepted; 1 failed; 3 budget stop (build exit 8); 4 error (any
other build exit: not a try of the pair). Exit 2, nothing logged,
for --model orchestrator on a stage that is not session_only.
Stages "review" and "revise" are logged for spend only.
Stages "review" and "revise" are logged for spend only. --live
streams each check to stderr as it runs: "[check-<stage>] $ <cmd>",
each output line (stdout and stderr merged) and "[check-<stage>]
exit N".
reject marks the stage's accepted, uncommitted attempt rejected.
commit commits the stage's changed files with the stage trailers (an
empty commit for a session-only or reopened stage with none),
Expand Down Expand Up @@ -220,8 +226,20 @@ def outside_paths(top, plan_dir, pj, stages, sid):
if p not in allowed and not is_cache(p) and not in_dir(p, rel(top, plan_dir))]


def run_checks(top, commands):
return [{"cmd": c, "exit": subprocess.run(["sh", "-c", c], cwd=top, capture_output=True).returncode}
def run_live(top, stage, cmd):
tag = f"[check-{stage}]"
print(f"{tag} $ {cmd}", file=sys.stderr, flush=True)
with subprocess.Popen(["sh", "-c", cmd], cwd=top, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as p:
for raw in p.stdout:
line = raw.decode(errors="replace").rstrip("\r\n")
print(f"{tag} {line}", file=sys.stderr, flush=True)
print(f"{tag} exit {p.returncode}", file=sys.stderr, flush=True)
return p.returncode


def run_checks(top, commands, live_stage=None):
return [{"cmd": c, "exit": run_live(top, live_stage, c) if live_stage
else subprocess.run(["sh", "-c", c], cwd=top, capture_output=True).returncode}
for c in commands]


Expand All @@ -236,15 +254,21 @@ def count(x):
# ---- subcommands

def cmd_start(a):
pdir, _ = phase_paths(a.phase_dir)
pdir, plan_dir = phase_paths(a.phase_dir)
name = os.path.basename(pdir)
pj, stages, problems = checked_phase(pdir)
if problems:
return report(problems)
if pj["record"].get("start_commit"):
return 0
return 5 if report(problems) and all(p["kind"] == "revision" for p in problems) else 1
top = toplevel(a.repo)
now = changed_paths(top)
if pj["record"].get("start_commit"):
# resume: keep paths changed since the last run, so a restore never deletes or reverts them
known = set(pj["record"]["preexisting"]) | {p for s in stages.values() for p in brief_files(s)}
new = [p for p in now if p not in known and not is_cache(p) and not in_dir(p, rel(top, plan_dir))]
if new:
save(os.path.join(pdir, "phase.json"),
with_record(pj, preexisting=pj["record"]["preexisting"] + new))
return 0
dirty = [{"file": f"{name}/{sid}.json", "where": sid, "msg": f"stage file already modified: {p}"}
for sid, s in stages.items() for p in brief_files(s) if p in now]
if dirty:
Expand Down Expand Up @@ -285,7 +309,7 @@ def cmd_record(a):
top = toplevel(a.repo)
same = [x for x in attempts_of(s) if x["fix"] == a.fix and x["result"] != "error" and not x["commit"]]
outside = outside_paths(top, plan_dir, pj, stages, a.stage)
checks = [] if a.exit_code or outside else run_checks(top, s["brief"]["checks"])
checks = [] if a.exit_code or outside else run_checks(top, s["brief"]["checks"], a.stage if a.live else None)
if a.exit_code == 8:
outcome, code = {"result": "stopped", "why": "budget reached"}, 3
elif a.exit_code != 0:
Expand Down Expand Up @@ -437,6 +461,7 @@ def parse_args(argv):
s.add_argument("--tool-calls", type=number)
s.add_argument("--premium", action="store_true")
s.add_argument("--fix", action="store_true")
s.add_argument("--live", action="store_true")
s.add_argument("--repo", default=".")
s = sub.add_parser("reject")
for k in ("phase_dir", "stage", "why"):
Expand Down
63 changes: 52 additions & 11 deletions plugins/phased-delivery/scripts/run-phase.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,10 @@ def py(script, *args):
return sh(sys.executable, os.path.join(HERE, script), *args)


def say(text):
print(f"[driver] {text}", file=sys.stderr, flush=True)


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):
Expand Down Expand Up @@ -271,9 +275,33 @@ def call(c, label, guide, inputs, pair, keep_briefs, what, *flags):


def record(c, what, pair, res, *flags):
return py("build-check.py", "record", c.pdir, what, "--tool", "claude-code", "--model", pair["model"],
"--effort", pair["effort"], "--exit", res["exit"], "--tokens", res["tokens"], "--cost", res["cost"],
"--cap", pair["cap_usd"], *(["--premium"] if pair["premium"] else []), *flags, "--repo", c.top)
"""build-check.py record --live: its [check-] lines go to stderr as it writes them; the result keeps the rest."""
stage = what not in ("review", "revise")
cmd = [sys.executable, os.path.join(HERE, "build-check.py"), "record", c.pdir, what, "--tool", "claude-code",
"--model", pair["model"], "--effort", pair["effort"], "--exit", res["exit"], "--tokens", res["tokens"],
"--cost", res["cost"], "--cap", pair["cap_usd"], *(["--premium"] if pair["premium"] else []), *flags,
"--repo", c.top, "--live"]
# bytes, not text=True: universal newlines would split a check's '\r' progress into lines without [check-
with subprocess.Popen([str(x) for x in cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as p:
kept, checking = [], False
for line in (raw.decode() for raw in p.stderr):
if line.startswith("[check-"):
if not checking: # only record knows whether checks run (not after a failed build or outside paths)
say(f"stage {what}: checks")
checking = True
print(line, end="", file=sys.stderr, flush=True)
else:
kept.append(line)
out = p.stdout.read().decode() # one JSON line, written after the checks
if stage and p.returncode in (0, 1, 3, 4):
logged = json.loads(last(out))
say(f"stage {what}: {logged['result']}" + (f", outside: {', '.join(logged['outside'])}" if logged["outside"] else ""))
return subprocess.CompletedProcess(p.args, p.returncode, out, "".join(kept))


def reject(c, sid, why):
must(py("build-check.py", "reject", c.pdir, sid, why), "reject")
say(f"stage {sid}: rejected: {why}")


def stage_pair(c, brief, *steps):
Expand Down Expand Up @@ -335,11 +363,13 @@ def revise(c, problem):

def pre_phase(c, stages):
"""Revise and start a phase not yet revised; check the plan while no stage has an attempt."""
started = py("build-check.py", "start", c.pdir, "--repo", c.top) # every run: a resume adds new user edits
if started.returncode == 5:
raise Halt("brief-changed", started.stdout.strip())
if started.returncode:
raise Halt("revise-failed", (started.stdout + started.stderr).strip())
runs = plan_check.read_json(os.path.join(c.pdir, "phase.json"))["record"].get("runs", [])
if not any(x["stage"] == "revise" and x["exit"] != 7 for x in runs): # a stalled revise is not one
started = py("build-check.py", "start", c.pdir, "--repo", c.top)
if started.returncode:
raise Halt("revise-failed", (started.stdout + started.stderr).strip())
current = py("select-models.py", "check", os.path.join(c.plan_dir, "models.md"), *c.profiles)
if current.returncode:
raise Halt("models-stale", last(current.stdout + current.stderr))
Expand All @@ -357,6 +387,7 @@ def failed(c, sid, times, unchanged, why):
restore(c)
if times >= MAX_REVISIONS:
raise Halt("revise-capped", f"stage {sid} was revised {times} times for failures in this run; then: {why}")
say(f"stage {sid}: revising: {why}")
if revise(c, f"stage {sid}: {why}") == "unchanged":
raise Halt(unchanged, why)
return "revised"
Expand All @@ -382,6 +413,7 @@ def build(c, sid, s, times):
"against the brief in the packet"] if fix else []
inputs = [c.instructions, "- Anything else the brief links to: none", *earlier, "- Stage packet:", "",
plan_check.packet(c.plan_dir, sid)]
say(f"stage {sid}: build")
res = call(c, f"build-{sid}", STAGE_BUILDER, inputs, pair, True, sid, *(["--fix"] if fix else []))
logged = record(c, sid, pair, res, *(["--fix"] if fix else []))
if logged.returncode == 4:
Expand All @@ -391,13 +423,12 @@ def build(c, sid, s, times):
if stopped or (accepted and res["edited"]):
why = "edited the plan" if not stopped else stopped.group(1) or "the builder stopped"
if accepted:
must(py("build-check.py", "reject", c.pdir, sid, why), "reject")
reject(c, sid, why)
return failed(c, sid, times, "builder-stopped", why) if stopped else "retry"
if accepted:
done = commit(c, sid)
if done.returncode: # reject it first, so a rerun builds the stage again
must(py("build-check.py", "reject", c.pdir, sid, f"commit: {last(done.stderr) or last(done.stdout)}"),
"reject")
reject(c, sid, f"commit: {last(done.stderr) or last(done.stdout)}")
must(done, "commit")
return "built"
restore(c, json.loads(last(logged.stdout))["outside"])
Expand Down Expand Up @@ -468,8 +499,11 @@ def load_review(c):


def commit(c, sid):
return py("build-check.py", "commit", c.pdir, sid, "--subject-suffix", c.a.subject_suffix, *c.trailers,
done = py("build-check.py", "commit", c.pdir, sid, "--subject-suffix", c.a.subject_suffix, *c.trailers,
"--repo", c.top)
if done.returncode == 0:
say(f"stage {sid}: committed {done.stdout.strip()}")
return done


def fix(c, sid, s, f):
Expand All @@ -487,7 +521,7 @@ def fix(c, sid, s, f):
why = "the fix changed none of the stage's files"
if why:
if logged.returncode == 0:
must(py("build-check.py", "reject", c.pdir, sid, why), "reject")
reject(c, sid, why)
raise Halt("fix-failed", why)


Expand All @@ -499,8 +533,10 @@ def review_and_fix(c):
"""With every stage committed: review, fix what the review says to fix, ask the rest; returns when all is settled."""
stages = read_stages(c.pdir)
if not os.path.isfile(os.path.join(c.pdir, "review.json")):
say("review: start")
step("review", None, review, c, stages)
findings = step("review", None, load_review, c)
say(f"review: {len(findings)} findings")
known = {x["index"]: x["status"]
for x in plan_check.read_json(os.path.join(c.pdir, "phase.json"))["record"].get("findings", [])}
# asked on an earlier run: the session has handled them since
Expand All @@ -509,6 +545,7 @@ def review_and_fix(c):
is_fix = lambda f: f["action"] in ("remove", "fix") and f["stage"] in stages
for i, f in enumerate(findings):
if states[i] == "open" and is_fix(f):
say(f"fix {f['stage']}: finding {i}")
try:
fix(c, f["stage"], stages[f["stage"]], f)
except Halt as h:
Expand All @@ -518,6 +555,7 @@ def review_and_fix(c):
ask = [i for i, f in enumerate(findings) if states[i] == "open" and not is_fix(f)]
if ask:
mark(c, ask, "asked")
say(f"review: asked {len(ask)} findings")
gap = any(findings[i]["action"] == "plan-gap" for i in ask)
raise Halt("plan-gap" if gap else "question", "\n".join(describe(findings[i], "asked") for i in ask), "review")

Expand Down Expand Up @@ -565,15 +603,18 @@ def run(a):
if rec.get("built"): # already built: report it and write nothing
print("\n".join(report(c, None)))
return 0
say(f"phase {os.path.basename(pdir)}: start")
try:
pre_phase(c, read_stages(pdir))
stage_loop(c)
review_and_fix(c)
step("finish", None, finish, c)
say("finish: built")
halt = None
except Halt as h:
halt = {"step": h.step, "stage": h.stage, "reason": h.reason, "detail": h.detail, "next": NEXT[h.reason]}
set_halt(pdir, plan_dir, halt)
say(f"halted at {h.step}" + (f" {h.stage}" if h.stage else "") + f": {h.reason}")
print("\n".join(report(c, halt)))
return 10 if halt else 0

Expand Down
4 changes: 3 additions & 1 deletion plugins/phased-delivery/skills/implement-in-phases/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,9 @@ works this way is in
(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
messages and tool calls, the driver's own steps as `[driver]` lines and
each stage check's command, output and exit as `[check-NN.n]` lines) 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`,
Expand Down
24 changes: 16 additions & 8 deletions plugins/phased-delivery/skills/implement-in-phases/build-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,11 @@ outcome, the halt, that Codex is off and, for a built phase,
`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.
tool results and result. It also prints a `[driver]` line for each step it
takes (stage build, checks, result, commit, reject, revise, review, fixes,
finish, halt) and passes through `[check-01.2]` lines for each check's
command, output and exit code, which it gets from `build-check.py record
--live`.

## The parts

Expand All @@ -45,20 +49,24 @@ sets it already).

## Revise and start

On a phase with no revise run recorded, the driver:
Every run starts with `build-check.py start`, which validates the phase.
The first time it writes `start_commit` and the paths already modified
(`preexisting`); on a rerun it adds the paths modified since, other than
stage files and the plan's, so files the user added or edited between runs
are never restored. A brief changed without a higher revision halts
`brief-changed`; any other refusal halts `revise-failed`.

1. runs `build-check.py start`, which validates the phase and writes
`start_commit` and the paths already modified (`preexisting`); a refusal
halts `revise-failed`;
2. runs `select-models.py check <plan>/models.md`; a stale table halts
On a phase with no revise run recorded, the driver then:

1. runs `select-models.py check <plan>/models.md`; a stale table halts
`models-stale`;
3. gives [revise-guide.md](revise-guide.md) to a headless reviser at the
2. gives [revise-guide.md](revise-guide.md) to a headless reviser at the
review pair (`route --review`), with "none" as the problem, and records
the run. A report without `Result: revised` or `Result: unchanged` halts
`escalated`; a revised plan that fails `plan-check.py` halts
`revise-failed`.

On a rerun before any stage has an attempt it only runs `plan-check.py`.
On a rerun before any stage has an attempt it then only runs `plan-check.py`.

## Build each stage

Expand Down
6 changes: 3 additions & 3 deletions plugins/phased-delivery/skills/plan-in-phases/phase-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -221,9 +221,9 @@ Never written by planning or revising: write `"record": {}` in
reader of a built plan knows them.

- `phase.json`: `start_commit`, the commit the build started from;
`preexisting`, the paths with edits present before the build; `runs`,
the revise and review attempts; `findings`, the review's findings by
`index` with a `status` (`open`, `fixed`, `asked`, `answered`); `halt`,
`preexisting`, the paths with edits present before the build or added
between runs; `runs`, the revise and review attempts; `findings`, the
review's findings by `index` with a `status` (`open`, `fixed`, `asked`, `answered`); `halt`,
why the build stopped, or null; `built`, the commit that finished the
phase, or null.
- Stage file: `revisions`, the hash of the brief at each revision that was
Expand Down
12 changes: 10 additions & 2 deletions plugins/phased-delivery/tests/test_build_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,14 +157,22 @@ def test_failed_check_then_retry(repo):
(repo / "src/a.txt").write_text("a2\n")
first = record(repo, "01.1", "haiku", "high", 0, "500", "0.10")
assert first.returncode == 1
assert json.loads(first.stdout)["checks"] == [{"cmd": "test -f src/done.txt", "exit": 1}]
assert "[check-" not in first.stderr
live = record(repo, "01.1", "sonnet", "high", 0, "600", "0.20", "--live")
assert live.returncode == 1
assert live.stderr.splitlines() == ["[check-01.1] $ test -f src/done.txt", "[check-01.1] exit 1"]
for run in (first, live):
assert len(run.stdout.splitlines()) == 1
assert json.loads(run.stdout)["checks"] == [{"cmd": "test -f src/done.txt", "exit": 1}]
(repo / "src/done.txt").write_text("done\n")
second = record(repo, "01.1", "opus", "medium", 0, "900", "0.30")
assert second.returncode == 0
assert len(second.stdout.splitlines()) == 1
assert bc(repo, "commit", PHASE, "01.1").returncode == 0
msg = message(repo)
assert "Attempt: 2" in msg
assert "Attempt: 3" in msg
assert "Earlier-Attempt: haiku high 500 check failed" in msg
assert "Earlier-Attempt: sonnet high 600 check failed" in msg


def test_can_try_refuses_repeat(repo):
Expand Down
Loading
Loading