cohorte 3.1.1 → 3.1.3

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,4 +1,8 @@
1
1
  #!/usr/bin/env python3
2
+ # GENERATED from core/hooks/gate/*.py by scripts/build-gate.mjs — edit the modules, then run
3
+ # `node scripts/build-gate.mjs`. validate-core fails when this file and the modules disagree.
4
+ # Build order: runtime, shell, git, config, ownership, patterns, context, findings, rules,
5
+ # protect, indirect, analyze, preflight, evaluate, main.
2
6
  """Cohorte PreToolUse gate for Claude Code (3.0 — Claude Code only).
3
7
 
4
8
  Installed per project as `.claude/hooks/cohorte-gate.py` and registered in the project's
@@ -109,6 +113,8 @@ import sys
109
113
  import tempfile
110
114
  import time
111
115
 
116
+
117
+ # ══ core/hooks/gate/runtime.py ═══════════════════════════════════════════════
112
118
  # ── time budget ──────────────────────────────────────────────────────────────
113
119
  # The hook is registered with onFailure "block": a timeout blocks the tool call. Every git
114
120
  # call draws on one global budget, and an exhausted budget answers "ask", never "allow".
@@ -182,6 +188,7 @@ def warn(msg):
182
188
  pass
183
189
 
184
190
 
191
+ # ══ core/hooks/gate/shell.py ═════════════════════════════════════════════════
185
192
  # ── lexer ────────────────────────────────────────────────────────────────────
186
193
  DYN = "\x00" # stands for a run-time expansion inside a word's value
187
194
 
@@ -840,6 +847,7 @@ def strip_prefixes(words):
840
847
  return words[i:], assigns, env_s, relocated, False
841
848
 
842
849
 
850
+ # ══ core/hooks/gate/git.py ═══════════════════════════════════════════════════
843
851
  # ── git ──────────────────────────────────────────────────────────────────────
844
852
  GIT_GLOBAL_WITH_ARG = {"-c", "-C", "--git-dir", "--work-tree", "--namespace", "--super-prefix",
845
853
  "--config-env", "--list-cmds", "--attr-source"}
@@ -1048,6 +1056,7 @@ def normalize_ref(name):
1048
1056
  return name
1049
1057
 
1050
1058
 
1059
+ # ══ core/hooks/gate/config.py ════════════════════════════════════════════════
1051
1060
  # ── config ───────────────────────────────────────────────────────────────────
1052
1061
  DEFAULT_AGENTS = ["cohorte-review", "review"]
1053
1062
  RENAMED_AGENTS = {"review": "cohorte-review", "release": "cohorte-release",
@@ -1183,6 +1192,7 @@ def resolve_roots(cwd):
1183
1192
  return roots, top
1184
1193
 
1185
1194
 
1195
+ # ══ core/hooks/gate/ownership.py ═════════════════════════════════════════════
1186
1196
  # ── surface ownership ────────────────────────────────────────────────────────
1187
1197
  # A surface implementer (a subagent whose `agent_type` is a `surfaces[].agent` of the
1188
1198
  # project's `.claude/profile.json`) may only write under its own `surfaces[].path`, plus
@@ -1369,116 +1379,7 @@ class Ownership(object):
1369
1379
  % (self.agent, "`, `".join(mine), rel, whose))
1370
1380
 
1371
1381
 
1372
- class Ctx(object):
1373
- def __init__(self, cwd, mode):
1374
- self.cwd0 = os.path.realpath(cwd) if cwd and os.path.isdir(cwd) else None
1375
- self.mode = mode
1376
- self.roots, self.top0 = resolve_roots(self.cwd0)
1377
- self.warnings = []
1378
- self.errors = []
1379
- self.config_found = False
1380
- merged = {"deny": [], "ask": [], "ask_on_default_branch": [], "default_branches": [],
1381
- "preflight": None}
1382
- for r in self.roots:
1383
- for sub in (".claude", ".cohorte"):
1384
- p = os.path.join(r, sub, "gate-config.json")
1385
- if not os.path.isfile(p):
1386
- continue
1387
- if sub == ".cohorte" and os.path.isfile(os.path.join(r, ".claude", "gate-config.json")):
1388
- self.warnings.append("%s and .claude/gate-config.json both exist; their "
1389
- "rules are combined" % p)
1390
- self.config_found = True
1391
- try:
1392
- with open(p, "r", encoding="utf-8") as fh:
1393
- obj = json.load(fh)
1394
- cfg = validate_config(obj, p, self.warnings)
1395
- except ConfigError as e:
1396
- self.errors.append("%s: %s" % (p, e))
1397
- continue
1398
- except Exception as e:
1399
- self.errors.append("%s: not valid JSON (%s)" % (p, e))
1400
- continue
1401
- for k in ("deny", "ask", "ask_on_default_branch"):
1402
- for pat in cfg[k]:
1403
- if pat not in merged[k]:
1404
- merged[k].append(pat)
1405
- if cfg["default_branch"] and cfg["default_branch"] not in merged["default_branches"]:
1406
- merged["default_branches"].append(cfg["default_branch"])
1407
- if merged["preflight"] is None and cfg["preflight"] is not None:
1408
- merged["preflight"] = cfg["preflight"]
1409
- self.cfg = merged
1410
- self.has_pointer = any(os.path.isfile(os.path.join(r, ".claude", "pipeline.json"))
1411
- for r in self.roots)
1412
- self.active = self.has_pointer or self.config_found
1413
- for w in self.warnings:
1414
- warn(w)
1415
- self.deny_pats = [compile_pattern(p) for p in merged["deny"]]
1416
- self.ask_pats = [compile_pattern(p) for p in merged["ask"]]
1417
- self.branch_pats = [compile_pattern(p) for p in merged["ask_on_default_branch"]]
1418
- self.has_rules = bool(merged["deny"] or merged["ask"] or merged["ask_on_default_branch"]
1419
- or self.errors)
1420
- self._defaults = None
1421
- self._branches = {}
1422
- self._aliases = {}
1423
- self.owner = None # Ownership, set by evaluate() for a surface agent
1424
- self._build_protected()
1425
-
1426
- def _build_protected(self):
1427
- write, delete = set(), set()
1428
-
1429
- def add(s, p):
1430
- s.add(os.path.normpath(p))
1431
- s.add(os.path.realpath(p))
1432
-
1433
- for r in self.roots:
1434
- for rel in ((".claude", "gate-config.json"), (".claude", "preflight.ok"),
1435
- (".claude", "settings.json"), (".claude", "settings.local.json"),
1436
- (".claude", "hooks", "cohorte-gate.py"), (".cohorte", "gate-config.json"),
1437
- # profile.json drives ownership enforcement: as protected as the config.
1438
- (".claude", "profile.json")):
1439
- add(write, os.path.join(r, *rel))
1440
- add(delete, os.path.join(r, ".claude", "pipeline.json"))
1441
- home = os.path.expanduser("~")
1442
- for rel in ("settings.json", "settings.local.json"):
1443
- add(write, os.path.join(home, ".claude", rel))
1444
- self.protected = write
1445
- self.delete_protected = write | delete
1446
-
1447
- # git state, cached
1448
- def current_branch(self, cwd):
1449
- if cwd not in self._branches:
1450
- r = run_git(["symbolic-ref", "-q", "--short", "HEAD"], cwd)
1451
- self._branches[cwd] = r[1].strip() if r and r[0] == 0 and r[1].strip() else None
1452
- return self._branches[cwd]
1453
-
1454
- def defaults(self):
1455
- if self._defaults is None:
1456
- if self.cfg["default_branches"]:
1457
- self._defaults = list(self.cfg["default_branches"])
1458
- else:
1459
- d = ["main", "master"]
1460
- if self.cwd0:
1461
- r = run_git(["symbolic-ref", "-q", "--short", "refs/remotes/origin/HEAD"],
1462
- self.cwd0)
1463
- if r and r[0] == 0 and "/" in r[1].strip():
1464
- name = r[1].strip().split("/", 1)[1]
1465
- if name not in d:
1466
- d.insert(0, name)
1467
- self._defaults = d
1468
- return self._defaults
1469
-
1470
- def is_default(self, branch):
1471
- return any(fnmatch.fnmatchcase(d, branch) if any(c in branch for c in "*?[") else d == branch
1472
- for d in self.defaults())
1473
-
1474
- def git_alias(self, sub, cwd):
1475
- key = (sub, cwd)
1476
- if key not in self._aliases:
1477
- r = run_git(["config", "--get", "alias." + sub], cwd)
1478
- self._aliases[key] = r[1].strip() if r and r[0] == 0 and r[1].strip() else None
1479
- return self._aliases[key]
1480
-
1481
-
1382
+ # ══ core/hooks/gate/patterns.py ══════════════════════════════════════════════
1482
1383
  # ── patterns ─────────────────────────────────────────────────────────────────
1483
1384
  class PatSeg(object):
1484
1385
  def __init__(self, name, args, sep):
@@ -1763,92 +1664,129 @@ def match_push(pat_args, cargs, pi):
1763
1664
  return res
1764
1665
 
1765
1666
 
1766
- # ── analysis ─────────────────────────────────────────────────────────────────
1767
- PROTECTED_HINT_RE = re.compile(r"(^|/)\.claude(/|$)|gate-config\.json|preflight\.ok|"
1768
- r"settings(\.local)?\.json|cohorte-gate\.py|pipeline\.json|"
1769
- r"(^|/)\.cohorte(/|$)")
1770
- PROTECTED_NAME_RE = re.compile(r"gate-config\.json|preflight\.ok|\.claude/settings(\.local)?\.json|"
1771
- r"cohorte-gate\.py|\.claude/profile\.json")
1772
- SPAWN_RE = {
1773
- "py": re.compile(r"\bos\.(system|popen|exec\w*|spawn\w*)|\bsubprocess\b|\bpty\.spawn|"
1774
- r"\bcommands\.getoutput|\bpexpect\b|\bsh\.\w+\("),
1775
- "js": re.compile(r"child_process|\bexecSync\b|\bspawnSync\b|\bexecFileSync\b|\bexecFile\(|"
1776
- r"\bexec\(|\bspawn\(|Bun\.spawn|Deno\.(Command|run)|\$`|zx"),
1777
- "pl": re.compile(r"\bsystem\b|\bexec\b|`|\bqx\b|IO\.popen|Open3|\bspawn\b|%x|\bpopen\b|"
1778
- r"\bshell_exec\b|\bpassthru\b|\bproc_open\b"),
1779
- }
1780
- STRING_LIT_RE = re.compile(r"'((?:[^'\\]|\\.)*)'|\"((?:[^\"\\]|\\.)*)\"")
1781
- PROTECTED_BASENAMES = {"gate-config.json", "preflight.ok", "settings.json", "settings.local.json", "profile.json",
1782
- "cohorte-gate.py", "pipeline.json", ".claude", ".cohorte", "hooks", "~", "",
1783
- ".", ".."}
1667
+ # ══ core/hooks/gate/context.py ═══════════════════════════════════════════════
1668
+ # ── context ──────────────────────────────────────────────────────────────────
1669
+ class Ctx(object):
1670
+ def __init__(self, cwd, mode):
1671
+ self.cwd0 = os.path.realpath(cwd) if cwd and os.path.isdir(cwd) else None
1672
+ self.mode = mode
1673
+ self.roots, self.top0 = resolve_roots(self.cwd0)
1674
+ self.warnings = []
1675
+ self.errors = []
1676
+ self.config_found = False
1677
+ merged = {"deny": [], "ask": [], "ask_on_default_branch": [], "default_branches": [],
1678
+ "preflight": None}
1679
+ for r in self.roots:
1680
+ for sub in (".claude", ".cohorte"):
1681
+ p = os.path.join(r, sub, "gate-config.json")
1682
+ if not os.path.isfile(p):
1683
+ continue
1684
+ if sub == ".cohorte" and os.path.isfile(os.path.join(r, ".claude", "gate-config.json")):
1685
+ self.warnings.append("%s and .claude/gate-config.json both exist; their "
1686
+ "rules are combined" % p)
1687
+ self.config_found = True
1688
+ try:
1689
+ with open(p, "r", encoding="utf-8") as fh:
1690
+ obj = json.load(fh)
1691
+ cfg = validate_config(obj, p, self.warnings)
1692
+ except ConfigError as e:
1693
+ self.errors.append("%s: %s" % (p, e))
1694
+ continue
1695
+ except Exception as e:
1696
+ self.errors.append("%s: not valid JSON (%s)" % (p, e))
1697
+ continue
1698
+ for k in ("deny", "ask", "ask_on_default_branch"):
1699
+ for pat in cfg[k]:
1700
+ if pat not in merged[k]:
1701
+ merged[k].append(pat)
1702
+ if cfg["default_branch"] and cfg["default_branch"] not in merged["default_branches"]:
1703
+ merged["default_branches"].append(cfg["default_branch"])
1704
+ if merged["preflight"] is None and cfg["preflight"] is not None:
1705
+ merged["preflight"] = cfg["preflight"]
1706
+ self.cfg = merged
1707
+ self.has_pointer = any(os.path.isfile(os.path.join(r, ".claude", "pipeline.json"))
1708
+ for r in self.roots)
1709
+ self.active = self.has_pointer or self.config_found
1710
+ for w in self.warnings:
1711
+ warn(w)
1712
+ self.deny_pats = [compile_pattern(p) for p in merged["deny"]]
1713
+ self.ask_pats = [compile_pattern(p) for p in merged["ask"]]
1714
+ self.branch_pats = [compile_pattern(p) for p in merged["ask_on_default_branch"]]
1715
+ self.has_rules = bool(merged["deny"] or merged["ask"] or merged["ask_on_default_branch"]
1716
+ or self.errors)
1717
+ self._defaults = None
1718
+ self._branches = {}
1719
+ self._aliases = {}
1720
+ self.owner = None # Ownership, set by evaluate() for a surface agent
1721
+ self._build_protected()
1784
1722
 
1723
+ def _build_protected(self):
1724
+ write, delete = set(), set()
1785
1725
 
1786
- def suspicious(tail, raw):
1787
- """For a path the gate can't resolve: could it name a protected file? Its static tail
1788
- decides — `…/.claude/pipeline-metrics.jsonl` can't, `$DIR/.claude/settings.json` can."""
1789
- base = os.path.basename(tail.rstrip("/")) if tail else ""
1790
- if tail and "/" in tail and base not in PROTECTED_BASENAMES and not tail.endswith("/"):
1791
- return False
1792
- return bool(PROTECTED_HINT_RE.search(raw))
1726
+ def add(s, p):
1727
+ s.add(os.path.normpath(p))
1728
+ s.add(os.path.realpath(p))
1793
1729
 
