@caddis/cli 0.4.93 → 0.4.95

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 (56) hide show
  1. package/bundles/antigravity-plugin/guard_agy.py +6 -2
  2. package/bundles/antigravity-plugin/plugin.json +1 -1
  3. package/bundles/antigravity-plugin/repo_freshness.py +71 -6
  4. package/bundles/antigravity-plugin/repo_hygiene.py +516 -0
  5. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_exit.cpython-311.pyc +0 -0
  6. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_file_lock.cpython-311.pyc +0 -0
  7. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_frontmatter.cpython-311.pyc +0 -0
  8. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_redact.cpython-311.pyc +0 -0
  9. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_roadmap.cpython-311.pyc +0 -0
  10. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_rows.cpython-311.pyc +0 -0
  11. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_status.cpython-311.pyc +0 -0
  12. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_tidy.cpython-311.pyc +0 -0
  13. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_todo.cpython-311.pyc +0 -0
  14. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_workstreams.cpython-311.pyc +0 -0
  15. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_worktree_safety.cpython-311.pyc +0 -0
  16. package/bundles/antigravity-plugin/scripts/caddis_finished.py +537 -0
  17. package/bundles/antigravity-plugin/scripts/caddis_guide.json +9 -8
  18. package/bundles/antigravity-plugin/scripts/caddis_own_cleanup.py +23 -248
  19. package/bundles/antigravity-plugin/scripts/caddis_prepush_config.py +222 -0
  20. package/bundles/antigravity-plugin/scripts/caddis_repo_tidy.py +240 -0
  21. package/bundles/antigravity-plugin/scripts/caddis_tidy.py +12 -0
  22. package/bundles/antigravity-plugin/scripts/caddis_worktree_root.py +111 -2
  23. package/bundles/antigravity-plugin/scripts/setup_project_ai.py +703 -174
  24. package/bundles/antigravity-plugin/skills/_registry.md +4 -4
  25. package/bundles/antigravity-plugin/skills/adopt-app/SKILL.md +2 -5
  26. package/bundles/antigravity-plugin/skills/cloud-phases/SKILL.md +1 -1
  27. package/bundles/antigravity-plugin/skills/dashboard-perf-sweep/SKILL.md +1 -1
  28. package/bundles/antigravity-plugin/skills/db-diagram/SKILL.md +1 -1
  29. package/bundles/antigravity-plugin/skills/explainer-doc/SKILL.md +1 -1
  30. package/bundles/antigravity-plugin/skills/implement/SKILL.md +4 -0
  31. package/bundles/antigravity-plugin/skills/port-to-github/SKILL.md +2 -5
  32. package/bundles/antigravity-plugin/skills/pr-merge/SKILL.md +1 -1
  33. package/bundles/antigravity-plugin/skills/ship-merge/SKILL.md +1 -1
  34. package/bundles/antigravity-plugin/skills/ship-pr/SKILL.md +1 -1
  35. package/bundles/antigravity-plugin/skills/tech-explainer/SKILL.md +2 -6
  36. package/bundles/antigravity-plugin/skills/using-git-worktrees/SKILL.md +19 -2
  37. package/bundles/antigravity-plugin/skills/warm-editorial-ui/SKILL.md +1 -1
  38. package/bundles/antigravity-plugin-extras/plugin.json +1 -1
  39. package/bundles/antigravity-plugin-extras/skills/_registry.md +2 -2
  40. package/bundles/antigravity-plugin-extras/skills/building-ai-agent-on-cloudflare/SKILL.md +1 -2
  41. package/bundles/antigravity-plugin-extras/skills/building-mcp-server-on-cloudflare/SKILL.md +1 -2
  42. package/bundles/antigravity-plugin-extras/skills/data-contract-pipeline/SKILL.md +1 -1
  43. package/bundles/antigravity-plugin-extras/skills/responsive-mobile-native/SKILL.md +2 -4
  44. package/bundles/antigravity-plugin-extras/skills/runner-move/SKILL.md +2 -4
  45. package/bundles/antigravity-plugin-extras/skills/setup-project-ai/SKILL.md +1 -1
  46. package/bundles/antigravity-plugin-extras/skills/understand-anything/SKILL.md +2 -5
  47. package/bundles/codex/.codex/skills/coding/dashboard-perf-sweep/SKILL.md +1 -1
  48. package/bundles/codex/.codex/skills/data/db-diagram/SKILL.md +1 -1
  49. package/bundles/codex/.codex/skills/devops/adopt-app/SKILL.md +2 -5
  50. package/bundles/codex/.codex/skills/devops/port-to-github/SKILL.md +2 -5
  51. package/bundles/codex/.codex/skills/devops/using-git-worktrees/SKILL.md +19 -2
  52. package/bundles/codex/.codex/skills/docs/explainer-doc/SKILL.md +1 -1
  53. package/bundles/codex/.codex/skills/docs/tech-explainer/SKILL.md +2 -6
  54. package/bundles/codex/.codex/skills/frontend/warm-editorial-ui/SKILL.md +1 -1
  55. package/bundles/manifest.json +3 -3
  56. package/package.json +1 -1
