@caddis/cli 0.4.89 → 0.4.91

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/bundles/antigravity-plugin/plugin.json +1 -1
  2. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_exit.cpython-311.pyc +0 -0
  3. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_file_lock.cpython-311.pyc +0 -0
  4. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_frontmatter.cpython-311.pyc +0 -0
  5. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_redact.cpython-311.pyc +0 -0
  6. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_roadmap.cpython-311.pyc +0 -0
  7. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_rows.cpython-311.pyc +0 -0
  8. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_status.cpython-311.pyc +0 -0
  9. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_tidy.cpython-311.pyc +0 -0
  10. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_todo.cpython-311.pyc +0 -0
  11. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_workstreams.cpython-311.pyc +0 -0
  12. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_worktree_safety.cpython-311.pyc +0 -0
  13. package/bundles/antigravity-plugin/scripts/caddis_budget.py +26 -2
  14. package/bundles/antigravity-plugin/scripts/caddis_checkout_guard.py +31 -2
  15. package/bundles/antigravity-plugin/scripts/caddis_docs_pr.py +8 -0
  16. package/bundles/antigravity-plugin/scripts/caddis_fleet.py +10 -5
  17. package/bundles/antigravity-plugin/scripts/caddis_guide.json +3 -3
  18. package/bundles/antigravity-plugin/scripts/caddis_handoff.py +73 -45
  19. package/bundles/antigravity-plugin/scripts/caddis_lanes.py +96 -14
  20. package/bundles/antigravity-plugin/scripts/caddis_roadmap_run.py +136 -67
  21. package/bundles/antigravity-plugin/scripts/caddis_workstreams.py +86 -20
  22. package/bundles/antigravity-plugin/scripts/check_doc_coverage.py +17 -0
  23. package/bundles/antigravity-plugin/scripts/oss_review.py +89 -24
  24. package/bundles/antigravity-plugin/scripts/templates/coordinator.md +1 -1
  25. package/bundles/antigravity-plugin/skills/code-review/SKILL.md +2 -0
  26. package/bundles/antigravity-plugin/skills/coordinate/SKILL.md +17 -4
  27. package/bundles/antigravity-plugin/skills/cross-review/SKILL.md +18 -5
  28. package/bundles/antigravity-plugin/skills/feature-plan/SKILL.md +5 -0
  29. package/bundles/antigravity-plugin/skills/handoff/SKILL.md +18 -4
  30. package/bundles/antigravity-plugin/skills/implement/SKILL.md +23 -2
  31. package/bundles/antigravity-plugin/skills/park/SKILL.md +1 -0
  32. package/bundles/antigravity-plugin/skills/preflight/SKILL.md +1 -0
  33. package/bundles/antigravity-plugin/skills/roadmap/SKILL.md +2 -1
  34. package/bundles/antigravity-plugin/skills/roadmap/assets/plan-resume-prompt.md +8 -1
  35. package/bundles/antigravity-plugin-extras/plugin.json +1 -1
  36. package/bundles/antigravity-plugin-extras/skills/cross-review/SKILL.md +6 -5
  37. package/bundles/codex/.codex/skills/coding/code-review/SKILL.md +2 -0
  38. package/bundles/codex/.codex/skills/workflow/preflight/SKILL.md +1 -0
  39. package/bundles/codex/.codex/skills/workflow/roadmap/SKILL.md +2 -1
  40. package/bundles/codex/.codex/skills/workflow/roadmap/assets/plan-resume-prompt.md +8 -1
  41. package/bundles/manifest.json +3 -3
  42. package/dist/cli.js +12 -4
  43. package/package.json +1 -1
@@ -908,8 +908,47 @@ def oss_review_path() -> Path | None:
908
908
  return source if source.exists() else None
909
909
 
910
910
 