1730
+ for r in self.roots:
1731
+ for rel in ((".claude", "gate-config.json"), (".claude", "preflight.ok"),
1732
+ (".claude", "settings.json"), (".claude", "settings.local.json"),
1733
+ (".claude", "hooks", "cohorte-gate.py"), (".cohorte", "gate-config.json"),
1734
+ # profile.json drives ownership enforcement: as protected as the config.
1735
+ (".claude", "profile.json")):
1736
+ add(write, os.path.join(r, *rel))
1737
+ add(delete, os.path.join(r, ".claude", "pipeline.json"))
1738
+ home = os.path.expanduser("~")
1739
+ for rel in ("settings.json", "settings.local.json"):
1740
+ add(write, os.path.join(home, ".claude", rel))
1741
+ self.protected = write
1742
+ self.delete_protected = write | delete
1794
1743
 
1795
- MAX_DEPTH = 6
1796
- WRITE_OPS = {">", ">>", ">|", "&>", "&>>", "<>"}
1744
+ # git state, cached
1745
+ def current_branch(self, cwd):
1746
+ if cwd not in self._branches:
1747
+ r = run_git(["symbolic-ref", "-q", "--short", "HEAD"], cwd)
1748
+ self._branches[cwd] = r[1].strip() if r and r[0] == 0 and r[1].strip() else None
1749
+ return self._branches[cwd]
1750
+
1751
+ def defaults(self):
1752
+ if self._defaults is None:
1753
+ if self.cfg["default_branches"]:
1754
+ self._defaults = list(self.cfg["default_branches"])
1755
+ else:
1756
+ d = ["main", "master"]
1757
+ if self.cwd0:
1758
+ r = run_git(["symbolic-ref", "-q", "--short", "refs/remotes/origin/HEAD"],
1759
+ self.cwd0)
1760
+ if r and r[0] == 0 and "/" in r[1].strip():
1761
+ name = r[1].strip().split("/", 1)[1]
1762
+ if name not in d:
1763
+ d.insert(0, name)
1764
+ self._defaults = d
1765
+ return self._defaults
1766
+
1767
+ def is_default(self, branch):
1768
+ return any(fnmatch.fnmatchcase(d, branch) if any(c in branch for c in "*?[") else d == branch
1769
+ for d in self.defaults())
1770
+
1771
+ def git_alias(self, sub, cwd):
1772
+ key = (sub, cwd)
1773
+ if key not in self._aliases:
1774
+ r = run_git(["config", "--get", "alias." + sub], cwd)
1775
+ self._aliases[key] = r[1].strip() if r and r[0] == 0 and r[1].strip() else None
1776
+ return self._aliases[key]
1797
1777
 
