@caddis/cli 0.4.92 → 0.4.94

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 (99) hide show
  1. package/README.md +4 -0
  2. package/bundles/antigravity-plugin/agents/debug.md +2 -0
  3. package/bundles/antigravity-plugin/guard_agy.py +6 -2
  4. package/bundles/antigravity-plugin/plugin.json +1 -1
  5. package/bundles/antigravity-plugin/repo_freshness.py +71 -6
  6. package/bundles/antigravity-plugin/repo_hygiene.py +516 -0
  7. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_exit.cpython-311.pyc +0 -0
  8. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_file_lock.cpython-311.pyc +0 -0
  9. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_frontmatter.cpython-311.pyc +0 -0
  10. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_redact.cpython-311.pyc +0 -0
  11. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_roadmap.cpython-311.pyc +0 -0
  12. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_rows.cpython-311.pyc +0 -0
  13. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_status.cpython-311.pyc +0 -0
  14. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_tidy.cpython-311.pyc +0 -0
  15. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_todo.cpython-311.pyc +0 -0
  16. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_workstreams.cpython-311.pyc +0 -0
  17. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_worktree_safety.cpython-311.pyc +0 -0
  18. package/bundles/antigravity-plugin/scripts/caddis_checkout_guard.py +1 -1
  19. package/bundles/antigravity-plugin/scripts/caddis_finished.py +537 -0
  20. package/bundles/antigravity-plugin/scripts/caddis_fleet.py +26 -9
  21. package/bundles/antigravity-plugin/scripts/caddis_guide.json +65 -12
  22. package/bundles/antigravity-plugin/scripts/caddis_own_cleanup.py +23 -248
  23. package/bundles/antigravity-plugin/scripts/caddis_preload_review.py +554 -0
  24. package/bundles/antigravity-plugin/scripts/caddis_repo_tidy.py +240 -0
  25. package/bundles/antigravity-plugin/scripts/caddis_roadmap_run.py +9 -3
  26. package/bundles/antigravity-plugin/scripts/caddis_run.py +160 -0
  27. package/bundles/antigravity-plugin/scripts/caddis_spawn.py +17 -1
  28. package/bundles/antigravity-plugin/scripts/caddis_tidy.py +12 -0
  29. package/bundles/antigravity-plugin/scripts/caddis_upstream_check.py +108 -10
  30. package/bundles/antigravity-plugin/scripts/caddis_worktree_root.py +111 -2
  31. package/bundles/antigravity-plugin/scripts/setup_project_ai.py +132 -11
  32. package/bundles/antigravity-plugin/skills/_registry.md +7 -5
  33. package/bundles/antigravity-plugin/skills/adopt-app/SKILL.md +2 -5
  34. package/bundles/antigravity-plugin/skills/brainstorming/SKILL.md +232 -40
  35. package/bundles/antigravity-plugin/skills/brainstorming/builder-check-prompt.md +25 -0
  36. package/bundles/antigravity-plugin/skills/cloud-phases/SKILL.md +1 -1
  37. package/bundles/antigravity-plugin/skills/dashboard-perf-sweep/SKILL.md +1 -1
  38. package/bundles/antigravity-plugin/skills/db-diagram/SKILL.md +1 -1
  39. package/bundles/antigravity-plugin/skills/explainer-doc/SKILL.md +1 -1
  40. package/bundles/antigravity-plugin/skills/feature-plan/SKILL.md +7 -1
  41. package/bundles/antigravity-plugin/skills/fleet-close/SKILL.md +4 -1
  42. package/bundles/antigravity-plugin/skills/graph-email/SKILL.md +15 -0
  43. package/bundles/antigravity-plugin/skills/handoff/SKILL.md +9 -2
  44. package/bundles/antigravity-plugin/skills/implement/SKILL.md +7 -0
  45. package/bundles/antigravity-plugin/skills/particle-art/SKILL.md +1 -3
  46. package/bundles/antigravity-plugin/skills/port-to-github/SKILL.md +2 -5
  47. package/bundles/antigravity-plugin/skills/pr-merge/SKILL.md +1 -1
  48. package/bundles/antigravity-plugin/skills/preload-review/SKILL.md +69 -0
  49. package/bundles/antigravity-plugin/skills/roadmap/SKILL.md +4 -0
  50. package/bundles/antigravity-plugin/skills/roadmap/assets/plan-resume-prompt.md +6 -5
  51. package/bundles/antigravity-plugin/skills/ship-merge/SKILL.md +1 -1
  52. package/bundles/antigravity-plugin/skills/ship-pr/SKILL.md +1 -1
  53. package/bundles/antigravity-plugin/skills/spawn-session/SKILL.md +5 -0
  54. package/bundles/antigravity-plugin/skills/tdd/SKILL.md +2 -1
  55. package/bundles/antigravity-plugin/skills/tech-explainer/SKILL.md +2 -6
  56. package/bundles/antigravity-plugin/skills/usage-review/SKILL.md +2 -0
  57. package/bundles/antigravity-plugin/skills/using-git-worktrees/SKILL.md +19 -2
  58. package/bundles/antigravity-plugin/skills/warm-editorial-ui/SKILL.md +1 -1
  59. package/bundles/antigravity-plugin-extras/plugin.json +1 -1
  60. package/bundles/antigravity-plugin-extras/skills/_registry.md +3 -2
  61. package/bundles/antigravity-plugin-extras/skills/building-ai-agent-on-cloudflare/SKILL.md +1 -2
  62. package/bundles/antigravity-plugin-extras/skills/building-mcp-server-on-cloudflare/SKILL.md +1 -2
  63. package/bundles/antigravity-plugin-extras/skills/data-contract-pipeline/SKILL.md +1 -1
  64. package/bundles/antigravity-plugin-extras/skills/graph-email/SKILL.md +53 -0
  65. package/bundles/antigravity-plugin-extras/skills/graph-email/email.toml.example +44 -0
  66. package/bundles/antigravity-plugin-extras/skills/graph-email/scripts/send_email.py +432 -0
  67. package/bundles/antigravity-plugin-extras/skills/responsive-mobile-native/SKILL.md +2 -4
  68. package/bundles/antigravity-plugin-extras/skills/runner-move/SKILL.md +2 -4
  69. package/bundles/antigravity-plugin-extras/skills/setup-project-ai/SKILL.md +1 -1
  70. package/bundles/antigravity-plugin-extras/skills/understand-anything/SKILL.md +2 -5
  71. package/bundles/codex/.codex/skills/coding/dashboard-perf-sweep/SKILL.md +1 -1
  72. package/bundles/codex/.codex/skills/data/db-diagram/SKILL.md +1 -1
  73. package/bundles/codex/.codex/skills/devops/adopt-app/SKILL.md +2 -5
  74. package/bundles/codex/.codex/skills/devops/port-to-github/SKILL.md +2 -5
  75. package/bundles/codex/.codex/skills/devops/using-git-worktrees/SKILL.md +19 -2
  76. package/bundles/codex/.codex/skills/docs/explainer-doc/SKILL.md +1 -1
  77. package/bundles/codex/.codex/skills/docs/tech-explainer/SKILL.md +2 -6
  78. package/bundles/codex/.codex/skills/frontend/warm-editorial-ui/SKILL.md +1 -1
  79. package/bundles/codex/.codex/skills/media/particle-art/SKILL.md +1 -3
  80. package/bundles/codex/.codex/skills/workflow/brainstorming/SKILL.md +232 -40
  81. package/bundles/codex/.codex/skills/workflow/brainstorming/builder-check-prompt.md +25 -0
  82. package/bundles/codex/.codex/skills/workflow/roadmap/SKILL.md +4 -0
  83. package/bundles/codex/.codex/skills/workflow/roadmap/assets/plan-resume-prompt.md +6 -5
  84. package/bundles/manifest.json +3 -3
  85. package/dist/export/assets/export-CMtV-slT.css +1 -0
  86. package/dist/export/index.html +2 -2
  87. package/dist/ui/assets/{Activity-DZKPMOeV.js → Activity-BDjet2xd.js} +1 -1
  88. package/dist/ui/assets/Guide-Czn5sK0f.js +9 -0
  89. package/dist/ui/assets/Guide-D-Zy4cUT.css +1 -0
  90. package/dist/ui/assets/{RoadmapTab-DPsiSmIF.js → RoadmapTab-Bd8geyQx.js} +1 -1
  91. package/dist/ui/assets/index-Bd0Z4jR8.css +1 -0
  92. package/dist/ui/assets/{index-xl156OCN.js → index-CmngQ8Mk.js} +12 -12
  93. package/dist/ui/index.html +2 -2
  94. package/package.json +1 -1
  95. package/dist/export/assets/export-HxTgj3z2.css +0 -1
  96. package/dist/ui/assets/Guide-5ZFfL6sl.js +0 -9
  97. package/dist/ui/assets/Guide-Dnsb-TRd.css +0 -1
  98. package/dist/ui/assets/index-DGlNAmeA.css +0 -1
  99. /package/dist/export/assets/{export-B7BBDg5I.js → export-DtlDFN4L.js} +0 -0
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schema": 1,
3
- "version": "1.3.175",
4
- "generated": "2026-11-01 21:34 UTC",
3
+ "version": "1.3.177",
4
+ "generated": "2026-11-04 23:23 UTC",
5
5
  "commands": [
6
6
  {
7
7
  "name": "add-rules",
@@ -338,7 +338,6 @@
338
338
  ]
339
339
  ],
