@caddis/cli 0.4.104 → 0.4.106

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 (22) hide show
  1. package/bundles/antigravity-plugin/plugin.json +1 -1
  2. package/bundles/antigravity-plugin/repo_hygiene.py +87 -5
  3. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_exit.cpython-311.pyc +0 -0
  4. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_file_lock.cpython-311.pyc +0 -0
  5. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_frontmatter.cpython-311.pyc +0 -0
  6. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_redact.cpython-311.pyc +0 -0
  7. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_roadmap.cpython-311.pyc +0 -0
  8. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_rows.cpython-311.pyc +0 -0
  9. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_status.cpython-311.pyc +0 -0
  10. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_tidy.cpython-311.pyc +0 -0
  11. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_todo.cpython-311.pyc +0 -0
  12. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_workstreams.cpython-311.pyc +0 -0
  13. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_worktree_safety.cpython-311.pyc +0 -0
  14. package/bundles/antigravity-plugin/scripts/caddis_finished.py +47 -25
  15. package/bundles/antigravity-plugin/scripts/caddis_guide.json +4 -2
  16. package/bundles/antigravity-plugin/scripts/caddis_repo_tidy.py +150 -21
  17. package/bundles/antigravity-plugin/scripts/caddis_tidy.py +14 -1
  18. package/bundles/antigravity-plugin/scripts/caddis_worktree_safety.py +26 -4
  19. package/bundles/antigravity-plugin/skills/pr-merge/SKILL.md +20 -0
  20. package/bundles/antigravity-plugin/skills/ship-merge/SKILL.md +20 -0
  21. package/bundles/manifest.json +2 -2
  22. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "name": "caddis",
3
- "version": "1.3.188",
3
+ "version": "1.3.190",
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,9 +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 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
- candidate with the deletion-grade test in `caddis_finished.py`.
6
+ REPORT ONLY, with one exception. Nothing here deletes, moves or changes anything. The only files it writes are the gh cache
7
+ `<git-common-dir>/caddis-hygiene-prs.json`, the Orca cache `~/.caddis/orca-worktrees.json` and the Orca sweep stamp.
8
+ Removal is `caddis_tidy.py --hygiene --apply`, which re-proves every candidate with the deletion-grade test in
9
+ `caddis_finished.py`. The exception: when the current repo has an Orca-managed linked worktree, this starts
10
+ `caddis_tidy.py --hygiene --apply --orca-only` in the background and does not wait (the Orca sweep). That run
11
+ removes only Orca worktrees that are merged, clean and have no open Orca terminal. At most once per
12
+ ORCA_SWEEP_EVERY_S per repo; `CADDIS_ORCA_SWEEP=0` turns it off.
9
13
 
10
14
  Every decision lives in `caddis_finished.py` (stdlib only). This module holds the I/O and the formatting. Every git
11
15
  call goes through the `git(cwd, *args) -> (code, stdout)` seam (`repo_freshness._git` in the hook). gh goes
@@ -61,6 +65,8 @@ NO_TIME_LEFT = "no time left in the session-start budget"
61
65
 
62
66
  # No child opens a console window on Windows; git never takes an optional lock or asks for a credential.
63
67
  _NO_WINDOW = 0x08000000 if os.name == "nt" else 0
68
+ _NEW_GROUP = 0x00000200 if os.name == "nt" else 0 # CREATE_NEW_PROCESS_GROUP: the sweep outlives the hook
69
+ ORCA_SWEEP_EVERY_S = 900
64
70
  _ENV_OVERRIDES = {"GIT_OPTIONAL_LOCKS": "0", "GIT_TERMINAL_PROMPT": "0", "GCM_INTERACTIVE": "never"}
65
71
 
66
72
 