1798
1778
 
1779
+ # ══ core/hooks/gate/findings.py ══════════════════════════════════════════════
1799
1780
  def norm_lower(s):
1800
1781
  return " ".join(s.lower().split())
1801
1782
 
1802
1783
 
1803
- def lang_of(name):
1804
- if name.startswith("py"):
1805
- return "py"
1806
- if name in ("node", "nodejs", "deno", "bun"):
1807
- return "js"
1808
- return "pl"
1784
+ def short(text, n=90):
1785
+ t = " ".join(text.split())
1786
+ return t if len(t) <= n else t[:n - 1] + "…"
1809
1787
 
1810
1788
 
1811
- class State(object):
1812
- def __init__(self, cwd):
1813
- self.cwd = cwd
1814
- self.cwd_known = cwd is not None
1815
- self.sticky = False # branch unknown for the rest of the chain
1816
- self.written = set()
1817
- self.git_aliases = {}
1818
-
1819
- def copy(self):
1820
- s = State(self.cwd)
1821
- s.cwd_known = self.cwd_known
1822
- s.sticky = self.sticky
1823
- s.written = set(self.written)
1824
- s.git_aliases = dict(self.git_aliases)
1825
- return s
1826
-
1827
-
1828
- class Inv(object):
1829
- def __init__(self, name, args, seg):
1830
- self.name = name
1831
- self.args = args
1832
- self.seg = seg
1833
- self.git = None
1834
- self.push = None
1835
- self.push_touches = False
1836
- self.push_unknown = False
1837
- self.core = None
1838
- self.cores = []
1839
- self.prefixes = []
1840
-
1841
-
1842
- def short(text, n=90):
1843
- t = " ".join(text.split())
1844
- return t if len(t) <= n else t[:n - 1] + "…"
1845
-
1846
-
1847
- class Analyzer(object):
1848
- def __init__(self, ctx):
1849
- self.ctx = ctx
1850
- self.findings = []
1851
-
1789
+ class Findings(object):
1852
1790
  def deny(self, why):
1853
1791
  self.findings.append(("deny", why))
1854
1792
 
@@ -1891,144 +1829,9 @@ class Analyzer(object):
1891
1829
  self.ask("the gate can't parse this command (%s), so it can't verify it — confirm"
1892
1830
  % err)
1893
1831
 
1894
- def analyze_text(self, text, state, depth):
1895
- if depth > MAX_DEPTH:
1896
- self.opaque("commands are nested too deep", text)
1897
- return
1898
- try:
1899
- segs = parse_command(text)
1900
- except ParseError as e:
1901
- self.unparseable(text, e)
1902
- return
1903
- self.walk(segs, state, depth, text)
1904
-
1905
- def walk(self, segs, state, depth, text=""):
1906
- invs = []
1907
- for idx, seg in enumerate(segs):
1908
- prev = segs[idx - 1] if idx else None
1909
- prev_inv = invs[-1] if invs else None
1910
- if seg.subshell:
1911
- state.sticky = True
1912
- self.walk_substs(seg, state, depth)
1913
- invs.append(self.eval_segment(seg, prev, prev_inv, state, depth))
1914
- self.multi_patterns(segs, invs, state)
1915
- for p in self.ctx.deny_pats + self.ctx.ask_pats:
1916
- if not p.segs and p.norm in norm_lower(text):
1917
- (self.deny if p in self.ctx.deny_pats else self.ask)(
1918
- "`%s` (raw-text rule) matches this command" % p.text)
1919
-
1920
- def walk_substs(self, seg, state, depth):
1921
- words = list(seg.words) + [r.target for r in seg.redirs]
1922
- for w in words:
1923
- for sub in w.substs:
1924
- self.walk(sub, state.copy(), depth + 1)
1925
- for h in seg.heredocs:
1926
- for sub in h.substs:
1927
- self.walk(sub, state.copy(), depth + 1)
1928
-
1929
- # -- one simple command ----------------------------------------------------
1930
- def eval_segment(self, seg, prev, prev_inv, state, depth):
1931
- words = list(seg.words)
1932
- if seg.funcdef:
1933
- while words and words[0].value != "{":
1934
- words.pop(0)
1935
- for r in seg.redirs:
1936
- if r.op in WRITE_OPS or (r.op == ">&" and not (r.target.value.isdigit()
1937
- or r.target.value == "-")):
1938
- self.check_path(r.target, state, "write", "a redirection")
1939
- self.remember_written(r.target, state)
1940
- while words and not words[0].quoted and words[0].value in RESERVED_SKIP:
1941
- words.pop(0)
1942
- if words and not words[0].quoted and words[0].value in RESERVED_HEADER:
1943
- return None
1944
- if words and words[-1].value == "}" and not words[-1].quoted:
1945
- words.pop()
1946
- argv, assigns, env_s, relocated, lookup = strip_prefixes(words)
1947
- prefixes = list(PREFIXES_SEEN)
1948
- seg_unknown = relocated
1949
- if GIT_ENV_VARS.intersection(assigns):
1950
- state.sticky = True
1951
- seg_unknown = True
1952
- if env_s is not None:
1953
- if env_s.dynamic:
1954
- self.opaque("`env -S` runs a string built at run time", seg.text)
1955
- else:
1956
- self.analyze_text(env_s.value, state.copy(), depth + 1)
1957
- return None
1958
- if lookup or not argv:
1959
- return None
1960
- cmd = argv[0]
1961
- if cmd.dynamic:
1962
- self.opaque("the command name is computed at run time", seg.text)
1963
- return None
1964
- name = cmd_name(cmd.value)
1965
- args = argv[1:]
1966
- inv = Inv(name, args, seg)
1967
- inv.prefixes = prefixes
1968
-
1969
- if name == "git":
1970
- g = self.expand_git(args, state, depth)
1971
- if g is None:
1972
- return None
1973
- inv.git = g
1974
- inv.args = args = (argv[1:1 + (g.sub_index or 0)] + [static_word(g.sub)] + g.args
1975
- if g.sub else args)
1976
- if g.relocated:
1977
- seg_unknown = True
1978
- if g.dynamic_global:
1979
- self.opaque("git's arguments are computed at run time", seg.text)
1980
- else:
1981
- inv.core = runner_core(name, args)
1982
- inv.cores = wrapper_cores(name, args)
1983
-
1984
- here_unknown = seg_unknown or state.sticky or not state.cwd_known
1985
- if inv.git and inv.git.sub == "push":
1986
- self.eval_push(inv, state, here_unknown)
1987
- self.match_config(inv, state, here_unknown)
1988
- self.indirection(inv, seg, prev, prev_inv, state, depth)
1989
- self.protect(inv, state, seg_unknown)
1990
- self.update_state(inv, seg, state, assigns)
1991
- return inv
1992
-
1993
- def expand_git(self, args, state, depth):
1994
- for _ in range(4):
1995
- g = parse_git(args)
1996
- if g.sub is None or g.sub in GIT_BUILTINS:
1997
- if g.sub == "config":
1998
- self.git_config_alias(g, state, depth)
1999
- return g
2000
- alias = g.c_aliases.get(g.sub) or state.git_aliases.get(g.sub)
2001
- if alias is None and state.cwd_known and not g.relocated:
2002
- alias = self.ctx.git_alias(g.sub, state.cwd)
2003
- if alias is None:
2004
- return g
2005
- if alias.startswith("!"):
2006
- extra = " ".join(shlex.quote(a.value) for a in g.args if not a.dynamic)
2007
- self.analyze_text(alias[1:] + " " + extra, state.copy(), depth + 1)
2008
- return None
2009
- try:
2010
- segs = parse_command(alias)
2011
- except ParseError:
2012
- self.opaque("git alias `%s` can't be parsed" % g.sub, alias)
2013
- return None
2014
- aw = segs[0].words if segs else []
2015
- args = args[:g.sub_index] + aw + g.args
2016
- return parse_git(args)
2017
-
2018
- def git_config_alias(self, g, state, depth):
2019
- a = g.args
2020
- for k, w in enumerate(a):
2021
- if not w.dynamic and w.value.lower().startswith("alias.") and k + 1 < len(a):
2022
- val = a[k + 1]
2023
- name = w.value[6:]
2024
- if val.dynamic:
2025
- self.opaque("a git alias is defined from a run-time value", val.raw)
2026
- return
2027
- state.git_aliases[name] = val.value
2028
- inner = val.value[1:] if val.value.startswith("!") else "git " + val.value
2029
- self.analyze_text(inner, state.copy(), depth + 1)
2030
- return
2031
1832
 
1833
+ # ══ core/hooks/gate/rules.py ═════════════════════════════════════════════════
1834
+ class RuleChecks(object):
2032
1835
  def branch_gated(self, state, here_unknown):
