@caddis/cli 0.4.94 → 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.
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "name": "caddis",
3
- "version": "1.3.178",
3
+ "version": "1.3.179",
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
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schema": 1,
3
- "version": "1.3.177",
4
- "generated": "2026-11-04 23:23 UTC",
3
+ "version": "1.3.178",
4
+ "generated": "2026-11-05 01:42 UTC",
5
5
  "commands": [
6
6
  {
7
7
  "name": "add-rules",
@@ -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"
@@ -597,203 +597,517 @@ if __name__ == "__main__":
597
597
  '''
598
598
 
599
599
 
600
- # Enforced "green before push" gate. Installed into .git/hooks/pre-push. Pure POSIX sh
601
- # so it runs under Git's bundled shell on Windows/Linux/macOS.
602
- #
603
- # TOOLS RUN IN THE PROJECT'S OWN INTERPRETER, NOT WHATEVER IS ON PATH. This was a real
604
- # defect found by app-forge's dry run (2026-08-06): the gate resolved bare `pytest` and
605
- # `mypy` off PATH, which on Windows is the machine-wide C:\Python interpreter — so it
606
- # tested the app in an environment without the app's dependencies. Meanwhile `ruff` was
607
- # not on PATH at all and was silently skipped, even though the app had ruff in its venv.
608
- # It ran the two checks that could not work and skipped the one that would.
609
- #
610
- # A DECLARED-BUT-MISSING TOOL NOW BLOCKS. The old rule was "auto-skip anything not
611
- # installed", which is degrade-open: the gate reported success precisely when it had
612
- # checked the least. If a project asks for ruff in its pyproject and ruff cannot run,
613
- # that is a broken environment, not a project without linting — and a check that cannot
614
- # run must not report success. Tools the project never asked for are still skipped
615
- # silently, because those genuinely are not part of its standards.
600
+ # Pre-push gate v3 runner, installed as .git/hooks/caddis_prepush.py. The sh hook only finds an interpreter and execs it.
601
+ # It runs the [pre_push] checks of .caddis/config.toml (the fast checks the repo's CI runs) inside one time budget, by
602
+ # the runtime rules of .caddis/plans/prepush-gate-matches-ci.md. It reuses kill_process_tree and format_elapsed from
603
+ # caddis_gate_step.py and ci_caller_sha256 from caddis_prepush_config.py, both in the same hooks folder.
604
+ PRE_PUSH_RUNNER_PY = r'''#!/usr/bin/env python3
605
+ """caddis_prepush.py - the caddis pre-push gate (version 3).
606
+
607
+ Runs the [pre_push] checks of .caddis/config.toml within budget_s seconds. It blocks a push ONLY when a check that ran
608
+ fails, or when a check that should run cannot start. Every skip prints one line that names the check.
609
+ 'git push --no-verify' skips the gate once. Delete .git/hooks/pre-push to remove it.
610
+ """
611
+ from __future__ import annotations
612
+
613
+ import argparse
614
+ import os
615
+ import shutil
616
+ import subprocess
617
+ import sys
618
+ import tempfile
619
+ import time
620
+ from dataclasses import dataclass
621
+ from pathlib import Path
622
+
623
+ HERE = Path(__file__).resolve().parent
624
+ if str(HERE) not in sys.path:
625
+ sys.path.insert(0, str(HERE))
626
+
627
+ try: # one kill logic for the gate: the step runner installed in the same hooks folder
628
+ from caddis_gate_step import format_elapsed, kill_process_tree
629
+ except ImportError: # main() blocks with a re-install line
630
+ format_elapsed = kill_process_tree = None
631
+
632
+ try:
633
+ import tomllib
634
+ except ImportError: # Python < 3.11: main() prints one line and passes
635
+ tomllib = None
636
+
637
+ NO_VERIFY = "'git push --no-verify' overrides"
638
+ CONFIG_REL = ".caddis/config.toml"
639
+
640
+
641
+ @dataclass
642
+ class Check:
643
+ name: str
644
+ cwd: str
645
+ argv: list
646
+ paths: list | None
647
+ measured_s: float | None
648
+ enabled: bool
649
+ ci_step: str
650
+ venv: str | None
651
+
652
+
653
+ def _num(value: float) -> str:
654
+ return f"{value:g}"
655
+
656
+
657
+ def scripts_dir_hint() -> str | None:
658
+ """The caddis scripts folder named on the HOOK_SCRIPTS_DIR line of the pre-push hook next to this file, if any."""
659
+ hook = HERE / "pre-push"
660
+ try:
661
+ text = hook.read_text(encoding="utf-8", errors="ignore")
662
+ except OSError:
663
+ return None
664
+ for line in text.splitlines():
665
+ if line.startswith('HOOK_SCRIPTS_DIR="'):
666
+ value = line[len('HOOK_SCRIPTS_DIR="'):].rstrip().rstrip('"')
667
+ if value and not value.startswith("__"):
668
+ return value
669
+ return None
670
+
671
+
672
+ def no_section_line(scripts_dir: str | None) -> str:
673
+ where = scripts_dir or "<caddis scripts>"
674
+ return ("[gate] no [pre_push] section in .caddis/config.toml - nothing checked here, CI is the first gate. "
675
+ f'Create it: python "{where}/setup_project_ai.py" . --gate-config')
676
+
677
+
678
+ def load_checks(root: Path, config: Path | None = None):
679
+ """(header, checks) from the [pre_push] section, or None when the file or the section is missing.
680
+
681
+ Raises ValueError for a file that does not parse or a check without a name or argv: the caller blocks, because a
682
+ gate that cannot read its checks checks nothing."""
683
+ path = config if config is not None else root / CONFIG_REL
684
+ if not path.is_file():
685
+ return None
686
+ try:
687
+ data = tomllib.loads(path.read_text(encoding="utf-8"))
688
+ except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError) as exc:
689
+ raise ValueError(f"{path} cannot be read: {exc}") from exc
690
+ section = data.get("pre_push")
691
+ if not isinstance(section, dict):
692
+ return None
693
+ header = {k: v for k, v in section.items() if k != "check"}
694
+ raw = section.get("check", [])
695
+ if not isinstance(raw, list):
696
+ raise ValueError(f"{path}: [pre_push] check must be an array of tables ([[pre_push.check]])")
697
+ checks = []
698
+ for i, item in enumerate(raw):
699
+ name = item.get("name") if isinstance(item, dict) else None
700
+ argv = item.get("argv") if isinstance(item, dict) else None
701
+ if not isinstance(name, str) or not name or not isinstance(argv, list) or not argv \
702
+ or not all(isinstance(a, str) for a in argv):
703
+ raise ValueError(f"{path}: [[pre_push.check]] number {i + 1} needs a name and a non-empty argv list")
704
+ paths = item.get("paths")
705
+ if paths is not None and not (isinstance(paths, list) and all(isinstance(p, str) for p in paths)):
706
+ raise ValueError(f"{path}: check {name}: paths must be a list of strings")
707
+ measured = item.get("measured_s")
708
+ if measured is not None and (isinstance(measured, bool) or not isinstance(measured, (int, float))):
709
+ raise ValueError(f"{path}: check {name}: measured_s must be a number")
710
+ enabled = item.get("enabled", True)
711
+ if not isinstance(enabled, bool):
712
+ raise ValueError(f"{path}: check {name}: enabled must be true or false")
713
+ venv = item.get("venv")
714
+ checks.append(Check(name=name, cwd=str(item.get("cwd", ".")), argv=list(argv),
715
+ paths=[p[2:] if p.startswith("./") else p for p in paths] if paths else None,
716
+ measured_s=float(measured) if measured is not None else None,
717
+ enabled=enabled, ci_step=str(item.get("ci_step", "")),
718
+ venv=str(venv) if venv else None))
719
+ return header, checks
720
+
721
+
722
+ def decide(checks: list, changed: set | None, budget_s: float) -> list:
723
+ """[(check, None)] to run it, or [(check, skip line)] by rules 1-4. `changed` None = unknown: paths skip nothing."""
724
+ out = []
725
+ for c in checks:
726
+ line = None
727
+ if not c.enabled:
728
+ line = f"[skip] {c.name}: disabled in .caddis/config.toml"
729
+ elif c.measured_s is None:
730
+ line = f"[skip] {c.name}: not measured on this box yet - CI runs it"
731
+ elif c.measured_s > budget_s:
732
+ line = f"[skip] {c.name}: measured {_num(c.measured_s)}s, over the {_num(budget_s)}s budget - CI runs it"
733
+ elif c.paths and changed is not None and not any(f.startswith(p) for f in changed for p in c.paths):
734
+ line = f"[skip] {c.name}: no pushed change under {', '.join(c.paths)}"
735
+ out.append((c, line))
736
+ return out
737
+
738
+
739
+ def ci_caller_sha256(text: str) -> str:
740
+ from caddis_prepush_config import ci_caller_sha256 as sha # the generator's own hash: one implementation
741
+ return sha(text)
742
+
743
+
744
+ def ci_drift_warning(root: Path, header: dict) -> str | None:
745
+ """Rule 9: a warning line when ci.yml no longer hashes to ci_caller_sha256 (derived configs only). Never a block."""
746
+ expected = header.get("ci_caller_sha256") or ""
747
+ if header.get("source") != "app-ci" or not expected:
748
+ return None
749
+ ci = root / ".github" / "workflows" / "ci.yml"
750
+ try:
751
+ with ci.open(encoding="utf-8", newline="") as fh:
752
+ actual = ci_caller_sha256(fh.read())
753
+ except ImportError:
754
+ return "[gate] note: caddis_prepush_config.py is missing next to this hook - ci.yml drift not checked"
755
+ except (OSError, UnicodeDecodeError):
756
+ actual = ""
757
+ if actual == expected:
758
+ return None
759
+ return ("[gate] WARNING: .github/workflows/ci.yml changed since [pre_push] was derived - "
760
+ "re-derive with --gate-config --force")
761
+
762
+
763
+ def _git_out(root: Path, *args: str) -> str | None:
764
+ """stdout of a git command in `root`, or None when git fails or cannot start."""
765
+ try:
766
+ r = subprocess.run(["git", *args], cwd=str(root), capture_output=True, text=True, timeout=30,
767
+ stdin=subprocess.DEVNULL, check=False)
768
+ except (OSError, subprocess.SubprocessError):
769
+ return None
770
+ return r.stdout if r.returncode == 0 else None
771
+
772
+
773
+ def _is_zero(sha: str) -> bool:
774
+ return set(sha) == {"0"}
775
+
776
+
777
+ def changed_paths(stdin_text: str, root: Path) -> set | None:
778
+ """The files a push changes, from git's pre-push stdin (`<local ref> <local sha> <remote ref> <remote sha>`).
779
+
780
+ None = unknown (empty stdin, a line that is not a ref line, or any git failure): rule 4 then runs every check.
781
+ A delete line (local sha all zeros) adds nothing, so a push of deletes only gives the empty set. A new branch
782
+ (remote sha all zeros) diffs against its merge base with origin/HEAD, else origin/main."""
783
+ if stdin_text.strip() == "":
784
+ return None
785
+ changed: set = set()
786
+ for line in stdin_text.splitlines():
787
+ if not line.strip():
788
+ continue
789
+ parts = line.split()
790
+ if len(parts) != 4:
791
+ return None
792
+ _, local, _, remote = parts
793
+ if _is_zero(local):
794
+ continue
795
+ if _is_zero(remote):
796
+ base = None
797
+ for upstream in ("origin/HEAD", "origin/main"):
798
+ out = _git_out(root, "merge-base", local, upstream)
799
+ if out and out.strip():
800
+ base = out.strip()
801
+ break
802
+ if base is None:
803
+ return None
804
+ else:
805
+ base = remote
806
+ out = _git_out(root, "diff", "--name-only", "--no-renames", "-z", base, local)
807
+ if out is None:
808
+ return None
809
+ changed.update(p for p in out.split("\0") if p)
810
+ return changed
811
+
812
+
813
+ def in_linked_worktree(root: Path) -> bool:
814
+ """True in a linked git worktree (its git dir differs from the common dir). False outside a git checkout."""
815
+ git_dir = _git_out(root, "rev-parse", "--git-dir")
816
+ common = _git_out(root, "rev-parse", "--git-common-dir")
817
+ if not git_dir or not common:
818
+ return False
819
+ return (root / git_dir.strip()).resolve() != (root / common.strip()).resolve()
820
+
821
+
822
+ def _venv_candidates(check: Check, root: Path) -> list:
823
+ if check.venv:
824
+ base = root / check.venv
825
+ return [base / "Scripts" / "python.exe", base / "bin" / "python"]
826
+ cwd = root / check.cwd
827
+ found = [cwd / ".venv" / "Scripts" / "python.exe", cwd / ".venv" / "bin" / "python"]
828
+ if cwd.resolve() != root.resolve():
829
+ found += [root / ".venv" / "Scripts" / "python.exe", root / ".venv" / "bin" / "python"]
830
+ return found
831
+
832
+
833
+ def resolve_py(check: Check, root: Path, in_worktree: bool) -> tuple:
834
+ """(interpreter, message) for a {py} check (rule 7). The project venv first. A linked worktree with no venv gives
835
+ (None, block line): it never borrows the main checkout's venv or the system Python. The main checkout falls back to
836
+ python on PATH with a WARNING line."""
837
+ for cand in _venv_candidates(check, root):
838
+ if cand.is_file():
839
+ return str(cand), None
840
+ if in_worktree:
841
+ hint = scripts_dir_hint()
842
+ if hint and (Path(hint) / "caddis_worktree_root.py").is_file():
843
+ fix = f'python "{hint}/caddis_worktree_root.py" --bootstrap'
844
+ else:
845
+ fix = ('python "<caddis scripts>/caddis_worktree_root.py" --bootstrap '
846
+ "(the scripts folder of the installed caddis plugin)")
847
+ return None, (f"[gate] {check.name}: cannot start - this git worktree has no .venv, and the gate will not "
848
+ f"borrow the main checkout's or the system Python - {NO_VERIFY}\n"
849
+ f" fix, in this worktree: {fix}")
850
+ system = shutil.which("python") or shutil.which("python3")
851
+ if system:
852
+ return system, (f"[gate] WARNING: no .venv in this checkout - using the system Python ({system}). "
853
+ "Its packages may differ from the project's pins.")
854
+ return None, f"[gate] {check.name}: cannot start - no .venv and no python on PATH - {NO_VERIFY}"
855
+
856
+
857
+ def _resolve_argv0(arg0: str, cwd: Path) -> str | None:
858
+ """argv[0] as a full path. shutil.which also finds Windows .cmd launchers (npx, npm) that Popen cannot start by
859
+ bare name."""
860
+ if "/" in arg0 or "\\" in arg0:
861
+ p = Path(arg0)
862
+ return shutil.which(str(p if p.is_absolute() else cwd / p))
863
+ return shutil.which(arg0)
864
+
865
+
866
+ def _start(check: Check, root: Path, in_worktree: bool, said: set):
867
+ """(proc, output file, uses_py) or (None, block line, False)."""
868
+ uses_py = any("{py}" in a for a in check.argv)
869
+ py = None
870
+ if uses_py:
871
+ py, message = resolve_py(check, root, in_worktree)
872
+ if message and message not in said:
873
+ said.add(message)
874
+ print(message, file=sys.stderr, flush=True)
875
+ if py is None:
876
+ return None, None, False
877
+ argv = [a.replace("{runner_py}", sys.executable).replace("{py}", py or "") for a in check.argv]
878
+ cwd = root / check.cwd
879
+ exe = _resolve_argv0(argv[0], cwd)
880
+ if exe is None:
881
+ return None, f"[gate] {check.name}: cannot start - {argv[0]} not found - {NO_VERIFY}", False
882
+ argv[0] = exe
883
+ kwargs: dict = {}
884
+ if sys.platform == "win32":
885
+ kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
886
+ else:
887
+ kwargs["start_new_session"] = True
888
+ out = tempfile.TemporaryFile()
889
+ try:
890
+ proc = subprocess.Popen(argv, cwd=str(cwd), stdin=subprocess.DEVNULL, stdout=out, stderr=subprocess.STDOUT,
891
+ **kwargs)
892
+ except OSError as exc:
893
+ out.close()
894
+ return None, f"[gate] {check.name}: cannot start - {argv[0]}: {exc} - {NO_VERIFY}", False
895
+ return proc, out, uses_py
896
+
897
+
898
+ def run_checks(root: Path, checks: list, budget_s: float, jobs: int, *, changed: set | None = None,
899
+ start: float | None = None) -> int:
900
+ """Rules 1-7 and 10: skip by `decide`, run the rest `jobs` at a time (longest measured_s first) until one deadline.
901
+ 0 = pass, 1 = block."""
902
+ start = time.monotonic() if start is None else start
903
+ deadline = start + budget_s
904
+ decided = decide(checks, changed, budget_s)
905
+ skipped = 0
906
+ to_run = []
907
+ for check, line in decided:
908
+ if line is None:
909
+ to_run.append(check)
910
+ else:
911
+ print(line, flush=True)
912
+ skipped += 1
913
+ pending = sorted(to_run, key=lambda c: -(c.measured_s or 0.0))
914
+ in_worktree = any("{py}" in a for c in pending for a in c.argv) and in_linked_worktree(root)
915
+ running: list = []
916
+ failures: list = []
917
+ passed = 0
918
+ said: set = set()
919
+ jobs = max(1, jobs)
920
+ try:
921
+ while pending or running:
922
+ still = [] # poll first: a check that exited before the deadline counts as run, not as killed
923
+ for item in running:
924
+ check, proc, t0, out, uses_py = item
925
+ rc = proc.poll()
926
+ if rc is None:
927
+ still.append(item)
928
+ continue
929
+ took = format_elapsed(time.monotonic() - t0)
930
+ out.seek(0)
931
+ text = out.read().decode("utf-8", errors="replace")
932
+ out.close()
933
+ if rc == 0:
934
+ passed += 1
935
+ print(f"[gate] {check.name}: passed in {took}", flush=True)
936
+ continue
937
+ failures.append(check.name)
938
+ print(f"[gate] {check.name}: FAILED (exit {rc}) in {took}", file=sys.stderr, flush=True)
939
+ if text.strip():
940
+ print(text.rstrip(), file=sys.stderr, flush=True)
941
+ if uses_py and "No module named" in text:
942
+ print(f" fix: install the dev dependencies in the project venv (pip install -e \".[dev]\"), "
943
+ f"or run caddis_worktree_root.py --bootstrap - {NO_VERIFY}", file=sys.stderr, flush=True)
944
+ running = still
945
+ if not pending and not running:
946
+ break
947
+ now = time.monotonic()
948
+ if now >= deadline:
949
+ for check, proc, t0, out, _ in running:
950
+ kill_process_tree(proc)
951
+ out.close()
952
+ print(f"[gate] {check.name}: SKIPPED at the {_num(budget_s)}s budget "
953
+ f"(ran {format_elapsed(now - t0)}) - not checked here, CI runs it", flush=True)
954
+ skipped += 1
955
+ running = []
956
+ for check in pending:
957
+ print(f"[skip] {check.name}: no budget left - CI runs it", flush=True)
958
+ skipped += 1
959
+ pending = []
960
+ break
961
+ while pending and len(running) < jobs:
962
+ check = pending.pop(0)
963
+ proc, out, uses_py = _start(check, root, in_worktree, said)
964
+ if proc is None:
965
+ if out:
966
+ print(out, file=sys.stderr, flush=True)
967
+ failures.append(check.name)
968
+ continue
969
+ print(f"[gate] {check.name}: start", flush=True)
970
+ running.append((check, proc, time.monotonic(), out, uses_py))
971
+ if running:
972
+ time.sleep(0.05)
973
+ finally: # Ctrl+C or any error: no check tree outlives the gate
974
+ for _, proc, _, out, _ in running:
975
+ if proc.poll() is None:
976
+ kill_process_tree(proc)
977
+ out.close()
978
+ if failures:
979
+ print(f"[caddis] push BLOCKED - {', '.join(failures)} failed or could not start - {NO_VERIFY}",
980
+ file=sys.stderr, flush=True)
981
+ return 1
982
+ print(f"[caddis] gate passed - {passed} checked, {skipped} skipped (CI runs them)", flush=True)
983
+ return 0
984
+
985
+
986
+ def _env_number(name: str, default: float, cast):
987
+ raw = os.environ.get(name, "").strip()
988
+ if not raw:
989
+ return default
990
+ try:
991
+ value = cast(raw)
992
+ except ValueError:
993
+ value = 0
994
+ if not (0 < value < float("inf")): # also rejects nan: a deadline that never comes
995
+ print(f"[gate] warning: {name}={raw!r} is not a positive number - using {_num(default)}", file=sys.stderr,
996
+ flush=True)
997
+ return default
998
+ return value
999
+
1000
+
1001
+ def _read_stdin() -> str:
1002
+ try:
1003
+ if sys.stdin is None or sys.stdin.isatty():
1004
+ return ""
1005
+ return sys.stdin.read()
1006
+ except (OSError, ValueError):
1007
+ return ""
1008
+
1009
+
1010
+ def main(argv: list | None = None) -> int:
1011
+ start = time.monotonic()
1012
+ parser = argparse.ArgumentParser(prog="caddis_prepush.py", description="caddis pre-push gate (version 3)")
1013
+ parser.add_argument("remote", nargs="?", help="remote name (git passes it; not used)")
1014
+ parser.add_argument("url", nargs="?", help="remote URL (git passes it; not used)")
1015
+ parser.add_argument("--root", help="repo root (default: git rev-parse --show-toplevel, else the cwd)")
1016
+ parser.add_argument("--config", help="config file (default: <root>/.caddis/config.toml)")
1017
+ args = parser.parse_args(argv)
1018
+ print("[caddis] pre-push quality gate", flush=True)
1019
+ if tomllib is None:
1020
+ print(f"[gate] this gate needs Python 3.11 or later (found {sys.version.split()[0]}) - nothing checked here, "
1021
+ "CI is the first gate.", flush=True)
1022
+ return 0
1023
+ if kill_process_tree is None:
1024
+ print("[gate] caddis_gate_step.py is missing next to this hook - re-install the gate with "
1025
+ "setup_project_ai.py . --hooks-only", file=sys.stderr, flush=True)
1026
+ print(f"[caddis] push BLOCKED - {NO_VERIFY}", file=sys.stderr, flush=True)
1027
+ return 1
1028
+ if os.environ.get("CADDIS_GATE_PYTEST", "") == "1":
1029
+ print("[gate] note: CADDIS_GATE_PYTEST is no longer used - pytest runs in CI", flush=True)
1030
+ if args.root:
1031
+ root = Path(args.root)
1032
+ else:
1033
+ top = _git_out(Path.cwd(), "rev-parse", "--show-toplevel")
1034
+ root = Path(top.strip()) if top and top.strip() else Path.cwd()
1035
+ root = root.resolve()
1036
+ try:
1037
+ loaded = load_checks(root, Path(args.config) if args.config else None)
1038
+ except ValueError as exc:
1039
+ print(f"[gate] {exc}", file=sys.stderr, flush=True)
1040
+ print(f"[caddis] push BLOCKED - fix .caddis/config.toml - {NO_VERIFY}", file=sys.stderr, flush=True)
1041
+ return 1
1042
+ if loaded is None:
1043
+ print(no_section_line(scripts_dir_hint()), flush=True)
1044
+ return 0
1045
+ header, checks = loaded
1046
+ warning = ci_drift_warning(root, header)
1047
+ if warning:
1048
+ print(warning, file=sys.stderr, flush=True)
1049
+ budget = header.get("budget_s", 30)
1050
+ if isinstance(budget, bool) or not isinstance(budget, (int, float)) or not (0 < budget < float("inf")):
1051
+ print(f"[gate] warning: budget_s = {budget!r} in [pre_push] is not a positive number - using 30",
1052
+ file=sys.stderr, flush=True)
1053
+ budget = 30
1054
+ budget = _env_number("CADDIS_GATE_BUDGET_S", float(budget), float)
1055
+ jobs = _env_number("CADDIS_GATE_JOBS", 3, int)
1056
+ changed = changed_paths(_read_stdin(), root)
1057
+ return run_checks(root, checks, budget, jobs, changed=changed, start=start)
1058
+
1059
+
1060
+ if __name__ == "__main__":
1061
+ sys.exit(main())
1062
+ '''
1063
+
1064
+
1065
+ # Enforced "green before push" gate, installed into .git/hooks/pre-push. Pure POSIX sh, so it runs under Git's bundled
1066
+ # shell on Windows, Linux and macOS. Version 3 (2026-11-04) only finds an interpreter and execs the Python runner
1067
+ # (PRE_PUSH_RUNNER_PY, .git/hooks/caddis_prepush.py), which runs the [pre_push] checks of .caddis/config.toml: the
1068
+ # fast checks the repo's CI runs, with CI's scope, inside one time budget. The checks it no longer runs (`ruff check .`,
1069
+ # `mypy .`, the root package.json scripts, `npm test`, check_doc_coverage.py, the CADDIS_GATE_PYTEST opt-in) are not
1070
+ # what CI runs, or are tests. Interpreter and worktree rules for the checks live in the runner (rule 7 of
1071
+ # .caddis/plans/prepush-gate-matches-ci.md): the sh text has no venv check, so a push that needs no venv never asks for one.
616
1072
  # Bump when the hook text changes in a way an installed copy should pick up. install_git_hooks replaces a managed hook
617
1073
  # whose "caddis-pre-push-version" is lower (a hook with no marker counts as 0) and leaves a hook it does not manage alone.
618
- PRE_PUSH_HOOK_VERSION = 2
1074
+ PRE_PUSH_HOOK_VERSION = 3
619
1075
  _HOOK_SCRIPTS_PLACEHOLDER = "__CADDIS_SCRIPTS__"
620
1076
 
621
1077
  PRE_PUSH_HOOK = r"""#!/usr/bin/env sh
622
1078
  # Managed by caddis setup-project-ai. Delete this file to opt out.
623
- # caddis-pre-push-version: 2
1079
+ # caddis-pre-push-version: 3
1080
+ # Runs the [pre_push] checks of .caddis/config.toml (the fast checks CI runs) within a time budget.
1081
+ # 'git push --no-verify' skips it once.
624
1082
  set -eu
625
- echo "[caddis] pre-push quality gate"
626
- fail=0
1083
+ HOOK_SCRIPTS_DIR="__CADDIS_SCRIPTS__"
627
1084
  if command -v dirname >/dev/null 2>&1; then
628
- GATE_RUN="$(dirname "$0")/caddis_gate_step.py"
1085
+ HOOK_DIR="$(dirname "$0")"
629
1086
  elif [ -n "${0%/*}" ] && [ "${0%/*}" != "$0" ]; then
630
- GATE_RUN="${0%/*}/caddis_gate_step.py"
1087
+ HOOK_DIR="${0%/*}"
631
1088
  else
632
- GATE_RUN="./caddis_gate_step.py"
633
- fi
634
-
635
- # Use the project's own virtualenv, never whatever is on PATH. Both layouts are checked (Windows Scripts/, POSIX bin/).
636
- # A linked git WORKTREE uses ONLY its own .venv. The main checkout's venv is not an option: it belongs to a running
637
- # dev service and is often many commits behind the worktree's pins (found 2026-11-03: rbac-kit 0.2.0 against a 0.3.1
638
- # pin; the old lookup list also held a literal backslash-n typo). Every worktree installs its dependencies fresh.
639
- HOOK_SCRIPTS_DIR="__CADDIS_SCRIPTS__"
640
- PY=""
641
- IN_WORKTREE=0
642
- if [ "$(git rev-parse --git-dir 2>/dev/null || echo .git)" != "$(git rev-parse --git-common-dir 2>/dev/null || echo .git)" ]; then
643
- IN_WORKTREE=1
644
- fi
645
- for cand in .venv/Scripts/python.exe .venv/bin/python venv/Scripts/python.exe venv/bin/python; do
646
- if [ -x "$cand" ]; then PY="$cand"; break; fi
647
- done
648
- if [ -z "$PY" ] && [ "$IN_WORKTREE" -eq 0 ]; then
649
- PY=$(command -v python || command -v python3 || true)
650
- if [ -n "$PY" ] && { [ -f "pyproject.toml" ] || [ -f "requirements.txt" ]; }; then
651
- echo "[gate] WARNING: no .venv in this checkout - using the system Python ($PY). Its packages may differ from the project's pins." >&2
652
- fi
1089
+ HOOK_DIR="."
653
1090
  fi
654
1091
 
655
- # Runnable IN $PY - not merely present on PATH. This is the whole point: `command -v mypy`
656
- # answers a question about PATH, and the question we care about is about the environment
657
- # the app's code actually imports from.
658
- py_has() { [ -n "$PY" ] && "$PY" -m "$1" --version >/dev/null 2>&1; }
659
- # Does the project ASK for this tool? If so, being unable to run it is a failure.
660
- py_wants() { grep -qi -- "$1" pyproject.toml requirements.txt requirements-dev.txt 2>/dev/null; }
661
-
662
- # Does this project actually contain Python source? A pyproject.toml alone does not mean it
663
- # does - a config-only or frontend repo can carry one - and mypy exits non-zero with "There
664
- # are no .py[i] files in directory" when handed nothing. Skipping a checker that has nothing
665
- # to check is honest; failing the push over it is not.
666
- py_sources_exist() {
667
- [ -n "$(find . -name '*.py' -not -path './.venv/*' -not -path './venv/*' -not -path './node_modules/*' -not -path './.git/*' 2>/dev/null | head -1)" ]
668
- }
669
-
670
- py_gate() {
671
- tool=$1; shift
672
- timeout=300
673
- case "$tool" in
674
- ruff) timeout=300 ;;
675
- mypy) timeout=600 ;;
676
- pytest) timeout=1200 ;;
677
- esac
678
- if py_has "$tool"; then
679
- rc=0
680
- if [ -f "$GATE_RUN" ]; then
681
- "$PY" "$GATE_RUN" --name "$tool" --timeout "$timeout" -- "$PY" -m "$tool" "$@" || rc=$?
682
- else
683
- echo "[gate] $tool $*"
684
- "$PY" -m "$tool" "$@" || rc=$?
685
- fi
686
- if [ "$rc" -ne 0 ]; then
687
- # pytest exit 5 = "no tests collected". A repo that has not written tests yet is not a
688
- # failing repo, and blocking it would hit exactly the fresh-scaffold case this fix exists
689
- # for. Every other non-zero code is a real failure.
690
- if [ "$tool" = "pytest" ] && [ "$rc" -eq 5 ]; then
691
- echo "[gate] pytest: no tests collected yet - not treated as a failure"
692
- else
693
- fail=1
694
- fi
695
- fi
696
- elif py_wants "$tool"; then
697
- echo "[gate] $tool: DECLARED by this project but not runnable in $PY - environment is broken" >&2
698
- echo " fix: activate the venv, or reinstall dev deps (pip install -e '.[dev]')" >&2
699
- fail=1
700
- fi
701
- }
702
-
703
- if [ -f "pyproject.toml" ] || [ -f "requirements.txt" ]; then
704
- if [ -z "$PY" ] && [ "$IN_WORKTREE" -eq 1 ]; then
705
- echo "[gate] this git worktree has no .venv, and the gate will not borrow the main checkout's or the system Python." >&2
706
- if [ -f "$HOOK_SCRIPTS_DIR/caddis_worktree_root.py" ]; then
707
- echo " fix, in this worktree: python \"$HOOK_SCRIPTS_DIR/caddis_worktree_root.py\" --bootstrap" >&2
708
- else
709
- echo " fix, in this worktree: python \"<caddis scripts>/caddis_worktree_root.py\" --bootstrap (the scripts folder of the installed caddis plugin)" >&2
710
- fi
711
- echo "[caddis] push BLOCKED - 'git push --no-verify' overrides." >&2
712
- exit 1
713
- elif [ -z "$PY" ]; then
714
- echo "[gate] python project, but no interpreter found (.venv or PATH) - cannot verify" >&2
715
- fail=1
716
- else
717
- echo "[gate] interpreter: $PY"
718
- py_gate ruff check .
719
- if py_sources_exist; then py_gate mypy .; else echo "[skip] mypy: no Python sources"; fi
720
- # pytest is OPT-IN here (CADDIS_GATE_PYTEST=1). Found 2026-10-10: the full suite took 25-31 min in this
721
- # hook on a box whose system disk was slow, while CI ran the same suite in 5 min - and a merge needs green
722
- # CI anyway. A local gate five times slower than the check it stands in for trains people to --no-verify it.
723
- # When it does run: CADDIS_GATE_TMP moves TMPDIR/TEMP/TMP (tests write to tmp_path; Python reads TMPDIR
724
- # first, so set all three), CADDIS_GATE_PYTEST_ARGS adds arguments (for example "-n 4" with pytest-xdist;
725
- # use a number, not "auto"), and a machine-wide lock (CADDIS_GATE_LOCK, mkdir-based, waits up to
726
- # CADDIS_GATE_LOCK_WAIT seconds, a stale one is taken over after 60 min) lets only ONE pytest gate run at a time, so several repos pushing together cannot
727
- # pile their suites on the same disk and CI runners.
728
- if [ "${CADDIS_GATE_PYTEST:-0}" = "1" ]; then
729
- if [ -n "${CADDIS_GATE_TMP:-}" ]; then
730
- mkdir -p "$CADDIS_GATE_TMP" 2>/dev/null || true
731
- export TMPDIR="$CADDIS_GATE_TMP" TEMP="$CADDIS_GATE_TMP" TMP="$CADDIS_GATE_TMP"
732
- fi
733
- LOCK="${CADDIS_GATE_LOCK:-${TMPDIR:-${TEMP:-/tmp}}/caddis-pytest-gate.lock}"
734
- mkdir -p "$(dirname "$LOCK")" 2>/dev/null || true
735
- lock_wait="${CADDIS_GATE_LOCK_WAIT:-1800}"
736
- waited=0
737
- got_lock=0
738
- while :; do
739
- if mkdir "$LOCK" 2>/dev/null; then got_lock=1; break; fi
740
- # A stale lock is removed, then this round still sleeps and counts: if the removal fails (a lock owned
741
- # by another user), the loop ends at lock_wait instead of spinning forever.
742
- if [ -n "$(find "$LOCK" -maxdepth 0 -mmin +60 2>/dev/null)" ]; then
743
- rmdir "$LOCK" 2>/dev/null || true
744
- fi
745
- if [ "$waited" -ge "$lock_wait" ]; then break; fi
746
- if [ "$waited" -eq 0 ]; then echo "[gate] pytest: waiting for another repo's pytest gate ($LOCK)"; fi
747
- sleep 1
748
- waited=$((waited + 1))
749
- done
750
- if [ "$got_lock" -eq 1 ]; then
751
- trap 'rmdir "$LOCK" 2>/dev/null || true' EXIT INT TERM
752
- # shellcheck disable=SC2086 # CADDIS_GATE_PYTEST_ARGS is meant to word-split
753
- py_gate pytest -q ${CADDIS_GATE_PYTEST_ARGS:-}
754
- rmdir "$LOCK" 2>/dev/null || true
755
- trap - EXIT INT TERM
756
- else
757
- echo "[gate] pytest: another pytest gate holds $LOCK for over ${lock_wait}s - cannot run, so the gate fails" >&2
758
- fail=1
759
- fi
760
- else
761
- echo "[skip] pytest: runs in CI (set CADDIS_GATE_PYTEST=1 to run it here)"
762
- fi
763
- fi
764
- fi
765
- if [ -f "package.json" ] && command -v npm >/dev/null 2>&1; then
766
- if [ -f "$GATE_RUN" ] && [ -n "$PY" ]; then
767
- npm run 2>/dev/null | grep -q " lint" && { "$PY" "$GATE_RUN" --name npm-lint --timeout 600 -- npm run lint --silent || fail=1; }
768
- npm run 2>/dev/null | grep -q " typecheck" && { "$PY" "$GATE_RUN" --name npm-typecheck --timeout 600 -- npm run typecheck --silent || fail=1; }
769
- npm run 2>/dev/null | grep -q " test" && { "$PY" "$GATE_RUN" --name npm-test --timeout 1200 -- npm test --silent || fail=1; }
770
- else
771
- npm run 2>/dev/null | grep -q " lint" && { echo "[gate] npm run lint"; npm run lint --silent || fail=1; }
772
- npm run 2>/dev/null | grep -q " typecheck" && { echo "[gate] npm run typecheck"; npm run typecheck --silent || fail=1; }
773
- npm run 2>/dev/null | grep -q " test" && { echo "[gate] npm test"; npm test --silent || fail=1; }
774
- fi
1092
+ # The interpreter for the RUNNER only (it needs Python 3.11+ for tomllib; an older one prints a line and passes).
1093
+ # CADDIS_PREPUSH_PYTHON pins it; else python, then python3, on PATH.
1094
+ PYRUN=""
1095
+ if [ -n "${CADDIS_PREPUSH_PYTHON:-}" ] && [ -x "$CADDIS_PREPUSH_PYTHON" ]; then
1096
+ PYRUN="$CADDIS_PREPUSH_PYTHON"
1097
+ else
1098
+ PYRUN=$(command -v python || command -v python3 || true)
775
1099
  fi
776
- # Doc-coverage discipline (any stack). The checker exits non-zero ONLY on a hard invariant
777
- # (missing route / dangling doc-map link); soft signals warn without failing. Auto-skips when the
778
- # checker isn't present (older repos). Reuses $PY - resolved above with the project venv preferred -
779
- # rather than re-probing PATH, so it reads the same tree the rest of the gate does.
780
- if [ -f "scripts/check_doc_coverage.py" ]; then
781
- DOC_PY="$PY"
782
- if [ -z "$DOC_PY" ]; then DOC_PY=$(command -v python || command -v python3 || true); fi
783
- if [ -n "$DOC_PY" ]; then
784
- if [ -f "$GATE_RUN" ]; then
785
- "$DOC_PY" "$GATE_RUN" --name doc-coverage --timeout 120 -- "$DOC_PY" scripts/check_doc_coverage.py --check || fail=1
786
- else
787
- echo "[gate] doc coverage"
788
- "$DOC_PY" scripts/check_doc_coverage.py --check || fail=1
789
- fi
790
- fi
1100
+ if [ -z "$PYRUN" ]; then
1101
+ echo "[gate] no python on PATH to run the pre-push gate (set CADDIS_PREPUSH_PYTHON to pin one)" >&2
1102
+ echo "[caddis] push BLOCKED - 'git push --no-verify' overrides." >&2
1103
+ exit 1
791
1104
  fi
792
- if [ "$fail" -ne 0 ]; then
793
- echo "[caddis] push BLOCKED - fix the above, or 'git push --no-verify' to override." >&2
1105
+ if [ ! -f "$HOOK_DIR/caddis_prepush.py" ]; then
1106
+ echo "[gate] $HOOK_DIR/caddis_prepush.py is missing - re-install: python \"$HOOK_SCRIPTS_DIR/setup_project_ai.py\" . --hooks-only" >&2
1107
+ echo "[caddis] push BLOCKED - 'git push --no-verify' overrides." >&2
794
1108
  exit 1
795
1109
  fi
796
- echo "[caddis] gate passed - pushing."
1110
+ exec "$PYRUN" "$HOOK_DIR/caddis_prepush.py" "$@"
797
1111
  """
798
1112
 
799
1113
 
@@ -815,13 +1129,63 @@ def _installed_hook_state(hook_text: str) -> tuple[bool, int]:
815
1129
  return True, int(m.group(1)) if m else 0
816
1130
 
817
1131
 
818
- def install_git_hooks(target: Path, force: bool, dry: bool) -> list[str]:
819
- """Install the enforced pre-push quality gate into .git/hooks/pre-push.
1132
+ _NO_PRE_PUSH_NOTE = ("pre-push gate: installed, but .caddis/config.toml has no [pre_push] section - it checks nothing "
1133
+ "until you run --gate-config")
1134
+
820
1135
 
821
- An existing caddis-managed hook is replaced when its version is older than PRE_PUSH_HOOK_VERSION and kept when it is
822
- current. A hook caddis did not write is left alone unless `force`. Git shares `.git/hooks` with every worktree of the
823
- repo, so one install in the main checkout covers them all."""
1136
+ def _hook_companions() -> tuple[dict[str, str], list[str]]:
1137
+ """The files the v3 hook needs next to it in .git/hooks, as {name: text}, and notes for any that cannot be had.
1138
+
1139
+ `caddis_prepush_config.py` is copied from this scripts folder: the runner imports `ci_caller_sha256` from it (one
1140
+ implementation). Without it the runner prints a note and skips only the ci.yml drift check, so it is not fatal."""
1141
+ files = {"caddis_prepush.py": PRE_PUSH_RUNNER_PY, "caddis_gate_step.py": GATE_STEP_PY}
824
1142
  notes: list[str] = []
1143
+ src = Path(__file__).resolve().parent / "caddis_prepush_config.py"
1144
+ try:
1145
+ files["caddis_prepush_config.py"] = src.read_text(encoding="utf-8")
1146
+ except OSError as exc:
1147
+ notes.append(f"pre-push gate: cannot copy {src.name} ({exc}) - the gate runs, but ci.yml drift is not checked")
1148
+ return files, notes
1149
+
1150
+
1151
+ def _pre_push_section_note(target: Path) -> str | None:
1152
+ """A note when the gate would check nothing (no `[pre_push]` table) or block every push (unreadable config)."""
1153
+ cfg = target / ".caddis" / "config.toml"
1154
+ if not cfg.is_file():
1155
+ return _NO_PRE_PUSH_NOTE
1156
+ try:
1157
+ text = cfg.read_text(encoding="utf-8")
1158
+ except (OSError, UnicodeDecodeError) as exc:
1159
+ return f"pre-push gate: installed, but cannot read .caddis/config.toml ({exc}) - the gate blocks every push until it is fixed"
1160
+ try:
1161
+ import tomllib
1162
+ except ModuleNotFoundError: # Python < 3.11 runs setup: look for the header only
1163
+ has_table = any(_is_pre_push_header(line) for line in text.splitlines())
1164
+ return None if has_table else _NO_PRE_PUSH_NOTE
1165
+ try:
1166
+ data = tomllib.loads(text)
1167
+ except tomllib.TOMLDecodeError as exc:
1168
+ return f"pre-push gate: installed, but cannot read .caddis/config.toml ({exc}) - the gate blocks every push until it is fixed"
1169
+ return None if isinstance(data.get("pre_push"), dict) else _NO_PRE_PUSH_NOTE
1170
+
1171
+
1172
+ def _write_hook_file(path: Path, text: str) -> None:
1173
+ path.write_text(text, encoding="utf-8", newline="\n")
1174
+ try:
1175
+ import stat
1176
+ path.chmod(path.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
1177
+ except OSError:
1178
+ pass # no exec bits on this filesystem; git for Windows runs the hook anyway
1179
+
1180
+
1181
+ def install_git_hooks(target: Path, force: bool, dry: bool) -> list[str]:
1182
+ """Install the enforced pre-push quality gate: .git/hooks/pre-push and the files it runs next to it.
1183
+
1184
+ An existing caddis-managed hook is replaced when its version is older than PRE_PUSH_HOOK_VERSION. A current one is
1185
+ kept, but a missing or different companion file is written again (a v3 hook without caddis_prepush.py blocks every
1186
+ push). A hook caddis did not write is left alone unless `force`. Git shares `.git/hooks` with every worktree of the
1187
+ repo, so one install in the main checkout covers them all. A note says when `.caddis/config.toml` has no
1188
+ `[pre_push]` section, because the gate then checks nothing."""
825
1189
  git = target / ".git"
826
1190
  if not git.exists():
827
1191
  return ["pre-push gate: no .git (not a git repo) — skipped"]
@@ -829,31 +1193,125 @@ def install_git_hooks(target: Path, force: bool, dry: bool) -> list[str]:
829
1193
  return ["pre-push gate: .git is a worktree pointer — skipped (install manually if wanted)"]
830
1194
  hooks_dir = git / "hooks"
831
1195
  dest = hooks_dir / "pre-push"
832
- step_dest = hooks_dir / "caddis_gate_step.py"
1196
+ companions, notes = _hook_companions()
833
1197
  upgraded_from: int | None = None
834
1198
  if dest.exists() and not force:
835
1199
  managed, version = _installed_hook_state(dest.read_text(encoding="utf-8", errors="ignore"))
836
1200
  if not managed:
837
1201
  return ["pre-push gate: exists (yours — left intact, use --force to replace) — skipped"]
838
1202
  if version >= PRE_PUSH_HOOK_VERSION:
839
- return [f"pre-push gate: exists (ours) at version {version}, current — skipped"]
1203
+ stale = [name for name, text in companions.items() if not _same_text(hooks_dir / name, text)]
1204
+ if stale and not dry:
1205
+ for name in stale:
1206
+ _write_hook_file(hooks_dir / name, companions[name])
1207
+ if stale:
1208
+ notes.append(f"pre-push gate: exists (ours) at version {version}, current - repaired {', '.join(stale)}")
1209
+ else:
1210
+ notes.append(f"pre-push gate: exists (ours) at version {version}, current — skipped")
1211
+ section = _pre_push_section_note(target)
1212
+ return notes + ([section] if section else [])
840
1213
  upgraded_from = version
841
1214
  if not dry:
842
1215
  hooks_dir.mkdir(parents=True, exist_ok=True)
843
- dest.write_text(render_pre_push_hook(), encoding="utf-8", newline="\n")
844
- step_dest.write_text(GATE_STEP_PY, encoding="utf-8", newline="\n")
845
- try:
846
- import stat
847
- dest.chmod(dest.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
848
- step_dest.chmod(step_dest.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
849
- except Exception:
850
- pass
1216
+ _write_hook_file(dest, render_pre_push_hook())
1217
+ for name, text in companions.items():
1218
+ _write_hook_file(hooks_dir / name, text)
851
1219
  if upgraded_from is not None:
852
- notes.append(f"pre-push gate: upgraded .git/hooks/pre-push (version {upgraded_from} -> {PRE_PUSH_HOOK_VERSION}) "
853
- "and caddis_gate_step.py (green-before-push enforced)")
1220
+ head = f".git/hooks/pre-push (version {upgraded_from} -> {PRE_PUSH_HOOK_VERSION})"
1221
+ notes.append(f"pre-push gate: upgraded {_and_list([head, *companions])} (green-before-push enforced)")
854
1222
  else:
855
- notes.append("pre-push gate: installed .git/hooks/pre-push and caddis_gate_step.py (green-before-push enforced)")
856
- return notes
1223
+ notes.append(f"pre-push gate: installed {_and_list(['.git/hooks/pre-push', *companions])} "
1224
+ "(green-before-push enforced)")
1225
+ section = _pre_push_section_note(target)
1226
+ return notes + ([section] if section else [])
1227
+
1228
+
1229
+ def _and_list(items: list[str]) -> str:
1230
+ """'a', 'a and b', 'a, b and c'."""
1231
+ return items[0] if len(items) == 1 else ", ".join(items[:-1]) + " and " + items[-1]
1232
+
1233
+
1234
+ def _same_text(path: Path, text: str) -> bool:
1235
+ try:
1236
+ return path.read_text(encoding="utf-8") == text
1237
+ except (OSError, UnicodeDecodeError):
1238
+ return False
1239
+
1240
+
1241
+ # Anchored at the end so a line of a multi-line array (` ["a", "b"],`) is not read as a header.
1242
+ _TOML_HEADER_RE = re.compile(r"^\s*\[\[?\s*([^\]]+?)\s*\]\]?\s*(?:#.*)?$")
1243
+
1244
+
1245
+ def _is_pre_push_header(line: str) -> bool | None:
1246
+ """True for a `[pre_push]` / `[pre_push.x]` / `[[pre_push.x]]` header, False for another header, None for no header."""
1247
+ m = _TOML_HEADER_RE.match(line)
1248
+ if not m:
1249
+ return None
1250
+ name = m.group(1)
1251
+ return name == "pre_push" or name.startswith("pre_push.")
1252
+
1253
+
1254
+ def _remove_pre_push_tables(text: str) -> str:
1255
+ """`text` without any `[pre_push*]` table. Each table runs to the next other header or end of file."""
1256
+ kept: list[str] = []
1257
+ inside = False
1258
+ for line in text.splitlines(keepends=True):
1259
+ header = _is_pre_push_header(line)
1260
+ if header is not None:
1261
+ inside = header
1262
+ if not inside:
1263
+ kept.append(line)
1264
+ return "".join(kept)
1265
+
1266
+
1267
+ def write_pre_push_config(target: Path, force: bool, dry: bool) -> list[str]:
1268
+ """Append a `[pre_push]` section derived from `.github/workflows/ci.yml` to `.caddis/config.toml`.
1269
+
1270
+ Other sections are never rewritten. An existing `[pre_push]` is kept unless `force`, which removes every
1271
+ `[pre_push*]` table first. `dry` returns the section text and writes nothing. Raises `ValueError` for an
1272
+ app-ci tag this generator does not know (it stops, it does not guess).
1273
+ """
1274
+ here = str(Path(__file__).resolve().parent)
1275
+ if here not in sys.path:
1276
+ sys.path.insert(0, here)
1277
+ import caddis_prepush_config as pcfg
1278
+
1279
+ ci = target / ".github" / "workflows" / "ci.yml"
1280
+ manual = 'write [pre_push] by hand (source = "manual")'
1281
+ if not ci.is_file():
1282
+ return [f"pre-push config: no .github/workflows/ci.yml - {manual}"]
1283
+ ci_text = ci.read_text(encoding="utf-8")
1284
+ parsed = pcfg.parse_app_ci_caller(ci_text)
1285
+ if parsed is None:
1286
+ return [f"pre-push config: ci.yml does not call app-ci - {manual}"]
1287
+ tag, inputs = parsed
1288
+ checks = pcfg.derive_checks(tag, inputs, target)
1289
+ section = pcfg.render_pre_push_section(checks, source="app-ci", derived_from=tag,
1290
+ ci_sha256=pcfg.ci_caller_sha256(ci_text))
1291
+
1292
+ config = target / ".caddis" / "config.toml"
1293
+ existing = ""
1294
+ if config.is_file():
1295
+ with config.open(encoding="utf-8", newline="") as fh: # keep CRLF as is: other sections stay byte-identical
1296
+ existing = fh.read()
1297
+ has_section = any(_is_pre_push_header(line) for line in existing.splitlines())
1298
+ if has_section and not force:
1299
+ return ["pre-push config: [pre_push] exists - skipped (--force replaces it)"]
1300
+ if dry:
1301
+ return [f"pre-push config: would write [pre_push] to {config} (dry-run):", *section.splitlines()]
1302
+ base = _remove_pre_push_tables(existing) if has_section else existing
1303
+ eol = "\r\n" if "\r\n" in existing else "\n"
1304
+ if has_section:
1305
+ base = base.rstrip("\r\n") # one blank line before the new section, however many --force runs
1306
+ base = base + eol if base else base
1307
+ elif base and not base.endswith(("\n", "\r")):
1308
+ base += eol
1309
+ if base.strip():
1310
+ base += eol
1311
+ config.parent.mkdir(parents=True, exist_ok=True)
1312
+ config.write_text(base + section.replace("\n", eol), encoding="utf-8", newline="")
1313
+ verb = "replaced" if has_section else "wrote"
1314
+ return [f"pre-push config: {verb} [pre_push] in {config} ({len(checks)} checks from {tag})"]
857
1315
 
858
1316
 
859
1317
  def emit_doc_discipline(target: Path, ident: dict[str, str], force: bool, dry: bool) -> list[str]:
@@ -1860,6 +2318,10 @@ def main() -> int:
1860
2318
  "repo after deploying the harness - the generator runs this script at stage "
1861
2319
  "10 and `git init` at stage 11, so the gate could never install and no "
1862
2320
  "bootstrapped app has ever had one.")
2321
+ ap.add_argument("--gate-config", action="store_true",
2322
+ help="Write ONLY the [pre_push] section of .caddis/config.toml, derived from the app-ci "
2323
+ "caller in .github/workflows/ci.yml, and exit. An existing section is kept unless "
2324
+ "--force; --dry-run prints it.")
1863
2325
  ap.add_argument("--vendor", action="store_true",
1864
2326
  help="Copy plugin-owned agents+commands into .claude/ (for raw checkouts without "
1865
2327
  "the caddis plugin installed; plugin installs load them globally — no copy needed)")
@@ -1881,6 +2343,16 @@ def main() -> int:
1881
2343
  print(f" {note}")
1882
2344
  return 0
1883
2345
 
2346
+ if args.gate_config:
2347
+ try:
2348
+ gate_notes = write_pre_push_config(target, args.force, args.dry_run)
2349
+ except ValueError as exc:
2350
+ print(f"ERROR: pre-push config: {exc}", file=sys.stderr)
2351
+ return 2
2352
+ for note in gate_notes:
2353
+ print(f" {note}")
2354
+ return 0
2355
+
1884
2356
  name = args.name or target.name
1885
2357
  mapping: dict[str, str] = {"PROJECT_NAME": name}
1886
2358
  if args.desc:
@@ -1,7 +1,7 @@
1
1
  {
2
- "poolVersion": "1.3.178",
2
+ "poolVersion": "1.3.179",
3
3
  "bundles": {
4
- "antigravity-plugin": "1.3.178",
4
+ "antigravity-plugin": "1.3.179",
5
5
  "antigravity-plugin-extras": "1.3.51",
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.94",
3
+ "version": "0.4.95",
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",