@caddis/cli 0.4.96 → 0.4.98

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 (55) hide show
  1. package/README.md +2 -0
  2. package/bundles/antigravity-plugin/plugin.json +1 -1
  3. package/bundles/antigravity-plugin/repo_hygiene.py +134 -20
  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 +31 -21
  16. package/bundles/antigravity-plugin/scripts/caddis_gate.py +18 -1
  17. package/bundles/antigravity-plugin/scripts/caddis_guide.json +2 -2
  18. package/bundles/antigravity-plugin/scripts/caddis_handoff.py +235 -0
  19. package/bundles/antigravity-plugin/scripts/caddis_hub_collect.py +67 -15
  20. package/bundles/antigravity-plugin/scripts/caddis_lanes.py +154 -130
  21. package/bundles/antigravity-plugin/scripts/caddis_review.py +12 -0
  22. package/bundles/antigravity-plugin/scripts/caddis_tidy.py +152 -51
  23. package/bundles/antigravity-plugin/scripts/caddis_todo.py +314 -18
  24. package/bundles/antigravity-plugin/scripts/schemas/hub-collect.schema.json +117 -1
  25. package/bundles/antigravity-plugin/scripts/schemas/hub-plans.schema.json +117 -1
  26. package/bundles/antigravity-plugin/scripts/setup_project_ai.py +60 -2
  27. package/bundles/antigravity-plugin/scripts/templates/coordinator.md +3 -3
  28. package/bundles/antigravity-plugin/skills/coordinate/SKILL.md +4 -1
  29. package/bundles/antigravity-plugin/skills/cross-review/SKILL.md +6 -0
  30. package/bundles/antigravity-plugin/skills/handoff/SKILL.md +101 -23
  31. package/bundles/antigravity-plugin/skills/implement/SKILL.md +6 -0
  32. package/bundles/antigravity-plugin/skills/park/SKILL.md +7 -2
  33. package/bundles/antigravity-plugin/skills/pr-merge/SKILL.md +1 -0
  34. package/bundles/antigravity-plugin/skills/ship-pr/SKILL.md +1 -0
  35. package/bundles/manifest.json +2 -2
  36. package/dist/cli.js +276 -76
  37. package/dist/export/assets/export-B3cUoxL1.js +150 -0
  38. package/dist/export/assets/export-DQss44R1.css +1 -0
  39. package/dist/export/index.html +2 -2
  40. package/dist/ui/assets/Activity-CvEIJlnE.js +6 -0
  41. package/dist/ui/assets/{Guide-Czn5sK0f.js → Guide-BxS9L55s.js} +1 -1
  42. package/dist/ui/assets/Guide-DTd261-c.css +1 -0
  43. package/dist/ui/assets/RoadmapTab-CqlWs7dJ.js +31 -0
  44. package/dist/ui/assets/index-9pdDzLVp.css +1 -0
  45. package/dist/ui/assets/index-DSxeWPax.js +231 -0
  46. package/dist/ui/index.html +2 -2
  47. package/package.json +1 -1
  48. package/dist/export/assets/export-CMtV-slT.css +0 -1
  49. package/dist/export/assets/export-DtlDFN4L.js +0 -150
  50. package/dist/ui/assets/Activity-BDjet2xd.js +0 -6
  51. package/dist/ui/assets/Guide-D-Zy4cUT.css +0 -1
  52. package/dist/ui/assets/RoadmapTab-Bd8geyQx.js +0 -31
  53. package/dist/ui/assets/index-Bd0Z4jR8.css +0 -1
  54. package/dist/ui/assets/index-CmngQ8Mk.js +0 -231
  55. package/dist/ui/assets/time-D00tu2ZP.js +0 -1
package/README.md CHANGED
@@ -141,6 +141,8 @@ starts it in the background; `caddis hub stop` stops it.
141
141
 
142
142
  **Timeline first, Board second.** Roadmaps and plans open on the Timeline view by default, with the Board view as the second option. Click any phase tile on the Timeline to open the phase panel and read its Tracker status, PR links and plan section text.
143
143
 
144
+ **Branch progress.** A plan that an open PR changes shows the PR branch's Tracker and `status:`, with the badge `on branch (PR #n)`. Done on main never goes back, and forks are not shown. The hub reads PR heads from GitHub and branch refs from the local origin refs, and never fetches. With no PR data, the line above the plans says `branch progress off (no PR data)`. `caddis hub export --prs <file>` takes the output of `gh pr list --json number,headRefName,isDraft,isCrossRepository,updatedAt`. The export never publishes a branch name, and a privacy hit only in branch content publishes main only.
145
+
144
146
  **Guide Poster and Details.** The Guide page has a `Poster` tab (with `Workflow` and `Mind map` views, plus a `Print` button for a two-page A3 landscape wall poster) and a `Details` tab. Every item on the poster links to its entry in Details.
145
147
 