2033
1836
  if here_unknown or state.sticky or not state.cwd_known:
2034
1837
  return True
@@ -2138,87 +1941,340 @@ class Analyzer(object):
2138
1941
  if inv.name != "git" or inv.git is None:
2139
1942
  return None
2140
1943
  g = inv.git
2141
- if g.sub is None:
2142
- return "possible" if g.dynamic_global else None
2143
- if pat_seg.git.sub is None:
2144
- return "match"
2145
- if pat_seg.git.sub != g.sub:
2146
- return None
2147
- if g.sub == "push" and inv.push is not None:
2148
- return match_push(pat_seg.git.args, g.args, inv.push)
2149
- return match_args(pat_seg.git.args, g.args, git=True)
2150
- best = None
2151
- cands = [(inv.name, inv.args)] + ([inv.core] if inv.core else []) + inv.cores
2152
- pcands = [(pat_seg.name, pat_seg.args)] + ([pat_seg.core] if pat_seg.core else [])
2153
- for pn, pa in pcands:
2154
- for cn, ca in cands:
2155
- if pn != cn:
2156
- continue
2157
- r = match_args(pa, ca, aliases=FLAG_ALIASES.get(cn))
2158
- if r == "match":
2159
- return r
2160
- best = best or r
2161
- return best
1944
+ if g.sub is None:
1945
+ return "possible" if g.dynamic_global else None
1946
+ if pat_seg.git.sub is None:
1947
+ return "match"
1948
+ if pat_seg.git.sub != g.sub:
1949
+ return None
1950
+ if g.sub == "push" and inv.push is not None:
1951
+ return match_push(pat_seg.git.args, g.args, inv.push)
1952
+ return match_args(pat_seg.git.args, g.args, git=True)
1953
+ best = None
1954
+ cands = [(inv.name, inv.args)] + ([inv.core] if inv.core else []) + inv.cores
1955
+ pcands = [(pat_seg.name, pat_seg.args)] + ([pat_seg.core] if pat_seg.core else [])
1956
+ for pn, pa in pcands:
1957
+ for cn, ca in cands:
1958
+ if pn != cn:
1959
+ continue
1960
+ r = match_args(pa, ca, aliases=FLAG_ALIASES.get(cn))
1961
+ if r == "match":
1962
+ return r
1963
+ best = best or r
1964
+ return best
1965
+
1966
+ def match_config(self, inv, state, here_unknown):
1967
+ ctx = self.ctx
1968
+ for p in ctx.deny_pats:
1969
+ if p.multi or not p.segs:
1970
+ continue
1971
+ r = self.match_inv(p.segs[0], inv)
1972
+ if r == "match":
1973
+ self.deny("`%s` is forbidden by the project's gate (gate-config.json deny)" % p.text)
1974
+ elif r == "possible":
1975
+ self.ask("`%s` builds arguments at run time and might match the deny rule `%s` "
1976
+ "— confirm" % (short(inv.seg.text, 60), p.text))
1977
+ for p in ctx.ask_pats:
1978
+ if p.multi or not p.segs:
1979
+ continue
1980
+ if self.match_inv(p.segs[0], inv):
1981
+ self.ask("`%s` is a gated command — confirm first (gate-config.json ask)" % p.text)
1982
+ for p in ctx.branch_pats:
1983
+ if p.multi or not p.segs:
1984
+ continue
1985
+ if not self.match_inv(p.segs[0], inv):
1986
+ continue
1987
+ gated = self.branch_gated(state, here_unknown)
1988
+ why = "the branch is the default branch or can't be determined"
1989
+ if inv.push is not None and (inv.push_touches or inv.push_unknown):
1990
+ gated = True
1991
+ why = "the push reaches the default branch (or its destination is unknown)"
1992
+ if gated:
1993
+ self.ask("`%s` is gated on the default branch %s and %s — confirm "
1994
+ "(it runs freely on feature branches)"
1995
+ % (p.text, "/".join("`%s`" % d for d in ctx.defaults()[:2]), why))
1996
+
1997
+ def multi_patterns(self, segs, invs, state):
1998
+ def ns(s):
1999
+ return ";" if s in (";", "\n", None) else s
2000
+ tiers = [("deny", self.ctx.deny_pats), ("ask", self.ctx.ask_pats),
2001
+ ("branch", self.ctx.branch_pats)]
2002
+ for tier, pats in tiers:
2003
+ for p in pats:
2004
+ if not p.multi:
2005
+ continue
2006
+ k = len(p.segs)
2007
+ for start in range(0, len(segs) - k + 1):
2008
+ ok = True
2009
+ for j, ps in enumerate(p.segs):
2010
+ if not self.match_inv(ps, invs[start + j]):
2011
+ ok = False
2012
+ break
2013
+ if j < k - 1 and ns(segs[start + j].sep) != ns(ps.sep):
2014
+ ok = False
2015
+ break
2016
+ if not ok:
2017
+ continue
2018
+ if tier == "deny":
2019
+ self.deny("`%s` is forbidden by the project's gate" % p.text)
2020
+ elif tier == "ask" or self.branch_gated(state, False):
2021
+ self.ask("`%s` is a gated command sequence — confirm" % p.text)
2022
+ break
2023
+
2024
+
2025
+ # ══ core/hooks/gate/protect.py ═══════════════════════════════════════════════
2026
+ PROTECTED_HINT_RE = re.compile(r"(^|/)\.claude(/|$)|gate-config\.json|preflight\.ok|"
2027
+ r"settings(\.local)?\.json|cohorte-gate\.py|pipeline\.json|"
2028
+ r"(^|/)\.cohorte(/|$)")
2029
+ PROTECTED_BASENAMES = {"gate-config.json", "preflight.ok", "settings.json", "settings.local.json", "profile.json",
2030
+ "cohorte-gate.py", "pipeline.json", ".claude", ".cohorte", "hooks", "~", "",
2031
+ ".", ".."}
2032
+
2033
+
2034
+ def suspicious(tail, raw):
2035
+ """For a path the gate can't resolve: could it name a protected file? Its static tail
2036
+ decides — `…/.claude/pipeline-metrics.jsonl` can't, `$DIR/.claude/settings.json` can."""
2037
+ base = os.path.basename(tail.rstrip("/")) if tail else ""
2038
+ if tail and "/" in tail and base not in PROTECTED_BASENAMES and not tail.endswith("/"):
2039
+ return False
2040
+ return bool(PROTECTED_HINT_RE.search(raw))
2041
+
2042
+
2043
+ class SelfProtection(object):
2044
+ def path_key(self, w, state):
2045
+ v = os.path.expanduser(w.value)
2046
+ if not os.path.isabs(v) and state.cwd_known:
2047
+ v = os.path.join(state.cwd, v)
2048
+ return os.path.normpath(v)
2049
+
2050
+ def remember_written(self, w, state):
2051
+ if not w.dynamic:
2052
+ state.written.add(self.path_key(w, state))
2053
+
2054
+ def known_text(self, w, state):
2055
+ """A run-time word with only the variables the gate can resolve itself
2056
+ ($CLAUDE_PROJECT_DIR, $HOME, $PWD) substituted, or None if anything else is left."""
2057
+ t = w.raw
2058
+ if len(t) >= 2 and t[0] == t[-1] == '"':
2059
+ t = t[1:-1]
2060
+ for var, val in (("CLAUDE_PROJECT_DIR", os.environ.get("CLAUDE_PROJECT_DIR")),
2061
+ ("HOME", os.path.expanduser("~")),
2062
+ ("PWD", state.cwd if state.cwd_known else None)):
2063
+ if val:
2064
+ # Forward slashes: a Windows value (C:\\Users\\…) would otherwise read as
2065
+ # shell escapes below and every expanded path would look suspect.
2066
+ val = val.replace("\\", "/")
2067
+ t = t.replace("${%s}" % var, val).replace("$" + var, val)
2068
+ if "$" in t or "`" in t or "'" in t or '"' in t or "\\" in t:
2069
+ return None
2070
+ return t
2071
+
2072
+ def classify_path(self, w, state, mode, relocated=False):
2073
+ ctx = self.ctx
2074
+ if w.dynamic:
2075
+ t = self.known_text(w, state)
2076
+ if t is None:
2077
+ return "suspect" if suspicious(w.value.split(DYN)[-1], w.raw) else None
2078
+ w = static_word(t)
2079
+ v = os.path.expanduser(w.value)
2080
+ if not v:
2081
+ return None
2082
+ if not os.path.isabs(v):
2083
+ if relocated or not state.cwd_known:
2084
+ return "suspect" if suspicious(v, v) else None
2085
+ v = os.path.join(state.cwd, v)
2086
+ prot = ctx.delete_protected if mode in ("delete", "recursive", "chmod") else ctx.protected
2087
+ targets = [v]
2088
+ if w.glob:
2089
+ pat = os.path.normpath(v)
2090
+ if any(fnmatch.fnmatchcase(p, pat) for p in prot):
2091
+ return "protected"
2092
+ try:
2093
+ targets = glob.glob(v)[:500]
2094
+ except Exception:
2095
+ targets = []
2096
+ for t in targets:
2097
+ for cand in {os.path.normpath(os.path.abspath(t)), os.path.realpath(t)}:
2098
+ if cand in prot:
2099
+ return "protected"
2100
+ if mode in ("delete", "recursive", "chmod"):
2101
+ pre = cand if cand.endswith(os.sep) else cand + os.sep
2102
+ if any(p.startswith(pre) for p in prot):
2103
+ return "protected" if mode == "delete" else "suspect"
2104
+ return None
2105
+
2106
+ def check_owner(self, w, state, mode, via, relocated=False, existing=False):
2107
+ """Surface ownership for a Bash write — best effort: a target the gate can't resolve
2108
+ statically (a run-time word, a relative path after an unresolvable `cd`) is let
2109
+ through, never asked about (an ask is a deny in unattended runs)."""
2110
+ try:
2111
+ t = self.known_text(w, state) if w.dynamic else w.value
2112
+ if not t:
2113
+ return
2114
+ v = os.path.expanduser(t)
2115
+ if not os.path.isabs(v):
2116
+ if relocated or not state.cwd_known:
2117
+ return
2118
+ v = os.path.join(state.cwd, v)
2119
+ if existing and not os.path.exists(v):
2120
+ return
2121
+ why = self.ctx.owner.judge(v)
2122
+ except Exception as e:
2123
+ warn("surface ownership could not judge `%s`: %s: %s" % (w.raw, type(e).__name__, e))
2124
+ return
2125
+ if why:
2126
+ verb = {"write": "write", "delete": "delete or move", "recursive": "write into",
2127
+ "chmod": "change the permissions of"}.get(mode, "write")
2128
+ self.deny("%s would %s `%s`: %s" % (via, verb, w.raw, why))
2129
+
2130
+ def check_path(self, w, state, mode, via, relocated=False, existing=False):
2131
+ if self.ctx.owner is not None:
2132
+ self.check_owner(w, state, mode, via, relocated, existing)
2133
+ kind = self.classify_path(w, state, mode, relocated)
2134
+ if kind is None:
2135
+ return
2136
+ verb = {"write": "overwrite", "delete": "delete or move", "recursive": "overwrite",
2137
+ "chmod": "change the permissions of"}[mode]
2138
+ if kind == "protected" and mode in ("write", "delete"):
2139
+ self.deny("%s would %s `%s`, which the Cohorte gate depends on (self-protection). "
2140
+ "Edit gate rules through PIPELINE.md and /cohorte-update-pipeline, or ask "
2141
+ "the human" % (via, verb, w.raw))
2142
+ else:
2143
+ self.ask("%s may %s a file the Cohorte gate depends on (`%s`) — confirm"
2144
+ % (via, verb, w.raw))
2145
+
2146
+ def protect(self, inv, state, relocated):
2147
+ name, args = inv.name, inv.args
2148
+
2149
+ def positionals(tokens, with_arg=()):
2150
+ out = []
2151
+ end = False
2152
+ k = 0
2153
+ while k < len(tokens):
2154
+ w = tokens[k]
2155
+ v = w.value
2156
+ if not end and v == "--":
2157
+ end = True
2158
+ elif not end and is_flag_word(w):
2159
+ if v in with_arg:
2160
+ k += 1
2161
+ else:
2162
+ out.append(w)
2163
+ k += 1
2164
+ return out
2165
+
2166
+ def recursive(tokens):
2167
+ fl = flag_names(tokens)
2168
+ return bool(fl & {"-r", "-R", "-a", "--recursive", "--archive"})
2169
+
2170
+ def copy_like(srcs, dst, label, mv=False):
2171
+ for s in srcs:
2172
+ if mv:
2173
+ self.check_path(s, state, "delete", "`%s`" % label, relocated)
2174
+ self.check_path(dst, state, "write", "`%s`" % label, relocated)
2175
+ dk = self.path_key(dst, state) if not dst.dynamic else None
2176
+ if dk and state.cwd_known and (os.path.isdir(dk) or dst.value.endswith("/")):
2177
+ for s in srcs:
2178
+ if not s.dynamic:
2179
+ self.check_path(static_word(os.path.join(dk, os.path.basename(
2180
+ s.value.rstrip("/")))), state, "write", "`%s`" % label, relocated)
2181
+ if recursive(args) or mv:
2182
+ self.check_path(dst, state, "recursive", "`%s`" % label, relocated)
2183
+
2184
+ if name in ("rm", "unlink", "shred", "rmdir", "srm", "trash", "trash-put"):
2185
+ for p in positionals(args):
2186
+ self.check_path(p, state, "delete", "`%s`" % name, relocated)
2187
+ elif name in ("mv", "cp", "install", "ln", "rsync", "scp", "ditto"):
2188
+ pos = positionals(args, ("-t", "--target-directory", "-S", "--suffix", "-m",
2189
+ "--mode", "-o", "-g", "-e", "--exclude", "--include"))
2190
+ target = None
2191
+ for k, w in enumerate(args):
2192
+ if w.value in ("-t", "--target-directory") and k + 1 < len(args):
2193
+ target = args[k + 1]
2194
+ elif w.value.startswith("--target-directory="):
2195
+ target = static_word(w.value.split("=", 1)[1])
2196
+ if target is not None:
2197
+ copy_like(pos, static_word(target.value.rstrip("/") + "/")
2198
+ if not target.dynamic else target, name, mv=(name == "mv"))
2199
+ elif len(pos) >= 2:
2200
+ copy_like(pos[:-1], pos[-1], name, mv=(name == "mv"))
2201
+ elif name == "tee":
2202
+ for p in positionals(args):
2203
+ self.check_path(p, state, "write", "`tee`", relocated)
2204
+ self.remember_written(p, state)
2205
+ elif name == "truncate":
2206
+ for p in positionals(args, ("-s", "-r", "--size", "--reference")):
2207
+ self.check_path(p, state, "write", "`truncate`", relocated)
2208
+ elif name in ("sed", "gsed", "perl", "ruby"):
2209
+ inplace = any(
2210
+ not w.dynamic and (w.value.startswith("--in-place") or (
2211
+ w.value.startswith("-") and not w.value.startswith("--")
2212
+ and "i" in w.value[1:].split(".")[0]))
2213
+ for w in args)
2214
+ if inplace:
2215
+ # Only existing files can be edited in place, so for ownership a positional
2216
+ # that names nothing on disk is the sed script (`sed -i 's/a/b/' f`) or a BSD
2217
+ # backup suffix (`sed -i .bak …`), not a target.
2218
+ for p in positionals(args, ("-e", "-f")):
2219
+ self.check_path(p, state, "write", "`%s -i`" % name, relocated, existing=True)
2220
+ elif name == "dd":
2221
+ for w in args:
2222
+ if w.value.startswith("of="):
2223
+ self.check_path(static_word(w.value[3:]) if not w.dynamic else w,
2224
+ state, "write", "`dd of=`", relocated)
2225
+ elif name in ("curl", "wget"):
2226
+ opts = ("-o", "--output") if name == "curl" else ("-O", "--output-document")
2227
+ for k, w in enumerate(args):
2228
+ v = w.value
2229
+ if v in opts and k + 1 < len(args):
2230
+ self.check_path(args[k + 1], state, "write", "`%s %s`" % (name, v), relocated)
2231
+ elif any(v.startswith(o + "=") for o in opts if o.startswith("--")):
2232
+ self.check_path(static_word(v.split("=", 1)[1]), state, "write",
2233
+ "`%s`" % name, relocated)
2234
+ elif name in ("chmod", "chown", "chgrp", "chflags", "chattr", "setfacl"):
2235
+ for p in positionals(args)[1:]:
2236
+ self.check_path(p, state, "chmod", "`%s`" % name, relocated)
2237
+ elif name == "find" and any(w.value == "-delete" for w in args):
2238
+ for w in args:
2239
+ if w.value.startswith("-") or w.value in ("(", "!", ")"):
2240
+ break
2241
+ self.check_path(w, state, "delete", "`find -delete`", relocated)
2242
+ elif name == "git" and inv.git and inv.git.sub in ("rm", "mv"):
2243
+ g = inv.git
2244
+ pos = positionals(g.args)
2245
+ reloc = relocated or g.relocated
2246
+ if g.sub == "rm" and not any(w.value == "--cached" for w in g.args):
2247
+ for p in pos:
2248
+ self.check_path(p, state, "delete", "`git rm`", reloc)
2249
+ elif g.sub == "mv" and len(pos) >= 2:
2250
+ for p in pos[:-1]:
2251
+ self.check_path(p, state, "delete", "`git mv`", reloc)
2252
+ self.check_path(pos[-1], state, "write", "`git mv`", reloc)
2162
2253
 