@@ -0,0 +1,240 @@
1
+ #!/usr/bin/env python3
2
+ """caddis_tidy.py --hygiene: list every worktree and local branch of one repo, and remove only what is proved finished.
3
+
4
+ Dry run is the default; only `apply=True` acts. Every row gets one action and a reason:
5
+
6
+ REMOVE proved finished (dry run) REMOVED removed (--apply)
7
+ KEPT a guard holds it, the reason says which TRIAGE no PR or a CLOSED unmerged PR: listed, never removed
8
+ GONE the folder vanished before removal FAILED removal was tried and did not complete
9
+
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
13
+ file equals origin/<default>). A branch with no worktree gets `caddis_finished.prove_branch_finished`.
14
+
15
+ The live-session rule is the PowerShell report's: a transcript written within 60 min PROVES a session is live;
16
+ an older one proves nothing (idle-session, KEPT). A session id with no transcript is "removable" to the classifier,
17
+ but tidy still needs the merged proof. Removal goes through `caddis_finished.remove_finished` (links first,
18
+ `force=False`, compare-and-delete push), so the rules live in one place.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import json
24
+ import os
25
+ import shutil
26
+ import subprocess
27
+ import sys
28
+ import time
29
+ from collections.abc import Callable
30
+ from pathlib import Path
31
+
32
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
33
+ import caddis_finished as cf
34
+
35
+ ORCA_TIMEOUT_S = 10.0
36
+ _ACTIONS = ("REMOVE", "REMOVED", "KEPT", "TRIAGE", "GONE", "FAILED")
37
+
38
+
39
+ def _key(path: str | Path) -> str:
40
+ return os.path.normcase(os.path.realpath(path))
41
+
42
+
43
+ def orca_lookup(run: Callable = subprocess.run, which: Callable = shutil.which,
44
+ timeout_s: float = ORCA_TIMEOUT_S) -> tuple[dict[str, str] | None, str]:
45
+ """({normcase(realpath(path)): id}, "") from `orca worktree list`, or (None, why) when the list cannot be trusted.
46
+
47
+ None (not on PATH, non-zero exit, timeout, bad JSON, `ok` false, `truncated` true) means NO worktree counts as
48
+ Orca-managed; the caller prints the reason every run (plan decision 7).
49
+ """
50
+ if not which("orca"):
51
+ return None, "orca not on PATH"
52
+ cmd = ["orca", "worktree", "list", "--limit", "10000", "--json"]
53
+ try:
54
+ proc = run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace",
55
+ stdin=subprocess.DEVNULL, timeout=timeout_s, check=False)
56
+ except subprocess.TimeoutExpired:
57
+ return None, f"orca took longer than {timeout_s:g} s"
58
+ except OSError as exc:
59
+ return None, f"orca could not start: {exc}"
60
+ if proc.returncode != 0:
61
+ text = (proc.stderr or proc.stdout or "").strip()
62
+ return None, f"orca failed: {text.splitlines()[-1] if text else f'exit {proc.returncode}'}"
63
+ try:
64
+ data = json.loads(proc.stdout or "null")
65
+ except ValueError:
66
+ return None, "orca printed bad JSON"
67
+ if not isinstance(data, dict) or not data.get("ok"):
68
+ return None, "orca answered not ok"
69
+ result = data.get("result")
70
+ if not isinstance(result, dict) or not isinstance(result.get("worktrees"), list):
71
+ return None, "orca printed an unexpected shape"
72
+ 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, ""
79
+
80
+
81
+ def _row(kind: str, name: str, path: str | None, action: str, reason: str) -> dict:
82
+ return {"kind": kind, "name": name, "path": path, "action": action, "reason": reason}
83
+
84
+
85
+ def _triage_reason(reason: str) -> str | None:
86
+ """The `why` for TRIAGE when a KEPT proof reason means "no PR" or "a CLOSED unmerged PR", else None."""
87
+ if reason.startswith("no merged PR found: no PR"):
88
+ return "no PR"
89
+ if reason.startswith("PR #") and reason.endswith(" is CLOSED"):
90
+ return f"{reason[:-len(' is CLOSED')]} closed unmerged"
91
+ return None
92
+
93
+
94
+ def _listing(repo: Path) -> list[dict] | None:
95
+ proc = cf._git(repo, "worktree", "list", "--porcelain")
96
+ return cf.parse_worktree_porcelain(proc.stdout) if proc.returncode == 0 else None
97
+
98
+
99
+ def _prune(repo: Path, path: str) -> tuple[str, str]:
100
+ proc = cf._git(repo, "worktree", "prune")
101
+ if proc.returncode != 0:
102
+ return "FAILED", f"git worktree prune failed: {cf._err(proc)}"
103
+ after = _listing(repo)
104
+ if after is None:
105
+ return "FAILED", "git worktree list failed after the prune"
106
+ if any(_key(w["path"]) == _key(path) for w in after):
107
+ return "FAILED", "git kept the registration"
108
+ return "REMOVED", "registration pruned"
109
+
110
+
111
+ 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]:
113
+ """(row, facts) for one linked worktree; facts is non-empty only for REMOVE from the merged proof."""
114
+ path, branch = rec["path"], rec["branch"]
115
+ name = branch
116
+
117
+ def row(action: str, reason: str) -> tuple[dict, dict]:
118
+ return _row("worktree", name, path, action, reason), {}
119
+
120
+ if not os.path.lexists(path):
121
+ if rec["locked"]:
122
+ return row("KEPT", "folder gone but locked; git worktree prune keeps it")
123
+ return _row("worktree", name, path, "REMOVE", "folder gone; git worktree prune"), {"orphan": True}
124
+ try:
125
+ import caddis_worktree_safety as safety
126
+
127
+ if safety.is_link(os.lstat(path)):
128
+ return row("KEPT", "the folder is a junction or symlink")
129
+ except OSError as exc:
130
+ return row("KEPT", f"cannot inspect it: {exc}")
131
+ if cf._inside(cwd, path):
132
+ 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)]}`)")
135
+ status = cf._git(Path(path), "status", "--porcelain", "--untracked-files=normal")
136
+ if status.returncode != 0:
137
+ return row("KEPT", f"git status failed: {cf._err(status)}")
138
+ session = cf.session_id_from_path(path)
139
+ idle = cf.session_idle_minutes(session, projects_root, now) if session else -1
140
+ state = cf.worktree_state(True, bool(status.stdout.strip()), session is not None, idle)
141
+ if state == "DIRTY":
142
+ return row("KEPT", "DIRTY: uncommitted changes (incl. untracked)")
143
+ if state == "IN USE":
144
+ return row("KEPT", f"IN USE: session {session[:8]} wrote {idle} min ago")
145
+ if state == "idle-session":
146
+ return row("KEPT", f"owned by session {session[:8]}, idle {idle} min; not proof it ended")
147
+ if state != "removable":
148
+ return row("KEPT", f"unexpected state {state}")
149
+ if rec["locked"]:
150
+ return row("KEPT", "it is locked")
151
+ entry = {"repo": str(repo), "branch": None if branch == "(detached)" else branch}
152
+ action, reason, facts = cf.prove_worktree_finished(entry, Path(path), cwd, pr_lookup)
153
+ if action == "KEPT":
154
+ why = _triage_reason(reason)
155
+ if why and entry["branch"]:
156
+ action, reason, _ = cf._triage(repo, branch, default, why)
157
+ return _row("worktree", name, path, action, reason), facts
158
+
159
+
160
+ def _local_branches(repo: Path) -> list[str] | None:
161
+ proc = cf._git(repo, "for-each-ref", "--format=%(refname)", "refs/heads")
162
+ if proc.returncode != 0:
163
+ return None
164
+ return [ln[len("refs/heads/"):] for ln in proc.stdout.splitlines() if ln.startswith("refs/heads/")]
165
+
166
+
167
+ def tidy_repo(repo_root: Path, *, apply: bool = False, cwd: str | None = None, pr_lookup: Callable | None = None,
168
+ 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."""
171
+ pr_lookup = pr_lookup or cf.gh_pr_lookup
172
+ ask_orca = orca_lookup or globals()["orca_lookup"]
173
+ cwd = cwd or os.getcwd()
174
+ now = time.time() if now is None else now
175
+ notes: list[str] = []
176
+ repo = cf.main_repo({"repo": str(repo_root)}, Path(repo_root))
177
+ if repo is None:
178
+ return [], [f"[TIDY] skipped: {repo_root} is not a git repository"]
179
+ records = _listing(repo)
180
+ if not records: # None (git failed) or empty (unparseable): never guess which is the main checkout
181
+ return [], ["[TIDY] skipped: git worktree list failed or was empty; nothing is listed or removed"]
182
+ default = cf.default_branch(repo)
183
+ rows: list[dict] = []
184
+ main, linked = records[0], records[1:]
185
+ rows.append(_row("worktree", main["branch"], main["path"], "KEPT", "it is the main checkout"))
186
+ orca: dict[str, str] | None = {}
187
+ if linked:
188
+ orca, why = ask_orca()
189
+ if orca is None:
190
+ notes.append(f"[TIDY] skipped: Orca check - {why}; no worktree is treated as Orca-managed")
191
+ for rec in linked:
192
+ row, facts = _worktree_row(repo, rec, default=default, cwd=cwd, orca=orca, pr_lookup=pr_lookup,
193
+ projects_root=projects_root, now=now)
194
+ if apply and row["action"] == "REMOVE":
195
+ if facts.get("orphan"): # no folder and no PR proof: only the registration goes, never a branch
196
+ row["action"], row["reason"] = _prune(repo, rec["path"])
197
+ elif not os.path.lexists(rec["path"]):
198
+ row["action"], row["reason"] = "GONE", "the folder vanished before removal"
199
+ else:
200
+ row["action"], row["reason"] = cf.remove_finished(Path(rec["path"]), facts)
201
+ rows.append(row)
202
+ branches = _local_branches(repo)
203
+ if branches is None:
204
+ notes.append("[TIDY] skipped: branches - git for-each-ref failed; no branch is listed or removed")
205
+ return rows, notes
206
+ checked_out = {rec["branch"] for rec in records}
207
+ for branch in branches:
208
+ if branch == default or branch in checked_out:
209
+ continue # the default branch is never a candidate; a checked-out branch is its worktree's row
210
+ action, reason, facts = cf.prove_branch_finished(repo, branch, pr_lookup)
211
+ if apply and action == "REMOVE":
212
+ action, reason = cf.remove_finished(None, facts)
213
+ rows.append(_row("branch", branch, None, action, reason))
214
+ return rows, notes
215
+
216
+
217
+ def print_rows(rows: list[dict], notes: list[str], apply: bool) -> None:
218
+ """The notes, one line per row, then `[TIDY] <would remove|removed> <n>, kept <n>, triage <n>, gone <n>, failed <n>`."""
219
+ for note in notes:
220
+ print(note)
221
+ for r in rows:
222
+ where = f" ({r['path']})" if r["path"] else ""
223
+ print(f"[TIDY] {r['action']:<7} {r['kind']:<8} {r['name']}{where}: {r['reason']}")
224
+ n = {a: sum(1 for r in rows if r["action"] == a) for a in _ACTIONS}
225
+ done = f"removed {n['REMOVED']}" if apply else f"would remove {n['REMOVE']}"
226
+ print(f"[TIDY] {done}, kept {n['KEPT']}, triage {n['TRIAGE']}, gone {n['GONE']}, failed {n['FAILED']}")
227
+
228
+
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)
232
+ if as_json:
233
+ print(json.dumps({"apply": apply, "rows": [dict(r, path=None if r["path"] is None else str(r["path"]))
234
+ for r in rows], "notes": notes}, indent=2))
235
+ else:
236
+ print(f"[TIDY] hygiene {'APPLY' if apply else 'DRY-RUN'} {repo_root}")
237
+ print_rows(rows, notes, apply)
238
+ if not rows:
239
+ return 2
240
+ return 1 if any(r["action"] == "FAILED" for r in rows) else 0
@@ -1273,6 +1273,10 @@ def main(argv: list[str] | None = None) -> int:
1273
1273
  ap.add_argument("--verbose", action="store_true",
1274
1274
  help="with --temp: list every folder and note (default: totals, the 10 largest, "
1275
1275
  "kept notes grouped by reason)")
