@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
@@ -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 ----------------------------------------------------------------------------------------------------
@@ -0,0 +1,222 @@
1
+ """Generate the `[pre_push]` section of `.caddis/config.toml` from a repo's app-ci caller.
2
+
3
+ The pre-push gate must run the same fast checks as CI, with the same scope. For a repo whose
4
+ `.github/workflows/ci.yml` calls the shared app-ci workflow, this module reads the caller's pinned tag
5
+ and its `with:` inputs, and derives the check list. The hook reads only the TOML at push time; this
6
+ line parser runs once, at generation, where a failure is loud.
7
+
8
+ Stdlib only: no yaml import. Plan: `.caddis/plans/prepush-gate-matches-ci.md`, Phase 2.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import hashlib
14
+ import json
15
+ from pathlib import Path
16
+
17
+ # Match the workflow path and the `@` only. The owner/repo part is never named here (privacy scan).
18
+ APP_CI_SUFFIX = "/.github/workflows/app-ci.yml@"
19
+
20
+
21
+ def _indent(line: str) -> int:
22
+ return len(line) - len(line.lstrip(" "))
23
+
24
+
25
+ def _is_content(line: str) -> bool:
26
+ """True for a line that carries YAML content (not blank, not a whole-line comment)."""
27
+ stripped = line.strip()
28
+ return bool(stripped) and not stripped.startswith("#")
29
+
30
+
31
+ def _scalar(raw: str) -> str:
32
+ """A YAML scalar as a plain string: quotes removed, an inline `#` comment cut off."""
33
+ value = raw.strip()
34
+ if value.startswith("#"): # `key: # comment` is an empty value
35
+ return ""
36
+ if value[:1] in ("'", '"'):
37
+ quote = value[0]
38
+ end = value.find(quote, 1)
39
+ if end != -1:
40
+ return value[1:end]
41
+ return value[1:]
42
+ cut = value.find(" #")
43
+ if cut != -1:
44
+ value = value[:cut]
45
+ return value.strip()
46
+
47
+
48
+ def parse_app_ci_caller(text: str) -> tuple[str, dict[str, str]] | None:
49
+ """`(tag, with_inputs)` for the job that calls app-ci, or `None` when no job calls it.
50
+
51
+ Only the `with:` block of the job that holds the `uses:` line is read. Values are plain strings.
52
+ """
53
+ lines = text.replace("\r\n", "\n").split("\n")
54
+ uses_idx = None
55
+ tag = ""
56
+ for i, line in enumerate(lines):
57
+ stripped = line.strip()
58
+ if not stripped.startswith("uses:"):
59
+ continue
60
+ value = _scalar(stripped[len("uses:"):])
61
+ if APP_CI_SUFFIX in value:
62
+ uses_idx = i
63
+ tag = value.split("@", 1)[1].strip()
64
+ break
65
+ if uses_idx is None:
66
+ return None
67
+
68
+ key_indent = _indent(lines[uses_idx])
69
+ # The job header is the nearest content line above with a smaller indent.
70
+ start = 0
71
+ for j in range(uses_idx - 1, -1, -1):
72
+ if _is_content(lines[j]) and _indent(lines[j]) < key_indent:
73
+ start = j + 1
74
+ break
75
+ end = len(lines)
76
+ for j in range(uses_idx + 1, len(lines)):
77
+ if _is_content(lines[j]) and _indent(lines[j]) < key_indent:
78
+ end = j
79
+ break
80
+
81
+ inputs: dict[str, str] = {}
82
+ j = start
83
+ while j < end:
84
+ line = lines[j]
85
+ if _is_content(line) and _indent(line) == key_indent and line.strip().split("#", 1)[0].strip() == "with:":
86
+ child_indent = None
87
+ k = j + 1
88
+ while k < end:
89
+ child = lines[k]
90
+ if not _is_content(child):
91
+ k += 1
92
+ continue
93
+ ind = _indent(child)
94
+ if ind <= key_indent:
95
+ break
96
+ if child_indent is None:
97
+ child_indent = ind
98
+ if ind == child_indent and ":" in child:
99
+ key, raw = child.strip().split(":", 1)
100
+ inputs[key.strip()] = _scalar(raw)
101
+ k += 1
102
+ break
103
+ j += 1
104
+ return tag, inputs
105
+
106
+
107
+ def ci_caller_sha256(text: str) -> str:
108
+ """SHA-256 hex of the caller text with CRLF normalised to LF (an autocrlf checkout hashes the same)."""
109
+ return hashlib.sha256(text.replace("\r\n", "\n").encode("utf-8")).hexdigest()
110
+
111
+
112
+ # -- derivation ---------------------------------------------------------------------------------------
113
+
114
+ _PY_PATHS = ["src/", "tests/", "pyproject.toml"]
115
+
116
+
117
+ def _off(inputs: dict[str, str], key: str) -> bool:
118
+ return inputs.get(key, "").strip().lower() == "false"
119
+
120
+
121
+ def derive_checks(tag: str, inputs: dict[str, str], repo: Path) -> list[dict]:
122
+ """The pre-push checks app-ci v1.x runs for these caller inputs, in the plan's derivation-map order.
123
+
124
+ Never derived: pytest, frontend unit tests, build, the frontend hook, docs drift (PR only).
125
+ `measured_s` is not set: the rollout measures each check on this box. A tag outside app-ci v1
126
+ is an error, not a guess.
127
+ """
128
+ if not tag.startswith("app-ci-v1."):
129
+ raise ValueError(f"unknown app-ci version {tag!r}: this generator knows app-ci-v1.x only")
130
+ checks: list[dict] = [
131
+ {
132
+ "name": "ruff-check",
133
+ "ci_step": "ci / lint_and_test / Ruff lint",
134
+ "cwd": ".",
135
+ "argv": ["{py}", "-m", "ruff", "check", "src/", "tests/"],
136
+ "paths": list(_PY_PATHS),
137
+ "enabled": True,
138
+ },
139
+ {
140
+ "name": "ruff-format",
141
+ "ci_step": "ci / lint_and_test / Ruff format check",
142
+ "cwd": ".",
143
+ "argv": ["{py}", "-m", "ruff", "format", "--check", "src/", "tests/"],
144
+ "paths": list(_PY_PATHS),
145
+ "enabled": True,
146
+ },
147
+ ]
148
+ if not _off(inputs, "mypy"):
149
+ checks.append({
150
+ "name": "mypy",
151
+ "ci_step": "ci / lint_and_test / Mypy",
152
+ "cwd": ".",
153
+ "argv": ["{py}", "-m", "mypy", "src/"],
154
+ "paths": ["src/", "pyproject.toml"],
155
+ "enabled": True,
156
+ })
157
+ frontend = inputs.get("frontend", "").strip() == "required" or (repo / "frontend" / "package.json").is_file()
158
+ if frontend:
159
+ if not _off(inputs, "typescript_check"):
160
+ checks.append({
161
+ "name": "tsc",
162
+ "ci_step": "ci / frontend_checks / TypeScript check",
163
+ "cwd": "frontend",
164
+ "argv": ["npx", "tsc", "--noEmit"],
165
+ "paths": ["frontend/"],
166
+ "enabled": True,
167
+ })
168
+ lint_script = inputs.get("frontend_lint_script", "").strip()
169
+ checks.append({
170
+ "name": "eslint",
171
+ "ci_step": "ci / frontend_checks / ESLint",
172
+ "cwd": "frontend",
173
+ "argv": ["npm", "run", lint_script] if lint_script else ["npx", "eslint", "src/"],
174
+ "paths": ["frontend/"],
175
+ "enabled": True,
176
+ })
177
+ hook = inputs.get("checks_hook", "").strip()
178
+ if hook:
179
+ # App content: it may hold slow or test-like steps. The rollout enables it per repo after reading it.
180
+ checks.append({
181
+ "name": "checks-hook",
182
+ "ci_step": "ci / lint_and_test / App checks hook",
183
+ "cwd": ".",
184
+ "argv": ["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", hook],
185
+ "enabled": False,
186
+ })
187
+ return checks
188
+
189
+
190
+ # -- rendering ----------------------------------------------------------------------------------------
191
+
192
+
193
+ def _toml_value(value: object) -> str:
194
+ if isinstance(value, bool):
195
+ return "true" if value else "false"
196
+ if isinstance(value, (int, float)):
197
+ return repr(value)
198
+ if isinstance(value, str):
199
+ # A JSON string with ASCII escapes is a valid TOML basic string.
200
+ return json.dumps(value, ensure_ascii=True)
201
+ if isinstance(value, list):
202
+ return "[" + ", ".join(_toml_value(v) for v in value) + "]"
203
+ raise TypeError(f"cannot write {type(value).__name__} to TOML: {value!r}")
204
+
205
+
206
+ def render_pre_push_section(
207
+ checks: list[dict], *, source: str, derived_from: str, ci_sha256: str, budget_s: int = 30
208
+ ) -> str:
209
+ """The `[pre_push]` section as TOML text; `tomllib.loads` gives back the same check dicts."""
210
+ out = [
211
+ "[pre_push]",
212
+ f"source = {_toml_value(source)}",
213
+ f"derived_from = {_toml_value(derived_from)}",
214
+ f"ci_caller_sha256 = {_toml_value(ci_sha256)}",
215
+ f"budget_s = {_toml_value(budget_s)}",
216
+ ]
217
+ for check in checks:
218
+ out.append("")
219
+ out.append("[[pre_push.check]]")
220
+ for key, value in check.items():
221
+ out.append(f"{key} = {_toml_value(value)}")
222
+ return "\n".join(out) + "\n"