2163
- def match_config(self, inv, state, here_unknown):
2164
- ctx = self.ctx
2165
- for p in ctx.deny_pats:
2166
- if p.multi or not p.segs:
2167
- continue
2168
- r = self.match_inv(p.segs[0], inv)
2169
- if r == "match":
2170
- self.deny("`%s` is forbidden by the project's gate (gate-config.json deny)" % p.text)
2171
- elif r == "possible":
2172
- self.ask("`%s` builds arguments at run time and might match the deny rule `%s` "
2173
- "— confirm" % (short(inv.seg.text, 60), p.text))
2174
- for p in ctx.ask_pats:
2175
- if p.multi or not p.segs:
2176
- continue
2177
- if self.match_inv(p.segs[0], inv):
2178
- self.ask("`%s` is a gated command — confirm first (gate-config.json ask)" % p.text)
2179
- for p in ctx.branch_pats:
2180
- if p.multi or not p.segs:
2181
- continue
2182
- if not self.match_inv(p.segs[0], inv):
2183
- continue
2184
- gated = self.branch_gated(state, here_unknown)
2185
- why = "the branch is the default branch or can't be determined"
2186
- if inv.push is not None and (inv.push_touches or inv.push_unknown):
2187
- gated = True
2188
- why = "the push reaches the default branch (or its destination is unknown)"
2189
- if gated:
2190
- self.ask("`%s` is gated on the default branch %s and %s — confirm "
2191
- "(it runs freely on feature branches)"
2192
- % (p.text, "/".join("`%s`" % d for d in ctx.defaults()[:2]), why))
2193
2254
 