911
- def run_review(worktree: Path, env: dict, timeout_s: int = 900) -> ReviewResult:
912
- fake_review = os.environ.get("CADDIS_REVIEW_FAKE")
911
+ # The lane review timeout. oss_review cannot tell the lane its batch count in advance, so the bound is generous:
912
+ # every batch may take one full agy call, plus a margin for the 429 waits, the HTTP fallbacks and start-up.
913
+ # Mirrors of `.github/tools/oss_review.py` (AGY_TIMEOUT_S, MAX_REVIEW_BATCHES); a test fails if they drift.
914
+ # A timeout before the last batch would always kill a review of 2+ batches (the old 900 s equalled one agy call).
915
+ REVIEW_AGY_CALL_TIMEOUT_S = 15 * 60
916
+ REVIEW_MAX_BATCHES = 12
917
+ REVIEW_TIMEOUT_MARGIN_S = 600
918
+ LANE_REVIEW_TIMEOUT_S = REVIEW_MAX_BATCHES * REVIEW_AGY_CALL_TIMEOUT_S + REVIEW_TIMEOUT_MARGIN_S
919
+ # oss_review prints this line before its verdict when the secret filter dropped files: CLEAN then covers only part.
920
+ _PARTIAL_SCOPE = re.compile(r"(?m)^REVIEW-SCOPE: PARTIAL\b")
921
+
922
+
923
+ def _review_fake() -> str | None:
924
+ """CADDIS_REVIEW_FAKE, honoured only inside a pytest run (pytest sets PYTEST_CURRENT_TEST, and child processes
925
+ inherit it). A copy left exported in a shell would otherwise fake every later real lane review."""
926
+ fake = os.environ.get("CADDIS_REVIEW_FAKE")
927
+ if not fake:
928
+ return None
929
+ if os.environ.get("PYTEST_CURRENT_TEST"):
930
+ return fake
931
+ print("[caddis-lanes] CADDIS_REVIEW_FAKE is ignored outside a pytest run; running the real review",
932
+ file=sys.stderr)
933
+ return None
934
+
935
+
936
+ def _kill_tree(proc: subprocess.Popen) -> None:
937
+ """Kill the child and everything it started (taskkill /T on Windows, the process group on POSIX)."""
938
+ if sys.platform == "win32":
939
+ try:
940
+ subprocess.run(["taskkill", "/T", "/F", "/PID", str(proc.pid)], capture_output=True, timeout=15)
941
+ except (OSError, subprocess.TimeoutExpired):
942
+ proc.kill()
943
+ else:
944
+ try:
945
+ os.killpg(proc.pid, signal.SIGKILL)
946
+ except (ProcessLookupError, PermissionError):
947
+ proc.kill()
948
+
949
+
950
+ def run_review(worktree: Path, env: dict, timeout_s: int = LANE_REVIEW_TIMEOUT_S) -> ReviewResult:
951
+ fake_review = _review_fake()
913
952
  if fake_review:
914
953
  return ReviewResult(fake_review, 0 if fake_review == "CLEAN" else 1, f"fake review: {fake_review}")
915
954
 
@@ -917,26 +956,56 @@ def run_review(worktree: Path, env: dict, timeout_s: int = 900) -> ReviewResult:
917
956
  if path is None:
918
957
  return ReviewResult("MISSING", None, "oss_review.py not found")
919
958
 