340
340
  "scripts": [
341
- "caddis_gate.py",
342
341
  "caddis_lanes.py",
343
342
  "caddis_routing.py",
344
343
  "caddis_spend.py",
@@ -499,6 +498,16 @@
499
498
  "stage": "knowledge",
500
499
  "daily": false
501
500
  },
501
+ {
502
+ "name": "graph-email",
503
+ "description": "Send a Markdown file as an email through Microsoft Graph or SMTP, as set in ~/.caddis/email.toml. Default recipient is the owner.",
504
+ "hint": "<file.md> [subject words] [--to address] [--attach file]",
505
+ "steps": [],
506
+ "scripts": [],
507
+ "noArgs": false,
508
+ "stage": "ship",
509
+ "daily": false
510
+ },
502
511
  {
503
512
  "name": "handoff",
504
513
  "description": "End-of-session handoff — capture exact state so the next session resumes with zero re-discovery",
@@ -621,6 +630,7 @@
621
630
  "caddis_gate.py",
622
631
  "caddis_lanes.py",
623
632
  "caddis_routing.py",
633
+ "caddis_silence_watch.py",
624
634
  "caddis_spend.py",
625
635
  "caddis_status.py",
626
636
  "caddis_tidy.py",
@@ -935,6 +945,43 @@
935
945
  "stage": "plan",
936
946
  "daily": false
937
947
  },