1276
+ ap.add_argument("--hygiene", action="store_true",
1277
+ help="list every worktree and local branch of the repo with an action and a reason "
1278
+ "(with --apply: remove only the ones proved finished)")
1279
+ ap.add_argument("--json", action="store_true", help="with --hygiene: print the rows as JSON")
1276
1280
  args = ap.parse_args(argv)
1277
1281
  # A status or path the console cannot encode prints as `?`, never a crash (a cp1252 pipe).
1278
1282
  for stream in (sys.stdout, sys.stderr):
@@ -1282,6 +1286,14 @@ def main(argv: list[str] | None = None) -> int:
1282
1286
  pass
1283
1287
 
1284
1288
  repo_root = Path(args.repo_root).resolve()
1289
+ if args.json and not args.hygiene:
1290
+ ap.error("--json only works together with --hygiene")
1291
+ if args.hygiene:
1292
+ if args.check or args.commit_range or args.only or args.prune or args.temp or args.verbose:
1293
+ ap.error("--hygiene runs alone: not with --check, --commit-range, --only, --prune, --temp or --verbose")
1294
+ import caddis_repo_tidy # ships beside this file
1295
+
1296
+ return caddis_repo_tidy.run_cli(repo_root, apply=args.apply, as_json=args.json)
1285
1297
  if args.temp and not args.prune:
