@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.
- package/bundles/antigravity-plugin/guard_agy.py +6 -2
- package/bundles/antigravity-plugin/plugin.json +1 -1
- package/bundles/antigravity-plugin/repo_freshness.py +71 -6
- package/bundles/antigravity-plugin/repo_hygiene.py +516 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_exit.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_file_lock.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_frontmatter.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_redact.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_roadmap.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_rows.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_status.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_tidy.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_todo.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_workstreams.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_worktree_safety.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/caddis_finished.py +537 -0
- package/bundles/antigravity-plugin/scripts/caddis_guide.json +9 -8
- package/bundles/antigravity-plugin/scripts/caddis_own_cleanup.py +23 -248
- package/bundles/antigravity-plugin/scripts/caddis_prepush_config.py +222 -0
- package/bundles/antigravity-plugin/scripts/caddis_repo_tidy.py +240 -0
- package/bundles/antigravity-plugin/scripts/caddis_tidy.py +12 -0
- package/bundles/antigravity-plugin/scripts/caddis_worktree_root.py +111 -2
- package/bundles/antigravity-plugin/scripts/setup_project_ai.py +703 -174
- package/bundles/antigravity-plugin/skills/_registry.md +4 -4
- package/bundles/antigravity-plugin/skills/adopt-app/SKILL.md +2 -5
- package/bundles/antigravity-plugin/skills/cloud-phases/SKILL.md +1 -1
- package/bundles/antigravity-plugin/skills/dashboard-perf-sweep/SKILL.md +1 -1
- package/bundles/antigravity-plugin/skills/db-diagram/SKILL.md +1 -1
- package/bundles/antigravity-plugin/skills/explainer-doc/SKILL.md +1 -1
- package/bundles/antigravity-plugin/skills/implement/SKILL.md +4 -0
- package/bundles/antigravity-plugin/skills/port-to-github/SKILL.md +2 -5
- package/bundles/antigravity-plugin/skills/pr-merge/SKILL.md +1 -1
- package/bundles/antigravity-plugin/skills/ship-merge/SKILL.md +1 -1
- package/bundles/antigravity-plugin/skills/ship-pr/SKILL.md +1 -1
- package/bundles/antigravity-plugin/skills/tech-explainer/SKILL.md +2 -6
- package/bundles/antigravity-plugin/skills/using-git-worktrees/SKILL.md +19 -2
- package/bundles/antigravity-plugin/skills/warm-editorial-ui/SKILL.md +1 -1
- package/bundles/antigravity-plugin-extras/plugin.json +1 -1
- package/bundles/antigravity-plugin-extras/skills/_registry.md +2 -2
- package/bundles/antigravity-plugin-extras/skills/building-ai-agent-on-cloudflare/SKILL.md +1 -2
- package/bundles/antigravity-plugin-extras/skills/building-mcp-server-on-cloudflare/SKILL.md +1 -2
- package/bundles/antigravity-plugin-extras/skills/data-contract-pipeline/SKILL.md +1 -1
- package/bundles/antigravity-plugin-extras/skills/responsive-mobile-native/SKILL.md +2 -4
- package/bundles/antigravity-plugin-extras/skills/runner-move/SKILL.md +2 -4
- package/bundles/antigravity-plugin-extras/skills/setup-project-ai/SKILL.md +1 -1
- package/bundles/antigravity-plugin-extras/skills/understand-anything/SKILL.md +2 -5
- package/bundles/codex/.codex/skills/coding/dashboard-perf-sweep/SKILL.md +1 -1
- package/bundles/codex/.codex/skills/data/db-diagram/SKILL.md +1 -1
- package/bundles/codex/.codex/skills/devops/adopt-app/SKILL.md +2 -5
- package/bundles/codex/.codex/skills/devops/port-to-github/SKILL.md +2 -5
- package/bundles/codex/.codex/skills/devops/using-git-worktrees/SKILL.md +19 -2
- package/bundles/codex/.codex/skills/docs/explainer-doc/SKILL.md +1 -1
- package/bundles/codex/.codex/skills/docs/tech-explainer/SKILL.md +2 -6
- package/bundles/codex/.codex/skills/frontend/warm-editorial-ui/SKILL.md +1 -1
- package/bundles/manifest.json +3 -3
- package/package.json +1 -1
|
@@ -597,182 +597,595 @@ if __name__ == "__main__":
|
|
|
597
597
|
'''
|
|
598
598
|
|
|
599
599
|
|
|
600
|
-
#
|
|
601
|
-
#
|
|
602
|
-
#
|
|
603
|
-
#
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
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.
|
|
1072
|
+
# Bump when the hook text changes in a way an installed copy should pick up. install_git_hooks replaces a managed hook
|
|
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.
|
|
1074
|
+
PRE_PUSH_HOOK_VERSION = 3
|
|
1075
|
+
_HOOK_SCRIPTS_PLACEHOLDER = "__CADDIS_SCRIPTS__"
|
|
1076
|
+
|
|
616
1077
|
PRE_PUSH_HOOK = r"""#!/usr/bin/env sh
|
|
617
1078
|
# Managed by caddis setup-project-ai. Delete this file to opt out.
|
|
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.
|
|
618
1082
|
set -eu
|
|
619
|
-
|
|
620
|
-
fail=0
|
|
1083
|
+
HOOK_SCRIPTS_DIR="__CADDIS_SCRIPTS__"
|
|
621
1084
|
if command -v dirname >/dev/null 2>&1; then
|
|
622
|
-
|
|
1085
|
+
HOOK_DIR="$(dirname "$0")"
|
|
623
1086
|
elif [ -n "${0%/*}" ] && [ "${0%/*}" != "$0" ]; then
|
|
624
|
-
|
|
1087
|
+
HOOK_DIR="${0%/*}"
|
|
625
1088
|
else
|
|
626
|
-
|
|
1089
|
+
HOOK_DIR="."
|
|
627
1090
|
fi
|
|
628
1091
|
|
|
629
|
-
#
|
|
630
|
-
#
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
# Runnable IN $PY - not merely present on PATH. This is the whole point: `command -v mypy`
|
|
638
|
-
# answers a question about PATH, and the question we care about is about the environment
|
|
639
|
-
# the app's code actually imports from.
|
|
640
|
-
py_has() { [ -n "$PY" ] && "$PY" -m "$1" --version >/dev/null 2>&1; }
|
|
641
|
-
# Does the project ASK for this tool? If so, being unable to run it is a failure.
|
|
642
|
-
py_wants() { grep -qi -- "$1" pyproject.toml requirements.txt requirements-dev.txt 2>/dev/null; }
|
|
643
|
-
|
|
644
|
-
# Does this project actually contain Python source? A pyproject.toml alone does not mean it
|
|
645
|
-
# does - a config-only or frontend repo can carry one - and mypy exits non-zero with "There
|
|
646
|
-
# are no .py[i] files in directory" when handed nothing. Skipping a checker that has nothing
|
|
647
|
-
# to check is honest; failing the push over it is not.
|
|
648
|
-
py_sources_exist() {
|
|
649
|
-
[ -n "$(find . -name '*.py' -not -path './.venv/*' -not -path './venv/*' -not -path './node_modules/*' -not -path './.git/*' 2>/dev/null | head -1)" ]
|
|
650
|
-
}
|
|
651
|
-
|
|
652
|
-
py_gate() {
|
|
653
|
-
tool=$1; shift
|
|
654
|
-
timeout=300
|
|
655
|
-
case "$tool" in
|
|
656
|
-
ruff) timeout=300 ;;
|
|
657
|
-
mypy) timeout=600 ;;
|
|
658
|
-
pytest) timeout=1200 ;;
|
|
659
|
-
esac
|
|
660
|
-
if py_has "$tool"; then
|
|
661
|
-
rc=0
|
|
662
|
-
if [ -f "$GATE_RUN" ]; then
|
|
663
|
-
"$PY" "$GATE_RUN" --name "$tool" --timeout "$timeout" -- "$PY" -m "$tool" "$@" || rc=$?
|
|
664
|
-
else
|
|
665
|
-
echo "[gate] $tool $*"
|
|
666
|
-
"$PY" -m "$tool" "$@" || rc=$?
|
|
667
|
-
fi
|
|
668
|
-
if [ "$rc" -ne 0 ]; then
|
|
669
|
-
# pytest exit 5 = "no tests collected". A repo that has not written tests yet is not a
|
|
670
|
-
# failing repo, and blocking it would hit exactly the fresh-scaffold case this fix exists
|
|
671
|
-
# for. Every other non-zero code is a real failure.
|
|
672
|
-
if [ "$tool" = "pytest" ] && [ "$rc" -eq 5 ]; then
|
|
673
|
-
echo "[gate] pytest: no tests collected yet - not treated as a failure"
|
|
674
|
-
else
|
|
675
|
-
fail=1
|
|
676
|
-
fi
|
|
677
|
-
fi
|
|
678
|
-
elif py_wants "$tool"; then
|
|
679
|
-
echo "[gate] $tool: DECLARED by this project but not runnable in $PY - environment is broken" >&2
|
|
680
|
-
echo " fix: activate the venv, or reinstall dev deps (pip install -e '.[dev]')" >&2
|
|
681
|
-
fail=1
|
|
682
|
-
fi
|
|
683
|
-
}
|
|
684
|
-
|
|
685
|
-
if [ -f "pyproject.toml" ] || [ -f "requirements.txt" ]; then
|
|
686
|
-
if [ -z "$PY" ]; then
|
|
687
|
-
echo "[gate] python project, but no interpreter found (.venv or PATH) - cannot verify" >&2
|
|
688
|
-
fail=1
|
|
689
|
-
else
|
|
690
|
-
echo "[gate] interpreter: $PY"
|
|
691
|
-
py_gate ruff check .
|
|
692
|
-
if py_sources_exist; then py_gate mypy .; else echo "[skip] mypy: no Python sources"; fi
|
|
693
|
-
# pytest is OPT-IN here (CADDIS_GATE_PYTEST=1). Found 2026-10-10: the full suite took 25-31 min in this
|
|
694
|
-
# hook on a box whose system disk was slow, while CI ran the same suite in 5 min - and a merge needs green
|
|
695
|
-
# CI anyway. A local gate five times slower than the check it stands in for trains people to --no-verify it.
|
|
696
|
-
# When it does run: CADDIS_GATE_TMP moves TMPDIR/TEMP/TMP (tests write to tmp_path; Python reads TMPDIR
|
|
697
|
-
# first, so set all three), CADDIS_GATE_PYTEST_ARGS adds arguments (for example "-n 4" with pytest-xdist;
|
|
698
|
-
# use a number, not "auto"), and a machine-wide lock (CADDIS_GATE_LOCK, mkdir-based, waits up to
|
|
699
|
-
# 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
|
|
700
|
-
# pile their suites on the same disk and CI runners.
|
|
701
|
-
if [ "${CADDIS_GATE_PYTEST:-0}" = "1" ]; then
|
|
702
|
-
if [ -n "${CADDIS_GATE_TMP:-}" ]; then
|
|
703
|
-
mkdir -p "$CADDIS_GATE_TMP" 2>/dev/null || true
|
|
704
|
-
export TMPDIR="$CADDIS_GATE_TMP" TEMP="$CADDIS_GATE_TMP" TMP="$CADDIS_GATE_TMP"
|
|
705
|
-
fi
|
|
706
|
-
LOCK="${CADDIS_GATE_LOCK:-${TMPDIR:-${TEMP:-/tmp}}/caddis-pytest-gate.lock}"
|
|
707
|
-
mkdir -p "$(dirname "$LOCK")" 2>/dev/null || true
|
|
708
|
-
lock_wait="${CADDIS_GATE_LOCK_WAIT:-1800}"
|
|
709
|
-
waited=0
|
|
710
|
-
got_lock=0
|
|
711
|
-
while :; do
|
|
712
|
-
if mkdir "$LOCK" 2>/dev/null; then got_lock=1; break; fi
|
|
713
|
-
# A stale lock is removed, then this round still sleeps and counts: if the removal fails (a lock owned
|
|
714
|
-
# by another user), the loop ends at lock_wait instead of spinning forever.
|
|
715
|
-
if [ -n "$(find "$LOCK" -maxdepth 0 -mmin +60 2>/dev/null)" ]; then
|
|
716
|
-
rmdir "$LOCK" 2>/dev/null || true
|
|
717
|
-
fi
|
|
718
|
-
if [ "$waited" -ge "$lock_wait" ]; then break; fi
|
|
719
|
-
if [ "$waited" -eq 0 ]; then echo "[gate] pytest: waiting for another repo's pytest gate ($LOCK)"; fi
|
|
720
|
-
sleep 1
|
|
721
|
-
waited=$((waited + 1))
|
|
722
|
-
done
|
|
723
|
-
if [ "$got_lock" -eq 1 ]; then
|
|
724
|
-
trap 'rmdir "$LOCK" 2>/dev/null || true' EXIT INT TERM
|
|
725
|
-
# shellcheck disable=SC2086 # CADDIS_GATE_PYTEST_ARGS is meant to word-split
|
|
726
|
-
py_gate pytest -q ${CADDIS_GATE_PYTEST_ARGS:-}
|
|
727
|
-
rmdir "$LOCK" 2>/dev/null || true
|
|
728
|
-
trap - EXIT INT TERM
|
|
729
|
-
else
|
|
730
|
-
echo "[gate] pytest: another pytest gate holds $LOCK for over ${lock_wait}s - cannot run, so the gate fails" >&2
|
|
731
|
-
fail=1
|
|
732
|
-
fi
|
|
733
|
-
else
|
|
734
|
-
echo "[skip] pytest: runs in CI (set CADDIS_GATE_PYTEST=1 to run it here)"
|
|
735
|
-
fi
|
|
736
|
-
fi
|
|
737
|
-
fi
|
|
738
|
-
if [ -f "package.json" ] && command -v npm >/dev/null 2>&1; then
|
|
739
|
-
if [ -f "$GATE_RUN" ] && [ -n "$PY" ]; then
|
|
740
|
-
npm run 2>/dev/null | grep -q " lint" && { "$PY" "$GATE_RUN" --name npm-lint --timeout 600 -- npm run lint --silent || fail=1; }
|
|
741
|
-
npm run 2>/dev/null | grep -q " typecheck" && { "$PY" "$GATE_RUN" --name npm-typecheck --timeout 600 -- npm run typecheck --silent || fail=1; }
|
|
742
|
-
npm run 2>/dev/null | grep -q " test" && { "$PY" "$GATE_RUN" --name npm-test --timeout 1200 -- npm test --silent || fail=1; }
|
|
743
|
-
else
|
|
744
|
-
npm run 2>/dev/null | grep -q " lint" && { echo "[gate] npm run lint"; npm run lint --silent || fail=1; }
|
|
745
|
-
npm run 2>/dev/null | grep -q " typecheck" && { echo "[gate] npm run typecheck"; npm run typecheck --silent || fail=1; }
|
|
746
|
-
npm run 2>/dev/null | grep -q " test" && { echo "[gate] npm test"; npm test --silent || fail=1; }
|
|
747
|
-
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)
|
|
748
1099
|
fi
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
if [ -f "scripts/check_doc_coverage.py" ]; then
|
|
754
|
-
DOC_PY="$PY"
|
|
755
|
-
if [ -z "$DOC_PY" ]; then DOC_PY=$(command -v python || command -v python3 || true); fi
|
|
756
|
-
if [ -n "$DOC_PY" ]; then
|
|
757
|
-
if [ -f "$GATE_RUN" ]; then
|
|
758
|
-
"$DOC_PY" "$GATE_RUN" --name doc-coverage --timeout 120 -- "$DOC_PY" scripts/check_doc_coverage.py --check || fail=1
|
|
759
|
-
else
|
|
760
|
-
echo "[gate] doc coverage"
|
|
761
|
-
"$DOC_PY" scripts/check_doc_coverage.py --check || fail=1
|
|
762
|
-
fi
|
|
763
|
-
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
|
|
764
1104
|
fi
|
|
765
|
-
if [ "$
|
|
766
|
-
echo "[
|
|
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
|
|
767
1108
|
exit 1
|
|
768
1109
|
fi
|
|
769
|
-
|
|
1110
|
+
exec "$PYRUN" "$HOOK_DIR/caddis_prepush.py" "$@"
|
|
770
1111
|
"""
|
|
771
1112
|
|
|
772
1113
|
|
|
773
|
-
|
|
774
|
-
|
|
1114
|
+
_HOOK_MARKER_RE = re.compile(r"Managed by (caddis|claudster)\b")
|
|
1115
|
+
_HOOK_VERSION_RE = re.compile(r"^#\s*caddis-pre-push-version:\s*(\d+)", re.MULTILINE)
|
|
1116
|
+
|
|
1117
|
+
|
|
1118
|
+
def render_pre_push_hook() -> str:
|
|
1119
|
+
"""The hook text to install: the template with this install's scripts folder filled in (forward slashes)."""
|
|
1120
|
+
return PRE_PUSH_HOOK.replace(_HOOK_SCRIPTS_PLACEHOLDER, Path(__file__).resolve().parent.as_posix())
|
|
1121
|
+
|
|
1122
|
+
|
|
1123
|
+
def _installed_hook_state(hook_text: str) -> tuple[bool, int]:
|
|
1124
|
+
"""(managed by caddis, its version). A managed hook with no version marker is version 0. A hook this tool did not
|
|
1125
|
+
write is (False, 0): it is never replaced without --force."""
|
|
1126
|
+
if not _HOOK_MARKER_RE.search(hook_text): # also recognises pre-rename ("claudster") hooks
|
|
1127
|
+
return False, 0
|
|
1128
|
+
m = _HOOK_VERSION_RE.search(hook_text)
|
|
1129
|
+
return True, int(m.group(1)) if m else 0
|
|
1130
|
+
|
|
1131
|
+
|
|
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
|
+
|
|
1135
|
+
|
|
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}
|
|
775
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."""
|
|
776
1189
|
git = target / ".git"
|
|
777
1190
|
if not git.exists():
|
|
778
1191
|
return ["pre-push gate: no .git (not a git repo) — skipped"]
|
|
@@ -780,23 +1193,125 @@ def install_git_hooks(target: Path, force: bool, dry: bool) -> list[str]:
|
|
|
780
1193
|
return ["pre-push gate: .git is a worktree pointer — skipped (install manually if wanted)"]
|
|
781
1194
|
hooks_dir = git / "hooks"
|
|
782
1195
|
dest = hooks_dir / "pre-push"
|
|
783
|
-
|
|
1196
|
+
companions, notes = _hook_companions()
|
|
1197
|
+
upgraded_from: int | None = None
|
|
784
1198
|
if dest.exists() and not force:
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
1199
|
+
managed, version = _installed_hook_state(dest.read_text(encoding="utf-8", errors="ignore"))
|
|
1200
|
+
if not managed:
|
|
1201
|
+
return ["pre-push gate: exists (yours — left intact, use --force to replace) — skipped"]
|
|
1202
|
+
if version >= PRE_PUSH_HOOK_VERSION:
|
|
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 [])
|
|
1213
|
+
upgraded_from = version
|
|
788
1214
|
if not dry:
|
|
789
1215
|
hooks_dir.mkdir(parents=True, exist_ok=True)
|
|
790
|
-
dest
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
1216
|
+
_write_hook_file(dest, render_pre_push_hook())
|
|
1217
|
+
for name, text in companions.items():
|
|
1218
|
+
_write_hook_file(hooks_dir / name, text)
|
|
1219
|
+
if upgraded_from is not None:
|
|
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)")
|
|
1222
|
+
else:
|
|
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})"]
|
|
800
1315
|
|
|
801
1316
|
|
|
802
1317
|
def emit_doc_discipline(target: Path, ident: dict[str, str], force: bool, dry: bool) -> list[str]:
|
|
@@ -1803,6 +2318,10 @@ def main() -> int:
|
|
|
1803
2318
|
"repo after deploying the harness - the generator runs this script at stage "
|
|
1804
2319
|
"10 and `git init` at stage 11, so the gate could never install and no "
|
|
1805
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.")
|
|
1806
2325
|
ap.add_argument("--vendor", action="store_true",
|
|
1807
2326
|
help="Copy plugin-owned agents+commands into .claude/ (for raw checkouts without "
|
|
1808
2327
|
"the caddis plugin installed; plugin installs load them globally — no copy needed)")
|
|
@@ -1824,6 +2343,16 @@ def main() -> int:
|
|
|
1824
2343
|
print(f" {note}")
|
|
1825
2344
|
return 0
|
|
1826
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
|
+
|
|
1827
2356
|
name = args.name or target.name
|
|
1828
2357
|
mapping: dict[str, str] = {"PROJECT_NAME": name}
|
|
1829
2358
|
if args.desc:
|