146
148
  **Guide Wall poster.** A third tab, `Wall poster` (`#/guide/wall`), shows one A4 landscape sheet: the daily commands in order, a card per stage (plan, build, review, ship, continuity, knowledge, setup), and the agents. The `Print` button prints exactly that sheet on one page. It is built from the same installed guide data as the other tabs, so a new command, agent or count appears by itself after `caddis update` and a hub restart. The text shrinks (to 60% at most) when the guide grows, so nothing is cut off. Each line is the first clause of the description; the Details tab has the full text.
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "name": "caddis",
3
- "version": "1.3.180",
3
+ "version": "1.3.182",
4
4
  "description": "caddis — agent-agnostic dev harness as an Antigravity (agy) plugin: TDD skills + commands, single-sourced with the Claude Code plugin."
5
5
  }
@@ -3,13 +3,13 @@
3
3
  Plan: `.caddis/plans/repo-hygiene-report.md` (Phase 3). `repo_freshness._report` calls `report_lines()`, so Claude
4
4
  Code, Codex and agy all get the report through one function, one process and one time budget.
5
5
 
6
- REPORT ONLY. Nothing here deletes, moves or changes anything. The one file it writes is the gh cache
7
- `<git-common-dir>/caddis-hygiene-prs.json`. Removal is `caddis_tidy.py --hygiene --apply`, which re-proves every
6
+ REPORT ONLY. Nothing here deletes, moves or changes anything. The only files it writes are the gh cache
7
+ `<git-common-dir>/caddis-hygiene-prs.json` and the Orca cache `~/.caddis/orca-worktrees.json`. Removal is `caddis_tidy.py --hygiene --apply`, which re-proves every
8
8
  candidate with the deletion-grade test in `caddis_finished.py`.
9
9
 
10
10
  Every decision lives in `caddis_finished.py` (stdlib only). This module holds the I/O and the formatting. Every git