1286
1298
  ap.error("--temp only works together with --prune")
1287
1299
  if args.verbose and not args.temp:
@@ -24,6 +24,10 @@ stays where it is: moving it breaks a venv, which keeps absolute paths.
24
24
  CLI: `python caddis_worktree_root.py [--repo PATH] [--root PATH] [--record --purpose TEXT] <short-name>` prints the path.
25
25
  Exit 2 on a bad name or a folder that is not in a git repo.
26
26
 
27
+ `python caddis_worktree_root.py --bootstrap [--repo PATH]` runs INSIDE a linked worktree and gives it its own
28
+ dependencies (uv sync, or venv + pip; npm ci per package-lock.json). The pre-push gate needs that `.venv`.
29
+ Exit 0 done, 1 a step failed or a tool is missing, 2 not a linked worktree.
30
+
27
31
  `--record` also appends the path to this session's created list (`caddis_created.py`, by="helper"), so `/handoff` can
28
32
  remove the worktree later. The helper creates nothing, so the path is recorded as INTENDED: run `git worktree add` on the
29
33
  path it printed. A session with no session id, or a record that cannot be written, only prints a warning on stderr: the
@@ -34,6 +38,7 @@ from __future__ import annotations
34
38
 
35
39
  import argparse
36
40
  import os