2194
- def multi_patterns(self, segs, invs, state):
2195
- def ns(s):
2196
- return ";" if s in (";", "\n", None) else s
2197
- tiers = [("deny", self.ctx.deny_pats), ("ask", self.ctx.ask_pats),
2198
- ("branch", self.ctx.branch_pats)]
2199
- for tier, pats in tiers:
2200
- for p in pats:
2201
- if not p.multi:
2202
- continue
2203
- k = len(p.segs)
2204
- for start in range(0, len(segs) - k + 1):
2205
- ok = True
2206
- for j, ps in enumerate(p.segs):
2207
- if not self.match_inv(ps, invs[start + j]):
2208
- ok = False
2209
- break
2210
- if j < k - 1 and ns(segs[start + j].sep) != ns(ps.sep):
2211
- ok = False
2212
- break
2213
- if not ok:
2214
- continue
2215
- if tier == "deny":
2216
- self.deny("`%s` is forbidden by the project's gate" % p.text)
2217
- elif tier == "ask" or self.branch_gated(state, False):
2218
- self.ask("`%s` is a gated command sequence — confirm" % p.text)
2219
- break
2255
+ # ══ core/hooks/gate/indirect.py ══════════════════════════════════════════════
2256
+ PROTECTED_NAME_RE = re.compile(r"gate-config\.json|preflight\.ok|\.claude/settings(\.local)?\.json|"
2257
+ r"cohorte-gate\.py|\.claude/profile\.json")
2258
+ SPAWN_RE = {
2259
+ "py": re.compile(r"\bos\.(system|popen|exec\w*|spawn\w*)|\bsubprocess\b|\bpty\.spawn|"
2260
+ r"\bcommands\.getoutput|\bpexpect\b|\bsh\.\w+\("),
2261
+ "js": re.compile(r"child_process|\bexecSync\b|\bspawnSync\b|\bexecFileSync\b|\bexecFile\(|"
2262
+ r"\bexec\(|\bspawn\(|Bun\.spawn|Deno\.(Command|run)|\$`|zx"),
2263
+ "pl": re.compile(r"\bsystem\b|\bexec\b|`|\bqx\b|IO\.popen|Open3|\bspawn\b|%x|\bpopen\b|"
2264
+ r"\bshell_exec\b|\bpassthru\b|\bproc_open\b"),
2265
+ }
2266
+ STRING_LIT_RE = re.compile(r"'((?:[^'\\]|\\.)*)'|\"((?:[^\"\\]|\\.)*)\"")
2267
+
2268
+
2269
+ def lang_of(name):
2270
+ if name.startswith("py"):
2271
+ return "py"
2272
+ if name in ("node", "nodejs", "deno", "bun"):
2273
+ return "js"
2274
+ return "pl"
2275
+
2220
2276
 
2221
- # -- indirection ---------------------------------------------------------------
2277
+ class Indirection(object):
2222
2278
  def indirection(self, inv, seg, prev, prev_inv, state, depth):
2223
2279
  name, args = inv.name, inv.args
2224
2280
  if name in SHELLS:
@@ -2530,216 +2586,185 @@ class Analyzer(object):
2530
2586
  self.opaque("`%s` executes whatever the pipe feeds it" % name,
2531
2587
  prev.text + " | " + seg.text)
2532
2588
 
2533
- # -- self-protection --------------------------------------------------------------
2534
- def path_key(self, w, state):
2535
- v = os.path.expanduser(w.value)
2536
- if not os.path.isabs(v) and state.cwd_known:
2537
- v = os.path.join(state.cwd, v)
2538
- return os.path.normpath(v)
2539
2589
 
2540
- def remember_written(self, w, state):
2541
- if not w.dynamic:
2542
- state.written.add(self.path_key(w, state))
2590
+ # ══ core/hooks/gate/analyze.py ═══════════════════════════════════════════════
2591
+ MAX_DEPTH = 6
2592
+ WRITE_OPS = {">", ">>", ">|", "&>", "&>>", "<>"}
2543
2593
 
2544
- def known_text(self, w, state):
2545
- """A run-time word with only the variables the gate can resolve itself
2546
- ($CLAUDE_PROJECT_DIR, $HOME, $PWD) substituted, or None if anything else is left."""
2547
- t = w.raw
2548
- if len(t) >= 2 and t[0] == t[-1] == '"':
2549
- t = t[1:-1]
2550
- for var, val in (("CLAUDE_PROJECT_DIR", os.environ.get("CLAUDE_PROJECT_DIR")),
2551
- ("HOME", os.path.expanduser("~")),
2552
- ("PWD", state.cwd if state.cwd_known else None)):
2553
- if val:
2554
- # Forward slashes: a Windows value (C:\\Users\\…) would otherwise read as
2555
- # shell escapes below and every expanded path would look suspect.
2556
- val = val.replace("\\", "/")
2557
- t = t.replace("${%s}" % var, val).replace("$" + var, val)
2558
- if "$" in t or "`" in t or "'" in t or '"' in t or "\\" in t:
2559
- return None
2560
- return t
2561
2594
 
2562
- def classify_path(self, w, state, mode, relocated=False):
2563
- ctx = self.ctx
2564
- if w.dynamic:
2565
- t = self.known_text(w, state)
2566
- if t is None:
2567
- return "suspect" if suspicious(w.value.split(DYN)[-1], w.raw) else None
2568
- w = static_word(t)
2569
- v = os.path.expanduser(w.value)
2570
- if not v:
2571
- return None
2572
- if not os.path.isabs(v):
2573
- if relocated or not state.cwd_known:
2574
- return "suspect" if suspicious(v, v) else None
2575
- v = os.path.join(state.cwd, v)
2576
- prot = ctx.delete_protected if mode in ("delete", "recursive", "chmod") else ctx.protected
2577
- targets = [v]
2578
- if w.glob:
2579
- pat = os.path.normpath(v)
2580
- if any(fnmatch.fnmatchcase(p, pat) for p in prot):
2581
- return "protected"
2582
- try:
2583
- targets = glob.glob(v)[:500]
2584
- except Exception:
2585
- targets = []
2586
- for t in targets:
2587
- for cand in {os.path.normpath(os.path.abspath(t)), os.path.realpath(t)}:
2588
- if cand in prot:
2589
- return "protected"
2590
- if mode in ("delete", "recursive", "chmod"):
2591
- pre = cand if cand.endswith(os.sep) else cand + os.sep
2592
- if any(p.startswith(pre) for p in prot):
2593
- return "protected" if mode == "delete" else "suspect"
2594
- return None
2595
+ class State(object):
2596
+ def __init__(self, cwd):
2597
+ self.cwd = cwd
2598
+ self.cwd_known = cwd is not None
2599
+ self.sticky = False # branch unknown for the rest of the chain
2600
+ self.written = set()
2601
+ self.git_aliases = {}
2595
2602
 