@@ -568,10 +574,81 @@ def start_jobs(top: Path, git: Callable, remaining: Callable[[], float], *, want
568
574
  return Jobs(main, roots, any_linked, gh, orca)
569
575
 
570
576
 
577
+ def _start_sweep(argv: list[str], log: Path) -> None:
578
+ """The default sweep seam: start `argv` detached, output appended to `log`, and do not wait."""
579
+ with open(log, "ab") as fo:
580
+ subprocess.Popen(argv, stdout=fo, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL,
581
+ env={**os.environ, **_ENV_OVERRIDES}, creationflags=_NO_WINDOW | _NEW_GROUP,
582
+ start_new_session=os.name != "nt", close_fds=True)
583
+
584
+
585
+ def _claim_stamp(stamp: Path, now: float) -> bool:
586
+ """True when this process won the sweep for this window. Two sessions that start at once: exactly one wins.
587
+
588
+ The stamp is created with O_EXCL. An existing stamp inside the window means no. An expired one is moved aside
589
+ with one rename (only one racer's rename succeeds), then created again with O_EXCL. An empty stamp (a racer
590
+ has not written the time yet, or was killed before it did) dates from its modified time, so it expires too.
591
+ """
592
+ for _ in range(2):
593
+ try:
594
+ fd = os.open(stamp, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
595
+ except FileExistsError:
596
+ try:
597
+ text = stamp.read_text(encoding="utf-8").strip()
598
+ last = float(text) if text else stamp.stat().st_mtime
599
+ except ValueError:
600
+ last = 0.0 # unreadable: treat as expired
601
+ except OSError:
602
+ return False
603
+ if 0 <= now - last < ORCA_SWEEP_EVERY_S:
604
+ return False
605
+ try:
606
+ stamp.rename(stamp.with_name(f"{stamp.name}.{os.getpid()}.old"))
607
+ except OSError:
608
+ return False # another racer moved it first
609
+ stamp.with_name(f"{stamp.name}.{os.getpid()}.old").unlink(missing_ok=True)
610
+ continue
611
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
612
+ fh.write(str(int(now)))
613
+ return True
614
+ return False
615
+
616
+
617
+ def orca_sweep(main: Path, orca_linked: int, env: Mapping[str, str], home: Path, now: float,
618
+ start: Callable = _start_sweep) -> str | None:
619
+ """Start the background Orca sweep for `main` and return the report line, or None when it does not start.
620
+
621
+ It starts only when the repo has an Orca-managed linked worktree, the switch is not off, `caddis_tidy.py` is
622
+ found beside `caddis_finished.py`, and the repo's stamp is older than ORCA_SWEEP_EVERY_S. Any error: no sweep.
623
+ """
624
+ if orca_linked <= 0 or str(env.get("CADDIS_ORCA_SWEEP", "1")).strip() == "0" or cf is None:
625
+ return None
626
+ tidy = Path(cf.__file__).resolve().parent / "caddis_tidy.py"
627
+ if not tidy.is_file():
628
+ return None
629
+ stamps = home / ".caddis" / "orca-sweep"
630
+ stamp = stamps / (_key(main).replace(":", "").replace("\\", "-").replace("/", "-").strip("-") + ".stamp")
631
+ try:
632
+ stamps.mkdir(parents=True, exist_ok=True)
633
+ if not _claim_stamp(stamp, now):
634
+ return None
635
+ log = home / ".caddis" / "logs" / "orca-sweep.log"
636
+ log.parent.mkdir(parents=True, exist_ok=True)
637
+ try:
638
+ start([sys.executable, str(tidy), "--hygiene", "--apply", "--orca-only", "--repo-root", str(main)], log)
639
+ except OSError:
640
+ stamp.unlink(missing_ok=True) # a failed start must not block the sweep for a whole window
641
+ return None
642
+ except OSError:
643
+ return None
644
+ return (f"[HARNESS] Orca sweep started in the background for {orca_linked} Orca worktree(s): removes the merged, "
645
+ f"clean ones with no open terminal; log ~/.caddis/logs/orca-sweep.log")
646
+
647
+
571
648
  def report_lines(top: Path | None, fresh: dict, git: Callable, remaining: Callable[[], float],
572
649
  env: Mapping[str, str] | None = None, home: Path | None = None,
573
- jobs: Jobs | None = None) -> list[str]:
574
- """The summary line, then the skipped and detail lines. REPORT ONLY: nothing here changes anything.
650
+ jobs: Jobs | None = None, sweep: Callable | None = None) -> list[str]:
651
+ """The summary line, then the skipped and detail lines. Report only, except the Orca sweep (`orca_sweep`).
575
652
 
576
653
  `fresh` holds `branch`, `ref`, `behind`, `ahead`, `dirty`, `gate_missing` from repo_freshness. The current repo
577
654
  (resolved to its MAIN checkout, so a session in a linked worktree counts it once) gets the full report; every
@@ -627,4 +704,9 @@ def report_lines(top: Path | None, fresh: dict, git: Callable, remaining: Callab
627
704
  lines.append(_stale_line(here, other, home, main))
628
705
  if triage:
629
706
  lines.append(_triage_line(triage, main, ref, tips, git, time.time()))
707
+ orca_linked = sum(1 for r in records[1:] if orca_id(orca_map, r["path"])) if orca_map else 0
708
+ swept = orca_sweep(main, orca_linked, os.environ if env is None else env, home, time.time(),
709
+ sweep or _start_sweep)
710
+ if swept:
711
+ lines.append(swept)
630
712
  return lines
@@ -19,7 +19,7 @@ aliases), so "finished" has one definition for `/handoff` own-cleanup and `caddi
19
19
 
20
20
  prove_worktree_finished(entry, path, cwd, pr_lookup) -> ("REMOVE", reason, facts) | ("KEPT"/"GONE", reason, {})
21
21
  prove_branch_finished(repo, branch, pr_lookup) -> ("REMOVE", reason, facts) | ("KEPT"/"TRIAGE", reason, {})
22
- remove_finished(path | None, facts) -> ("REMOVED" | "FAILED", notes); path None = branches only
22
+ remove_finished(path | None, facts, remover=None) -> ("REMOVED" | "FAILED", notes); path None = branches only
23
23
 
24
24
  `pr_lookup(main_repo, branch, pr) -> list[{number, state, headRefOid, headRefName}]` (newest first) is the gh seam;
25
25
  it raises PrLookupError. `gh_pr_lookup` calls plain `gh` with the inherited environment (never `gh auth switch`).
@@ -488,26 +488,52 @@ def prove_branch_finished(repo: Path, branch: str, pr_lookup: Callable) -> tuple
488
488
  return "REMOVE", f"PR #{number} merged, tree equals origin/{default}", facts
489
489
 
490
490
 
491
- def remove_finished(path: Path | None, facts: dict) -> tuple[str, str]:
491
+ def remove_finished(path: Path | None, facts: dict, remover: Callable | None = None,
492
+ branches_first: bool = False) -> tuple[str, str]:
492
493
  """Remove what a proof returned REMOVE for: ("REMOVED", notes) or ("FAILED", problem).
493
494
 
494
495
  `path` None skips the worktree step and removes only the branches; then any kept branch is "FAILED", so a
495
496
  caller that reads only the outcome never reports a kept branch as removed. Worktree: `safe_remove_worktree(...,
496
497
  force=False)` (links first, never --force). Local branch: only while its tip is HEAD or the PR head and no
497
498
  worktree has it checked out. Remote branch: only while its tip is the PR head or HEAD, as one compare-and-delete
498
- push.
499
+ push. `remover(path) -> None | problem` replaces `git worktree remove` (an Orca worktree goes through Orca).
500
+ `branches_first`: detach the worktree's HEAD, delete the branches, then remove the worktree. For a session that
501
+ removes its own Orca worktree: the removal stops that session, so nothing may be left to do after it.
499
502
  """
500
503
  import caddis_worktree_safety as safety
501
504
 
502
505
  repo, branch, head, pr_head = facts["repo"], facts["branch"], facts["head"], facts["pr_head"]
503
- local_tip = branch_tip(repo, branch) if branch else None
504
506
  landed = {pr_head, head.lower()} - {""} # only tips this proof showed landed
507
+ if path is not None and branches_first:
508
+ if branch: # update-ref detaches without running a post-checkout hook (git switch would run it)
509
+ detach = _git(path, "update-ref", "--no-deref", "HEAD", head)
510
+ if detach.returncode != 0:
511
+ return "FAILED", f"git update-ref --no-deref HEAD failed: {_err(detach)}"
512
+ notes = _delete_branches(repo, branch, landed)
513
+ problem = safety.safe_remove_worktree(repo, path, force=False, env=_env(), remover=remover)
514
+ if problem:
515
+ return "FAILED", "; ".join([problem, *notes, "HEAD was detached and the branches went first"])
516
+ return "REMOVED", "; ".join(notes)
517
+ local_tip = branch_tip(repo, branch) if branch else None
505
518
  if path is not None:
506
- problem = safety.safe_remove_worktree(repo, path, force=False, env=_env())
519
+ problem = safety.safe_remove_worktree(repo, path, force=False, env=_env(), remover=remover)
507
520
  if problem:
508
521
  return "FAILED", problem
522
+ notes = _delete_branches(repo, branch, landed, local_tip)
523
+ if path is None and any(" branch kept:" in n for n in notes):
524
+ return "FAILED", "; ".join(notes)
525
+ return "REMOVED", "; ".join(notes)
526
+
527
+
528
+ def _delete_branches(repo: Path, branch: str | None, landed: set[str], local_tip: str | None = None) -> list[str]:
529
+ """Delete the local and the remote `branch`, each only while its tip is one the proof showed landed."""
530
+ import caddis_worktree_safety as safety
531
+
509
532
  notes: list[str] = []
510
- if branch and local_tip:
533
+ if not branch:
534
+ return notes
535
+ local_tip = local_tip or branch_tip(repo, branch)
536
+ if local_tip:
511
537
  listing = _git(repo, "worktree", "list", "--porcelain")
512
538
  if listing.returncode != 0 or f"branch refs/heads/{branch}" in listing.stdout.splitlines():
513
539
  notes.append("local branch kept: another worktree has it checked out")
@@ -516,22 +542,18 @@ def remove_finished(path: Path | None, facts: dict) -> tuple[str, str]:
516
542
  else:
517
543
  gone = _git(repo, "branch", "-D", "--", branch)
518
544
  notes.append("local branch deleted" if gone.returncode == 0 else f"local branch kept: {_err(gone)}")
519
- if branch:
520
- ls = _git(repo, "ls-remote", "--heads", "origin", f"refs/heads/{branch}", timeout=NET_TIMEOUT)
521
- tips = [ln.split()[0] for ln in ls.stdout.splitlines() if ln.strip()] if ls.returncode == 0 else []
522
- if ls.returncode != 0:
523
- notes.append(f"remote branch kept: ls-remote failed: {_err(ls)}")
524
- elif tips:
525
- tip = tips[0].lower()
526
- if tip in landed:
527
- try:
528
- push = _git(repo, *safety.remote_delete_args(branch, tip), timeout=NET_TIMEOUT)
529
- notes.append("remote branch deleted" if push.returncode == 0
530
- else f"remote branch kept: {_err(push)}")
531
- except ValueError as exc:
532
- notes.append(f"remote branch kept: {exc}")
533
- else:
534
- notes.append("remote branch kept: its tip moved past the PR head")
535
- if path is None and any(" branch kept:" in n for n in notes):
536
- return "FAILED", "; ".join(notes)
537
- return "REMOVED", "; ".join(notes)
545
+ ls = _git(repo, "ls-remote", "--heads", "origin", f"refs/heads/{branch}", timeout=NET_TIMEOUT)
546
+ tips = [ln.split()[0] for ln in ls.stdout.splitlines() if ln.strip()] if ls.returncode == 0 else []
547
+ if ls.returncode != 0:
548
+ notes.append(f"remote branch kept: ls-remote failed: {_err(ls)}")
549
+ elif tips:
550
+ tip = tips[0].lower()
551
+ if tip in landed:
552
+ try:
553
+ push = _git(repo, *safety.remote_delete_args(branch, tip), timeout=NET_TIMEOUT)
554
+ notes.append("remote branch deleted" if push.returncode == 0 else f"remote branch kept: {_err(push)}")
555
+ except ValueError as exc:
556
+ notes.append(f"remote branch kept: {exc}")
557
+ else:
558
+ notes.append("remote branch kept: its tip moved past the PR head")
559
+ return notes
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schema": 1,
3
- "version": "1.3.187",
4
- "generated": "2026-11-11 02:32 UTC",
3
+ "version": "1.3.189",
4
+ "generated": "2026-11-11 23:11 UTC",
5
5
  "commands": [
6
6
  {
7
7
  "name": "add-rules",
@@ -892,6 +892,7 @@
892
892
  "caddis_gate.py",
893
893
  "caddis_lanes.py",
894
894
  "caddis_merge_chain.py",
895
+ "caddis_tidy.py",
895
896
  "caddis_worktree_root.py"
896
897
  ],
897
898
  "noArgs": false,
@@ -1119,6 +1120,7 @@
1119
1120
  "caddis_checkout_guard.py",
1120
1121
  "caddis_lanes.py",
1121
1122
  "caddis_merge_chain.py",
1123
+ "caddis_tidy.py",
1122
1124
  "caddis_worktree_root.py"
1123
1125
  ],
1124
1126
  "noArgs": false,
@@ -8,14 +8,23 @@ Dry run is the default; only `apply=True` acts. Every row gets one action and a
8
8
  GONE the folder vanished before removal FAILED removal was tried and did not complete
9
9
 
10
10
  Order per linked worktree, first match wins: orphan registration (folder gone) -> a junction or symlink -> the
11
- process cwd is inside it -> Orca-managed -> DIRTY (incl. untracked) -> IN USE -> idle-session -> locked -> the
12
- deletion-grade proof `caddis_finished.prove_worktree_finished` (merged PR, no commit after its head, every changed
11
+ process cwd (or `session_cwd`) is inside it -> Orca-managed with an open Orca terminal, or terminals unknown ->
12
+ DIRTY (incl. untracked) -> IN USE -> idle-session -> locked -> the deletion-grade proof `caddis_finished.prove_worktree_finished` (merged PR, no commit after its head, every changed
13
13
  file equals origin/<default>). A branch with no worktree gets `caddis_finished.prove_branch_finished`.
14
14
 
15
15
  The live-session rule is the PowerShell report's: a transcript written within 60 min PROVES a session is live;
16
16
  an older one proves nothing (idle-session, KEPT). A session id with no transcript is "removable" to the classifier,
17
17
  but tidy still needs the merged proof. Removal goes through `caddis_finished.remove_finished` (links first,
18
18
  `force=False`, compare-and-delete push), so the rules live in one place.
19
+
20
+ An Orca-managed worktree passes the same guards and the same proof. Orca's `worktree rm` also stops every session
21
+ in the worktree, so one more guard keeps it while any Orca terminal is open in it (`own_terminal`, the caller's own
22
+ handle, is the one exception: a session that removes its own worktree). It is removed with `orca worktree rm`
23
+ (never --force, never --run-hooks) after its links go; the branches go through the same tip checks. When the caller
24
+ removes its own worktree, the branches go first, because the removal stops the caller.
25
+
26
+ `only` limits the run to one linked worktree (no branch rows); `orca_only` to Orca-managed worktrees (the
27
+ session-start sweep).
19
28
  """
20
29
 
21
30
  from __future__ import annotations
@@ -33,6 +42,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
33
42
  import caddis_finished as cf
34
43
 
35
44
  ORCA_TIMEOUT_S = 10.0
45
+ ORCA_RM_TIMEOUT_S = 120.0
36
46
  _ACTIONS = ("REMOVE", "REMOVED", "KEPT", "TRIAGE", "GONE", "FAILED")
37
47
 
38
48
 
@@ -47,9 +57,22 @@ def orca_lookup(run: Callable = subprocess.run, which: Callable = shutil.which,
47
57
  None (not on PATH, non-zero exit, timeout, bad JSON, `ok` false, `truncated` true) means NO worktree counts as
48
58
  Orca-managed; the caller prints the reason every run (plan decision 7).
49
59
  """
60
+ result, why = _orca_json(["orca", "worktree", "list", "--limit", "10000", "--json"], "worktrees", run, which,
61
+ timeout_s)
62
+ if result is None:
63
+ return None, why
64
+ ids: dict[str, str] = {}
65
+ for wt in result["worktrees"]:
66
+ if isinstance(wt, dict) and wt.get("path") and wt.get("id"):
67
+ ids[_key(str(wt["path"]))] = str(wt["id"])
68
+ return ids, ""
69
+
70
+
71
+ def _orca_json(cmd: list[str], what: str, run: Callable, which: Callable,
72
+ timeout_s: float) -> tuple[dict | None, str]:
73
+ """(result dict, "") from an `orca ... --json` list command whose result holds the list `what`, or (None, why)."""
50
74
  if not which("orca"):
51
75
  return None, "orca not on PATH"
52
- cmd = ["orca", "worktree", "list", "--limit", "10000", "--json"]
53
76
  try:
54
77
  proc = run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace",
55
78
  stdin=subprocess.DEVNULL, timeout=timeout_s, check=False)
@@ -67,15 +90,57 @@ def orca_lookup(run: Callable = subprocess.run, which: Callable = shutil.which,
67
90
  if not isinstance(data, dict) or not data.get("ok"):
68
91
  return None, "orca answered not ok"
69
92
  result = data.get("result")
70
- if not isinstance(result, dict) or not isinstance(result.get("worktrees"), list):
93
+ if not isinstance(result, dict) or not isinstance(result.get(what), list):
71
94
  return None, "orca printed an unexpected shape"
72
95
  if result.get("truncated"):
73
- return None, "orca list is truncated"
74
- ids: dict[str, str] = {}
75
- for wt in result["worktrees"]:
76
- if isinstance(wt, dict) and wt.get("path") and wt.get("id"):
77
- ids[_key(str(wt["path"]))] = str(wt["id"])
78
- return ids, ""
96
+ return None, "orca terminal list is truncated" if what == "terminals" else "orca list is truncated"
97
+ return result, ""
98
+
99
+
100
+ def orca_terminals(run: Callable = subprocess.run, which: Callable = shutil.which,
101
+ timeout_s: float = ORCA_TIMEOUT_S) -> tuple[dict[str, set[str]] | None, str]:
102
+ """({normcase(realpath(worktree path)): {terminal handle}}, "") for every live Orca terminal, or (None, why).
103
+
104
+ None means "unknown": the caller keeps every Orca-managed worktree, because `orca worktree rm` stops them.
105
+ """
106
+ result, why = _orca_json(["orca", "terminal", "list", "--limit", "10000", "--json"], "terminals", run, which,
107
+ timeout_s)
108
+ if result is None:
109
+ return None, why
110
+ out: dict[str, set[str]] = {}
111
+ for t in result["terminals"]:
112
+ if isinstance(t, dict) and t.get("worktreePath"):
113
+ out.setdefault(_key(str(t["worktreePath"])), set()).add(str(t.get("handle") or ""))
114
+ return out, ""
115
+
116
+
117
+ def orca_remove(orca_id: str, repo: Path, run: Callable = subprocess.run,
118
+ timeout_s: float = ORCA_RM_TIMEOUT_S) -> str | None:
119
+ """`orca worktree rm --worktree id:<id>`, run from the main checkout: None when Orca says ok, else the problem.
120
+
121
+ No --force (a dirty worktree must stay), no --run-hooks (a repo archive hook is not ours to run), no
122
+ --delete-branch (the caller deletes the branches with its own tip checks, which also prove a squash merge).
123
+ """
124
+ cmd = ["orca", "worktree", "rm", "--worktree", f"id:{orca_id}", "--json"]
125
+ try:
126
+ proc = run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", cwd=str(repo),
127
+ stdin=subprocess.DEVNULL, timeout=timeout_s, check=False)
128
+ except subprocess.TimeoutExpired:
129
+ return f"orca worktree rm took longer than {timeout_s:g} s"
130
+ except OSError as exc:
131
+ return f"orca could not start: {exc}"
132
+ if proc.returncode != 0:
133
+ text = (proc.stderr or proc.stdout or "").strip()
134
+ return f"orca worktree rm failed: {text.splitlines()[-1] if text else f'exit {proc.returncode}'}"
135
+ try:
136
+ data = json.loads(proc.stdout or "null")
137
+ except ValueError:
138
+ return "orca worktree rm printed bad JSON"
139
+ if not isinstance(data, dict) or not data.get("ok"):
140
+ err = data.get("error") if isinstance(data, dict) else None
141
+ code = err.get("code") if isinstance(err, dict) else err
142
+ return f"orca worktree rm answered not ok: {code or 'no error code'}"
143
+ return None
79
144
 
80
145
 
81
146
  def _row(kind: str, name: str, path: str | None, action: str, reason: str) -> dict:
@@ -109,7 +174,8 @@ def _prune(repo: Path, path: str) -> tuple[str, str]:
109
174
 
110
175
 
111
176
  def _worktree_row(repo: Path, rec: dict, *, default: str, cwd: str, orca: dict[str, str] | None,
112
- pr_lookup: Callable, projects_root: Path | None, now: float | None) -> tuple[dict, dict]:
177
+ pr_lookup: Callable, projects_root: Path | None, now: float | None, session_cwd: str | None = None,
178
+ terminals: Callable = lambda: ({}, ""), own_terminal: str | None = None) -> tuple[dict, dict]:
113
179
  """(row, facts) for one linked worktree; facts is non-empty only for REMOVE from the merged proof."""
114
180
  path, branch = rec["path"], rec["branch"]
115
181
  name = branch
@@ -130,8 +196,22 @@ def _worktree_row(repo: Path, rec: dict, *, default: str, cwd: str, orca: dict[s
130
196
  return row("KEPT", f"cannot inspect it: {exc}")
131
197
  if cf._inside(cwd, path):
132
198
  return row("KEPT", "this session is working in it")
133
- if orca is not None and _key(path) in orca:
134
- return row("KEPT", f"Orca-managed: remove it in Orca (`orca worktree rm --worktree id:{orca[_key(path)]}`)")
199
+ orca_id = orca.get(_key(path)) if orca is not None else None
200
+ own = False
201
+ if orca_id:
202
+ open_terms, why = terminals()
203
+ if open_terms is None:
204
+ return row("KEPT", f"Orca-managed: cannot list Orca terminals: {why}; `orca worktree rm` would stop them")
205
+ here = open_terms.get(_key(path), set())
206
+ others = here - ({own_terminal} if own_terminal else set())
207
+ if others:
208
+ return row("KEPT", f"Orca-managed: an Orca terminal is open in it ({len(others)}); removed after it "
209
+ "closes (next session start, or caddis_tidy.py --hygiene --apply)")
210
+ own = bool(own_terminal) and own_terminal in here
211
+ # The calling session's folder is inside: keep it, unless that session is the Orca terminal removing its own
212
+ # worktree (Orca stops the session first, so nothing holds the folder when it goes).
213
+ if session_cwd and cf._inside(session_cwd, path) and not own:
214
+ return row("KEPT", "this session is working in it")
135
215
  status = cf._git(Path(path), "status", "--porcelain", "--untracked-files=normal")
136
216
  if status.returncode != 0:
137
217
  return row("KEPT", f"git status failed: {cf._err(status)}")
@@ -154,6 +234,9 @@ def _worktree_row(repo: Path, rec: dict, *, default: str, cwd: str, orca: dict[s
154
234
  why = _triage_reason(reason)
155
235
  if why and entry["branch"]:
156
236
  action, reason, _ = cf._triage(repo, branch, default, why)
237
+ if orca_id and action == "REMOVE":
238
+ reason = f"Orca-managed; {reason}"
239
+ facts = dict(facts, orca_id=orca_id, own=own)
157
240
  return _row("worktree", name, path, action, reason), facts
158
241
 
159
242
 
@@ -166,10 +249,23 @@ def _local_branches(repo: Path) -> list[str] | None:
166
249
 
167
250
  def tidy_repo(repo_root: Path, *, apply: bool = False, cwd: str | None = None, pr_lookup: Callable | None = None,
168
251
  orca_lookup: Callable | None = None, projects_root: Path | None = None,
169
- now: float | None = None) -> tuple[list[dict], list[str]]:
170
- """(rows, notes) for every worktree and every local non-default branch with no worktree. `apply` acts on REMOVE."""
252
+ now: float | None = None, orca_terminals: Callable | None = None, orca_remove: Callable | None = None,
253
+ only: Path | str | None = None, session_cwd: str | None = None, own_terminal: str | None = None,
254
+ orca_only: bool = False) -> tuple[list[dict], list[str]]:
255
+ """(rows, notes) for every worktree and every local non-default branch with no worktree. `apply` acts on REMOVE.
256
+
257
+ `only`: that one linked worktree, no branch rows. `orca_only`: Orca-managed worktrees only, no branch rows.
258
+ """
171
259
  pr_lookup = pr_lookup or cf.gh_pr_lookup
172
260
  ask_orca = orca_lookup or globals()["orca_lookup"]
261
+ ask_terminals = orca_terminals or globals()["orca_terminals"]
262
+ rm_orca = orca_remove or globals()["orca_remove"]
263
+ term_cache: list = []
264
+
265
+ def terminals():
266
+ if not term_cache:
267
+ term_cache.append(ask_terminals())
268
+ return term_cache[0]
173
269
  cwd = cwd or os.getcwd()
174
270
  now = time.time() if now is None else now
175
271
  notes: list[str] = []
@@ -182,23 +278,50 @@ def tidy_repo(repo_root: Path, *, apply: bool = False, cwd: str | None = None, p
182
278
  default = cf.default_branch(repo)
183
279
  rows: list[dict] = []
184
280
  main, linked = records[0], records[1:]
185
- rows.append(_row("worktree", main["branch"], main["path"], "KEPT", "it is the main checkout"))
281
+ if only is not None:
282
+ linked = [r for r in linked if _key(r["path"]) == _key(only)]
283
+ if not linked:
284
+ return [], [f"[TIDY] skipped: {only} is not a linked worktree of {repo}"]
285
+ elif not orca_only:
286
+ rows.append(_row("worktree", main["branch"], main["path"], "KEPT", "it is the main checkout"))
186
287
  orca: dict[str, str] | None = {}
187
288
  if linked:
188
289
  orca, why = ask_orca()
189
290
  if orca is None:
190
291
  notes.append(f"[TIDY] skipped: Orca check - {why}; no worktree is treated as Orca-managed")
292
+ if orca_only:
293
+ linked = [r for r in linked if orca and _key(r["path"]) in orca]
191
294
  for rec in linked:
192
295
  row, facts = _worktree_row(repo, rec, default=default, cwd=cwd, orca=orca, pr_lookup=pr_lookup,
193
- projects_root=projects_root, now=now)
296
+ projects_root=projects_root, now=now, session_cwd=session_cwd,
297
+ terminals=terminals, own_terminal=own_terminal)
194
298
  if apply and row["action"] == "REMOVE":
195
299
  if facts.get("orphan"): # no folder and no PR proof: only the registration goes, never a branch
196
300
  row["action"], row["reason"] = _prune(repo, rec["path"])
197
301
  elif not os.path.lexists(rec["path"]):
198
302
  row["action"], row["reason"] = "GONE", "the folder vanished before removal"
303
+ elif facts.get("orca_id"):
304
+ orca_id = facts["orca_id"]
305
+ # The list read for the guard can be minutes old by now: read it again, uncached, right before
306
+ # the removal, so a terminal opened during this run is never stopped.
307
+ fresh, why = ask_terminals()
308
+ late = None if fresh is None else fresh.get(_key(rec["path"]), set()) - (
309
+ {own_terminal} if own_terminal else set())
310
+ if fresh is None:
311
+ row["action"], row["reason"] = "KEPT", f"Orca-managed: cannot list Orca terminals: {why}"
312
+ elif late:
313
+ row["action"], row["reason"] = "KEPT", "Orca-managed: an Orca terminal opened in it during this run"
314
+ else:
315
+ row["action"], row["reason"] = cf.remove_finished(
316
+ Path(rec["path"]), facts, remover=lambda _p, i=orca_id: rm_orca(i, repo),
317
+ branches_first=facts.get("own", False))
318
+ if row["action"] == "FAILED" and facts.get("own"):
319
+ row["reason"] += f"; remove it with `orca worktree rm --worktree id:{orca_id}`"
199
320
  else:
200
321
  row["action"], row["reason"] = cf.remove_finished(Path(rec["path"]), facts)
201
322
  rows.append(row)
323
+ if only is not None or orca_only:
324
+ return rows, notes
202
325
  branches = _local_branches(repo)
203
326
  if branches is None:
204
327
  notes.append("[TIDY] skipped: branches - git for-each-ref failed; no branch is listed or removed")
@@ -226,15 +349,21 @@ def print_rows(rows: list[dict], notes: list[str], apply: bool) -> None:
226
349
  print(f"[TIDY] {done}, kept {n['KEPT']}, triage {n['TRIAGE']}, gone {n['GONE']}, failed {n['FAILED']}")
227
350
 
228
351
 
229
- def run_cli(repo_root: Path, *, apply: bool, as_json: bool) -> int:
230
- """`caddis_tidy.py --hygiene`: 0 when nothing failed, 1 when a removal FAILED, 2 when the repo cannot be read."""
231
- rows, notes = tidy_repo(Path(repo_root), apply=apply)
352
+ def run_cli(repo_root: Path, *, apply: bool, as_json: bool, only: str | None = None,
353
+ session_cwd: str | None = None, own_terminal: str | None = None, orca_only: bool = False) -> int:
354
+ """`caddis_tidy.py --hygiene`: 0 when nothing failed, 1 when a removal FAILED, 2 when the repo cannot be read.
355
+
356
+ With `orca_only`, a repo with no Orca worktree is 0, not 2.
357
+ """
358
+ rows, notes = tidy_repo(Path(repo_root), apply=apply, only=only, session_cwd=session_cwd,
359
+ own_terminal=own_terminal or None, orca_only=orca_only)
232
360
  if as_json:
233
361
  print(json.dumps({"apply": apply, "rows": [dict(r, path=None if r["path"] is None else str(r["path"]))
234
362
  for r in rows], "notes": notes}, indent=2))
235
363
  else:
236
364
  print(f"[TIDY] hygiene {'APPLY' if apply else 'DRY-RUN'} {repo_root}")
237
365
  print_rows(rows, notes, apply)
238
- if not rows:
366
+ unreadable = any(n.startswith(("[TIDY] skipped: git", "[TIDY] skipped: " + str(repo_root))) for n in notes)
367
+ if not rows and (unreadable or not orca_only):
239
368
  return 2
240
369
  return 1 if any(r["action"] == "FAILED" for r in rows) else 0
@@ -1360,6 +1360,15 @@ def main(argv: list[str] | None = None) -> int:
1360
1360
  help="list every worktree and local branch of the repo with an action and a reason "
1361
1361
  "(with --apply: remove only the ones proved finished)")
1362
1362
  ap.add_argument("--json", action="store_true", help="with --hygiene: print the rows as JSON")
1363
+ ap.add_argument("--worktree", default=None, metavar="PATH",
1364
+ help="with --hygiene: only this linked worktree (no branch rows)")
1365
+ ap.add_argument("--session-cwd", default=None, metavar="PATH",
1366
+ help="with --hygiene: keep a worktree that holds this folder (the calling session's folder)")
1367
+ ap.add_argument("--own-terminal", default=None, metavar="HANDLE",
1368
+ help="with --hygiene: this Orca terminal does not block removal (a session removing its own "
1369
+ "worktree; pass $ORCA_TERMINAL_HANDLE). The branches then go first.")
1370
+ ap.add_argument("--orca-only", action="store_true",
1371
+ help="with --hygiene: only Orca-managed worktrees (no branch rows)")
1363
1372
  args = ap.parse_args(argv)
1364
1373
  # A status or path the console cannot encode prints as `?`, never a crash (a cp1252 pipe).
1365
1374
  for stream in (sys.stdout, sys.stderr):
@@ -1373,12 +1382,16 @@ def main(argv: list[str] | None = None) -> int:
1373
1382
  ap.error("--json only works together with --hygiene")
1374
1383
  if args.all and (args.hygiene or args.prune):
1375
1384
  ap.error("--all is for the mover (--apply), not --hygiene or --prune")
1385
+ if (args.worktree or args.session_cwd or args.own_terminal or args.orca_only) and not args.hygiene:
1386
+ ap.error("--worktree, --session-cwd, --own-terminal and --orca-only only work together with --hygiene")
1376
1387
  if args.hygiene:
1377
1388
  if args.check or args.commit_range or args.only or args.prune or args.temp or args.verbose:
1378
1389
  ap.error("--hygiene runs alone: not with --check, --commit-range, --only, --prune, --temp or --verbose")
1379
1390
  import caddis_repo_tidy # ships beside this file
1380
1391
 
1381
- return caddis_repo_tidy.run_cli(repo_root, apply=args.apply, as_json=args.json)
1392
+ return caddis_repo_tidy.run_cli(repo_root, apply=args.apply, as_json=args.json, only=args.worktree,
1393
+ session_cwd=args.session_cwd, own_terminal=args.own_terminal,
1394
+ orca_only=args.orca_only)
1382
1395
  if args.temp and not args.prune:
1383
1396
  ap.error("--temp only works together with --prune")
1384
1397
  if args.verbose and not args.temp:
@@ -8,7 +8,8 @@ deleted: the caller gets the problem back.
8
8
  remove_links(root) -> the links removed (raises LinkRemovalError when one cannot go)
9
9
  remove_tree(path) -> None, or the problem (links first, then rmtree)
10
10
  safe_remove_worktree(repo, wt) -> None, or the problem (refuses the main checkout, unregistered paths, and
11
- a locked or dirty worktree that git would keep, before any link goes)
11
+ a locked or dirty worktree that git would keep, before any link goes).
12
+ `remover` replaces the final `git worktree remove` (Orca uses it).
12
13
  """
13
14
 
14
15
  from __future__ import annotations
@@ -17,7 +18,7 @@ import os
17
18
  import shutil
18
19
  import stat
19
20
  import subprocess
20
- from collections.abc import Mapping, Sequence
21
+ from collections.abc import Callable, Mapping, Sequence
21
22
  from pathlib import Path
22
23
 
23
24
  _REPARSE = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)
@@ -142,7 +143,8 @@ def remote_delete_args(branch: str, expected_tip: str, remote: str = "origin") -
142
143
 
143
144
 
144
145
  def safe_remove_worktree(repo: Path, worktree: Path, *, force: bool = True, force_locked: bool = False,
145
- git_flags: Sequence[str] = (), env: Mapping[str, str] | None = None) -> str | None:
146
+ git_flags: Sequence[str] = (), env: Mapping[str, str] | None = None,
147
+ remover: Callable[[Path], str | None] | None = None) -> str | None:
146
148
  """Remove the linked worktree `worktree` of `repo`: its links first, then `git worktree remove`.
147
149
 
148
150
  None when git removed it, else the problem. Before any link is touched it refuses a path that is a link, the
@@ -150,7 +152,9 @@ def safe_remove_worktree(repo: Path, worktree: Path, *, force: bool = True, forc
150
152
  `force_locked`, and a dirty one unless `force`: git would keep those, and a kept worktree must keep its links.
151
153
  `force` passes `--force` (a dirty worktree goes); `force_locked` passes it twice (a locked one goes too). A
152
154
  relative `worktree` is taken from `repo`, not from the process cwd. `git_flags` go before `-C` (for example
153
- `-c core.hooksPath=...`); `env` is the git environment."""
155
+ `-c core.hooksPath=...`); `env` is the git environment. `remover(worktree) -> None | problem` replaces the final
156
+ `git worktree remove` (for example `orca worktree rm`); every check and the link removal still run first, and
157
+ the worktree must then be gone from disk and from `git worktree list`."""
154
158
  worktree = Path(worktree)
155
159
  if not worktree.is_absolute():
156
160
  worktree = Path(repo) / worktree
@@ -184,6 +188,8 @@ def safe_remove_worktree(repo: Path, worktree: Path, *, force: bool = True, forc
184
188
  removed = remove_links(worktree)
185
189
  except OSError as exc:
186
190
  return f"not removed: {worktree}: a link could not be removed: {exc}; no file was deleted"
191
+ if remover is not None:
192
+ return _after_remover(Path(repo), worktree, remover(worktree), removed, git_flags, env)
187
193
  flags = ["--force", "--force"] if force_locked else (["--force"] if force else [])
188
194
  proc = _run_git(Path(repo), ("worktree", "remove", *flags, str(worktree)), git_flags, env)
189
195
  if proc.returncode != 0:
@@ -192,3 +198,19 @@ def safe_remove_worktree(repo: Path, worktree: Path, *, force: bool = True, forc
192
198
  detail += f" ({len(removed)} link(s) inside it were removed first)"
193
199
  return f"git worktree remove failed: {detail}"
194
200
  return None
201
+
202
+
203
+ def _after_remover(repo: Path, worktree: Path, problem: str | None, removed: list[Path],
204
+ git_flags: Sequence[str], env: Mapping[str, str] | None) -> str | None:
205
+ """None only when the remover reported success AND the worktree is gone from disk and from git's list."""
206
+ links = f" ({len(removed)} link(s) inside it were removed first)" if removed else ""
207
+ if problem:
208
+ return f"{problem}{links}"
209
+ if os.path.lexists(worktree):
210
+ return f"the remover reported success but {worktree} is still on disk{links}"
211
+ listing = _run_git(repo, ("worktree", "list", "--porcelain"), git_flags, env)
212
+ if listing.returncode != 0:
213
+ return f"git worktree list failed after the removal: {(listing.stderr or '').strip()}"
214
+ if any(_same(worktree, b[0][len("worktree "):]) for b in _worktree_blocks(listing.stdout)[1:]):
215
+ return f"the folder is gone but git still lists {worktree}"
216
+ return None
@@ -181,6 +181,9 @@ If the default branch triggers an automated deployment pipeline:
181
181
  ## Step 9 — Close feature-branch lifecycle (Clean up)
182
182
 
183
183
  **Only after** the merge is complete and deployment (if any) is validated green:
184
+ - In a linked worktree (an Orca one included), skip the switch, the pull and the local branch delete:
185
+ git cannot switch to a branch the main checkout holds. Delete only the remote branch here; the last
186
+ step removes an Orca worktree with its local branch.
184
187
  - Run `git status --short`. If it shows changes you did not make, do not switch, stash, reset or commit:
185
188
  leave them, report them, and stop cleanup here (a shared checkout often holds a peer's edits).
186
189
  - In a shared checkout (Step 0b says `SHARED: yes`), skip the switch and the pull below. Clean up as Step 0b
@@ -207,6 +210,23 @@ Prod SHA: matches merge ✓ | n/a
207
210
  Cleanup: remote branch deleted / local branch deleted / backup ref dropped | SKIPPED (<why>)
208
211
  ```
209
212
 
213
+ ## Step 11 — Remove this Orca worktree (the last action)
214
+
215
+ Only when cleanup ran (it was not skipped), this session works in a linked worktree, and `orca` is on PATH. Do this
216
+ after the report is printed: Orca stops this session when it removes the worktree. Run it from the main checkout,
217
+ in one command:
218
+ ```
219
+ (cd "<main checkout>" && python "${CLAUDE_PLUGIN_ROOT}/scripts/caddis_tidy.py" --hygiene --apply --orca-only \
220
+ --repo-root "<main checkout>" --worktree "<this worktree>" --session-cwd "<this worktree>" \
221
+ --own-terminal "$ORCA_TERMINAL_HANDLE")
222
+ ```
223
+ The parentheses keep this session in its own folder when the result is `KEPT`.
224
+ It acts only on an Orca-managed worktree that is merged (the same proof as `caddis_tidy.py --hygiene`) and clean, with
225
+ no Orca terminal open in it except this session's own. It deletes the local and remote branch first, then removes
226
+ the worktree with `orca worktree rm` (never `--force`). Any other case prints `KEPT` and the reason, and changes
227
+ nothing. A `KEPT` worktree is removed later by the Orca sweep at the next session start, after its terminal closes.
228
+ This step never fails the merge: if it prints `FAILED`, say so in one line and stop.
229
+
210
230
  ## Rules
211
231
 
212
232
  - Never merge a PR whose required checks are red or absent.
@@ -132,6 +132,9 @@ attempt a silent re-deploy — and **skip cleanup** (Step 6).
132
132
  ## Step 6 — Branch cleanup — only after a confirmed-green deploy
133
133
 
134
134
  **Only after** Step 5 is green:
135
+ - In a linked worktree (an Orca one included), skip the switch, the pull and the local branch delete:
136
+ git cannot switch to a branch the main checkout holds. Delete only the remote branch here; the last
137
+ step removes an Orca worktree with its local branch.
135
138
  - Run `git status --short`. If it shows changes you did not make, do not switch, stash, reset or commit:
136
139
  leave them, report them, and stop cleanup here.
137
140
  - In a shared checkout (Step 0b says `SHARED: yes`), do not switch or pull. Clean up as Step 0b says:
@@ -154,6 +157,23 @@ Health: green ✓ | red — reported, cleanup skipped
154
157
  Cleanup: remote branch ✗ deleted / local ✗ deleted / backup ref dropped | SKIPPED (<why>)
155
158
  ```
156
159
 
160
+ ## Step 8 — Remove this Orca worktree (the last action)
161
+
162
+ Only when cleanup ran (it was not skipped), this session works in a linked worktree, and `orca` is on PATH. Do this
163
+ after the report is printed: Orca stops this session when it removes the worktree. Run it from the main checkout,
164
+ in one command:
165
+ ```
166
+ (cd "<main checkout>" && python "${CLAUDE_PLUGIN_ROOT}/scripts/caddis_tidy.py" --hygiene --apply --orca-only \
167
+ --repo-root "<main checkout>" --worktree "<this worktree>" --session-cwd "<this worktree>" \
168
+ --own-terminal "$ORCA_TERMINAL_HANDLE")
169
+ ```
170
+ The parentheses keep this session in its own folder when the result is `KEPT`.
171
+ It acts only on an Orca-managed worktree that is merged (the same proof as `caddis_tidy.py --hygiene`) and clean, with
172
+ no Orca terminal open in it except this session's own. It deletes the local and remote branch first, then removes
173
+ the worktree with `orca worktree rm` (never `--force`). Any other case prints `KEPT` and the reason, and changes
174
+ nothing. A `KEPT` worktree is removed later by the Orca sweep at the next session start, after its terminal closes.
175
+ This step never fails the merge: if it prints `FAILED`, say so in one line and stop.
176
+
157
177
  ## Rules
158
178
  - Never merge without: green required checks **and** the explicit human deploy-confirm.
159
179
  - Never delete a branch before its deploy is validated green.
@@ -1,7 +1,7 @@
1
1
  {
2
- "poolVersion": "1.3.188",
2
+ "poolVersion": "1.3.190",
3
3
  "bundles": {
4
- "antigravity-plugin": "1.3.188",
4
+ "antigravity-plugin": "1.3.190",
5
5
  "antigravity-plugin-extras": "1.3.52",
6
6
  "codex": "unknown"
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@caddis/cli",
3
- "version": "0.4.104",
3
+ "version": "0.4.106",
4
4
  "description": "Install, update and diagnose the caddis dev harness across every coding agent you use (Claude Code, agy/Antigravity, and more).",
5
5
  "keywords": [
6
6
  "caddis",