11
- call goes through the `git(cwd, *args) -> (code, stdout)` seam (`repo_freshness._git` in the hook). gh and orca go
12
- through a `subprocess.run`-shaped seam that never opens a console window.
11
+ call goes through the `git(cwd, *args) -> (code, stdout)` seam (`repo_freshness._git` in the hook). gh goes
12
+ through a `subprocess.run`-shaped seam and orca through a `Popen`-shaped one; neither opens a console window.
13
13
  """
14
14
  from __future__ import annotations
15
15
 
@@ -49,6 +49,14 @@ PR_CACHE_MAX_AGE_S = 600 # the same as repo_freshness.FETCH_MAX_AGE_S
49
49
  GH_FIELDS = "headRefName,state,number,headRefOid"
50
50
  GH_TIMEOUT_S = 5.0 # the most gh may take; less when less of the session-start budget is left
51
51
  ORCA_TIMEOUT_S = 3.0 # the same for orca
52
+ # Orca lists the worktrees of every repo, so one cache under ~/.caddis serves all repos. A cold `orca worktree
53
+ # list` took 9.5 s on the owner's server (warm: 0.66 s), so a slow call is never killed: it keeps writing its
54
+ # `orca-worktrees.<pid>.out` file, and the next session start promotes that file to the cache.
55
+ ORCA_CACHE_NAME = "orca-worktrees.json"
56
+ ORCA_CACHE_FRESH_S = 600 # a younger cache answers with no orca call
57
+ ORCA_CACHE_MAX_AGE_S = 86400 # an older cache is never used
58
+ ORCA_PARTIAL_MAX_AGE_S = 3600 # an unreadable .out file older than this is a dead call: delete it
59
+ ORCA_CLOCK_SKEW_S = 60 # a cache this far in the "future" is still used (clock resolution); more is not
52
60
  NO_TIME_LEFT = "no time left in the session-start budget"
53
61
 
54
62
  # No child opens a console window on Windows; git never takes an optional lock or asks for a credential.
@@ -249,22 +257,18 @@ def fetch_prs(top: Path, git_dir: Path, run: Callable, now: float,
249
257
  return prs, ""
250
258
 
251
259
 
252
- def orca_worktrees(run: Callable, which: Callable, timeout_s: float = ORCA_TIMEOUT_S) -> tuple[dict[str, str] | None, str]:
253
- """Every path Orca manages -> its Orca id, keyed by `_key(path)`. (None, reason) when Orca cannot answer
254
- completely: not on PATH, a non-zero exit, a timeout, bad JSON, `ok` false, or `result.truncated` true."""
255
- exe = which("orca")
256
- if not exe:
257
- return None, "orca not on PATH"
258
- try:
259
- proc = run([exe, "worktree", "list", "--limit", "10000", "--json"], timeout=timeout_s)
260
- except subprocess.TimeoutExpired:
261
- return None, f"orca took longer than {timeout_s:g} s"
262
- except (OSError, subprocess.SubprocessError) as exc:
263
- return None, f"orca could not start: {exc}"
264
- if proc.returncode != 0:
265
- return None, _last_line(proc, "orca")
260
+ def _start_orca(argv: list[str], out: Path, err: Path) -> subprocess.Popen:
261
+ """The default orca seam: start `argv` with stdout to `out` and stderr to `err`, and do not wait. The caller
262
+ waits with `proc.wait(timeout)`. On a timeout nothing kills the child: it finishes and fills `out`."""
263
+ with open(out, "wb") as fo, open(err, "wb") as fe:
264
+ return subprocess.Popen(argv, stdout=fo, stderr=fe, stdin=subprocess.DEVNULL,
265
+ env={**os.environ, **_ENV_OVERRIDES}, creationflags=_NO_WINDOW)
266
+
267
+
268
+ def _parse_orca(text: str) -> tuple[dict[str, str] | None, str]:
269
+ """`orca worktree list --json` output -> (path key -> Orca id, "") or (None, reason)."""
266
270
  try:
267
- data = json.loads(proc.stdout)
271
+ data = json.loads(text)
268
272
  except ValueError:
269
273
  return None, "orca returned unreadable JSON"
270
274
  if not isinstance(data, dict) or data.get("ok") is not True:
@@ -281,6 +285,115 @@ def orca_worktrees(run: Callable, which: Callable, timeout_s: float = ORCA_TIMEO
281
285
  return mapping, ""
282
286
 
283
287
 
288
+ def _read_text(path: Path) -> str | None:
289
+ try:
290
+ return path.read_text(encoding="utf-8", errors="replace")
291
+ except OSError:
292
+ return None
293
+
294
+
295
+ def _remove(*paths: Path) -> None:
296
+ for p in paths:
297
+ try:
298
+ p.unlink()
299
+ except OSError:
300
+ pass # gone already, or still open: a later session start removes it
301
+
302
+
303
+ def _promote_finished(cache_dir: Path, now: float) -> None:
304
+ """Move the newest complete `orca-worktrees.<pid>.out` (from an earlier slow call) over the cache. Delete the
305
+ complete ones it does not use, and unreadable ones older than ORCA_PARTIAL_MAX_AGE_S. A young unreadable file is
306
+ a call that still runs: leave it."""
307
+ complete: list[tuple[float, Path]] = []
308
+ for out in cache_dir.glob("orca-worktrees.*.out"):
309
+ err = out.with_suffix(".err")
310
+ try:
311
+ mtime = out.stat().st_mtime
312
+ except OSError:
313
+ continue
314
+ text = _read_text(out)
315
+ if text is not None and _parse_orca(text)[0] is not None:
316
+ complete.append((mtime, out))
317
+ elif now - mtime > ORCA_PARTIAL_MAX_AGE_S:
318
+ _remove(out, err)
319
+ complete.sort(reverse=True)
320
+ cache = cache_dir / ORCA_CACHE_NAME
321
+ for i, (mtime, out) in enumerate(complete):
322
+ try:
323
+ newer = i == 0 and (not cache.exists() or mtime > cache.stat().st_mtime)
324
+ if newer:
325
+ os.replace(out, cache)
326
+ except OSError:
327
+ newer = False
328
+ if not newer:
329
+ _remove(out)
330
+ _remove(out.with_suffix(".err"))
331
+
332
+
333
+ def _read_orca_cache(cache_dir: Path, now: float) -> tuple[dict[str, str] | None, float]:
334
+ """(mapping, age in seconds) from the cache, or (None, 0) when it is missing, unreadable or too old."""
335
+ cache = cache_dir / ORCA_CACHE_NAME
336
+ try:
337
+ age = now - cache.stat().st_mtime
338
+ except OSError:
339
+ return None, 0.0
340
+ text = _read_text(cache)
341
+ # time.time() can lag a file's mtime by a few ms on Windows, so a just-written cache can look a little "future"
342
+ if text is None or not -ORCA_CLOCK_SKEW_S <= age < ORCA_CACHE_MAX_AGE_S:
343
+ return None, 0.0
344
+ return _parse_orca(text)[0], max(age, 0.0)
345
+
346
+
347
+ def orca_worktrees(start: Callable, which: Callable, timeout_s: float = ORCA_TIMEOUT_S,
348
+ cache_dir: Path | None = None, now: float | None = None) -> tuple[dict[str, str] | None, str]:
349
+ """Every path Orca manages -> its Orca id, keyed by `_key(path)`. (None, reason) when Orca cannot answer
350
+ completely: not on PATH, a non-zero exit, bad JSON, `ok` false, or `result.truncated` true.
351
+
352
+ A cache younger than ORCA_CACHE_FRESH_S answers with no orca call. Otherwise orca runs, and the hook waits at
353
+ most `timeout_s`. When orca is slower, the last cache (up to ORCA_CACHE_MAX_AGE_S old) answers; with no cache it
354
+ is a skip. The slow call is not killed, so the next session start has a fresh cache."""
355
+ now = time.time() if now is None else now
356
+ cache_dir = Path.home() / ".caddis" if cache_dir is None else Path(cache_dir)
357
+ try:
358
+ cache_dir.mkdir(parents=True, exist_ok=True)
359
+ _promote_finished(cache_dir, now)
360
+ except OSError:
361
+ pass # no cache this time: orca still answers below
362
+ cached, age = _read_orca_cache(cache_dir, now)
363
+ if cached is not None and age < ORCA_CACHE_FRESH_S:
364
+ return cached, ""
365
+ exe = which("orca")
366
+ if not exe:
367
+ return None, "orca not on PATH"
368
+ out = cache_dir / f"orca-worktrees.{os.getpid()}.out"
369
+ err = out.with_suffix(".err")
370
+ try:
371
+ proc = start([exe, "worktree", "list", "--limit", "10000", "--json"], out, err)
372
+ except (OSError, subprocess.SubprocessError) as exc:
373
+ return None, f"orca could not start: {exc}"
374
+ try:
375
+ code = proc.wait(timeout=timeout_s)
376
+ except subprocess.TimeoutExpired:
377
+ if cached is not None:
378
+ return cached, ""
379
+ return None, f"orca took longer than {timeout_s:g} s (its answer is cached for the next session start)"
380
+ text, err_text = _read_text(out) or "", _read_text(err) or ""
381
+ if code != 0:
382
+ _remove(out, err)
383
+ last = err_text.strip() or text.strip()
384
+ return None, last.splitlines()[-1].strip() if last else f"orca exited {code}"
385
+ mapping, reason = _parse_orca(text)
386
+ if mapping is None:
387
+ _remove(out, err)
388
+ return None, reason
389
+ try:
390
+ os.replace(out, cache_dir / ORCA_CACHE_NAME)
391
+ except OSError:
392
+ _remove(out)
393
+ _remove(err)
394
+ return mapping, ""
395
+
396
+
284
397
  def orca_id(mapping: dict[str, str] | None, path: str) -> str | None:
285
398
  """The Orca id of `path`, matched case- and slash-insensitively; None when Orca does not manage it."""
286
399
  return mapping.get(_key(path)) if mapping else None
@@ -448,7 +561,8 @@ def start_jobs(top: Path, git: Callable, remaining: Callable[[], float], *, want
448
561
  gh = (pool.submit(fetch_prs, main, git_dir, _run, time.time(), gh_s) if gh_s > 0
449
562
  else _done((None, NO_TIME_LEFT)))
450
563
  if any_linked:
451
- orca = pool.submit(orca_worktrees, _run, _which, orca_s) if orca_s > 0 else _done((None, NO_TIME_LEFT))
564
+ orca = (pool.submit(orca_worktrees, _start_orca, _which, orca_s, home / ".caddis") if orca_s > 0
565
+ else _done((None, NO_TIME_LEFT)))
452
566
  finally:
453
567
  pool.shutdown(wait=False) # the submitted calls still run; their timeouts bound them
454
568
  return Jobs(main, roots, any_linked, gh, orca)
@@ -204,10 +204,10 @@ def render_roster(acks: list[Ack], coordinator: str) -> str:
204
204
  return "\n".join(lines) + "\n"
205
205
 
206
206
 
207
- def _fenced(text: str) -> str:
207
+ def _fenced(text: str, lang: str = "text") -> str:
208
208
  longest = max((len(r) for r in re.findall(r"`+", text)), default=0)
209
209
  fence = "`" * max(3, longest + 1)
210
- return f"{fence}text\n{text}\n{fence}"
210
+ return f"{fence}{lang}\n{text}\n{fence}"
211
211
 
212
212
 
213
213
  def start_line(ack: Ack, stamp: datetime) -> str:
@@ -475,11 +475,15 @@ def resume_prompt(relay_text: str) -> str:
475
475
  return prompt
476
476
 
477
477
 
478
+ def one_line(text: str) -> str:
479
+ """The text on one line, with no `'` and no `"`: a `'` would end a single-quoted word in bash and a `"` is dropped
480
+ by Windows PowerShell 5.1, so both become typographic."""
481
+ return " ".join(text.split()).replace("'", "’").replace('"', "”")
482
+
483
+
478
484
  def shell_arg(text: str) -> str:
479
- """One word that PowerShell and bash read the same: one line, inside single quotes (no expansion in either).
480
- A `'` would end the word in bash and a `"` is dropped by Windows PowerShell 5.1, so both become typographic."""
481
- one_line = " ".join(text.split())
482
- return "'" + one_line.replace("'", "’").replace('"', "”") + "'"
485
+ """One word that PowerShell and bash read the same: one line, inside single quotes (no expansion in either)."""
486
+ return "'" + one_line(text) + "'"
483
487
 
484
488
 
485
489
  ANNOUNCE_ID = "<your session id>"
@@ -501,27 +505,33 @@ def announce_text(name: str, folder: str) -> str:
501
505
  f"a reply. If the script is missing or lists no peer, skip this.")
502
506
 
503
507
 
508
+ RESUME_PROMPT_LABEL = "After /clear in this window, paste this:"
509
+ RESUME_LINE_LABEL = "In a new terminal, paste this:"
510
+
511
+
504
512
  def render_resume(session: str, session_id: str, workstream: str, prompt: str, role: str, stamp: datetime,
505
513
  fleet_mode: bool = False, announce: bool = False, folder: str = "",
506
514
  root: Path | None = None) -> str:
507
- """The last output of `/caddis:handoff`. In a fleet close the restart sheet holds the only start line.
508
-
509
- With `announce`, the start line (not the fenced block, which stays the relay's text) ends with the
510
- whoami + announce sentence: the start line is what the new session receives with its name.
511
- With `root`, the block names the repo and the start line first changes to it, because the relay's paths are
512
- repo-relative. `;`, as in the restart sheet: Windows PowerShell 5.1 has no `&&`."""
513
- shown = prompt # the fenced block stays the relay text
515
+ """The last output of `/caddis:handoff`. In a fleet close the restart sheet holds the only start line, so the
516
+ block keeps the relay's own prompt and says so.
517
+
518
+ Otherwise it ends with two labelled copy blocks. The model re-types this output in a Markdown reply, so colour
519
+ cannot reach the owner; a label and a fence can (owner, 5 Nov). Block 1 is the prompt on one line, to paste after
520
+ `/clear` in the same window. Block 2 is the full start line, to paste in a new terminal.
521
+ With `announce`, both end with the whoami + announce sentence: the new session receives it with its name.
522
+ With `root`, block 2 first changes to the repo, because the relay's paths are repo-relative. `;`, as in the
523
+ restart sheet: Windows PowerShell 5.1 has no `&&`."""
514
524
  repo = f"Repo: {root.as_posix()}\n" if root is not None else ""
515
525
  cd = f'cd "{root.as_posix()}"; ' if root is not None else ""
526
+ head = f"{model_line(role)}=== RESUME ===\nSession: {session} ({session_id})\nWorkstream: {workstream}\n{repo}"
516
527
  if fleet_mode:
517
- start = "Start line: from the restart sheet"
518
- else:
519
- name = new_name(role, stamp)
520
- if announce:
521
- prompt = f"{prompt}\n{announce_text(name, folder)}"
522
- start = f"Start line:\n{cd}claude {_model_flags(role)} --name {name} {shell_arg(prompt)}"
523
- return (f"{model_line(role)}=== RESUME ===\nSession: {session} ({session_id})\nWorkstream: {workstream}\n"
524
- f"{repo}{_fenced(shown)}\n{start}\n")
528
+ return f"{head}{_fenced(prompt)}\nStart line: from the restart sheet\n"
529
+ name = new_name(role, stamp)
530
+ if announce:
531
+ prompt = f"{prompt}\n{announce_text(name, folder)}"
532
+ full = f"{cd}claude {_model_flags(role)} --name {name} {shell_arg(prompt)}"
533
+ return (f"{head}{RESUME_PROMPT_LABEL}\n{_fenced(one_line(prompt))}\n"
534
+ f"{RESUME_LINE_LABEL}\n{_fenced(full, 'bash')}\n")
525
535
 
526
536
 
527
537
  def render_coordinator_resume(session: str, session_id: str, workstream: str) -> str:
@@ -712,14 +712,28 @@ def review_tier(files: list[tuple[str, int]], plan_risk: str = "normal") -> str:
712
712
  return "1"
713
713
 
714
714
 
715
+ def area_reviewers(files: list[tuple[str, int]], phase_type: str | None = None) -> list[str]:
716
+ """Area reviewers for a diff: `security-analyst` when the auth trigger fires on a non-tier-0 path,
717
+ `ui-design-reviewer` when the plan phase's Type is `ui`. Never both for the wrong reason: docs and tests are tier 0."""
718
+ non_tier0 = [(p, lines) for p, lines in files if not is_tier0_file(p)]
719
+ names = []
720
+ fired = review_triggers([p for p, _ in non_tier0], 0)
721
+ if any(label == "auth" for label, _, _ in fired):
722
+ names.append("security-analyst")
723
+ if (phase_type or "").strip().lower() == "ui":
724
+ names.append("ui-design-reviewer")
725
+ return names
726
+
727
+
715
728
  def gate_review_tier(
716
729
  repo_root: Path,
717
730
  rev_range: str | None = None,
718
731
  plan: Path | str | None = None,
719
732
  phase: int | str | None = None,
720
733
  ) -> int:
721
- """Print the tier and reviewer count for the diff and plan phase."""
734
+ """Print the tier, reviewer count and area reviewers for the diff and plan phase."""
722
735
  risk = "normal"
736
+ ptype = None
723
737
  if plan and phase is None:
724
738
  risk = "high" # fail closed: a plan without a phase cannot give a risk
725
739
  elif plan and phase is not None:
@@ -730,6 +744,7 @@ def gate_review_tier(
730
744
  sys.path.insert(0, str(Path(__file__).resolve().parent))
731
745
  import caddis_review
732
746
  risk = caddis_review.phase_risk(Path(plan), phase)
747
+ ptype = caddis_review.phase_type(Path(plan), phase)
733
748
  except Exception:
734
749
  # Fail closed: a plan risk we cannot read counts as high (tier 2).
735
750
  risk = "high"
@@ -739,11 +754,13 @@ def gate_review_tier(
739
754
  sys.stderr.write(f"caddis-gate: review-tier could not read the diff ({exc}); counting it as tier 2\n")
740
755
  print("TIER: 2")
741
756
  print("REVIEWERS: 1")
757
+ print("AREA: none")
742
758
  return EXIT_OK
743
759
  tier = review_tier(files, plan_risk=risk)
744
760
  reviewers = TIER_REVIEWERS.get(tier, 1)
745
761
  print(f"TIER: {tier}")
746
762
  print(f"REVIEWERS: {reviewers}")
763
+ print(f"AREA: {', '.join(area_reviewers(files, ptype)) or 'none'}")
747
764
  return EXIT_OK
748
765
 
749
766
 
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schema": 1,
3
- "version": "1.3.179",
4
- "generated": "2026-11-05 13:49 UTC",
3
+ "version": "1.3.181",
4
+ "generated": "2026-11-08 05:49 UTC",
5
5
  "commands": [
6
6
  {
7
7
  "name": "add-rules",
@@ -1,5 +1,11 @@
1
1
  """The checkpoint tier of /caddis:handoff: a cheap mid-phase handoff in two calls.
2
2
 
3
+ `tidy-targets --own-files <f> [--root <dir>]` (full handoff Step 4) prints the finished top-level plans, prompts
4
+ and parking-lot items in this session's own-files list, one per line, for `caddis_tidy.py --apply --only`.
5
+ `carry --to <worktree> <path>...` (Step 4 on the default branch) copies those files, with their uncommitted edits,
6
+ into the docs-PR worktree; it never changes this checkout. `release --branch <docs-pr branch> <path>...` then restores
7
+ each one here, only when the pushed branch holds its moved copy, so no edit is lost and no move stays staged here.
8
+
3
9
  PREPARE (`checkpoint --session-id <id> [--name <ws>] [--plan <path> --phase <id>]`) reads the relay hash
4
10
  BEFORE the model composes the new relay, and prints the exact FINISH command. FINISH (`--relay-file` given)
5
11
  writes the relay with `put --require-status --expected-hash`, so a peer's change made in between is never
@@ -369,6 +375,215 @@ def _after_put(args: argparse.Namespace, name: str, rows: dict[str, str], state:
369
375
  return 0
370
376
 
371
377
 
378
+ _TIDY_KINDS = ("plans", "prompts", "parking-lot")
379
+
380
+
381
+ def _caddis_rel(raw: str) -> str | None:
382
+ """`.caddis/<kind>/<file>.md` for an own-files line that names a top-level plan, prompt or parking-lot
383
+ file, whichever checkout it was edited in (this one, or the Step 0 worktree); else None."""
384
+ item = raw.strip()
385
+ if item.startswith("- "):
386
+ item = item[2:].strip()
387
+ if len(item) >= 2 and item.startswith("`") and item.endswith("`"):
388
+ item = item[1:-1]
389
+ norm = "/" + item.replace("\\", "/").lstrip("/")
390
+ at = norm.rfind("/.caddis/")
391
+ if at < 0:
392
+ return None
393
+ parts = norm[at + 1:].split("/")
394
+ if len(parts) != 3 or parts[1] not in _TIDY_KINDS or not parts[2].lower().endswith(".md"):
395
+ return None
396
+ return "/".join(parts)
397
+
398
+
399
+ def tidy_targets(root: Path, own_files: Path, movable: bool = False) -> int:
400
+ """Print the finished top-level artifacts in this session's own-files list, one repo-relative path per
401
+ line: what `caddis_tidy.py --apply --only` should get at handoff Step 4. Another session's finished item
402
+ is never printed, so a handoff cannot sweep it (2026-11-07). Nothing printed means none.
403
+
404
+ By default a colliding item and a plan held for open Tracker rows are printed too: the `--only` run reports
405
+ them (exit 1 / exit 2). `movable` prints only what tidy would move now: Step 4 carries just those into the
406
+ docs-PR worktree, so a held or colliding item is never taken out of this checkout."""
407
+ root = Path(root).resolve()
408
+ try:
409
+ lines = own_files.read_text(encoding="utf-8", errors="replace").splitlines()
410
+ except OSError:
411
+ lines = []
412
+ own = {rel for rel in map(_caddis_rel, lines) if rel}
413
+ if not own:
414
+ return 0
415
+ caddis_tidy = _tidy_module()
416
+ report = caddis_tidy.tidy(root, apply=False)
417
+ finished = list(report.would_move) # would_move never holds a collision
418
+ if not movable:
419
+ finished += [*report.collisions, *(path for path, _ in report.open_rows_held)]
420
+ for rel in sorted({path.relative_to(root).as_posix() for path in finished} & own):
421
+ print(rel)
422
+ return 0
423
+
424
+
425
+ def _tidy_module():
426
+ if str(_HERE) not in sys.path:
427
+ sys.path.insert(0, str(_HERE))
428
+ import caddis_tidy # ships beside this file
429
+
430
+ return caddis_tidy
431
+
432
+
433
+ def _tracked(root: Path, rel: str) -> bool | None:
434
+ try:
435
+ res = subprocess.run(["git", "-C", str(root), "ls-files", "--error-unmatch", "--", rel],
436
+ capture_output=True, text=True, encoding="utf-8", errors="replace")
437
+ except OSError:
438
+ return None
439
+ if res.returncode == 0:
440
+ return True
441
+ return False if "did not match" in (res.stderr or "") else None
442
+
443
+
444
+ def _artifact_paths(root: Path, paths: list[str], verb: str) -> list[str] | None:
445
+ """The deduplicated repo-relative artifact paths, or None (after a refusal line) when one is not a real
446
+ top-level file of `.caddis/{plans,prompts,parking-lot}/` in `root` (a symlink is refused too)."""
447
+ out: list[str] = []
448
+ for raw in paths:
449
+ rel = raw.replace("\\", "/")
450
+ while rel.startswith("./"):
451
+ rel = rel[2:]
452
+ src = root / rel
453
+ if _caddis_rel(rel) != rel or src.is_symlink() or src.resolve() != src:
454
+ print(f"{verb}: refused: {raw} is not a top-level file in .caddis/plans/, .caddis/prompts/ or "
455
+ ".caddis/parking-lot/; nothing was changed")
456
+ return None
457
+ if rel not in out:
458
+ out.append(rel)
459
+ return out
460
+
461
+
462
+ def carry(root: Path, to: Path, paths: list[str]) -> int:
463
+ """Copy this session's own artifacts, with their uncommitted edits, from this checkout into the Step 4
464
+ docs-PR worktree, at the same relative paths (2026-11-08). The worktree comes from origin/<default>, so
465
+ without this the session's local status flips are not in it. COPIES ONLY: this checkout is never changed
466
+ (`release` restores it later, once the docs PR branch holds the moves).
467
+
468
+ All files are copied and checked byte-equal first. If any copy fails, every file this run wrote in the
469
+ worktree is put back as it was (deleted when it was new) and the exit is 1. Prints `CARRIED: <path>`."""
470
+ root, to = Path(root).resolve(), Path(to).resolve()
471
+ if root == to:
472
+ print("CARRY: refused: --to is this checkout")
473
+ return 1
474
+ if not to.is_dir():
475
+ print(f"CARRY: refused: no worktree at {to}")
476
+ return 1
477
+ rels = _artifact_paths(root, paths, "CARRY")
478
+ if rels is None:
479
+ return 1
480
+ for rel in rels:
481
+ if not (root / rel).is_file():
482
+ print(f"CARRY: refused: {rel} does not exist in this checkout; nothing was changed")
483
+ return 1
484
+ written: list[tuple[Path, bytes | None]] = [] # (worktree file, its bytes before this run; None = new)
485
+ try:
486
+ for rel in rels:
487
+ data = (root / rel).read_bytes()
488
+ dst = to / rel
489
+ before = dst.read_bytes() if dst.is_file() else None
490
+ dst.parent.mkdir(parents=True, exist_ok=True)
491
+ written.append((dst, before))
492
+ dst.write_bytes(data)
493
+ if dst.read_bytes() != data:
494
+ raise OSError(f"the copy of {rel} differs from this checkout")
495
+ except OSError as exc:
496
+ print(f"CARRY: failed: {exc}; the worktree is put back, this checkout was not changed")
497
+ for dst, before in reversed(written):
498
+ try:
499
+ if before is None:
500
+ dst.unlink(missing_ok=True)
501
+ else:
502
+ dst.write_bytes(before)
503
+ except OSError as undo:
504
+ print(f"CARRY: could not put back {dst}: {undo}")
505
+ return 1
506
+ for rel in rels:
507
+ print(f"CARRIED: {rel}")
508
+ return 0
509
+
510
+
511
+ def _blob_id(root: Path, rel: str, data: bytes) -> str | None:
512
+ """The blob id git would store for `data` at `rel` (its clean filters, such as CRLF to LF, applied)."""
513
+ try:
514
+ res = subprocess.run(["git", "-C", str(root), "hash-object", "--stdin", f"--path={rel}"], input=data,
515
+ capture_output=True)
516
+ except OSError:
517
+ return None
518
+ return res.stdout.decode("ascii", "replace").strip() if res.returncode == 0 else None
519
+
520
+
521
+ def release(root: Path, branch: str, paths: list[str]) -> int:
522
+ """After the Step 4 docs PR is open, restore each carried artifact in this checkout, but only when the
523
+ pushed branch holds it, moved: `origin/<branch>:.caddis/<kind>/done/<file>` must be the same blob as this
524
+ checkout's file (as git would store it), or as that file with the `status: done` that tidy writes into a
525
+ plan whose Tracker is complete. Then a tracked file is restored (`git checkout -- <path>`) and an untracked
526
+ one deleted. Anything else is left as it is with `kept: <path> (<reason>)`. Exit 0 when all were released."""
527
+ root = Path(root).resolve()
528
+ rels = _artifact_paths(root, paths, "RELEASE")
529
+ if rels is None:
530
+ return 1
531
+ if not re.fullmatch(r"[A-Za-z0-9._/-]+", branch) or branch.startswith("-"):
532
+ print(f"RELEASE: refused: {branch!r} is not a branch name")
533
+ return 1
534
+ fetched = _git(root, "fetch", "--quiet", "origin", f"+refs/heads/{branch}:refs/remotes/origin/{branch}")
535
+ if fetched is None:
536
+ for rel in rels:
537
+ print(f"kept: {rel} (cannot fetch origin/{branch})")
538
+ return 1
539
+ caddis_tidy = _tidy_module()
540
+ kept = 0
541
+ for rel in rels:
542
+ kind, name = rel.split("/")[1], rel.split("/")[2]
543
+ done_rel = f".caddis/{kind}/done/{name}"
544
+ src = root / rel
545
+ reason = None
546
+ remote = _git(root, "rev-parse", "--verify", "--quiet", f"refs/remotes/origin/{branch}:{done_rel}")
547
+ tracked = _tracked(root, rel)
548
+ try:
549
+ data = src.read_bytes() if src.is_file() else None
550
+ except OSError as exc:
551
+ data, reason = None, f"cannot read it: {exc}"
552
+ if reason is None and data is None:
553
+ reason = "it is no longer in this checkout"
554
+ elif reason is None and not remote:
555
+ reason = f"origin/{branch} has no {done_rel}"
556
+ elif reason is None and tracked is None:
557
+ reason = "git cannot say whether it is tracked"
558
+ elif reason is None and tracked and _git(root, "diff", "--cached", "--name-only", "--", rel):
559
+ reason = "it has a staged change"
560
+ if reason is None:
561
+ candidates = {_blob_id(root, rel, data)}
562
+ text = data.decode("utf-8", "replace")
563
+ flipped = caddis_tidy._set_header(text, {"status": "done"}) if kind == "plans" else None
564
+ if flipped is not None:
565
+ candidates.add(_blob_id(root, rel, flipped.encode("utf-8")))
566
+ if remote not in candidates:
567
+ reason = f"it differs from {done_rel} on origin/{branch}"
568
+ if reason is None:
569
+ try:
570
+ if tracked:
571
+ res = subprocess.run(["git", "-C", str(root), "checkout", "--", rel], capture_output=True,
572
+ text=True, encoding="utf-8", errors="replace")
573
+ if res.returncode != 0:
574
+ reason = "git could not restore it: " + (res.stderr or "").strip()[:160]
575
+ else:
576
+ src.unlink()
577
+ except OSError as exc:
578
+ reason = f"could not restore it: {exc}"
579
+ if reason is None:
580
+ print(f"released: {rel}")
581
+ else:
582
+ kept += 1
583
+ print(f"kept: {rel} ({reason})")
584
+ return 1 if kept else 0
585
+
586
+
372
587
  def main(argv: list[str] | None = None) -> int:
373
588
  try:
374
589
  sys.stdout.reconfigure(encoding="utf-8")
@@ -376,6 +591,10 @@ def main(argv: list[str] | None = None) -> int:
376
591
  pass
377
592
  parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
378
593
  sub = parser.add_subparsers(dest="cmd", required=True)
594
+ t = sub.add_parser("tidy-targets", help="print this session's finished top-level artifacts (handoff Step 4)")
595
+ t.add_argument("--own-files", required=True, type=Path,
596
+ help="the Step 0 temp file: this session's `## Files changed this session` lines")
597
+ t.add_argument("--root", type=Path, help="the checkout tidy runs in (default: the git top level of the cwd)")
379
598
  p = sub.add_parser("checkpoint", help="prepare (no --relay-file) or finish (--relay-file) a checkpoint")
380
599
  p.add_argument("--session-id", required=True)
381
600
  p.add_argument("--name", help="workstream name (default: caddis_workstreams.py resolve)")
@@ -385,7 +604,23 @@ def main(argv: list[str] | None = None) -> int:
385
604
  p.add_argument("--expected-hash", help="FINISH: the hash PREPARE printed")
386
605
  p.add_argument("--kt", help="FINISH: done | skipped:<reason>")
387
606
  p.add_argument("--idle", action="store_true", help="FINISH: no agent or background command runs")
607
+ t.add_argument("--movable", action="store_true",
608
+ help="print only what tidy would move now (no held plan, no collision): the set to carry")
609
+ c = sub.add_parser("carry", help="copy own artifacts with their edits into the Step 4 docs-PR worktree")
610
+ c.add_argument("--to", required=True, type=Path, help="the WORKTREE: path that caddis_docs_pr.py start printed")
611
+ c.add_argument("--root", type=Path, help="this checkout (default: the git top level of the cwd)")
612
+ c.add_argument("paths", nargs="+", help="repo-relative paths that tidy-targets --movable printed")
613
+ r = sub.add_parser("release", help="restore carried artifacts here once origin/<branch> holds their moves")
614
+ r.add_argument("--branch", required=True, help="the docs-PR branch that caddis_docs_pr.py finish pushed")
615
+ r.add_argument("--root", type=Path, help="this checkout (default: the git top level of the cwd)")
616
+ r.add_argument("paths", nargs="+", help="the paths given to carry")
388
617
  args = parser.parse_args(argv)
618
+ if args.cmd == "tidy-targets":
619
+ return tidy_targets(args.root or _repo_root(), args.own_files, movable=args.movable)
620
+ if args.cmd == "carry":
621
+ return carry(args.root or _repo_root(), args.to, args.paths)
622
+ if args.cmd == "release":
623
+ return release(args.root or _repo_root(), args.branch, args.paths)
389
624
  try:
390
625
  args.root = _repo_root() # once: every path and every sibling call uses it
391
626
  return finish(args) if args.relay_file else prepare(args)