2596
- def check_owner(self, w, state, mode, via, relocated=False, existing=False):
2597
- """Surface ownership for a Bash write — best effort: a target the gate can't resolve
2598
- statically (a run-time word, a relative path after an unresolvable `cd`) is let
2599
- through, never asked about (an ask is a deny in unattended runs)."""
2600
- try:
2601
- t = self.known_text(w, state) if w.dynamic else w.value
2602
- if not t:
2603
- return
2604
- v = os.path.expanduser(t)
2605
- if not os.path.isabs(v):
2606
- if relocated or not state.cwd_known:
2607
- return
2608
- v = os.path.join(state.cwd, v)
2609
- if existing and not os.path.exists(v):
2610
- return
2611
- why = self.ctx.owner.judge(v)
2612
- except Exception as e:
2613
- warn("surface ownership could not judge `%s`: %s: %s" % (w.raw, type(e).__name__, e))
2614
- return
2615
- if why:
2616
- verb = {"write": "write", "delete": "delete or move", "recursive": "write into",
2617
- "chmod": "change the permissions of"}.get(mode, "write")
2618
- self.deny("%s would %s `%s`: %s" % (via, verb, w.raw, why))
2603
+ def copy(self):
2604
+ s = State(self.cwd)
2605
+ s.cwd_known = self.cwd_known
2606
+ s.sticky = self.sticky
2607
+ s.written = set(self.written)
2608
+ s.git_aliases = dict(self.git_aliases)
2609
+ return s
2610
+
2611
+
2612
+ class Inv(object):
2613
+ def __init__(self, name, args, seg):
2614
+ self.name = name
2615
+ self.args = args
2616
+ self.seg = seg
2617
+ self.git = None
2618
+ self.push = None
2619
+ self.push_touches = False
2620
+ self.push_unknown = False
2621
+ self.core = None
2622
+ self.cores = []
2623
+ self.prefixes = []
2619
2624
 
2620
- def check_path(self, w, state, mode, via, relocated=False, existing=False):
2621
- if self.ctx.owner is not None:
2622
- self.check_owner(w, state, mode, via, relocated, existing)
2623
- kind = self.classify_path(w, state, mode, relocated)
2624
- if kind is None:
2625
+
2626
+ class Analyzer(Indirection, SelfProtection, RuleChecks, Findings):
2627
+ def __init__(self, ctx):
2628
+ self.ctx = ctx
2629
+ self.findings = []
2630
+
2631
+ def analyze_text(self, text, state, depth):
2632
+ if depth > MAX_DEPTH:
2633
+ self.opaque("commands are nested too deep", text)
2625
2634
  return
2626
- verb = {"write": "overwrite", "delete": "delete or move", "recursive": "overwrite",
2627
- "chmod": "change the permissions of"}[mode]
2628
- if kind == "protected" and mode in ("write", "delete"):
2629
- self.deny("%s would %s `%s`, which the Cohorte gate depends on (self-protection). "
2630
- "Edit gate rules through PIPELINE.md and /cohorte-update-pipeline, or ask "
2631
- "the human" % (via, verb, w.raw))
2632
- else:
2633
- self.ask("%s may %s a file the Cohorte gate depends on (`%s`) — confirm"
2634
- % (via, verb, w.raw))
2635
+ try:
2636
+ segs = parse_command(text)
2637
+ except ParseError as e:
2638
+ self.unparseable(text, e)
2639
+ return
2640
+ self.walk(segs, state, depth, text)
2635
2641
 
2636
- def protect(self, inv, state, relocated):
2637
- name, args = inv.name, inv.args
2642
+ def walk(self, segs, state, depth, text=""):
2643
+ invs = []
2644
+ for idx, seg in enumerate(segs):
2645
+ prev = segs[idx - 1] if idx else None
2646
+ prev_inv = invs[-1] if invs else None
2647
+ if seg.subshell:
2648
+ state.sticky = True
2649
+ self.walk_substs(seg, state, depth)
2650
+ invs.append(self.eval_segment(seg, prev, prev_inv, state, depth))
2651
+ self.multi_patterns(segs, invs, state)
2652
+ for p in self.ctx.deny_pats + self.ctx.ask_pats:
2653
+ if not p.segs and p.norm in norm_lower(text):
2654
+ (self.deny if p in self.ctx.deny_pats else self.ask)(
2655
+ "`%s` (raw-text rule) matches this command" % p.text)
2638
2656
 
2639
- def positionals(tokens, with_arg=()):
2640
- out = []
2641
- end = False
2642
- k = 0
2643
- while k < len(tokens):
2644
- w = tokens[k]
2645
- v = w.value
2646
- if not end and v == "--":
2647
- end = True
2648
- elif not end and is_flag_word(w):
2649
- if v in with_arg:
2650
- k += 1
2651
- else:
2652
- out.append(w)
2653
- k += 1
2654
- return out
2657
+ def walk_substs(self, seg, state, depth):
2658
+ words = list(seg.words) + [r.target for r in seg.redirs]
2659
+ for w in words:
2660
+ for sub in w.substs:
2661
+ self.walk(sub, state.copy(), depth + 1)
2662
+ for h in seg.heredocs:
2663
+ for sub in h.substs:
2664
+ self.walk(sub, state.copy(), depth + 1)
2655
2665
 
2656
- def recursive(tokens):
2657
- fl = flag_names(tokens)
2658
- return bool(fl & {"-r", "-R", "-a", "--recursive", "--archive"})
2666
+ # -- one simple command ----------------------------------------------------
2667
+ def eval_segment(self, seg, prev, prev_inv, state, depth):
2668
+ words = list(seg.words)
2669
+ if seg.funcdef:
2670
+ while words and words[0].value != "{":
2671
+ words.pop(0)
2672
+ for r in seg.redirs:
2673
+ if r.op in WRITE_OPS or (r.op == ">&" and not (r.target.value.isdigit()
2674
+ or r.target.value == "-")):
2675
+ self.check_path(r.target, state, "write", "a redirection")
2676
+ self.remember_written(r.target, state)
2677
+ while words and not words[0].quoted and words[0].value in RESERVED_SKIP:
2678
+ words.pop(0)
2679
+ if words and not words[0].quoted and words[0].value in RESERVED_HEADER:
2680
+ return None
2681
+ if words and words[-1].value == "}" and not words[-1].quoted:
2682
+ words.pop()
2683
+ argv, assigns, env_s, relocated, lookup = strip_prefixes(words)
2684
+ prefixes = list(PREFIXES_SEEN)
2685
+ seg_unknown = relocated
2686
+ if GIT_ENV_VARS.intersection(assigns):
2687
+ state.sticky = True
2688
+ seg_unknown = True
2689
+ if env_s is not None:
2690
+ if env_s.dynamic:
2691
+ self.opaque("`env -S` runs a string built at run time", seg.text)
2692
+ else:
2693
+ self.analyze_text(env_s.value, state.copy(), depth + 1)
2694
+ return None
2695
+ if lookup or not argv:
2696
+ return None
2697
+ cmd = argv[0]
2698
+ if cmd.dynamic:
2699
+ self.opaque("the command name is computed at run time", seg.text)
2700
+ return None
2701
+ name = cmd_name(cmd.value)
2702
+ args = argv[1:]
2703
+ inv = Inv(name, args, seg)
2704
+ inv.prefixes = prefixes
2659
2705
 
2660
- def copy_like(srcs, dst, label, mv=False):
2661
- for s in srcs:
2662
- if mv:
2663
- self.check_path(s, state, "delete", "`%s`" % label, relocated)
2664
- self.check_path(dst, state, "write", "`%s`" % label, relocated)
2665
- dk = self.path_key(dst, state) if not dst.dynamic else None
2666
- if dk and state.cwd_known and (os.path.isdir(dk) or dst.value.endswith("/")):
2667
- for s in srcs:
2668
- if not s.dynamic:
2669
- self.check_path(static_word(os.path.join(dk, os.path.basename(
2670
- s.value.rstrip("/")))), state, "write", "`%s`" % label, relocated)
2671
- if recursive(args) or mv:
2672
- self.check_path(dst, state, "recursive", "`%s`" % label, relocated)
2706
+ if name == "git":
2707
+ g = self.expand_git(args, state, depth)
2708
+ if g is None:
2709
+ return None
2710
+ inv.git = g
2711
+ inv.args = args = (argv[1:1 + (g.sub_index or 0)] + [static_word(g.sub)] + g.args
2712
+ if g.sub else args)
2713
+ if g.relocated:
2714
+ seg_unknown = True
2715
+ if g.dynamic_global:
2716
+ self.opaque("git's arguments are computed at run time", seg.text)
2717
+ else:
2718
+ inv.core = runner_core(name, args)
2719
+ inv.cores = wrapper_cores(name, args)
2673
2720
 