41
+ import shutil
37
42
  import subprocess
38
43
  import sys
39
44
  from pathlib import Path
@@ -89,21 +94,125 @@ def worktree_path(repo: Path | str, short_name: str, root: Path | str | None = N
89
94
  """The path for a NEW worktree of `repo`: `<root>/<main checkout folder name>/<short_name>`. Creates nothing.
90
95
  `short_name` is one plain folder name: ValueError for an empty name, `.`, `..`, or one with a path separator or a
91
96
  colon (a drive such as `C:foo` would replace the root on Windows)."""
92
- if (not short_name or short_name in (".", "..") or any(c in short_name for c in "/\:")
97
+ if (not short_name or short_name in (".", "..") or any(c in short_name for c in "/\\:")
93
98
  or short_name != short_name.strip()):
94
99
  raise ValueError(f"the short name must be one plain folder name, not {short_name!r}")
95
100
  main = main_checkout(repo) # one git call
96
101
  return (_explicit_root(root) or main.parent / FALLBACK_DIR) / main.name / short_name
97
102
 
98
103
 
104
+ # ---- bootstrap: give a fresh worktree its own dependencies ---------------------------------------------------------
105
+ # A worktree installs its dependencies fresh. It never links or borrows a venv or node_modules from another folder
106
+ # (the main checkout's venv belongs to a running dev service and is often behind). The pre-push gate uses only the
107
+ # worktree's own `.venv`, so this is the one command that makes a new worktree pass it.
108
+
109
+ NPM_FOLDERS = (".", "frontend") # folders checked for a package-lock.json
110
+
111
+
112
+ def is_linked_worktree(repo: Path) -> bool:
113
+ """True when `repo` is inside a linked worktree (its git dir is not the common dir)."""
114
+ git_dir = _git_out(repo, "rev-parse", "--absolute-git-dir")
115
+ common = _git_out(repo, "rev-parse", "--git-common-dir")
116
+ if not git_dir or not common:
117
+ return False
118
+ return os.path.normcase(os.path.normpath(git_dir)) != os.path.normcase(os.path.normpath(repo / common))
119
+
120
+
121
+ def venv_python(venv: Path) -> Path:
122
+ """The interpreter inside a venv folder (Windows `Scripts/`, POSIX `bin/`)."""
123
+ win = venv / "Scripts" / "python.exe"
124
+ return win if win.exists() or os.name == "nt" else venv / "bin" / "python"
125
+
126
+
127
+ def _declares_dev_extra(pyproject: Path) -> tuple[bool, bool]:
128
+ """(has a [project] table, declares a `dev` optional-dependency group)."""
129
+ try:
130
+ import tomllib
131
+ data = tomllib.loads(pyproject.read_text(encoding="utf-8"))
132
+ except Exception: # noqa: BLE001 - unreadable or invalid TOML: treat as "declares nothing"
133
+ return False, False
134
+ project = data.get("project")
135
+ if not isinstance(project, dict):
136
+ return False, False
137
+ return True, "dev" in (project.get("optional-dependencies") or {})
138
+
139
+
140
+ def plan_bootstrap(root: Path) -> list[tuple[Path, list[str]]]:
141
+ """The commands (cwd, argv) that bootstrap the worktree at `root`. Reads files only; runs nothing.
142
+
143
+ Python: `uv sync --frozen --all-extras` when `uv.lock` exists (pip would not honour the lock), else `python -m venv .venv`
144
+ then `pip install` of what the repo declares (`-e .[dev]` or `-e .`, then requirements.txt / requirements-dev.txt).
145
+ Node: `npm ci` in each of NPM_FOLDERS that has a `package-lock.json`."""
146
+ steps: list[tuple[Path, list[str]]] = []
147
+ pyproject = root / "pyproject.toml"
148
+ reqs = [f for f in ("requirements.txt", "requirements-dev.txt") if (root / f).is_file()]
149
+ if (root / "uv.lock").is_file():
150
+ steps.append((root, ["uv", "sync", "--frozen", "--all-extras"]))
151
+ elif pyproject.is_file() or reqs:
152
+ has_project, has_dev = _declares_dev_extra(pyproject) if pyproject.is_file() else (False, False)
153
+ if has_project or reqs: # a pyproject with only tool config declares nothing to install
154
+ venv = root / ".venv"
155
+ if not venv_python(venv).is_file(): # the folder alone is not enough: an interrupted `venv` leaves it empty
156
+ steps.append((root, [sys.executable, "-m", "venv", ".venv"]))
157
+ py = str(venv_python(venv))
158
+ if has_project:
159
+ steps.append((root, [py, "-m", "pip", "install", "-e", ".[dev]" if has_dev else "."]))
160
+ for f in reqs:
161
+ steps.append((root, [py, "-m", "pip", "install", "-r", f]))
162
+ for folder in NPM_FOLDERS:
163
+ d = root / folder
164
+ if (d / "package-lock.json").is_file():
165
+ steps.append((d, ["npm", "ci"]))
166
+ return steps
167
+
168
+
169
+ def bootstrap(repo: Path | str = ".", run=subprocess.run, which=shutil.which) -> int:
170
+ """Install the dependencies of the linked worktree that contains `repo`. Returns 0, 1 (a step failed or a tool is
171
+ missing) or 2 (not a linked worktree: this never touches a main checkout). `run` and `which` are test seams."""
172
+ repo = Path(repo).absolute()
173
+ top = _git_out(repo, "rev-parse", "--show-toplevel") if repo.is_dir() else None
174
+ if not top:
175
+ print(f"error: {repo} is not inside a git repository", file=sys.stderr)
176
+ return 2
177
+ root = Path(os.path.normpath(top))
178
+ if not is_linked_worktree(root):
179
+ print(f"error: {root} is a main checkout, not a linked worktree. Bootstrap only runs in a worktree "
180
+ "(it would change the checkout's own venv and node_modules).", file=sys.stderr)
181
+ return 2
182
+ steps = plan_bootstrap(root)
183
+ if not steps:
184
+ print(f"bootstrap: nothing to install in {root} (no pyproject.toml, requirements*.txt or package-lock.json)")
185
+ return 0
186
+ for cwd, argv in steps:
187
+ exe = which(argv[0]) if argv[0] in ("uv", "npm") else argv[0]
188
+ if exe is None:
189
+ hint = " (uv.lock needs uv; pip would ignore the lock)" if argv[0] == "uv" else ""
190
+ print(f"error: `{argv[0]}` not found on PATH{hint}", file=sys.stderr)
191
+ return 1
192
+ cmd = [exe, *argv[1:]]
193
+ print(f"bootstrap: ({cwd}) {' '.join(cmd)}", flush=True)
194
+ if run(cmd, cwd=cwd, check=False).returncode != 0:
195
+ print(f"error: step failed: {' '.join(cmd)}", file=sys.stderr)
196
+ return 1
197
+ print(f"bootstrap: done - {root} has its own dependencies")
198
+ return 0
199
+
200
+
99
201
  def main(argv: list[str] | None = None) -> int:
100
202
  ap = argparse.ArgumentParser(description="Print the path for a new git worktree (never under %TEMP%).")
101
- ap.add_argument("short_name", help="one folder name, e.g. fix-login")
203
+ ap.add_argument("short_name", nargs="?", help="one folder name, e.g. fix-login (not used with --bootstrap)")
204
+ ap.add_argument("--bootstrap", action="store_true",
205
+ help="instead of printing a path: install the dependencies of the worktree that contains --repo "
206
+ "(uv sync or venv + pip, and npm ci); exit 2 in a main checkout")
102
207
  ap.add_argument("--repo", default=".", help="any folder of the repo or of one of its worktrees (default: .)")
103
208
  ap.add_argument("--root", default=None, help=f"override the root (default: ${ENV_VAR}, then <repo parent>/.worktrees)")
104
209
  ap.add_argument("--record", action="store_true", help="also record the path in this session's created list")
105
210
  ap.add_argument("--purpose", default="", help="with --record: why the worktree is made")
106
211
  args = ap.parse_args(argv)
212
+ if args.bootstrap:
213
+ return bootstrap(args.repo)
214
+ if not args.short_name:
215
+ ap.error("a short name is required (or use --bootstrap)")
107
216
  try:
108
217
  path = worktree_path(args.repo, args.short_name, args.root)
109
218
  repo = main_checkout(args.repo) if args.record else None