@caddis/cli 0.4.88 → 0.4.90

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 (97) hide show
  1. package/README.md +46 -0
  2. package/bundles/antigravity-plugin/agents/preflight.md +4 -0
  3. package/bundles/antigravity-plugin/plugin.json +1 -1
  4. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_exit.cpython-311.pyc +0 -0
  5. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_file_lock.cpython-311.pyc +0 -0
  6. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_frontmatter.cpython-311.pyc +0 -0
  7. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_redact.cpython-311.pyc +0 -0
  8. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_roadmap.cpython-311.pyc +0 -0
  9. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_rows.cpython-311.pyc +0 -0
  10. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_status.cpython-311.pyc +0 -0
  11. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_tidy.cpython-311.pyc +0 -0
  12. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_todo.cpython-311.pyc +0 -0
  13. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_workstreams.cpython-311.pyc +0 -0
  14. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_worktree_safety.cpython-311.pyc +0 -0
  15. package/bundles/antigravity-plugin/scripts/caddis_fleet.py +37 -10
  16. package/bundles/antigravity-plugin/scripts/caddis_guide.json +16 -11
  17. package/bundles/antigravity-plugin/scripts/caddis_handoff.py +370 -0
  18. package/bundles/antigravity-plugin/scripts/caddis_heartbeat.py +339 -0
  19. package/bundles/antigravity-plugin/scripts/caddis_hub_collect.py +37 -8
  20. package/bundles/antigravity-plugin/scripts/caddis_roadmap_run.py +130 -63
  21. package/bundles/antigravity-plugin/scripts/caddis_routing.py +36 -0
  22. package/bundles/antigravity-plugin/scripts/caddis_todo.py +55 -10
  23. package/bundles/antigravity-plugin/scripts/caddis_workstreams.py +35 -12
  24. package/bundles/antigravity-plugin/scripts/schemas/hub-collect.schema.json +42 -0
  25. package/bundles/antigravity-plugin/scripts/schemas/hub-plans.schema.json +23 -0
  26. package/bundles/antigravity-plugin/session_end_agy.py +26 -1
  27. package/bundles/antigravity-plugin/skills/code-review/SKILL.md +2 -0
  28. package/bundles/antigravity-plugin/skills/coordinate/SKILL.md +5 -3
  29. package/bundles/antigravity-plugin/skills/cross-review/SKILL.md +1 -0
  30. package/bundles/antigravity-plugin/skills/feature-plan/SKILL.md +47 -19
  31. package/bundles/antigravity-plugin/skills/fleet-open/SKILL.md +1 -1
  32. package/bundles/antigravity-plugin/skills/handoff/SKILL.md +82 -7
  33. package/bundles/antigravity-plugin/skills/implement/SKILL.md +86 -6
  34. package/bundles/antigravity-plugin/skills/park/SKILL.md +1 -0
  35. package/bundles/antigravity-plugin/skills/preflight/SKILL.md +1 -0
  36. package/bundles/antigravity-plugin/skills/roadmap/assets/plan-resume-prompt.md +8 -1
  37. package/bundles/antigravity-plugin/warm_start_agy.py +29 -1
  38. package/bundles/antigravity-plugin-extras/plugin.json +1 -1
  39. package/bundles/antigravity-plugin-extras/skills/cross-review/SKILL.md +1 -0
  40. package/bundles/codex/.codex/skills/coding/code-review/SKILL.md +2 -0
  41. package/bundles/codex/.codex/skills/workflow/preflight/SKILL.md +1 -0
  42. package/bundles/codex/.codex/skills/workflow/roadmap/assets/plan-resume-prompt.md +8 -1
  43. package/bundles/manifest.json +3 -3
  44. package/dist/allowed-urls.txt +3 -2
  45. package/dist/cli.js +554 -275
  46. package/dist/export/assets/export-B7BBDg5I.js +150 -0
  47. package/dist/export/assets/export-HxTgj3z2.css +1 -0
  48. package/dist/export/assets/mark-anim-DZa95SHo.webp +0 -0
  49. package/dist/export/assets/mark-still-CcPgBc_-.png +0 -0
  50. package/dist/export/fonts/ibm-plex-mono-400.6d569bb7.woff2 +0 -0
  51. package/dist/export/fonts/ibm-plex-mono-700.9f478677.woff2 +0 -0
  52. package/dist/export/fonts/ibm-plex-sans-400.17fc1ce7.woff2 +0 -0
  53. package/dist/export/fonts/ibm-plex-sans-500.dcc69acf.woff2 +0 -0
  54. package/dist/export/fonts/ibm-plex-sans-600.d4dad061.woff2 +0 -0
  55. package/dist/export/fonts/ibm-plex-sans-700.40d9a530.woff2 +0 -0
  56. package/dist/export/index.html +2 -2
  57. package/dist/export/licenses/{OFL-MapleMono.txt → OFL-IBMPlexMono.txt} +4 -4
  58. package/dist/{ui/licenses/OFL-MapleMono.txt → export/licenses/OFL-IBMPlexSans.txt} +4 -4
  59. package/dist/ui/assets/{Activity-C9TCizJV.js → Activity-DZKPMOeV.js} +1 -1
  60. package/dist/ui/assets/Guide-5ZFfL6sl.js +9 -0
  61. package/dist/ui/assets/Guide-Dnsb-TRd.css +1 -0
  62. package/dist/ui/assets/RoadmapTab-DPsiSmIF.js +31 -0
  63. package/dist/ui/assets/index-DGlNAmeA.css +1 -0
  64. package/dist/ui/assets/index-xl156OCN.js +231 -0
  65. package/dist/ui/assets/mark-anim-DZa95SHo.webp +0 -0
  66. package/dist/ui/assets/mark-still-CcPgBc_-.png +0 -0
  67. package/dist/ui/fonts/ibm-plex-mono-400.6d569bb7.woff2 +0 -0
  68. package/dist/ui/fonts/ibm-plex-mono-700.9f478677.woff2 +0 -0
  69. package/dist/ui/fonts/ibm-plex-sans-400.17fc1ce7.woff2 +0 -0
  70. package/dist/ui/fonts/ibm-plex-sans-500.dcc69acf.woff2 +0 -0
  71. package/dist/ui/fonts/ibm-plex-sans-600.d4dad061.woff2 +0 -0
  72. package/dist/ui/fonts/ibm-plex-sans-700.40d9a530.woff2 +0 -0
  73. package/dist/ui/index.html +2 -2
  74. package/dist/{export/licenses/OFL-Atkinson.txt → ui/licenses/OFL-IBMPlexMono.txt} +3 -3
  75. package/dist/ui/licenses/{OFL-Atkinson.txt → OFL-IBMPlexSans.txt} +3 -3
  76. package/package.json +4 -1
  77. package/dist/export/assets/export-CEtCs5rg.css +0 -1
  78. package/dist/export/assets/export-v-kcNvPW.js +0 -150
  79. package/dist/export/assets/mark-small-B1q4Vk3J.svg +0 -8
  80. package/dist/export/fonts/atkinson-400.849ae6f0.woff2 +0 -0
  81. package/dist/export/fonts/atkinson-500.21d6ef26.woff2 +0 -0
  82. package/dist/export/fonts/atkinson-600.ce9f3210.woff2 +0 -0
  83. package/dist/export/fonts/atkinson-700.3a9cc18a.woff2 +0 -0
  84. package/dist/export/fonts/maple-mono-400.071799fd.woff2 +0 -0
  85. package/dist/export/fonts/maple-mono-700.1e17b237.woff2 +0 -0
  86. package/dist/ui/assets/Guide-6aEYW9oW.js +0 -9
  87. package/dist/ui/assets/Guide-zcVFGUxR.css +0 -1
  88. package/dist/ui/assets/RoadmapTab-hUK2kzCW.js +0 -31
  89. package/dist/ui/assets/index-DE7v-v_o.css +0 -1
  90. package/dist/ui/assets/index-d44hkSAE.js +0 -221
  91. package/dist/ui/assets/mark-small-B1q4Vk3J.svg +0 -8
  92. package/dist/ui/fonts/atkinson-400.849ae6f0.woff2 +0 -0
  93. package/dist/ui/fonts/atkinson-500.21d6ef26.woff2 +0 -0
  94. package/dist/ui/fonts/atkinson-600.ce9f3210.woff2 +0 -0
  95. package/dist/ui/fonts/atkinson-700.3a9cc18a.woff2 +0 -0
  96. package/dist/ui/fonts/maple-mono-400.071799fd.woff2 +0 -0
  97. package/dist/ui/fonts/maple-mono-700.1e17b237.woff2 +0 -0