2674
- if name in ("rm", "unlink", "shred", "rmdir", "srm", "trash", "trash-put"):
2675
- for p in positionals(args):
2676
- self.check_path(p, state, "delete", "`%s`" % name, relocated)
2677
- elif name in ("mv", "cp", "install", "ln", "rsync", "scp", "ditto"):
2678
- pos = positionals(args, ("-t", "--target-directory", "-S", "--suffix", "-m",
2679
- "--mode", "-o", "-g", "-e", "--exclude", "--include"))
2680
- target = None
2681
- for k, w in enumerate(args):
2682
- if w.value in ("-t", "--target-directory") and k + 1 < len(args):
2683
- target = args[k + 1]
2684
- elif w.value.startswith("--target-directory="):
2685
- target = static_word(w.value.split("=", 1)[1])
2686
- if target is not None:
2687
- copy_like(pos, static_word(target.value.rstrip("/") + "/")
2688
- if not target.dynamic else target, name, mv=(name == "mv"))
2689
- elif len(pos) >= 2:
2690
- copy_like(pos[:-1], pos[-1], name, mv=(name == "mv"))
2691
- elif name == "tee":
2692
- for p in positionals(args):
2693
- self.check_path(p, state, "write", "`tee`", relocated)
2694
- self.remember_written(p, state)
2695
- elif name == "truncate":
2696
- for p in positionals(args, ("-s", "-r", "--size", "--reference")):
2697
- self.check_path(p, state, "write", "`truncate`", relocated)
2698
- elif name in ("sed", "gsed", "perl", "ruby"):
2699
- inplace = any(
2700
- not w.dynamic and (w.value.startswith("--in-place") or (
2701
- w.value.startswith("-") and not w.value.startswith("--")
2702
- and "i" in w.value[1:].split(".")[0]))
2703
- for w in args)
2704
- if inplace:
2705
- # Only existing files can be edited in place, so for ownership a positional
2706
- # that names nothing on disk is the sed script (`sed -i 's/a/b/' f`) or a BSD
2707
- # backup suffix (`sed -i .bak …`), not a target.
2708
- for p in positionals(args, ("-e", "-f")):
2709
- self.check_path(p, state, "write", "`%s -i`" % name, relocated, existing=True)
2710
- elif name == "dd":
2711
- for w in args:
2712
- if w.value.startswith("of="):
2713
- self.check_path(static_word(w.value[3:]) if not w.dynamic else w,
2714
- state, "write", "`dd of=`", relocated)
2715
- elif name in ("curl", "wget"):
2716
- opts = ("-o", "--output") if name == "curl" else ("-O", "--output-document")
2717
- for k, w in enumerate(args):
2718
- v = w.value
2719
- if v in opts and k + 1 < len(args):
2720
- self.check_path(args[k + 1], state, "write", "`%s %s`" % (name, v), relocated)
2721
- elif any(v.startswith(o + "=") for o in opts if o.startswith("--")):
2722
- self.check_path(static_word(v.split("=", 1)[1]), state, "write",
2723
- "`%s`" % name, relocated)
2724
- elif name in ("chmod", "chown", "chgrp", "chflags", "chattr", "setfacl"):
2725
- for p in positionals(args)[1:]:
2726
- self.check_path(p, state, "chmod", "`%s`" % name, relocated)
2727
- elif name == "find" and any(w.value == "-delete" for w in args):
2728
- for w in args:
2729
- if w.value.startswith("-") or w.value in ("(", "!", ")"):
2730
- break
2731
- self.check_path(w, state, "delete", "`find -delete`", relocated)
2732
- elif name == "git" and inv.git and inv.git.sub in ("rm", "mv"):
2733
- g = inv.git
2734
- pos = positionals(g.args)
2735
- reloc = relocated or g.relocated
2736
- if g.sub == "rm" and not any(w.value == "--cached" for w in g.args):
2737
- for p in pos:
2738
- self.check_path(p, state, "delete", "`git rm`", reloc)
2739
- elif g.sub == "mv" and len(pos) >= 2:
2740
- for p in pos[:-1]:
2741
- self.check_path(p, state, "delete", "`git mv`", reloc)
2742
- self.check_path(pos[-1], state, "write", "`git mv`", reloc)
2721
+ here_unknown = seg_unknown or state.sticky or not state.cwd_known
2722
+ if inv.git and inv.git.sub == "push":
2723
+ self.eval_push(inv, state, here_unknown)
2724
+ self.match_config(inv, state, here_unknown)
2725
+ self.indirection(inv, seg, prev, prev_inv, state, depth)
2726
+ self.protect(inv, state, seg_unknown)
2727
+ self.update_state(inv, seg, state, assigns)
2728
+ return inv
2729
+
2730
+ def expand_git(self, args, state, depth):
2731
+ for _ in range(4):
2732
+ g = parse_git(args)
2733
+ if g.sub is None or g.sub in GIT_BUILTINS:
2734
+ if g.sub == "config":
2735
+ self.git_config_alias(g, state, depth)
2736
+ return g
2737
+ alias = g.c_aliases.get(g.sub) or state.git_aliases.get(g.sub)
2738
+ if alias is None and state.cwd_known and not g.relocated:
2739
+ alias = self.ctx.git_alias(g.sub, state.cwd)
2740
+ if alias is None:
2741
+ return g
2742
+ if alias.startswith("!"):
2743
+ extra = " ".join(shlex.quote(a.value) for a in g.args if not a.dynamic)
2744
+ self.analyze_text(alias[1:] + " " + extra, state.copy(), depth + 1)
2745
+ return None
2746
+ try:
2747
+ segs = parse_command(alias)
2748
+ except ParseError:
2749
+ self.opaque("git alias `%s` can't be parsed" % g.sub, alias)
2750
+ return None
2751
+ aw = segs[0].words if segs else []
2752
+ args = args[:g.sub_index] + aw + g.args
2753
+ return parse_git(args)
2754
+
2755
+ def git_config_alias(self, g, state, depth):
2756
+ a = g.args
2757
+ for k, w in enumerate(a):
2758
+ if not w.dynamic and w.value.lower().startswith("alias.") and k + 1 < len(a):
2759
+ val = a[k + 1]
2760
+ name = w.value[6:]
2761
+ if val.dynamic:
2762
+ self.opaque("a git alias is defined from a run-time value", val.raw)
2763
+ return
2764
+ state.git_aliases[name] = val.value
2765
+ inner = val.value[1:] if val.value.startswith("!") else "git " + val.value
2766
+ self.analyze_text(inner, state.copy(), depth + 1)
2767
+ return
2743
2768
 
2744
2769
  # -- chain state -----------------------------------------------------------------
2745
2770
  def update_state(self, inv, seg, state, assigns):
@@ -2814,6 +2839,7 @@ class Analyzer(object):
2814
2839
  return t
2815
2840
 
2816
2841
 
2842
+ # ══ core/hooks/gate/preflight.py ═════════════════════════════════════════════
2817
2843
  # ── preflight phase gate ─────────────────────────────────────────────────────
2818
2844
  HEX_RE = re.compile(r"^[0-9a-f]{40}([0-9a-f]{24})?$")
2819
2845
  DIGEST_EXCLUDES = (".claude", "specs")
@@ -2969,7 +2995,8 @@ class Dispatch(object):
2969
2995
  "(PIPELINE.md gate.preflight)." % (sub, why))
2970
2996
 
2971
2997
 
2972
- # ── entry points ─────────────────────────────────────────────────────────────
2998
+ # ══ core/hooks/gate/evaluate.py ══════════════════════════════════════════════
2999
+ # ── evaluation ───────────────────────────────────────────────────────────────
2973
3000
  DISPATCH_TOOLS = {"Task", "Agent"}
2974
3001
  EDIT_TOOLS = {"Write", "Edit", "MultiEdit", "NotebookEdit"}
2975
3002
  GATED_TOOLS = {"Bash"} | DISPATCH_TOOLS | EDIT_TOOLS
@@ -3083,6 +3110,8 @@ def evaluate(payload):
3083
3110
  return level, "Cohorte gate: " + reason
3084
3111
 
3085
3112
 
3113
+ # ══ core/hooks/gate/main.py ══════════════════════════════════════════════════
3114
+ # ── entry points ─────────────────────────────────────────────────────────────
3086
3115
  def emit(decision, reason):
3087
3116
  sys.stdout.write(json.dumps({"hookSpecificOutput": {
3088
3117
  "hookEventName": "PreToolUse",