959
+ # Its own process group (Windows) or session (POSIX): a timeout kills caddis_spend and agy too, not only
960
+ # oss_review, so nothing runs on and spends after the lane gave up.
961
+ group = ({"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP} if sys.platform == "win32"
962
+ else {"start_new_session": True})
963
+ argv = [sys.executable, str(path), "--cwd", str(worktree)]
920
964
  try:
921
- completed = subprocess.run(
922
- [sys.executable, str(path), "--cwd", str(worktree)],
965
+ proc = subprocess.Popen(
966
+ argv,
923
967
  cwd=worktree,
924
968
  env=env,
925
- capture_output=True,
969
+ stdout=subprocess.PIPE,
970
+ stderr=subprocess.PIPE,
926
971
  text=True,
927
972
  encoding="utf-8",
928
973
  errors="replace",
929
- timeout=timeout_s,
974
+ **group,
930
975
  )
931
- except subprocess.TimeoutExpired as exc:
932
- captured = _as_text(exc.stdout) + _as_text(exc.stderr)
933
- tail = (captured + f"\ntimed out after {timeout_s}s").lstrip("\n")[-3000:]
934
- return ReviewResult("MISSING", None, tail)
935
976
  except OSError as exc:
936
977
  return ReviewResult("MISSING", None, str(exc)[-3000:])
978
+ try:
979
+ stdout, stderr = proc.communicate(timeout=timeout_s)
980
+ except subprocess.TimeoutExpired:
981
+ _kill_tree(proc)
982
+ try:
983
+ stdout, stderr = proc.communicate(timeout=30)
984
+ except subprocess.TimeoutExpired:
985
+ stdout, stderr = "", ""
986
+ captured = _as_text(stdout) + _as_text(stderr)
987
+ tail = (captured + f"\ntimed out after {timeout_s}s; process tree killed").lstrip("\n")[-3000:]
988
+ return ReviewResult("MISSING", None, tail)
937
989
 
938
- status = {0: "CLEAN", 1: "BLOCKING"}.get(completed.returncode, "MISSING")
939
- return ReviewResult(status, completed.returncode, _combined_output(completed)[-3000:])
990
+ output = _combined_output(subprocess.CompletedProcess(argv, proc.returncode, stdout, stderr))
991
+ status = {0: "CLEAN", 1: "BLOCKING"}.get(proc.returncode, "MISSING")
992
+ if status == "CLEAN" and _PARTIAL_SCOPE.search(output):
993
+ status = "PARTIAL"
994
+ return ReviewResult(status, proc.returncode, output[-3000:])
995
+
996
+
997
+ def lane_commit_reason(worktree: Path, branch: str, base_sha: str) -> str:
998
+ """Why the lane worktree holds commits the review did not see, or ''.
999
+
1000
+ The review covers uncommitted work only, and accept merges the whole lane branch. So both the worktree HEAD
1001
+ and the branch tip must still be the base: a new commit, an amended base, or a commit on a detached HEAD
1002
+ (or on the branch before a detach back to the base) all fail one of the two."""
1003
+ head = _git_output(worktree, "rev-parse", "HEAD")
1004
+ tip = _git_output(worktree, "rev-parse", "--verify", f"refs/heads/{branch}")
1005
+ if head == base_sha and tip == base_sha:
1006
+ return ""
1007
+ return (f"the lane committed work that was not reviewed (worktree HEAD {head[:7]}, branch {branch} at "
1008
+ f"{tip[:7]}, base {base_sha[:7]}); the review covers uncommitted work only")
940
1009
 
941
1010
 
942
1011
  def changed_files(worktree: Path) -> list[str]:
@@ -1964,7 +2033,12 @@ def _run_post_checks(
1964
2033
  return "stop", EXIT_NOT_RUN
1965
2034
 
1966
2035
  review_started = time.monotonic()
1967
- review = run_review(worktree, dict(os.environ))
2036
+ committed = lane_commit_reason(worktree, str(packet["branch"]), str(packet["base_sha"]))
2037
+ if committed:
2038
+ # No review: it would cover only the uncommitted part and could print CLEAN over the commit.
2039
+ review = ReviewResult("COMMITTED", None, committed)
2040
+ else:
2041
+ review = run_review(worktree, dict(os.environ))
1968
2042
  review_s = time.monotonic() - review_started
1969
2043
  pythons = list(before)
1970
2044
  if pythons:
@@ -1979,7 +2053,7 @@ def _run_post_checks(
1979
2053
  freeze_unchanged = None
1980
2054
 
1981
2055
  gates_passed = all(gate.passed for gate in gates)
1982
- if gates_passed and freeze_unchanged is not False:
2056
+ if gates_passed and freeze_unchanged is not False and not committed:
1983
2057
  next_step = "review"
1984
2058
  exit_code = EXIT_OK
1985
2059
  else:
@@ -2255,6 +2329,9 @@ def _accept_command(
2255
2329
  if review_status != "CLEAN" and not override_reason:
2256
2330
  if review_status == "BLOCKING":
2257
2331
  print("refusing: review BLOCKING; pass --override-review with a reason")
2332
+ elif review_status == "PARTIAL":
2333
+ print("refusing: review PARTIAL (the secret filter dropped files, so CLEAN covers only part of "
2334
+ "the diff); review the dropped files, or pass --override-review with a reason")
2258
2335
  else:
2259
2336
  # MISSING = no verdict (provider down, 429, secret-filter refusal). Anything else
2260
2337
  # that is not CLEAN (absent, null, unknown, lowercase) is also no valid verdict.
@@ -2272,6 +2349,11 @@ def _accept_command(
2272
2349
 
2273
2350
  wt = _worktree_from_packet(packet)
2274
2351
  _validate_packet_worktree(repo, plan, args.phase, args.attempt, wt)
2352
+ # Not overridable: --override-review accepts a verdict, and no verdict covers a lane commit.
2353
+ committed = lane_commit_reason(wt.path, wt.branch, wt.base_sha)
2354
+ if committed:
2355
+ print(f"refusing: {_printable(committed)}; abandon and redo the phase")
2356
+ return EXIT_FAIL
2275
2357
  files = packet.get("changed_files")
2276
2358
  if not isinstance(files, list) or not files:
2277
2359
  print("refusing: packet has no changed files")
@@ -7,7 +7,8 @@ thin shim over this file. The programme layer (programme folders, ledger, budget
7
7
  One session: stop checks (STOP file, session, hour and dollar caps); for agy, a reservation under the global spend cap
8
8
  (`caddis_spend.py`, settled after the session); read the relay hash; launch ONE session through the governor with the
9
9
  resume prompt and `CADDIS_HEADLESS=1` in its environment; parse its JSON result (cost, error); read the relay status
10
- line; decide. CONTINUE with an unchanged relay is `FAILED no progress`; three sessions in a row with no newly closed
10
+ line; decide. A relay the session did not change (same hash as before it, any status line) is `FAILED no relay
11
+ written`, so a status an earlier session wrote is never acted on again; three sessions in a row with no newly closed
11
12
  row is `BLOCKED stuck`.
12
13
 
13
14
  Plan mode (`--plan <slug>`, decision D-I, design section 8.5) runs `.caddis/plans/<slug>.md`. A closed row in its
@@ -38,6 +39,16 @@ folder, never the `--repo` checkout); when the roadmap is finished the runner re
38
39
  origin: `rollup` when every phase of the milestone is merged, then the next batch. A relay `STATUS: OWNER-GATE <r>`
39
40
  becomes an `owner-gate` blocker, `STATUS: BLOCKED <r>` an `external` one, and the loop goes on.
40
41
 
42
+ Context restarts (context-handoff Phase 15): a headless session at the 280k stop line ends `STATUS: BLOCKED context
43
+ <n>` (the context_size hook tells it to). The runner then starts a fresh session for the SAME batch when HEAD moved
44
+ in the session's cwd (`git rev-parse HEAD` before and after; no git or no change: no restart), the batch has restarts
45
+ left (`CONTEXT_RESTARTS`, 2 per batch) and, in roadmap mode, the worktree has no uncommitted work and is still on the
46
+ runner's branch. Plan mode reuses the same prompt; the count resets when a Tracker row closes. Roadmap mode runs the
47
+ same `<plan>#<phase>` on the same branch in the same worktree: no `next`, no branch reset. The session record gets
48
+ `status` `BLOCKED context (restart <k>)` and `context_restart` <k>; no toast, no push, no blocker row; every cap and
49
+ the stuck rule still apply. With no restart, the record gets `context_restart` `no commits`, `limit 2`, `dirty tree`
50
+ or `off branch`, and the stop goes on as for any other `BLOCKED` line.
51
+
41
52
  Review gate (caddis-next Phase 11): a phase is pending review when its Tracker row is done in the working copy of
42
53
  the plan (its path, or `.caddis/plans/done/` after tidy moved it), not done on origin/<default>, marked
43
54
  `**Risk:** high` in any copy (working, origin, the copy from before the session; `caddis_review.phase_risk`), and not
@@ -147,6 +158,8 @@ ENGINES: dict[str, dict] = {
147
158
  }
148
159
  PROMPT_ON_STDIN = {"claude"}
149
160
  STUCK_SESSIONS = 3
161
+ CONTEXT_RESTARTS = 2 # fresh sessions per batch after `STATUS: BLOCKED context <n>` (context-handoff Phase 15)
162
+ _CONTEXT_RE = re.compile(r"context\b")
150
163
  PLAN_PROMPT_NAME = "plan-resume-prompt.md"
151
164
  # CLAUDE_CODE_FORK_SUBAGENT=0: since 2.1.302 fork subagents are on by default in `claude -p`. A fork can run in the
152
165
  # background, and a print-mode session can end before it finishes, so its work is lost; the session prompt already
@@ -1332,6 +1345,7 @@ def _run_plan(ctx: _Ctx, template: Path, dry_run: bool, after_session: Callable[
1332
1345
  print(f"caddis_roadmap_run: engine {ctx.engine} is an adapter, not live-tested", file=sys.stderr)
1333
1346
 
1334
1347
  sessions, spent, stuck, pushed = 0, 0.0, 0, False
1348
+ restarts = 0 # context restarts of the current batch; reset when a Tracker row closes
1335
1349
  plan_before = ""
1336
1350
  start = ctx.clock()
1337
1351
  try:
@@ -1356,6 +1370,7 @@ def _run_plan(ctx: _Ctx, template: Path, dry_run: bool, after_session: Callable[
1356
1370
  working = _working_plan(repo, slug)
1357
1371
  plan_before = working[1] if working else ""
1358
1372
  state_before = state_snapshot(repo, "plan", slug)
1373
+ head_before = _git_out(repo, "rev-parse", "HEAD") # a context block restarts only when HEAD moved
1359
1374
  s = _one_session(ctx, prompt, slug, sessions + 1, spent, elapsed, slug)
1360
1375
  _check_state(repo, "plan", slug, state_before)
1361
1376
  sessions += 1
@@ -1366,12 +1381,24 @@ def _run_plan(ctx: _Ctx, template: Path, dry_run: bool, after_session: Callable[
1366
1381
  if stop is None:
1367
1382
  closed = _closed(target)
1368
1383
  stuck = 0 if closed > closed_before else stuck + 1
1384
+ restarts = 0 if closed > closed_before else restarts
1369
1385
  s.record["status"] = "CONTINUE"
1370
1386
  if stuck >= STUCK_SESSIONS:
1371
1387
  raise _Stop("BLOCKED stuck", caddis_exit.BLOCKED)
1372
1388
  else:
1373
- s.record["status"] = stop.reason
1374
- raise stop
1389
+ restart = None
1390
+ if _context_block(stop):
1391
+ restarts = 0 if _closed(target) > closed_before else restarts
1392
+ restart = _context_restart(stop, repo, head_before, restarts)
1393
+ if isinstance(restart, int): # a fresh session for the same plan, with the same prompt
1394
+ restarts = restart
1395
+ s.record.update({"status": f"BLOCKED context (restart {restart})",
1396
+ "context_restart": restart})
1397
+ else:
1398
+ if restart is not None:
1399
+ s.record["context_restart"] = restart
1400
+ s.record["status"] = stop.reason
1401
+ raise stop
1375
1402
  finally:
1376
1403
  s.record.setdefault("status", "FAILED")
1377
1404
  ctx.log(s.record)
@@ -1964,6 +1991,7 @@ def _run_roadmap(ctx: _Ctx, template: Path, dry_run: bool, after_session: Callab
1964
1991
  relay_slug: str | None = None
1965
1992
  last_write: tuple[str, str] | None = None
1966
1993
  wt: Path | None = None
1994
+ rerun = restarts = 0 # rerun > 0: the next session runs the same batch again (context restart number)
1967
1995
  start = ctx.clock()
1968
1996
 
1969
1997
  try:
@@ -2022,68 +2050,74 @@ def _run_roadmap(ctx: _Ctx, template: Path, dry_run: bool, after_session: Callab
2022
2050
  if rollup(mid) == 0: # nothing written: a recorded stop, and recheck must not retry it
2023
2051
  _write_record(failed_file, {**_read_record(failed_file), mid: _roadmap_sha(snap.text)})
2024
2052
  raise _Stop(f"BLOCKED rollup of {mid} wrote nothing; the owner decides", caddis_exit.BLOCKED)
2025
- with _claim(repo): # choose and claim atomically: no other runner can choose the same batch
2026
- try:
2027
- batch, snap = caddis_roadmap.next_with_snapshot(repo, slug)
2028
- except caddis_roadmap.RoadmapError as exc:
2029
- raise _Stop(f"FAILED roadmap changed: the origin copy no longer loads: "
2030
- f"{str(exc).splitlines()[0]}", caddis_exit.BLOCKED) from None
2031
- baseline.observe(snap)
2032
- if batch is not None:
2033
- lock.set_batch(f"{batch['plan']}#{batch['phase']}")
2034
- if batch is None:
2035
- detail = _status_line(repo, slug)
2036
- if snap.roadmap.milestones and all(ms.status in caddis_roadmap.FINISHED
2037
- for ms in snap.roadmap.milestones):
2038
- gone = remove_worktree_if_clean(repo, slug, worktree_root)
2039
- detail += "; roadmap finished; " + gone
2040
- if gone.startswith(("worktree removed", "no worktree")):
2041
- detail += "; " + _cleanup_finished_branches(repo, slug, snap.branch, pr_merged,
2042
- delete_remote_branch)
2043
- raise _Stop(RESTARTABLE_STOP, caddis_exit.BLOCKED, detail=detail,
2044
- record={"held": _held_batches(repo, slug, snap)})
2045
- mid, plan, phase = batch["milestone"], batch["plan"], batch["phase"]
2046
- ref = f"{plan}#{phase}"
2047
- print(f"next: {mid} {ref}")
2048
- if last_write == (mid, ref): # the runner's own block did not take the batch off `next`
2049
- raise _Stop(f"FAILED roadmap unchanged after the runner's write for {mid} {ref}",
2050
- caddis_exit.BLOCKED)
2051
- relay_slug = plan
2052
- plan_text = _plan_text(snap, plan)
2053
- lane = phase_lane(plan_text, phase) or "none" # no Lane line: not the runner's (fail closed)
2054
- if not lane_runs_here(lane, ctx.engine):
2055
- reason = f"phase {phase} lane: {' '.join(lane.split())[:160]}".strip()
2056
- write(["block", "--id", mid, "--type", "owner-gate", "--reason", reason],
2057
- ("blocker", mid, "owner-gate", reason))
2058
- last_write = (mid, ref)
2059
- continue
2060
- last_write = None
2061
- if snap.roadmap.get(mid).status == "todo":
2062
- write(["set", "--id", mid, "--col", "Status", "--value", "in-progress"],
2063
- ("status", mid, "in-progress"))
2064
- snap = _load_observed(repo, slug, baseline) # the write window is guarded too
2065
- # Every session runs in the roadmap's own worktree, on a fresh branch made from origin/<default>.
2066
- wt = wt or ensure_worktree(repo, slug, snap.branch, worktree_root)
2067
- branch = session_branch(slug, plan, phase)
2068
- if branch not in made_branches and _branch_on_origin(repo, branch):
2069
- raise _Stop(f"BLOCKED branch {branch} is on origin and this runner did not make it",
2070
- caddis_exit.BLOCKED)
2071
- for ref_name in (f"refs/heads/{branch}", f"refs/remotes/origin/{branch}"):
2072
- if _git_out(wt, "rev-parse", "--verify", "--quiet", ref_name) is None:
2053
+ if not rerun: # a new batch: choose it, then a fresh branch (a context restart keeps both)
2054
+ with _claim(repo): # choose and claim atomically: no other runner can choose the same batch
2055
+ try:
2056
+ batch, snap = caddis_roadmap.next_with_snapshot(repo, slug)
2057
+ except caddis_roadmap.RoadmapError as exc:
2058
+ raise _Stop(f"FAILED roadmap changed: the origin copy no longer loads: "
2059
+ f"{str(exc).splitlines()[0]}", caddis_exit.BLOCKED) from None
2060
+ baseline.observe(snap)
2061
+ if batch is not None:
2062
+ lock.set_batch(f"{batch['plan']}#{batch['phase']}")
2063
+ if batch is None:
2064
+ detail = _status_line(repo, slug)
2065
+ if snap.roadmap.milestones and all(ms.status in caddis_roadmap.FINISHED
2066
+ for ms in snap.roadmap.milestones):
2067
+ gone = remove_worktree_if_clean(repo, slug, worktree_root)
2068
+ detail += "; roadmap finished; " + gone
2069
+ if gone.startswith(("worktree removed", "no worktree")):
2070
+ detail += "; " + _cleanup_finished_branches(repo, slug, snap.branch, pr_merged,
2071
+ delete_remote_branch)
2072
+ raise _Stop(RESTARTABLE_STOP, caddis_exit.BLOCKED, detail=detail,
2073
+ record={"held": _held_batches(repo, slug, snap)})
2074
+ mid, plan, phase = batch["milestone"], batch["plan"], batch["phase"]
2075
+ ref = f"{plan}#{phase}"
2076
+ print(f"next: {mid} {ref}")
2077
+ if last_write == (mid, ref): # the runner's own block did not take the batch off `next`
2078
+ raise _Stop(f"FAILED roadmap unchanged after the runner's write for {mid} {ref}",
2079
+ caddis_exit.BLOCKED)
2080
+ relay_slug = plan
2081
+ plan_text = _plan_text(snap, plan)
2082
+ lane = phase_lane(plan_text, phase) or "none" # no Lane line: not the runner's (fail closed)
2083
+ if not lane_runs_here(lane, ctx.engine):
2084
+ reason = f"phase {phase} lane: {' '.join(lane.split())[:160]}".strip()
2085
+ write(["block", "--id", mid, "--type", "owner-gate", "--reason", reason],
2086
+ ("blocker", mid, "owner-gate", reason))
2087
+ last_write = (mid, ref)
2073
2088
  continue
2074
- ahead = _git_out(wt, "rev-list", "--count", f"origin/{snap.branch}..{ref_name}")
2075
- if ahead is None or ahead != "0": # an earlier session's work: never reset it
2076
- raise _Stop(f"BLOCKED {branch} has unpublished commits from an earlier session",
2089
+ last_write = None
2090
+ if snap.roadmap.get(mid).status == "todo":
2091
+ write(["set", "--id", mid, "--col", "Status", "--value", "in-progress"],
2092
+ ("status", mid, "in-progress"))
2093
+ snap = _load_observed(repo, slug, baseline) # the write window is guarded too
2094
+ # Every session runs in the roadmap's own worktree, on a fresh branch made from origin/<default>.
2095
+ wt = wt or ensure_worktree(repo, slug, snap.branch, worktree_root)
2096
+ branch = session_branch(slug, plan, phase)
2097
+ if branch not in made_branches and _branch_on_origin(repo, branch):
2098
+ raise _Stop(f"BLOCKED branch {branch} is on origin and this runner did not make it",
2077
2099
  caddis_exit.BLOCKED)
2078
- left = _worktree_work(wt) # a blocked session's uncommitted work must never ride into another branch
2079
- if left is None or left:
2080
- was = _git_out(wt, "rev-parse", "--abbrev-ref", "HEAD") or "?"
2081
- raise _Stop(f"BLOCKED roadmap worktree has uncommitted work from {was} ({wt})", caddis_exit.BLOCKED)
2082
- made = _git_out(wt, "checkout", "-q", "-B", branch, f"origin/{snap.branch}")
2083
- if made is None:
2084
- raise _Stop(f"FAILED cannot make the session branch {branch} in {wt} (is it clean?)",
2085
- caddis_exit.BLOCKED)
2086
- head_before = _git_out(wt, "rev-parse", "HEAD")
2100
+ for ref_name in (f"refs/heads/{branch}", f"refs/remotes/origin/{branch}"):
2101
+ if _git_out(wt, "rev-parse", "--verify", "--quiet", ref_name) is None:
2102
+ continue
2103
+ ahead = _git_out(wt, "rev-list", "--count", f"origin/{snap.branch}..{ref_name}")
2104
+ if ahead is None or ahead != "0": # an earlier session's work: never reset it
2105
+ raise _Stop(f"BLOCKED {branch} has unpublished commits from an earlier session",
2106
+ caddis_exit.BLOCKED)
2107
+ left = _worktree_work(wt) # a blocked session's uncommitted work must never ride into another branch
2108
+ if left is None or left:
2109
+ was = _git_out(wt, "rev-parse", "--abbrev-ref", "HEAD") or "?"
2110
+ raise _Stop(f"BLOCKED roadmap worktree has uncommitted work from {was} ({wt})", caddis_exit.BLOCKED)
2111
+ made = _git_out(wt, "checkout", "-q", "-B", branch, f"origin/{snap.branch}")
2112
+ if made is None:
2113
+ raise _Stop(f"FAILED cannot make the session branch {branch} in {wt} (is it clean?)",
2114
+ caddis_exit.BLOCKED)
2115
+ head_before = _git_out(wt, "rev-parse", "HEAD")
2116
+ restarts = 0 # context restarts of this batch
2117
+ else:
2118
+ print(f"again: {mid} {ref} (context restart {rerun})")
2119
+ rerun = 0
2120
+ session_head = _git_out(wt, "rev-parse", "HEAD") # a context block restarts only when HEAD moved
2087
2121
  done_before = _done_phases(snap, plan)
2088
2122
  state_before = state_snapshot(repo, "roadmap", slug)
2089
2123
  s = _one_session(ctx, render_prompt(template, plan, phase), plan, sessions + 1, spent,
@@ -2098,7 +2132,14 @@ def _run_roadmap(ctx: _Ctx, template: Path, dry_run: bool, after_session: Callab
2098
2132
  s.record["status"] = "CONTINUE" if stop is None else stop.reason
2099
2133
  after = _load_observed(repo, slug, baseline) # one read after the session (no merge wait)
2100
2134
  stuck = 0 if _done_phases(after, plan) > done_before else stuck + 1
2101
- if stop is not None:
2135
+ restart = _context_restart(stop, wt, session_head, restarts, branch)
2136
+ if isinstance(restart, int): # the same batch again: same branch, same worktree, no blocker row
2137
+ restarts = rerun = restart
2138
+ snap = after
2139
+ s.record.update({"status": f"BLOCKED context (restart {restart})", "context_restart": restart})
2140
+ elif stop is not None:
2141
+ if restart is not None:
2142
+ s.record["context_restart"] = restart
2102
2143
  if stop.status is None or stop.status[0] not in ("OWNER-GATE", "BLOCKED"):
2103
2144
  raise stop
2104
2145
  btype = "owner-gate" if stop.status[0] == "OWNER-GATE" else "external"
@@ -2366,25 +2407,53 @@ def _launch(cmd: list[str], cwd: Path, timeout_s: float, stdin_text: str | None
2366
2407
 
2367
2408
  def _decide(engine: str, outcome: _Outcome, result: dict | None, relay_text: str, hash_before: str | None,
2368
2409
  hash_after: str | None) -> _Stop | None:
2369
- """None to go on; else the stop. A missing or bad status line is FAILED, never CONTINUE (design 8.1)."""
2410
+ """None to go on; else the stop. A missing or bad status line is FAILED, never CONTINUE (design 8.1). A relay
2411
+ this session did not change is FAILED whatever its status: its line belongs to an earlier session (audit 10)."""
2370
2412
  failed = _session_failed(engine, outcome, result)
2371
2413
  if failed is not None:
2372
2414
  return failed
2373
2415
  if hash_after is None:
2374
2416
  return _Stop("FAILED no relay", caddis_exit.BLOCKED)
2417
+ if hash_after == hash_before:
2418
+ return _Stop("FAILED no relay written", caddis_exit.BLOCKED)
2375
2419
  try:
2376
2420
  kind, arg = caddis_workstreams.parse_status(relay_text)
2377
2421
  except ValueError as exc:
2378
2422
  return _Stop(f"FAILED bad status line: {exc}", caddis_exit.BLOCKED)
2379
2423
  if kind == "CONTINUE":
2380
- if hash_after == hash_before:
2381
- return _Stop("FAILED no progress", caddis_exit.BLOCKED)
2382
2424
  return None
2383
2425
  if kind == "FAILED":
2384
2426
  return _Stop(f"FAILED {arg}", caddis_exit.BLOCKED, from_relay=True, status=(kind, arg))
2385
2427
  return _Stop(f"{kind} {arg}", caddis_exit.CLEAN, from_relay=True, status=(kind, arg))
2386
2428
 
2387
2429
 
2430
+ def _context_block(stop: _Stop | None) -> bool:
2431
+ """True for a relay `STATUS: BLOCKED context <n>` (the context_size hook's 280k stop line, headless)."""
2432
+ return (stop is not None and stop.status is not None and stop.status[0] == "BLOCKED"
2433
+ and _CONTEXT_RE.match(stop.status[1]) is not None)
2434
+
2435
+
2436
+ def _context_restart(stop: _Stop | None, cwd: Path, head_before: str | None, used: int,
2437
+ branch: str | None = None) -> int | str | None:
2438
+ """For a `STATUS: BLOCKED context <n>` stop: the restart number (1, 2) when the runner starts a fresh session for
2439
+ the same batch, else why not (`no commits`, `limit 2`, `dirty tree`, `off branch`). None for any other stop.
2440
+ `used` is the restarts this batch had; `branch` (roadmap mode) is the runner's branch in the worktree `cwd`."""
2441
+ if not _context_block(stop):
2442
+ return None
2443
+ head_after = _git_out(cwd, "rev-parse", "HEAD")
2444
+ if head_before is None or head_after is None or head_after == head_before: # no git, or nothing committed
2445
+ return "no commits"
2446
+ if used >= CONTEXT_RESTARTS:
2447
+ return f"limit {CONTEXT_RESTARTS}"
2448
+ if branch is not None:
2449
+ work = _worktree_work(cwd)
2450
+ if work is None or work:
2451
+ return "dirty tree"
2452
+ if _git_out(cwd, "rev-parse", "--abbrev-ref", "HEAD") != branch:
2453
+ return "off branch"
2454
+ return used + 1
2455
+
2456
+
2388
2457
  def _session_failed(engine: str, outcome: _Outcome, result: dict | None) -> _Stop | None:
2389
2458
  """The stop for a session that did not finish cleanly (usage limit, timeout, exit code, output, error); None when
2390
2459
  it did. The relay is not read here: a review fix session writes no status line."""