948
+ {
949
+ "name": "preload-review",
950
+ "description": "Show what loads before the first prompt in every repo (rules, memory index, skills, MCP names) and list what to shorten",
951
+ "hint": "[--root PATH]",
952
+ "steps": [
953
+ [
954
+ "1",
955
+ "find the script"
956
+ ],
957
+ [
958
+ "2",
959
+ "run it"
960
+ ],
961
+ [
962
+ "3",
963
+ "show the output"
964
+ ],
965
+ [
966
+ "4",
967
+ "point to /context"
968
+ ],
969
+ [
970
+ "5",
971
+ "offer actions only"
972
+ ],
973
+ [
974
+ "6",
975
+ "record the review"
976
+ ]
977
+ ],
978
+ "scripts": [
979
+ "caddis_preload_review.py"
980
+ ],
981
+ "noArgs": false,
982
+ "stage": "setup",
983
+ "daily": false
984
+ },
938
985
  {
939
986
  "name": "rca",
940
987
  "description": "Record a root cause in one step — .caddis/rca/<date>-<slug>.md — or close one with the fixing commit",
@@ -1618,7 +1665,7 @@
1618
1665
  {
1619
1666
  "name": "dashboard-perf-sweep",
1620
1667
  "category": "coding",
1621
- "description": "Re-measure dashboard/API endpoints for load-time regressions and decide by checklist if a slow one needs the rs-kit refresher, an index, keyset paging, gzip, or nothing. Use when the user says \"sweep dashboard performance\", \"check if this app needs rs-kit\", \"re-measure the perf tracker\", \"is this endpoint a refresher candidate\", or dashboard-performance-tracker.md is stale. Read-only.",
1668
+ "description": "Re-measure dashboard/API endpoints for load-time regressions. Use when the user says \"sweep dashboard performance\", \"check if this app needs rs-kit\", or \"re-measure the perf tracker\".",
1622
1669
  "core": true
1623
1670
  },
1624
1671
  {
@@ -1714,7 +1761,7 @@
1714
1761
  {
1715
1762
  "name": "db-diagram",
1716
1763
  "category": "data",
1717
- "description": "Diagram a SQL artifact (stored proc, view, query, .sql file, table) as Mermaid or Excalidraw. Use when the user says \"diagram this query/proc/view/schema\", \"explain this SQL visually\", \"draw the ER diagram\", \"show me the data flow of this stored proc\", \"/mermaid-db\", or \"/excalidraw-db\". Read-only.",
1764
+ "description": "Diagram SQL artifacts (procs, views, queries, tables) as Mermaid or Excalidraw. Use when the user says \"diagram this SQL\", \"draw the ER diagram\", \"/mermaid-db\", or \"/excalidraw-db\".",
1718
1765
  "core": true
1719
1766
  },
1720
1767
  {
@@ -1765,6 +1812,12 @@
1765
1812
  "description": "Create well-structured conventional commit messages following Conventional Commits standard. Use when committing changes, preparing PRs, or generating changelogs.",
1766
1813
  "core": true
1767
1814
  },
1815
+ {
1816
+ "name": "graph-email",
1817
+ "category": "devops",
1818
+ "description": "Email a Markdown file via Microsoft Graph or SMTP. Use to email a draft or note.",
1819
+ "core": false
1820
+ },
1768
1821
  {
1769
1822
  "name": "monorepo",
1770
1823
  "category": "devops",
@@ -1840,7 +1893,7 @@
1840
1893
  {
1841
1894
  "name": "explainer-doc",
1842
1895
  "category": "docs",
1843
- "description": "Hand-off doc for a team that did NOT do the investigation (vendor, contractor, another team) — the \"stranger must follow it alone\" case. Use when the user says \"write a spec for the X team\", \"document this for someone outside the team\", \"explainer doc\", \"implementation spec for a vendor\", or \"hand this off to Y\". Not for readers with full context.",
1896
+ "description": "Write a self-contained hand-off spec for an external team or vendor. Use when the user says \"write a spec for the X team\", \"explainer doc\", \"spec for a vendor\", or \"hand this off to Y\".",
1844
1897
  "core": true
1845
1898
  },
1846
1899
  {
@@ -2062,7 +2115,7 @@
2062
2115
  {
2063
2116
  "name": "warm-editorial-ui",
2064
2117
  "category": "frontend",
2065
- "description": "Apply the \"Warm Editorial Refinement\" design system (warm cream/charcoal surfaces, Bahnschrift + Plus Jakarta Sans, layered shadows), the canonical template for new frontend builds. Use for apps, dashboards or UI in the abc-project style, or on \"use our design system\", \"apply our template\", \"make it look like abc-project\", \"use the warm editorial style\", \"use our brand template\", \"add dark mode\", or a new tool for XYZ Brand.",
2118
+ "description": "Apply the Warm Editorial Refinement design system. Use when the user says \"use our design system\", \"warm editorial style\", \"apply our template\", or \"make it look like abc-project\".",
2066
2119
  "core": true
2067
2120
  },
2068
2121
  {
@@ -2218,7 +2271,7 @@
2218
2271
  {
2219
2272
  "name": "brainstorming",
2220
2273
  "category": "workflow",
2221
- "description": "You MUST use this before any creative work - creating features, building components, adding functionality, or modifying behavior. Explores user intent, requirements and design before implementation.",
2274
+ "description": "Use before any creative work: new features, components or behavior changes, or planning anything new. Finds what the user wants first.",
2222
2275
  "core": true
2223
2276
  },
2224
2277
  {
@@ -2230,7 +2283,7 @@
2230
2283
  {
2231
2284
  "name": "data-contract-pipeline",
2232
2285
  "category": "workflow",
2233
- "description": "Build, audit and validate data-to-UI contracts. Use when the user mentions data mapping, UI lineage, DB-to-UI, DisplayDTOs, source-to-screen mapping, data contracts, schema drift, typed API responses, mockup grounding, or asks whether a UI is backed by real data.",
2286
+ "description": "Build, audit, and validate DB-to-UI data contracts. Use when the user mentions data mapping, UI lineage, DisplayDTOs, source-to-screen mapping, or asks if a UI is backed by real data.",
2234
2287
  "core": false
2235
2288
  },
2236
2289
  {
@@ -2284,7 +2337,7 @@
2284
2337
  {
2285
2338
  "name": "setup-project-ai",
2286
2339
  "category": "workflow",
2287
- "description": "Install or refresh the agent-agnostic harness in a project: AGENTS.md rules with CLAUDE.md shims, subagents, commands and settings. Use when setting up AI resources on a project, or the user says 'set up the harness', 'setup-project-ai', 'generate CLAUDE.md', 'onboard this project to Claude Code / Codex / agy', or runs /setup-project-ai.",
2340
+ "description": "Install or refresh the project AI harness: AGENTS.md, CLAUDE.md shims, agents, settings. Use when the user says 'set up the harness', 'generate CLAUDE.md', or runs /setup-project-ai.",
2288
2341
  "core": false
2289
2342
  },
2290
2343
  {
@@ -2409,9 +2462,9 @@
2409
2462
  ]
2410
2463
  },
2411
2464
  "counts": {
2412
- "commands": 39,
2465
+ "commands": 41,
2413
2466
  "agents": 12,
2414
- "skills": 133,
2467
+ "skills": 134,
2415
2468
  "core": 50,
2416
2469
  "hooks": 17
2417
2470
  }
@@ -31,269 +31,44 @@ from __future__ import annotations
31
31
 
32
32
  import json
33
33
  import os
34
- import re
35
- import subprocess
36
34
  import sys
37
35
  from collections.abc import Callable
38
36
  from pathlib import Path
39
37
 
40
38
  import caddis_created
39
+ import caddis_finished
41
40
  import caddis_worktree_safety as safety
42
41
 
43
- GIT_TIMEOUT = 60
44
- NET_TIMEOUT = 120
45
- _GH_FIELDS = "number,state,headRefOid,mergedAt,headRefName"
46
-
47
-
48
- class PrLookupError(Exception):
49
- """gh is missing, failed, or the repo cannot be named."""
50
-
51
-
52
- def _env() -> dict[str, str]:
53
- env = dict(os.environ)
54
- env["GIT_TERMINAL_PROMPT"] = "0" # a credential prompt must fail, not hang the handoff
55
- return env
56
-
57
-
58
- def _run(cmd: list[str], cwd: Path | None = None, timeout: int = GIT_TIMEOUT) -> subprocess.CompletedProcess:
59
- """Never raises: a missing program or a timeout comes back as returncode -1 with the problem in stderr."""
60
- try:
61
- return subprocess.run(cmd, cwd=str(cwd) if cwd else None, capture_output=True, text=True, encoding="utf-8",
62
- errors="replace", stdin=subprocess.DEVNULL, timeout=timeout, check=False, env=_env())
63
- except FileNotFoundError:
64
- return subprocess.CompletedProcess(cmd, -1, "", f"{cmd[0]} is not installed")
65
- except subprocess.TimeoutExpired:
66
- return subprocess.CompletedProcess(cmd, -1, "", f"{cmd[0]} timed out after {timeout} s")
67
- except OSError as exc:
68
- return subprocess.CompletedProcess(cmd, -1, "", str(exc))
69
-
70
-
71
- def _git(path: Path, *args: str, timeout: int = GIT_TIMEOUT) -> subprocess.CompletedProcess:
72
- return _run(["git", "-c", "core.quotepath=off", "-C", str(path), *args], timeout=timeout)
73
-
74
-
75
- def _err(proc: subprocess.CompletedProcess) -> str:
76
- text = (proc.stderr or proc.stdout or "").strip()
77
- return text.splitlines()[-1] if text else f"exit {proc.returncode}"
78
-
79
-
80
- def _same(a: str | Path, b: str | Path) -> bool:
81
- return os.path.normcase(os.path.realpath(a)) == os.path.normcase(os.path.realpath(b))
82
-
83
-
84
- def _inside(child: str | Path, parent: str | Path) -> bool:
85
- """`child` is `parent` or under it (both resolved, case-folded on Windows)."""
86
- c = os.path.normcase(os.path.realpath(child))
87
- p = os.path.normcase(os.path.realpath(parent))
88
- return c == p or c.startswith(p.rstrip("\\/") + os.sep)
89
-
90
-
91
- # -- gh ---------------------------------------------------------------------------------------------------------
92
-
93
- def _slug(main_repo: Path) -> str | None:
94
- """`owner/name` from the origin URL (https, ssh or scp form), else None."""
95
- proc = _git(main_repo, "remote", "get-url", "origin")
96
- url = proc.stdout.strip() if proc.returncode == 0 else ""
97
- if "://" not in url and "@" not in url:
98
- return None # a local path origin has no GitHub name
99
- match = re.search(r"[:/]([^/:]+)/([^/]+?)(?:\.git)?/?$", url)
100
- return f"{match.group(1)}/{match.group(2)}" if match else None
101
-
102
-
103
- def gh_pr_lookup(main_repo: Path, branch: str | None, pr: str | None) -> list[dict]:
104
- slug = _slug(main_repo)
105
- if not slug:
106
- raise PrLookupError("cannot read owner/name from the origin URL")
107
- if pr:
108
- proc = _run(["gh", "pr", "view", pr, "--repo", slug, "--json", _GH_FIELDS], timeout=NET_TIMEOUT)
109
- elif branch:
110
- proc = _run(["gh", "pr", "list", "--repo", slug, "--head", branch, "--state", "all", "--limit", "20",
111
- "--json", _GH_FIELDS], timeout=NET_TIMEOUT)
112
- else:
113
- return []
114
- if proc.returncode != 0:
115
- raise PrLookupError(f"gh failed: {_err(proc)}")
116
- try:
117
- data = json.loads(proc.stdout or "null")
118
- except ValueError as exc:
119
- raise PrLookupError(f"gh printed bad JSON: {exc}") from exc
120
- data = [data] if isinstance(data, dict) else data
121
- if not isinstance(data, list):
122
- raise PrLookupError("gh printed an unexpected shape")
123
- return [d for d in data if isinstance(d, dict)]
124
-
125
-
126
- def _pr_number(value: str | None) -> str | None:
127
- match = re.search(r"(\d+)\s*$", str(value or ""))
128
- return match.group(1) if match else None
129
-
130
-
131
- def _pick_pr(prs: list[dict], branch: str | None, by_number: bool) -> tuple[dict | None, str]:
132
- """(the merged PR, "") or (None, why the worktree is kept)."""
133
- if not prs:
134
- return None, f"no merged PR found: no PR for branch {branch}" if branch else "no merged PR found: no PR"
135
- open_pr = next((p for p in prs if str(p.get("state", "")).upper() == "OPEN"), None)
136
- pick = open_pr or prs[0]
137
- state = str(pick.get("state", "")).upper() or "UNKNOWN"
138
- if state != "MERGED":
139
- return None, f"PR #{pick.get('number')} is {state}"
140
- head_name = pick.get("headRefName")
141
- if by_number and branch and head_name and head_name != branch:
142
- return None, f"PR #{pick.get('number')} is for branch {head_name}, not {branch}"
143
- return pick, ""
42
+ # The worktree proof, the gh seam and the removal live in caddis_finished (one definition of "finished", shared with
43
+ # `caddis_tidy.py --hygiene`). The old private names stay here as aliases: the tests and the scratch code use them.
44
+ GIT_TIMEOUT = caddis_finished.GIT_TIMEOUT
45
+ NET_TIMEOUT = caddis_finished.NET_TIMEOUT
46
+ PrLookupError = caddis_finished.PrLookupError
47
+ gh_pr_lookup = caddis_finished.gh_pr_lookup
48
+ _env = caddis_finished._env
49
+ _run = caddis_finished._run
50
+ _git = caddis_finished._git
51
+ _err = caddis_finished._err
52
+ _same = caddis_finished._same
53
+ _inside = caddis_finished._inside
54
+ _slug = caddis_finished.repo_slug
55
+ _pr_number = caddis_finished.pr_number
56
+ _pick_pr = caddis_finished.pick_pr
57
+ _main_repo = caddis_finished.main_repo
58
+ _default_branch = caddis_finished.default_branch
59
+ _ref = caddis_finished.ref
60
+ _names = caddis_finished.changed_names
61
+ _branch_tip = caddis_finished.branch_tip
62
+ _remove_worktree = caddis_finished.remove_finished
144
63
 
145
64
 
146
65
  # -- worktree ---------------------------------------------------------------------------------------------------
147
66
 
148
- def _main_repo(entry: dict, path: Path) -> Path | None:
149
- """The repo to list worktrees from: the entry's `repo` when it is a git checkout, else from the path's common dir."""
150
- for start in (entry.get("repo"), str(path)):
151
- if not start or not os.path.isdir(start):
152
- continue
153
- proc = _git(Path(start), "rev-parse", "--path-format=absolute", "--git-common-dir")
154
- if proc.returncode == 0 and proc.stdout.strip():
155
- common = Path(proc.stdout.strip())
156
- return common.parent if common.name == ".git" else Path(start)
157
- return None
158
-
159
-
160
- def _default_branch(wt: Path) -> str:
161
- proc = _git(wt, "symbolic-ref", "--short", "-q", "refs/remotes/origin/HEAD")
162
- name = proc.stdout.strip() if proc.returncode == 0 else ""
163
- return name.split("/", 1)[1] if name.startswith("origin/") else "main"
164
-
165
-
166
- def _ref(wt: Path, rev: str) -> str | None:
167
- proc = _git(wt, "rev-parse", "-q", "--verify", f"{rev}^{{commit}}")
168
- return proc.stdout.strip() if proc.returncode == 0 and proc.stdout.strip() else None
169
-
170
-
171
- def _names(wt: Path, a: str, b: str) -> set[str] | None:
172
- proc = _git(wt, "diff", "--name-only", "-z", "--no-renames", "--no-ext-diff", a, b)
173
- return None if proc.returncode != 0 else {n for n in proc.stdout.split("\0") if n}
174
-
175
-
176
67
  def _check_worktree(entry: dict, path: Path, cwd: str, pr_lookup: Callable) -> tuple[str, str, dict]:
177
68
  """("REMOVE", reason, facts) or ("KEPT"/"GONE", reason, {})."""
178
69
  if entry.get("by") == "roadmap-run":
179
70
  return "KEPT", "owned by the roadmap runner", {}
180
- if not os.path.lexists(path):
181
- return "GONE", "", {}
182
- try:
183
- if safety.is_link(os.lstat(path)):
184
- return "KEPT", "the folder is a junction or symlink", {}
185
- except OSError as exc:
186
- return "KEPT", f"cannot inspect it: {exc}", {}
187
- repo = _main_repo(entry, path)
188
- if repo is None:
189
- return "KEPT", "not a registered linked worktree (no git repo found)", {}
190
- listing = _git(repo, "worktree", "list", "--porcelain")
191
- if listing.returncode != 0:
192
- return "KEPT", f"git worktree list failed: {_err(listing)}", {}
193
- blocks = safety._worktree_blocks(listing.stdout)
194
- if not blocks:
195
- return "KEPT", "git listed no worktrees", {}
196
- main = Path(blocks[0][0][len("worktree "):])
197
- if _same(path, main):
198
- return "KEPT", "it is the main checkout", {}
199
- block = next((b for b in blocks[1:] if _same(path, b[0][len("worktree "):])), None)
200
- if block is None:
201
- return "KEPT", f"not a registered linked worktree of {main}", {}
202
- if _inside(cwd, path):
203
- return "KEPT", "this session is working in it", {}
204
- status = _git(path, "status", "--porcelain", "--untracked-files=normal")
205
- if status.returncode != 0:
206
- return "KEPT", f"git status failed: {_err(status)}", {}
207
- if status.stdout.strip():
208
- return "KEPT", "uncommitted changes", {}
209
- if any(line == "locked" or line.startswith("locked ") for line in block):
210
- return "KEPT", "it is locked", {}
211
- sym = _git(path, "symbolic-ref", "--short", "-q", "HEAD")
212
- branch = sym.stdout.strip() if sym.returncode == 0 and sym.stdout.strip() else (entry.get("branch") or None)
213
- default = _default_branch(path)
214
- if branch and branch == default:
215
- return "KEPT", f"it is on the default branch {default}", {}
216
- pr = _pr_number(entry.get("pr"))
217
- if not branch and not pr:
218
- return "KEPT", "no merged PR found: no branch and no PR in the record", {}
219
- try:
220
- prs = pr_lookup(main, branch, pr)
221
- except PrLookupError as exc:
222
- return "KEPT", f"no merged PR found: {exc}", {}
223
- except Exception as exc: # noqa: BLE001 - any lookup failure keeps the worktree
224
- return "KEPT", f"no merged PR found: lookup failed: {exc}", {}
225
- merged, why = _pick_pr(prs, branch, by_number=bool(pr))
226
- if merged is None:
227
- return "KEPT", why, {}
228
- number = str(merged.get("number") or pr or "?")
229
- head = _ref(path, "HEAD")
230
- if not head:
231
- return "KEPT", "cannot read HEAD", {}
232
- pr_head = str(merged.get("headRefOid") or "").strip().lower()
233
- if not pr_head or not _ref(path, pr_head): # a reused branch name: without the PR head, nothing proves HEAD landed
234
- return "KEPT", f"PR #{number} head commit is not in the local repo", {}
235
- after = _git(path, "rev-list", "--max-count=1", f"{pr_head}..HEAD")
236
- if after.returncode != 0:
237
- return "KEPT", f"git rev-list failed: {_err(after)}", {}
238
- if after.stdout.strip():
239
- return "KEPT", f"commits after the merged PR #{number}", {}
240
- fetch = _git(path, "fetch", "--quiet", "--no-tags", "origin",
241
- f"+refs/heads/{default}:refs/remotes/origin/{default}", timeout=NET_TIMEOUT)
242
- if fetch.returncode != 0:
243
- return "KEPT", f"cannot fetch origin/{default}: {_err(fetch)}", {}
244
- target = f"refs/remotes/origin/{default}"
245
- base = _git(path, "merge-base", target, "HEAD")
246
- if base.returncode != 0 or not base.stdout.strip():
247
- return "KEPT", f"no merge base with origin/{default}", {}
248
- changed = _names(path, base.stdout.strip(), "HEAD")
249
- differ_all = _names(path, target, "HEAD")
250
- if changed is None or differ_all is None:
251
- return "KEPT", f"git diff against origin/{default} failed", {}
252
- differ = sorted(changed & differ_all)
253
- if differ:
254
- return "KEPT", f"{len(differ)} file(s) differ from origin/{default}: {', '.join(differ[:3])}", {}
255
- facts = {"repo": main, "branch": branch, "pr": number, "pr_head": pr_head, "head": head}
256
- return "REMOVE", f"PR #{number} merged, clean, tree equals origin/{default}", facts
257
-
258
-
259
- def _branch_tip(repo: Path, branch: str) -> str | None:
260
- proc = _git(repo, "rev-parse", "-q", "--verify", f"refs/heads/{branch}")
261
- return proc.stdout.strip() if proc.returncode == 0 and proc.stdout.strip() else None
262
-
263
-
264
- def _remove_worktree(path: Path, facts: dict) -> tuple[str, str]:
265
- repo, branch, head, pr_head = facts["repo"], facts["branch"], facts["head"], facts["pr_head"]
266
- local_tip = _branch_tip(repo, branch) if branch else None
267
- problem = safety.safe_remove_worktree(repo, path, force=False, env=_env())
268
- if problem:
269
- return "FAILED", problem
270
- notes: list[str] = []
271
- if branch and local_tip:
272
- listing = _git(repo, "worktree", "list", "--porcelain")
273
- if listing.returncode != 0 or f"branch refs/heads/{branch}" in listing.stdout.splitlines():
274
- notes.append("local branch kept: another worktree has it checked out")
275
- elif local_tip not in {head, pr_head}:
276
- notes.append("local branch kept: its tip is not the removed HEAD or the PR head")
277
- else:
278
- gone = _git(repo, "branch", "-D", "--", branch)
279
- notes.append("local branch deleted" if gone.returncode == 0 else f"local branch kept: {_err(gone)}")
280
- if branch:
281
- ls = _git(repo, "ls-remote", "--heads", "origin", f"refs/heads/{branch}", timeout=NET_TIMEOUT)
282
- tips = [ln.split()[0] for ln in ls.stdout.splitlines() if ln.strip()] if ls.returncode == 0 else []
283
- if ls.returncode != 0:
284
- notes.append(f"remote branch kept: ls-remote failed: {_err(ls)}")
285
- elif tips:
286
- tip = tips[0].lower()
287
- if tip in {pr_head, head.lower()} - {""}: # only a tip this check proved landed
288
- try:
289
- push = _git(repo, *safety.remote_delete_args(branch, tip), timeout=NET_TIMEOUT)
290
- notes.append("remote branch deleted" if push.returncode == 0
291
- else f"remote branch kept: {_err(push)}")
292
- except ValueError as exc:
293
- notes.append(f"remote branch kept: {exc}")
294
- else:
295
- notes.append("remote branch kept: its tip moved past the PR head")
296
- return "REMOVED", "; ".join(notes)
71
+ return caddis_finished.prove_worktree_finished(entry, path, cwd, pr_lookup)
297
72
 
298
73
 
299
74
  # -- scratch ----------------------------------------------------------------------------------------------------