@@ -38,6 +38,16 @@ folder, never the `--repo` checkout); when the roadmap is finished the runner re
38
38
  origin: `rollup` when every phase of the milestone is merged, then the next batch. A relay `STATUS: OWNER-GATE <r>`
39
39
  becomes an `owner-gate` blocker, `STATUS: BLOCKED <r>` an `external` one, and the loop goes on.
40
40
 
41
+ Context restarts (context-handoff Phase 15): a headless session at the 280k stop line ends `STATUS: BLOCKED context
42
+ <n>` (the context_size hook tells it to). The runner then starts a fresh session for the SAME batch when HEAD moved
43
+ in the session's cwd (`git rev-parse HEAD` before and after; no git or no change: no restart), the batch has restarts
44
+ left (`CONTEXT_RESTARTS`, 2 per batch) and, in roadmap mode, the worktree has no uncommitted work and is still on the
45
+ runner's branch. Plan mode reuses the same prompt; the count resets when a Tracker row closes. Roadmap mode runs the
46
+ same `<plan>#<phase>` on the same branch in the same worktree: no `next`, no branch reset. The session record gets
47
+ `status` `BLOCKED context (restart <k>)` and `context_restart` <k>; no toast, no push, no blocker row; every cap and
48
+ the stuck rule still apply. With no restart, the record gets `context_restart` `no commits`, `limit 2`, `dirty tree`
49
+ or `off branch`, and the stop goes on as for any other `BLOCKED` line.
50
+
41
51
  Review gate (caddis-next Phase 11): a phase is pending review when its Tracker row is done in the working copy of
42
52
  the plan (its path, or `.caddis/plans/done/` after tidy moved it), not done on origin/<default>, marked
43
53
  `**Risk:** high` in any copy (working, origin, the copy from before the session; `caddis_review.phase_risk`), and not
@@ -147,6 +157,8 @@ ENGINES: dict[str, dict] = {
147
157
  }
148
158
  PROMPT_ON_STDIN = {"claude"}
149
159
  STUCK_SESSIONS = 3
160
+ CONTEXT_RESTARTS = 2 # fresh sessions per batch after `STATUS: BLOCKED context <n>` (context-handoff Phase 15)
161
+ _CONTEXT_RE = re.compile(r"context\b")
150
162
  PLAN_PROMPT_NAME = "plan-resume-prompt.md"
151
163
  # 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
164
  # background, and a print-mode session can end before it finishes, so its work is lost; the session prompt already
@@ -1332,6 +1344,7 @@ def _run_plan(ctx: _Ctx, template: Path, dry_run: bool, after_session: Callable[
1332
1344
  print(f"caddis_roadmap_run: engine {ctx.engine} is an adapter, not live-tested", file=sys.stderr)
1333
1345
 
1334
1346
  sessions, spent, stuck, pushed = 0, 0.0, 0, False
1347
+ restarts = 0 # context restarts of the current batch; reset when a Tracker row closes
1335
1348
  plan_before = ""
1336
1349
  start = ctx.clock()
1337
1350
  try:
@@ -1356,6 +1369,7 @@ def _run_plan(ctx: _Ctx, template: Path, dry_run: bool, after_session: Callable[
1356
1369
  working = _working_plan(repo, slug)
1357
1370
  plan_before = working[1] if working else ""
1358
1371
  state_before = state_snapshot(repo, "plan", slug)
1372
+ head_before = _git_out(repo, "rev-parse", "HEAD") # a context block restarts only when HEAD moved
1359
1373
  s = _one_session(ctx, prompt, slug, sessions + 1, spent, elapsed, slug)
1360
1374
  _check_state(repo, "plan", slug, state_before)
1361
1375
  sessions += 1
@@ -1366,12 +1380,24 @@ def _run_plan(ctx: _Ctx, template: Path, dry_run: bool, after_session: Callable[
1366
1380
  if stop is None:
1367
1381
  closed = _closed(target)
1368
1382
  stuck = 0 if closed > closed_before else stuck + 1
1383
+ restarts = 0 if closed > closed_before else restarts
1369
1384
  s.record["status"] = "CONTINUE"
1370
1385
  if stuck >= STUCK_SESSIONS:
1371
1386
  raise _Stop("BLOCKED stuck", caddis_exit.BLOCKED)
1372
1387
  else:
1373
- s.record["status"] = stop.reason
1374
- raise stop
1388
+ restart = None
1389
+ if _context_block(stop):
1390
+ restarts = 0 if _closed(target) > closed_before else restarts
1391
+ restart = _context_restart(stop, repo, head_before, restarts)
1392
+ if isinstance(restart, int): # a fresh session for the same plan, with the same prompt
1393
+ restarts = restart
1394
+ s.record.update({"status": f"BLOCKED context (restart {restart})",
1395
+ "context_restart": restart})
1396
+ else:
1397
+ if restart is not None:
1398
+ s.record["context_restart"] = restart
1399
+ s.record["status"] = stop.reason
1400
+ raise stop
1375
1401
  finally:
1376
1402
  s.record.setdefault("status", "FAILED")
1377
1403
  ctx.log(s.record)
@@ -1964,6 +1990,7 @@ def _run_roadmap(ctx: _Ctx, template: Path, dry_run: bool, after_session: Callab
1964
1990
  relay_slug: str | None = None
1965
1991
  last_write: tuple[str, str] | None = None
1966
1992
  wt: Path | None = None
1993
+ rerun = restarts = 0 # rerun > 0: the next session runs the same batch again (context restart number)
1967
1994
  start = ctx.clock()
1968
1995
 
1969
1996
  try:
@@ -2022,68 +2049,74 @@ def _run_roadmap(ctx: _Ctx, template: Path, dry_run: bool, after_session: Callab
2022
2049
  if rollup(mid) == 0: # nothing written: a recorded stop, and recheck must not retry it
2023
2050
  _write_record(failed_file, {**_read_record(failed_file), mid: _roadmap_sha(snap.text)})
2024
2051
  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:
2052
+ if not rerun: # a new batch: choose it, then a fresh branch (a context restart keeps both)
2053
+ with _claim(repo): # choose and claim atomically: no other runner can choose the same batch
2054
+ try:
2055
+ batch, snap = caddis_roadmap.next_with_snapshot(repo, slug)
2056
+ except caddis_roadmap.RoadmapError as exc:
2057
+ raise _Stop(f"FAILED roadmap changed: the origin copy no longer loads: "
2058
+ f"{str(exc).splitlines()[0]}", caddis_exit.BLOCKED) from None
2059
+ baseline.observe(snap)
2060
+ if batch is not None:
2061
+ lock.set_batch(f"{batch['plan']}#{batch['phase']}")
2062
+ if batch is None:
2063
+ detail = _status_line(repo, slug)
2064
+ if snap.roadmap.milestones and all(ms.status in caddis_roadmap.FINISHED
2065
+ for ms in snap.roadmap.milestones):
2066
+ gone = remove_worktree_if_clean(repo, slug, worktree_root)
2067
+ detail += "; roadmap finished; " + gone
2068
+ if gone.startswith(("worktree removed", "no worktree")):
2069
+ detail += "; " + _cleanup_finished_branches(repo, slug, snap.branch, pr_merged,
2070
+ delete_remote_branch)
2071
+ raise _Stop(RESTARTABLE_STOP, caddis_exit.BLOCKED, detail=detail,
2072
+ record={"held": _held_batches(repo, slug, snap)})
2073
+ mid, plan, phase = batch["milestone"], batch["plan"], batch["phase"]
2074
+ ref = f"{plan}#{phase}"
2075
+ print(f"next: {mid} {ref}")
2076
+ if last_write == (mid, ref): # the runner's own block did not take the batch off `next`
2077
+ raise _Stop(f"FAILED roadmap unchanged after the runner's write for {mid} {ref}",
2078
+ caddis_exit.BLOCKED)
2079
+ relay_slug = plan
2080
+ plan_text = _plan_text(snap, plan)
2081
+ lane = phase_lane(plan_text, phase) or "none" # no Lane line: not the runner's (fail closed)
2082
+ if not lane_runs_here(lane, ctx.engine):
2083
+ reason = f"phase {phase} lane: {' '.join(lane.split())[:160]}".strip()
2084
+ write(["block", "--id", mid, "--type", "owner-gate", "--reason", reason],
2085
+ ("blocker", mid, "owner-gate", reason))
2086
+ last_write = (mid, ref)
2073
2087
  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",
2088
+ last_write = None
2089
+ if snap.roadmap.get(mid).status == "todo":
2090
+ write(["set", "--id", mid, "--col", "Status", "--value", "in-progress"],
2091
+ ("status", mid, "in-progress"))
2092
+ snap = _load_observed(repo, slug, baseline) # the write window is guarded too
2093
+ # Every session runs in the roadmap's own worktree, on a fresh branch made from origin/<default>.
2094
+ wt = wt or ensure_worktree(repo, slug, snap.branch, worktree_root)
2095
+ branch = session_branch(slug, plan, phase)
2096
+ if branch not in made_branches and _branch_on_origin(repo, branch):
2097
+ raise _Stop(f"BLOCKED branch {branch} is on origin and this runner did not make it",
2077
2098
  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")
2099
+ for ref_name in (f"refs/heads/{branch}", f"refs/remotes/origin/{branch}"):
2100
+ if _git_out(wt, "rev-parse", "--verify", "--quiet", ref_name) is None:
2101
+ continue
2102
+ ahead = _git_out(wt, "rev-list", "--count", f"origin/{snap.branch}..{ref_name}")
2103
+ if ahead is None or ahead != "0": # an earlier session's work: never reset it
2104
+ raise _Stop(f"BLOCKED {branch} has unpublished commits from an earlier session",
2105
+ caddis_exit.BLOCKED)
2106
+ left = _worktree_work(wt) # a blocked session's uncommitted work must never ride into another branch
2107
+ if left is None or left:
2108
+ was = _git_out(wt, "rev-parse", "--abbrev-ref", "HEAD") or "?"
2109
+ raise _Stop(f"BLOCKED roadmap worktree has uncommitted work from {was} ({wt})", caddis_exit.BLOCKED)
2110
+ made = _git_out(wt, "checkout", "-q", "-B", branch, f"origin/{snap.branch}")
2111
+ if made is None:
2112
+ raise _Stop(f"FAILED cannot make the session branch {branch} in {wt} (is it clean?)",
2113
+ caddis_exit.BLOCKED)
2114
+ head_before = _git_out(wt, "rev-parse", "HEAD")
2115
+ restarts = 0 # context restarts of this batch
2116
+ else:
2117
+ print(f"again: {mid} {ref} (context restart {rerun})")
2118
+ rerun = 0
2119
+ session_head = _git_out(wt, "rev-parse", "HEAD") # a context block restarts only when HEAD moved
2087
2120
  done_before = _done_phases(snap, plan)
2088
2121
  state_before = state_snapshot(repo, "roadmap", slug)
2089
2122
  s = _one_session(ctx, render_prompt(template, plan, phase), plan, sessions + 1, spent,
@@ -2098,7 +2131,14 @@ def _run_roadmap(ctx: _Ctx, template: Path, dry_run: bool, after_session: Callab
2098
2131
  s.record["status"] = "CONTINUE" if stop is None else stop.reason
2099
2132
  after = _load_observed(repo, slug, baseline) # one read after the session (no merge wait)
2100
2133
  stuck = 0 if _done_phases(after, plan) > done_before else stuck + 1
2101
- if stop is not None:
2134
+ restart = _context_restart(stop, wt, session_head, restarts, branch)
2135
+ if isinstance(restart, int): # the same batch again: same branch, same worktree, no blocker row
2136
+ restarts = rerun = restart
2137
+ snap = after
2138
+ s.record.update({"status": f"BLOCKED context (restart {restart})", "context_restart": restart})
2139
+ elif stop is not None:
2140
+ if restart is not None:
2141
+ s.record["context_restart"] = restart
2102
2142
  if stop.status is None or stop.status[0] not in ("OWNER-GATE", "BLOCKED"):
2103
2143
  raise stop
2104
2144
  btype = "owner-gate" if stop.status[0] == "OWNER-GATE" else "external"
@@ -2385,6 +2425,33 @@ def _decide(engine: str, outcome: _Outcome, result: dict | None, relay_text: str
2385
2425
  return _Stop(f"{kind} {arg}", caddis_exit.CLEAN, from_relay=True, status=(kind, arg))
2386
2426
 
2387
2427
 
2428
+ def _context_block(stop: _Stop | None) -> bool:
2429
+ """True for a relay `STATUS: BLOCKED context <n>` (the context_size hook's 280k stop line, headless)."""
2430
+ return (stop is not None and stop.status is not None and stop.status[0] == "BLOCKED"
2431
+ and _CONTEXT_RE.match(stop.status[1]) is not None)
2432
+
2433
+
2434
+ def _context_restart(stop: _Stop | None, cwd: Path, head_before: str | None, used: int,
2435
+ branch: str | None = None) -> int | str | None:
2436
+ """For a `STATUS: BLOCKED context <n>` stop: the restart number (1, 2) when the runner starts a fresh session for
2437
+ the same batch, else why not (`no commits`, `limit 2`, `dirty tree`, `off branch`). None for any other stop.
2438
+ `used` is the restarts this batch had; `branch` (roadmap mode) is the runner's branch in the worktree `cwd`."""
2439
+ if not _context_block(stop):
2440
+ return None
2441
+ head_after = _git_out(cwd, "rev-parse", "HEAD")
2442
+ if head_before is None or head_after is None or head_after == head_before: # no git, or nothing committed
2443
+ return "no commits"
2444
+ if used >= CONTEXT_RESTARTS:
2445
+ return f"limit {CONTEXT_RESTARTS}"
2446
+ if branch is not None:
2447
+ work = _worktree_work(cwd)
2448
+ if work is None or work:
2449
+ return "dirty tree"
2450
+ if _git_out(cwd, "rev-parse", "--abbrev-ref", "HEAD") != branch:
2451
+ return "off branch"
2452
+ return used + 1
2453
+
2454
+
2388
2455
  def _session_failed(engine: str, outcome: _Outcome, result: dict | None) -> _Stop | None:
2389
2456
  """The stop for a session that did not finish cleanly (usage limit, timeout, exit code, output, error); None when
2390
2457
  it did. The relay is not read here: a review fix session writes no status line."""
@@ -29,6 +29,33 @@ DEFAULT_ROUTING: dict[str, list[str]] = {
29
29
  }
30
30
  KNOWN_MODELS = frozenset({"opus", "sonnet", "haiku", "agy", "codex", "glm", "deepseek", "claude"})
31
31
 
32
+ # One session model+effort table (owner, 27 Oct; .caddis/plans/context-handoff-strategy.md Phase 7). handoff,
33
+ # coordinate and implement read it; DEFAULT_ROUTING and `show` stay as they are. `orchestrator` stays high until
34
+ # Phase 9 measures it; `measure` is for measurement and screenshot subagents. Review is not a row: it goes by tier
35
+ # (`caddis_gate.py review-tier`).
36
+ SESSION_DEFAULTS: dict[str, tuple[str, str]] = {
37
+ "orchestrator": ("sonnet", "high"),
38
+ "plan-writer": ("opus", "high"),
39
+ "coordinator": ("sonnet", "low"),
40
+ "measure": ("sonnet", "medium"),
41
+ "critical-phase": ("opus", "medium"),
42
+ "coding-phase": ("agy", "medium"),
43
+ "mechanical-phase": ("haiku", "low"),
44
+ }
45
+ AGY_MODEL_BY_EFFORT: dict[str, str] = {"medium": "gemini-4-argon-medium", "high": "gemini-4-argon-high"}
46
+ CLAUDE_SESSION_MODELS = frozenset({"opus", "sonnet", "haiku"})
47
+
48
+
49
+ def session_start(role: str) -> tuple[str, str]:
50
+ """The `claude --model --effort` pair for a new session of `role`.
51
+
52
+ A start line can name only a Claude model, so a role with no Claude row (any session-name role, or
53
+ `coding-phase`) starts as the orchestrator."""
54
+ model, effort = SESSION_DEFAULTS.get(role, SESSION_DEFAULTS["orchestrator"])
55
+ if model not in CLAUDE_SESSION_MODELS:
56
+ return SESSION_DEFAULTS["orchestrator"]
57
+ return model, effort
58
+
32
59
 
33
60
  class RoutingConfigError(Exception):
34
61
  """A routing file has an invalid value or cannot be parsed."""
@@ -89,8 +116,17 @@ def main(argv: list[str] | None = None, env: Mapping[str, str] | None = None) ->
89
116
  show = commands.add_parser("show", help="print the resolved routing table")
90
117
  show.add_argument("--json", action="store_true", help="print JSON")
91
118
  show.add_argument("--repo", type=Path, default=Path.cwd(), help="repository path")
119
+ session = commands.add_parser("session", help="print the model and effort for a session role")
120
+ session.add_argument("--role", required=True, help=f"one of: {', '.join(SESSION_DEFAULTS)}")
92
121
  args = parser.parse_args(argv)
93
122
 
123
+ if args.command == "session":
124
+ if args.role not in SESSION_DEFAULTS:
125
+ print(f"unknown session role {args.role!r}; known: {', '.join(SESSION_DEFAULTS)}", file=sys.stderr)
126
+ return 4
127
+ print(" ".join(SESSION_DEFAULTS[args.role]))
128
+ return 0
129
+
94
130
  try:
95
131
  routing = resolve(Path.home(), args.repo, env=env)
96
132
  except RoutingConfigError as exc:
@@ -182,6 +182,32 @@ def _plan_files(root: Path) -> list[Path]:
182
182
  return sorted(p for p in plans_dir.glob("*.md") if p.is_file() and not p.is_symlink())
183
183
 
184
184
 
185
+ _PHASE_HEADING = re.compile(r"^(#{2,3})\s+Phase\s+([^\s:—]+)\s*[:—-]?\s*(.*)$", re.M | re.I)
186
+
187
+
188
+ def phase_key(cell: str) -> str:
189
+ s = cell.replace("`", "").replace("*", "").strip()
190
+ s = re.sub(r"^phase\s+", "", s, flags=re.I)
191
+ s = re.split(r" -|[\s:—]", s, maxsplit=1)[0]
192
+ return s.rstrip(".").lower()
193
+
194
+
195
+ def phase_sections(text: str) -> dict[str, dict]:
196
+ out: dict[str, dict] = {}
197
+ for m in _PHASE_HEADING.finditer(text):
198
+ key = phase_key(m.group(2))
199
+ if key in out:
200
+ continue
201
+ title = m.group(3).rstrip(" \t\r\n⏳🔲✅\ufe0f").strip()
202
+ rest = text[m.end():]
203
+ stop = re.search(rf"^#{{1,{len(m.group(1))}}} ", rest, re.M)
204
+ body = (rest[:stop.start()] if stop else rest).strip()
205
+ if len(body) > 2000:
206
+ body = body[:2000] + "…"
207
+ out[key] = {"title": title, "text": body}
208
+ return out
209
+
210
+
185
211
  def _plan_entry(root: Path, path: Path) -> dict:
186
212
  return _plan_entry_text(path.relative_to(Path(root)).as_posix(), path.read_text(encoding="utf-8"))
187
213
 
@@ -205,15 +231,22 @@ def _plan_entry_text(rel: str, text: str) -> dict:
205
231
  if table is not None:
206
232
  columns, lines = table
207
233
  status_at = columns.index("status")
234
+ ms_at = columns.index("milestone") if "milestone" in columns else None
208
235
  for line in lines:
209
236
  if not line.strip().startswith("|") or caddis_tidy._TABLE_RULE_RE.match(line.strip()):
210
237
  continue
211
238
  cells = caddis_tidy._row_cells(line)
212
239
  if cells:
213
240
  cell = cells[status_at] if len(cells) > status_at else ""
214
- tracker.append({"phase": cells[0], "status": cell, "state": status_state(cell)})
241
+ row: dict = {"phase": cells[0], "key": phase_key(cells[0])}
242
+ if ms_at is not None:
243
+ row["milestone"] = cells[ms_at].strip() if len(cells) > ms_at else ""
244
+ row["status"] = cell
245
+ row["state"] = status_state(cell)
246
+ tracker.append(row)
215
247
  return {"path": rel, "title": title,
216
248
  "status": meta.get("status"), "feature": meta.get("feature"),
249
+ "phases": phase_sections(text),
217
250
  "tracker": tracker, "open_rows": sum(1 for row in tracker if not _is_done(row["status"]))}
218
251
 
219
252
 
@@ -263,16 +296,27 @@ def _tree_blobs(tree: bytes, oid_len: int) -> list[tuple[str, str]]:
263
296
  return out
264
297
 
265
298
 
266
- def _origin_plan_texts(root: Path, branch: str) -> list[tuple[str, str]] | None:
267
- """[(path, text)] of the plan files on origin/<branch>: `.caddis/plans/*.md`, else `.github/plans/*.md`, never
268
- `done/`. One git process for the whole read. None when git cannot read the ref."""
299
+ def _origin_plan_texts(root: Path, branch: str) -> tuple[str, int | None, list[tuple[str, str]]] | None:
300
+ """(commit_oid, commit_at, [(path, text)]) of the plan files on origin/<branch>: `.caddis/plans/*.md`, else
301
+ `.github/plans/*.md`, never `done/`. One git process for the whole read. None when git cannot read the ref."""
269
302
  try:
270
303
  batch = _Batch(root)
271
304
  except OSError:
272
305
  return None
273
306
  try:
274
- if batch.get(f"refs/remotes/origin/{branch}") is None:
307
+ commit_obj = batch.get(f"refs/remotes/origin/{branch}")
308
+ if commit_obj is None:
275
309
  return None
310
+ commit_oid = commit_obj[0]
311
+ commit_at: int | None = None
312
+ for line in commit_obj[2].decode("utf-8", errors="replace").splitlines():
313
+ if not line:
314
+ break
315
+ if line.startswith("committer "):
316
+ try:
317
+ commit_at = int(line.split()[-2])
318
+ except (IndexError, ValueError):
319
+ commit_at = None
276
320
  for folder in (".caddis/plans", ".github/plans"):
277
321
  tree = batch.get(f"refs/remotes/origin/{branch}:{folder}")
278
322
  if tree is None or tree[1] != "tree":
@@ -286,8 +330,8 @@ def _origin_plan_texts(root: Path, branch: str) -> list[tuple[str, str]] | None:
286
330
  if blob is None:
287
331
  return None
288
332
  texts.append((f"{folder}/{name}", blob[2].decode("utf-8", errors="replace").replace("\r\n", "\n")))
289
- return texts
290
- return []
333
+ return commit_oid, commit_at, texts
334
+ return commit_oid, commit_at, []
291
335
  except (OSError, ValueError):
292
336
  return None
293
337
  finally:
@@ -345,14 +389,15 @@ def plans_json(root: Path, branch: str | None = None) -> dict:
345
389
  does not parse gives `{"path", "error"}`; the other plans still come back.
346
390
  """
347
391
  root = Path(root)
348
- texts = _origin_plan_texts(root, branch) if branch else None
349
- if texts is not None:
392
+ origin = _origin_plan_texts(root, branch) if branch else None
393
+ if origin is not None:
394
+ commit, commit_at, texts = origin
350
395
  plans = [_entry_or_error(rel, lambda rel=rel, text=text: _plan_entry_text(rel, text)) for rel, text in texts]
351
396
  times = _origin_plan_times(root, branch, texts[0][0].rsplit("/", 1)[0]) if texts else {}
352
397
  for plan in plans:
353
398
  if "error" not in plan:
354
399
  plan["changed_at"] = times.get(plan["path"])
355
- return {"schema": 1, "source": f"origin/{branch}", "plans": plans}
400
+ return {"schema": 1, "source": f"origin/{branch}", "commit": commit[:12], "commit_at": commit_at, "plans": plans}
356
401
  plans = []
357
402
  for path in _plan_files(root):
358
403
  plan = _entry_or_error(path.relative_to(root).as_posix(), lambda path=path: _plan_entry(root, path))
@@ -30,6 +30,10 @@ _BAD_REF = re.compile(r"[\x00-\x20\x7f~^:?*\[\\]")
30
30
  _NEXT = re.compile(r"^## Next step[^\n]*\n(.*?)(?=^## |\Z)", re.MULTILINE | re.DOTALL)
31
31
  _MAX_INDEX = 800
32
32
  _INDEX_MARKER = "<!-- caddis-workstream-index-v1 -->\n"
33
+ # `generated.by` of a relay that migrate-legacy writes.
34
+ _MIGRATED_BY = "caddis_workstreams.py migrate-legacy"
35
+ # The relay size budget in scripts/caddis_budget.py (`.caddis/relay/*.md`, chars).
36
+ _RELAY_BUDGET_CHARS = 4000
33
37
 
34
38
 
35
39
  @dataclass(frozen=True)
@@ -468,6 +472,20 @@ class MigrationReport(dict):
468
472
  return self["backups"]
469
473
 
470
474
 
475
+ def _utc_z(value: object = None) -> str:
476
+ """`value` (an ISO time; naive means UTC) or now, as relay headers write it: UTC, seconds, `Z`.
477
+ An unreadable value gives now, as the migration did before."""
478
+ when = datetime.now(timezone.utc)
479
+ if value:
480
+ try:
481
+ when = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
482
+ except ValueError:
483
+ pass
484
+ if when.tzinfo is None:
485
+ when = when.replace(tzinfo=timezone.utc)
486
+ return when.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
487
+
488
+
471
489
  def migrate_legacy(root: Path) -> MigrationReport:
472
490
  """Run the locked migration, then make sure an index exists when there was nothing to do.
473
491
 
@@ -550,10 +568,10 @@ def _migrate_legacy_locked(root: Path) -> MigrationReport:
550
568
  # No header, or an opening --- with no closing one: keep the whole file as the body.
551
569
  header_closed = split_document(candidate_text)[1] != candidate_text
552
570
  if not candidate_text.startswith("---\n") or not header_closed:
553
- now_iso = datetime.now(timezone.utc).isoformat()
554
571
  candidate_text = (
555
572
  f"---\ntype: relay\nworkstream: {relay_name}\nbranch: main\n"
556
- f"session_id: legacy-migrated\nplan:\ngenerated:\n at: {now_iso}\n---\n\n"
573
+ f"session_id: legacy-migrated\nplan:\ngenerated:\n by: {_MIGRATED_BY}\n"
574
+ f" at: {_utc_z()}\n---\n\n"
557
575
  f"# Relay — {relay_name}\n\n## Next step (exact)\n{raw_relay}\n"
558
576
  )
559
577
  else:
@@ -575,9 +593,13 @@ def _migrate_legacy_locked(root: Path) -> MigrationReport:
575
593
  meta["plan"] = ""
576
594
  modified = True
577
595
  if not isinstance(meta.get("generated"), dict) or not meta["generated"].get("at"):
578
- # Keep the original time from an inline "{ by: x, at: y }" map; else now.
579
- inline = re.search(r"\bat:\s*([0-9][0-9T:.+\-Z]+)", str(meta.get("generated", "")))
580
- meta["generated"] = {"at": inline.group(1) if inline else datetime.now(timezone.utc).isoformat()}
596
+ # Keep the original author and time from an inline "{ by: x, at: y }" map; else
597
+ # this script, now.
598
+ inline = str(meta.get("generated", ""))
599
+ by = re.search(r"\bby:\s*([^,}\n]+)", inline)
600
+ at = re.search(r"\bat:\s*([0-9][0-9T:.+\-Z]+)", inline)
601
+ meta["generated"] = {"by": by.group(1).strip() if by else _MIGRATED_BY,
602
+ "at": _utc_z(at.group(1) if at else None)}
581
603
  modified = True
582
604
  if modified:
583
605
  # Plain writer: the plugin ships no YAML library, and this runs in user installs.
@@ -629,17 +651,11 @@ def _migrate_legacy_locked(root: Path) -> MigrationReport:
629
651
  branch = frame.get("branch") or "main"
630
652
  session_id = frame.get("session_id") or "legacy-migrated"
631
653
  resume = frame.get("resumePointer") or "next step unrecorded"
632
- pushed = frame.get("pushedAt") or datetime.now(timezone.utc).isoformat()
633
- try:
634
- datetime.fromisoformat(str(pushed).replace("Z", "+00:00"))
635
- except ValueError:
636
- pushed = datetime.now(timezone.utc).isoformat()
637
-
638
654
  # _header_text folds every value to one line: a newline in workstreams.json
639
655
  # must not add or break header fields.
640
656
  header = _header_text({"type": "relay", "workstream": frame_name, "branch": str(branch),
641
657
  "session_id": str(session_id), "plan": str(plan or ""),
642
- "generated": {"at": str(pushed)}})
658
+ "generated": {"by": _MIGRATED_BY, "at": _utc_z(frame.get("pushedAt"))}})
643
659
  candidate_text = (f"---\n{header}---\n\n# Relay — {frame_name}\n\n"
644
660
  f"## Next step (exact)\n{' '.join(str(resume).split())}\n")
645
661
  try:
@@ -850,6 +866,13 @@ def main(argv: list[str] | None = None) -> int:
850
866
  print(f"Migration status: {report.status}")
851
867
  for conflict in report.conflicts:
852
868
  print(f" conflict: {conflict}")
869
+ # The old relay is kept verbatim, so it can be over the relay budget. Say so once, here;
870
+ # caddis_budget.py keeps reporting it until someone trims it.
871
+ for name in report.migrated:
872
+ size = len(read_relay(args.root, name)[0])
873
+ if size > _RELAY_BUDGET_CHARS:
874
+ print(f" note: .caddis/relay/{name}.md is {size} chars, over the {_RELAY_BUDGET_CHARS}-char "
875
+ "relay budget (the old relay is kept verbatim); trim it to the current state or delete it")
853
876
  return 0 if report.status in ("clean", "migrated") else 1
854
877
  elif args.command == "list":
855
878
  try:
@@ -341,6 +341,29 @@
341
341
  "source": {
342
342
  "type": "string"
343
343
  },
344
+ "commit": {
345
+ "type": "string"
346
+ },
347
+ "fetched_at": {
348
+ "oneOf": [
349
+ {
350
+ "type": "integer"
351
+ },
352
+ {
353
+ "type": "null"
354
+ }
355
+ ]
356
+ },
357
+ "commit_at": {
358
+ "oneOf": [
359
+ {
360
+ "type": "integer"
361
+ },
362
+ {
363
+ "type": "null"
364
+ }
365
+ ]
366
+ },
344
367
  "plans": {
345
368
  "type": "array",
346
369
  "items": {
@@ -592,6 +615,25 @@
592
615
  "type": "string"
593
616
  }
594
617
  }
618
+ },
619
+ {
620
+ "type": "object",
621
+ "required": [
622
+ "path",
623
+ "fingerprint",
624
+ "unchanged"
625
+ ],
626
+ "properties": {
627
+ "path": {
628
+ "type": "string"
629
+ },
630
+ "fingerprint": {
631
+ "type": "string"
632
+ },
633
+ "unchanged": {
634
+ "type": "boolean"
635
+ }
636
+ }
595
637
  }
596
638
  ]
597
639
  }
@@ -14,6 +14,29 @@
14
14
  "source": {
15
15
  "type": "string"
16
16
  },
17
+ "commit": {
18
+ "type": "string"
19
+ },
20
+ "fetched_at": {
21
+ "oneOf": [
22
+ {
23
+ "type": "integer"
24
+ },
25
+ {
26
+ "type": "null"
27
+ }
28
+ ]
29
+ },
30
+ "commit_at": {
31
+ "oneOf": [
32
+ {
33
+ "type": "integer"
34
+ },
35
+ {
36
+ "type": "null"
37
+ }
38
+ ]
39
+ },
17
40
  "plans": {
18
41
  "type": "array",
19
42
  "items": {