cohorte 3.1.2 → 3.2.0

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,8 +1,8 @@
1
1
  #!/usr/bin/env python3
2
2
  # GENERATED from core/hooks/gate/*.py by scripts/build-gate.mjs — edit the modules, then run
3
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, analyze, preflight,
5
- # evaluate, main.
4
+ # Build order: runtime, shell, git, config, ownership, patterns, context, findings, rules,
5
+ # protect, indirect, analyze, preflight, evaluate, main.
6
6
  """Cohorte PreToolUse gate for Claude Code (3.0 — Claude Code only).
7
7
 
8
8
  Installed per project as `.claude/hooks/cohorte-gate.py` and registered in the project's
@@ -1776,93 +1776,17 @@ class Ctx(object):
1776
1776
  return self._aliases[key]
1777
1777
 
1778
1778
 
1779
- # ══ core/hooks/gate/analyze.py ═══════════════════════════════════════════════
1780
- # ── analysis ─────────────────────────────────────────────────────────────────
1781
- PROTECTED_HINT_RE = re.compile(r"(^|/)\.claude(/|$)|gate-config\.json|preflight\.ok|"
1782
- r"settings(\.local)?\.json|cohorte-gate\.py|pipeline\.json|"
1783
- r"(^|/)\.cohorte(/|$)")
1784
- PROTECTED_NAME_RE = re.compile(r"gate-config\.json|preflight\.ok|\.claude/settings(\.local)?\.json|"
1785
- r"cohorte-gate\.py|\.claude/profile\.json")
1786
- SPAWN_RE = {
1787
- "py": re.compile(r"\bos\.(system|popen|exec\w*|spawn\w*)|\bsubprocess\b|\bpty\.spawn|"
1788
- r"\bcommands\.getoutput|\bpexpect\b|\bsh\.\w+\("),
1789
- "js": re.compile(r"child_process|\bexecSync\b|\bspawnSync\b|\bexecFileSync\b|\bexecFile\(|"
1790
- r"\bexec\(|\bspawn\(|Bun\.spawn|Deno\.(Command|run)|\$`|zx"),
1791
- "pl": re.compile(r"\bsystem\b|\bexec\b|`|\bqx\b|IO\.popen|Open3|\bspawn\b|%x|\bpopen\b|"
1792
- r"\bshell_exec\b|\bpassthru\b|\bproc_open\b"),
1793
- }
1794
- STRING_LIT_RE = re.compile(r"'((?:[^'\\]|\\.)*)'|\"((?:[^\"\\]|\\.)*)\"")
1795
- PROTECTED_BASENAMES = {"gate-config.json", "preflight.ok", "settings.json", "settings.local.json", "profile.json",
1796
- "cohorte-gate.py", "pipeline.json", ".claude", ".cohorte", "hooks", "~", "",
1797
- ".", ".."}
1798
-
1799
-
1800
- def suspicious(tail, raw):
1801
- """For a path the gate can't resolve: could it name a protected file? Its static tail
1802
- decides — `…/.claude/pipeline-metrics.jsonl` can't, `$DIR/.claude/settings.json` can."""
1803
- base = os.path.basename(tail.rstrip("/")) if tail else ""
1804
- if tail and "/" in tail and base not in PROTECTED_BASENAMES and not tail.endswith("/"):
1805
- return False
1806
- return bool(PROTECTED_HINT_RE.search(raw))
1807
-
1808
-
1809
- MAX_DEPTH = 6
1810
- WRITE_OPS = {">", ">>", ">|", "&>", "&>>", "<>"}
1811
-
1812
-
1779
+ # ══ core/hooks/gate/findings.py ══════════════════════════════════════════════
1813
1780
  def norm_lower(s):
1814
1781
  return " ".join(s.lower().split())
1815
1782
 
1816
1783
 
1817
- def lang_of(name):
1818
- if name.startswith("py"):
1819
- return "py"
1820
- if name in ("node", "nodejs", "deno", "bun"):
1821
- return "js"
1822
- return "pl"
1823
-
1824
-
1825
- class State(object):
1826
- def __init__(self, cwd):
1827
- self.cwd = cwd
1828
- self.cwd_known = cwd is not None
1829
- self.sticky = False # branch unknown for the rest of the chain
1830
- self.written = set()
1831
- self.git_aliases = {}
1832
-
1833
- def copy(self):
1834
- s = State(self.cwd)
1835
- s.cwd_known = self.cwd_known
1836
- s.sticky = self.sticky
1837
- s.written = set(self.written)
1838
- s.git_aliases = dict(self.git_aliases)
1839
- return s
1840
-
1841
-
1842
- class Inv(object):
1843
- def __init__(self, name, args, seg):
1844
- self.name = name
1845
- self.args = args
1846
- self.seg = seg
1847
- self.git = None
1848
- self.push = None
1849
- self.push_touches = False
1850
- self.push_unknown = False
1851
- self.core = None
1852
- self.cores = []
1853
- self.prefixes = []
1854
-
1855
-
1856
1784
  def short(text, n=90):
1857
1785
  t = " ".join(text.split())
1858
1786
  return t if len(t) <= n else t[:n - 1] + "…"
1859
1787
 
1860
1788
 
1861
- class Analyzer(object):
1862
- def __init__(self, ctx):
1863
- self.ctx = ctx
1864
- self.findings = []
1865
-
1789
+ class Findings(object):
1866
1790
  def deny(self, why):
1867
1791
  self.findings.append(("deny", why))
1868
1792
 
@@ -1905,144 +1829,9 @@ class Analyzer(object):
1905
1829
  self.ask("the gate can't parse this command (%s), so it can't verify it — confirm"
1906
1830
  % err)
1907
1831
 
1908
- def analyze_text(self, text, state, depth):
1909
- if depth > MAX_DEPTH:
1910
- self.opaque("commands are nested too deep", text)
1911
- return
1912
- try:
1913
- segs = parse_command(text)
1914
- except ParseError as e:
1915
- self.unparseable(text, e)
1916
- return
1917
- self.walk(segs, state, depth, text)
1918
-
1919
- def walk(self, segs, state, depth, text=""):
1920
- invs = []
1921
- for idx, seg in enumerate(segs):
1922
- prev = segs[idx - 1] if idx else None
1923
- prev_inv = invs[-1] if invs else None
1924
- if seg.subshell:
1925
- state.sticky = True
1926
- self.walk_substs(seg, state, depth)
1927
- invs.append(self.eval_segment(seg, prev, prev_inv, state, depth))
1928
- self.multi_patterns(segs, invs, state)
1929
- for p in self.ctx.deny_pats + self.ctx.ask_pats:
1930
- if not p.segs and p.norm in norm_lower(text):
1931
- (self.deny if p in self.ctx.deny_pats else self.ask)(
1932
- "`%s` (raw-text rule) matches this command" % p.text)
1933
-
1934
- def walk_substs(self, seg, state, depth):
1935
- words = list(seg.words) + [r.target for r in seg.redirs]
1936
- for w in words:
1937
- for sub in w.substs:
1938
- self.walk(sub, state.copy(), depth + 1)
1939
- for h in seg.heredocs:
1940
- for sub in h.substs:
1941
- self.walk(sub, state.copy(), depth + 1)
1942
-
1943
- # -- one simple command ----------------------------------------------------
1944
- def eval_segment(self, seg, prev, prev_inv, state, depth):
1945
- words = list(seg.words)
1946
- if seg.funcdef:
1947
- while words and words[0].value != "{":
1948
- words.pop(0)
1949
- for r in seg.redirs:
1950
- if r.op in WRITE_OPS or (r.op == ">&" and not (r.target.value.isdigit()
1951
- or r.target.value == "-")):
1952
- self.check_path(r.target, state, "write", "a redirection")
1953
- self.remember_written(r.target, state)
1954
- while words and not words[0].quoted and words[0].value in RESERVED_SKIP:
1955
- words.pop(0)
1956
- if words and not words[0].quoted and words[0].value in RESERVED_HEADER:
1957
- return None
1958
- if words and words[-1].value == "}" and not words[-1].quoted:
1959
- words.pop()
1960
- argv, assigns, env_s, relocated, lookup = strip_prefixes(words)
1961
- prefixes = list(PREFIXES_SEEN)
1962
- seg_unknown = relocated
1963
- if GIT_ENV_VARS.intersection(assigns):
1964
- state.sticky = True
1965
- seg_unknown = True
1966
- if env_s is not None:
1967
- if env_s.dynamic:
1968
- self.opaque("`env -S` runs a string built at run time", seg.text)
1969
- else:
1970
- self.analyze_text(env_s.value, state.copy(), depth + 1)
1971
- return None
1972
- if lookup or not argv:
1973
- return None
1974
- cmd = argv[0]
1975
- if cmd.dynamic:
1976
- self.opaque("the command name is computed at run time", seg.text)
1977
- return None
1978
- name = cmd_name(cmd.value)
1979
- args = argv[1:]
1980
- inv = Inv(name, args, seg)
1981
- inv.prefixes = prefixes
1982
-
1983
- if name == "git":
1984
- g = self.expand_git(args, state, depth)
1985
- if g is None:
1986
- return None
1987
- inv.git = g
1988
- inv.args = args = (argv[1:1 + (g.sub_index or 0)] + [static_word(g.sub)] + g.args
1989
- if g.sub else args)
1990
- if g.relocated:
1991
- seg_unknown = True
1992
- if g.dynamic_global:
1993
- self.opaque("git's arguments are computed at run time", seg.text)
1994
- else:
1995
- inv.core = runner_core(name, args)
1996
- inv.cores = wrapper_cores(name, args)
1997
-
1998
- here_unknown = seg_unknown or state.sticky or not state.cwd_known
1999
- if inv.git and inv.git.sub == "push":
2000
- self.eval_push(inv, state, here_unknown)
2001
- self.match_config(inv, state, here_unknown)
2002
- self.indirection(inv, seg, prev, prev_inv, state, depth)
2003
- self.protect(inv, state, seg_unknown)
2004
- self.update_state(inv, seg, state, assigns)
2005
- return inv
2006
-
2007
- def expand_git(self, args, state, depth):
2008
- for _ in range(4):
2009
- g = parse_git(args)
2010
- if g.sub is None or g.sub in GIT_BUILTINS:
2011
- if g.sub == "config":
2012
- self.git_config_alias(g, state, depth)
2013
- return g
2014
- alias = g.c_aliases.get(g.sub) or state.git_aliases.get(g.sub)
2015
- if alias is None and state.cwd_known and not g.relocated:
2016
- alias = self.ctx.git_alias(g.sub, state.cwd)
2017
- if alias is None:
2018
- return g
2019
- if alias.startswith("!"):
2020
- extra = " ".join(shlex.quote(a.value) for a in g.args if not a.dynamic)
2021
- self.analyze_text(alias[1:] + " " + extra, state.copy(), depth + 1)
2022
- return None
2023
- try:
2024
- segs = parse_command(alias)
2025
- except ParseError:
2026
- self.opaque("git alias `%s` can't be parsed" % g.sub, alias)
2027
- return None
2028
- aw = segs[0].words if segs else []
2029
- args = args[:g.sub_index] + aw + g.args
2030
- return parse_git(args)
2031
-
2032
- def git_config_alias(self, g, state, depth):
2033
- a = g.args
2034
- for k, w in enumerate(a):
2035
- if not w.dynamic and w.value.lower().startswith("alias.") and k + 1 < len(a):
2036
- val = a[k + 1]
2037
- name = w.value[6:]
2038
- if val.dynamic:
2039
- self.opaque("a git alias is defined from a run-time value", val.raw)
2040
- return
2041
- state.git_aliases[name] = val.value
2042
- inner = val.value[1:] if val.value.startswith("!") else "git " + val.value
2043
- self.analyze_text(inner, state.copy(), depth + 1)
2044
- return
2045
1832
 
1833
+ # ══ core/hooks/gate/rules.py ═════════════════════════════════════════════════
1834
+ class RuleChecks(object):
2046
1835
  def branch_gated(self, state, here_unknown):
2047
1836
  if here_unknown or state.sticky or not state.cwd_known:
2048
1837
  return True
@@ -2232,346 +2021,53 @@ class Analyzer(object):
2232
2021
  self.ask("`%s` is a gated command sequence — confirm" % p.text)
2233
2022
  break
2234
2023
 
2235
- # -- indirection ---------------------------------------------------------------
2236
- def indirection(self, inv, seg, prev, prev_inv, state, depth):
2237
- name, args = inv.name, inv.args
2238
- if name in SHELLS:
2239
- code, script, sargs = self.shell_args(args)
2240
- if code is not None:
2241
- if code.dynamic:
2242
- self.opaque("`%s -c` runs a command string built at run time" % name, code.raw)
2243
- else:
2244
- self.analyze_text(code.value, state.copy(), depth + 1)
2245
- elif script is not None:
2246
- self.run_script(name, script, sargs, state, depth)
2247
- else:
2248
- self.stdin_code(name, "sh", seg, prev, prev_inv, state, depth)
2249
- return
2250
- if name == "preflight.sh":
2251
- self.preflight_args(args, state, depth)
2252
- return
2253
- if name == "verify-run.sh":
2254
- self.verify_args(args, state, depth)
2255
- return
2256
- if name == "eval":
2257
- text = " ".join(a.value for a in args)
2258
- if any(a.dynamic for a in args):
2259
- self.opaque("`eval` of a string built at run time", " ".join(a.raw for a in args))
2260
- else:
2261
- self.analyze_text(text, state, depth + 1)
2262
- return
2263
- if name in ("source", "."):
2264
- if args:
2265
- self.run_script(name, args[0], args[1:], state, depth)
2266
- return
2267
- if INTERP_RE.match(name):
2268
- lang = lang_of(name)
2269
- code, has_script = self.interp_code(name, args)
2270
- if code is not None:
2271
- self.code_check(lang, code.raw if code.dynamic else code.value, state, depth)
2272
- elif not has_script:
2273
- self.stdin_code(name, lang, seg, prev, prev_inv, state, depth)
2274
- return
2275
- if name in ("xargs",):
2276
- k = 0
2277
- with_arg = {"-I", "-L", "-l", "-n", "-P", "-s", "-d", "-E", "-e", "-a",
2278
- "--max-args", "--delimiter", "--arg-file", "--max-procs", "--replace",
2279
- "--max-lines", "--max-chars", "--eof"}
2280
- while k < len(args) and args[k].value.startswith("-") and not args[k].dynamic:
2281
- k += 2 if args[k].value in with_arg else 1
2282
- rest = args[k:] or [static_word("echo")]
2283
- self.synthetic(rest + [wildcard_word()], seg, state, depth)
2284
- return
2285
- if name == "find":
2286
- k = 0
2287
- while k < len(args):
2288
- v = args[k].value
2289
- if v in ("-exec", "-execdir", "-ok", "-okdir"):
2290
- j = k + 1
2291
- while j < len(args) and args[j].value not in (";", "+"):
2292
- j += 1
2293
- if j > k + 1:
2294
- self.synthetic(args[k + 1:j], seg, state, depth)
2295
- k = j
2296
- k += 1
2297
- return
2298
- if name == "watch":
2299
- k = 0
2300
- while k < len(args) and args[k].value.startswith("-"):
2301
- k += 2 if args[k].value in ("-n", "--interval", "-d") else 1
2302
- if k < len(args):
2303
- if any(a.dynamic for a in args[k:]):
2304
- self.opaque("`watch` runs a command built at run time", seg.text)
2305
- else:
2306
- self.analyze_text(" ".join(a.value for a in args[k:]), state.copy(), depth + 1)
2307
- return
2308
- if name in ("su", "runuser"):
2309
- for k, a in enumerate(args):
2310
- if a.value in ("-c", "--command") and k + 1 < len(args):
2311
- c = args[k + 1]
2312
- if c.dynamic:
2313
- self.opaque("`su -c` runs a command built at run time", c.raw)
2314
- else:
2315
- self.analyze_text(c.value, state.copy(), depth + 1)
2316
- return
2317
- if name == "trap" and args:
2318
- a = args[0]
2319
- if a.dynamic:
2320
- self.opaque("`trap` installs a command built at run time", a.raw)
2321
- elif a.value not in ("-", "") and not a.value.startswith("-"):
2322
- self.analyze_text(a.value, state.copy(), depth + 1)
2323
- return
2324
- if name == "alias":
2325
- for a in args:
2326
- if "=" in a.value:
2327
- val = a.value.split("=", 1)[1]
2328
- if a.dynamic:
2329
- self.opaque("an alias is defined from a run-time value", a.raw)
2330
- elif val:
2331
- self.analyze_text(val, state.copy(), depth + 1)
2332
- return
2333
- if name in ("ssh", "mosh"):
2334
- k = 0
2335
- with_arg = set("-b -c -D -E -e -F -I -i -J -L -l -m -O -o -p -Q -R -S -W -w -B".split())
2336
- while k < len(args) and args[k].value.startswith("-") and not args[k].dynamic:
2337
- k += 2 if args[k].value in with_arg else 1
2338
- rest = args[k + 1:]
2339
- if rest:
2340
- remote = state.copy()
2341
- remote.cwd_known = False
2342
- remote.sticky = True
2343
- if any(a.dynamic for a in rest):
2344
- self.opaque("`ssh` runs a remote command built at run time", seg.text)
2345
- else:
2346
- self.analyze_text(" ".join(a.value for a in rest), remote, depth + 1)
2347
- return
2348
- if name in ("npx", "bunx", "pnpx"):
2349
- for k, a in enumerate(args):
2350
- if a.value in ("-c", "--call") and k + 1 < len(args):
2351
- c = args[k + 1]
2352
- if c.dynamic:
2353
- self.opaque("`npx -c` runs a command built at run time", c.raw)
2354
- else:
2355
- self.analyze_text(c.value, state.copy(), depth + 1)
2356
2024
 
2357
- def synthetic(self, words, seg, state, depth):
2358
- s = Seg(seg.src, seg.start, False)
2359
- s.end = seg.end
2360
- s.words = list(words)
2361
- s.sep = seg.sep
2362
- self.eval_segment(s, None, None, state.copy(), depth + 1)
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
+ ".", ".."}
2363
2032
 
2364
- def shell_args(self, args):
2365
- code_next = False
2366
- k = 0
2367
- while k < len(args):
2368
- a = args[k]
2369
- v = a.value
2370
- if a.dynamic and not code_next:
2371
- return None, a, args[k + 1:]
2372
- if code_next:
2373
- return a, None, args[k + 1:]
2374
- if v == "--" or v == "-":
2375
- k += 1
2376
- break
2377
- if v in ("-o", "+o", "-O", "+O", "--rcfile", "--init-file"):
2378
- k += 2
2379
- continue
2380
- if v.startswith("--"):
2381
- k += 1
2382
- continue
2383
- if len(v) > 1 and v[0] in "-+":
2384
- if v[0] == "-" and "c" in v[1:]:
2385
- code_next = True
2386
- k += 1
2387
- continue
2388
- break
2389
- if code_next:
2390
- return (args[k] if k < len(args) else static_word("")), None, args[k + 1:]
2391
- if k < len(args):
2392
- return None, args[k], args[k + 1:]
2393
- return None, None, []
2394
2033
 
2395
- def run_script(self, name, script, sargs, state, depth):
2396
- if script.dynamic:
2397
- self.opaque("`%s` runs a script whose path is computed at run time" % name, script.raw)
2398
- return
2399
- if self.path_key(script, state) in state.written:
2400
- self.opaque("`%s` runs a file written earlier in this same command" % name,
2401
- script.value)
2402
- return
2403
- if cmd_name(script.value) == "preflight.sh":
2404
- self.preflight_args(sargs, state, depth)
2405
- elif cmd_name(script.value) == "verify-run.sh":
2406
- self.verify_args(sargs, state, depth)
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))
2407
2041
 
2408
- def preflight_args(self, args, state, depth):
2409
- """preflight.sh <report> "<cmd>"…: it truncates <report>, and runs each cmd via sh -c."""
2410
- if not args:
2411
- return
2412
- self.check_path(args[0], state, "write", "preflight.sh's report argument")
2413
- for a in args[1:]:
2414
- if a.dynamic:
2415
- self.opaque("preflight.sh runs a check command built at run time", a.raw)
2416
- else:
2417
- self.analyze_text(a.value, state.copy(), depth + 1)
2418
2042
 
2419
- # verify-run.sh run <id> --dev "<cmd>" --check "<name>=<cmd>" --migrate "<cmd>" …: every
2420
- # command it is handed runs through a shell, so judge each one here — the script also asks
2421
- # the gate itself, but its `--confirmed` flag is the lead's word, and a DENIED command must
2422
- # stay denied whatever the flag says.
2423
- VERIFY_CMD_FLAGS = {"--dev": False, "--ready": False, "--migrate": False,
2424
- "--migrate-down": False, "--check": True}
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)
2425
2049
 
2426
- def verify_args(self, args, state, depth):
2427
- k = 0
2428
- while k < len(args):
2429
- flag = args[k].value
2430
- if flag in self.VERIFY_CMD_FLAGS and k + 1 < len(args):
2431
- a = args[k + 1]
2432
- if a.dynamic:
2433
- self.opaque("verify-run.sh runs a command built at run time", a.raw)
2434
- else:
2435
- cmd = a.value
2436
- if self.VERIFY_CMD_FLAGS[flag] and "=" in cmd:
2437
- cmd = cmd.split("=", 1)[1] # --check "<name>=<cmd>"
2438
- if not (flag == "--ready" and re.match(r"^https?://", cmd.strip())):
2439
- self.analyze_text(cmd, state.copy(), depth + 1)
2440
- k += 2
2441
- continue
2442
- k += 1
2050
+ def remember_written(self, w, state):
2051
+ if not w.dynamic:
2052
+ state.written.add(self.path_key(w, state))
2443
2053
 
2444
- def interp_code(self, name, args):
2445
- lang = lang_of(name)
2446
- k = 0
2447
- while k < len(args):
2448
- a = args[k]
2449
- v = a.value
2450
- if a.dynamic:
2451
- return None, True
2452
- if lang == "py":
2453
- if v.startswith("-") and not v.startswith("--") and "c" in v[1:]:
2454
- i = v.index("c", 1)
2455
- rest = v[i + 1:]
2456
- if rest:
2457
- return static_word(rest), False
2458
- return (args[k + 1] if k + 1 < len(args) else static_word("")), False
2459
- if v in ("-m",) or (v.startswith("-m") and len(v) > 2):
2460
- return None, True
2461
- if v in ("-W", "-X", "-Q"):
2462
- k += 2
2463
- continue
2464
- if v == "-":
2465
- return None, False
2466
- elif lang == "js":
2467
- if v in ("-e", "--eval", "-p", "--print") or v.startswith("--eval=") \
2468
- or v.startswith("--print="):
2469
- if "=" in v:
2470
- return static_word(v.split("=", 1)[1]), False
2471
- return (args[k + 1] if k + 1 < len(args) else static_word("")), False
2472
- if name == "deno" and v == "eval":
2473
- return (args[k + 1] if k + 1 < len(args) else static_word("")), False
2474
- if v in ("-r", "--require", "--import", "--loader", "-C", "--conditions"):
2475
- k += 2
2476
- continue
2477
- if name in ("deno", "bun") and not v.startswith("-"):
2478
- return None, True
2479
- else:
2480
- letters = {"php": "r", "ruby": "e"}.get(name, "eE")
2481
- if v.startswith("-") and not v.startswith("--") and any(c in v[1:] for c in letters):
2482
- j = min(v.index(c, 1) for c in letters if c in v[1:])
2483
- rest = v[j + 1:]
2484
- if rest and not rest.startswith("."):
2485
- return static_word(rest), False
2486
- return (args[k + 1] if k + 1 < len(args) else static_word("")), False
2487
- if v == "--":
2488
- return None, k + 1 < len(args)
2489
- if not v.startswith("-"):
2490
- return None, True
2491
- k += 1
2492
- return None, False
2493
-
2494
- def code_check(self, lang, code, state, depth):
2495
- if PROTECTED_NAME_RE.search(code):
2496
- self.ask("inline code references a file the Cohorte gate depends on (gate config, "
2497
- "settings or preflight stamp) — confirm it only reads it")
2498
- if not SPAWN_RE[lang].search(code):
2499
- return
2500
- joined = re.sub(r"(['\"])\s*\+\s*\1", "", code)
2501
- for m in STRING_LIT_RE.finditer(joined):
2502
- lit = m.group(1) if m.group(1) is not None else m.group(2)
2503
- if lit and " " in lit:
2504
- self.analyze_text(lit, state.copy(), depth + 1)
2505
- self.opaque("inline code starts processes", joined)
2506
-
2507
- def stdin_code(self, name, lang, seg, prev, prev_inv, state, depth):
2508
- def feed(text, static):
2509
- if lang == "sh":
2510
- if static:
2511
- self.analyze_text(text, state.copy(), depth + 1)
2512
- else:
2513
- self.opaque("`%s` reads commands built at run time" % name, text)
2514
- else:
2515
- self.code_check(lang, text, state, depth)
2516
-
2517
- for h in seg.heredocs:
2518
- feed(h.body, True)
2519
- return
2520
- for r in seg.redirs:
2521
- if r.op == "<<<":
2522
- feed(r.target.raw if r.target.dynamic else r.target.value, not r.target.dynamic)
2523
- return
2524
- if r.op == "<":
2525
- if r.target.dynamic or self.path_key(r.target, state) in state.written:
2526
- self.opaque("`%s` reads commands from a file written or computed in this "
2527
- "same command" % name, seg.text)
2528
- return
2529
- if prev is not None and prev.sep in ("|", "|&"):
2530
- if prev_inv is not None and prev_inv.name in ("echo", "printf") \
2531
- and not any(a.dynamic for a in prev_inv.args):
2532
- vals = [a.value for a in prev_inv.args]
2533
- if prev_inv.name == "echo":
2534
- while vals and re.match(r"^-[neE]+$", vals[0]):
2535
- vals.pop(0)
2536
- text = " ".join(vals)
2537
- else:
2538
- text = vals[0] if vals else ""
2539
- for v in vals[1:]:
2540
- text = text.replace("%s", v, 1) if "%s" in text else text + " " + v
2541
- text = text.replace("\\n", "\n")
2542
- feed(text, True)
2543
- else:
2544
- self.opaque("`%s` executes whatever the pipe feeds it" % name,
2545
- prev.text + " | " + seg.text)
2546
-
2547
- # -- self-protection --------------------------------------------------------------
2548
- def path_key(self, w, state):
2549
- v = os.path.expanduser(w.value)
2550
- if not os.path.isabs(v) and state.cwd_known:
2551
- v = os.path.join(state.cwd, v)
2552
- return os.path.normpath(v)
2553
-
2554
- def remember_written(self, w, state):
2555
- if not w.dynamic:
2556
- state.written.add(self.path_key(w, state))
2557
-
2558
- def known_text(self, w, state):
2559
- """A run-time word with only the variables the gate can resolve itself
2560
- ($CLAUDE_PROJECT_DIR, $HOME, $PWD) substituted, or None if anything else is left."""
2561
- t = w.raw
2562
- if len(t) >= 2 and t[0] == t[-1] == '"':
2563
- t = t[1:-1]
2564
- for var, val in (("CLAUDE_PROJECT_DIR", os.environ.get("CLAUDE_PROJECT_DIR")),
2565
- ("HOME", os.path.expanduser("~")),
2566
- ("PWD", state.cwd if state.cwd_known else None)):
2567
- if val:
2568
- # Forward slashes: a Windows value (C:\\Users\\…) would otherwise read as
2569
- # shell escapes below and every expanded path would look suspect.
2570
- val = val.replace("\\", "/")
2571
- t = t.replace("${%s}" % var, val).replace("$" + var, val)
2572
- if "$" in t or "`" in t or "'" in t or '"' in t or "\\" in t:
2573
- return None
2574
- return t
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
2575
2071
 
2576
2072
  def classify_path(self, w, state, mode, relocated=False):
2577
2073
  ctx = self.ctx
@@ -2755,6 +2251,521 @@ class Analyzer(object):
2755
2251
  self.check_path(p, state, "delete", "`git mv`", reloc)
2756
2252
  self.check_path(pos[-1], state, "write", "`git mv`", reloc)
2757
2253
 
2254
+
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
+
2276
+
2277
+ class Indirection(object):
2278
+ def indirection(self, inv, seg, prev, prev_inv, state, depth):
2279
+ name, args = inv.name, inv.args
2280
+ if name in SHELLS:
2281
+ code, script, sargs = self.shell_args(args)
2282
+ if code is not None:
2283
+ if code.dynamic:
2284
+ self.opaque("`%s -c` runs a command string built at run time" % name, code.raw)
2285
+ else:
2286
+ self.analyze_text(code.value, state.copy(), depth + 1)
2287
+ elif script is not None:
2288
+ self.run_script(name, script, sargs, state, depth)
2289
+ else:
2290
+ self.stdin_code(name, "sh", seg, prev, prev_inv, state, depth)
2291
+ return
2292
+ if name == "preflight.sh":
2293
+ self.preflight_args(args, state, depth)
2294
+ return
2295
+ if name == "verify-run.sh":
2296
+ self.verify_args(args, state, depth)
2297
+ return
2298
+ if name == "eval":
2299
+ text = " ".join(a.value for a in args)
2300
+ if any(a.dynamic for a in args):
2301
+ self.opaque("`eval` of a string built at run time", " ".join(a.raw for a in args))
2302
+ else:
2303
+ self.analyze_text(text, state, depth + 1)
2304
+ return
2305
+ if name in ("source", "."):
2306
+ if args:
2307
+ self.run_script(name, args[0], args[1:], state, depth)
2308
+ return
2309
+ if INTERP_RE.match(name):
2310
+ lang = lang_of(name)
2311
+ code, has_script = self.interp_code(name, args)
2312
+ if code is not None:
2313
+ self.code_check(lang, code.raw if code.dynamic else code.value, state, depth)
2314
+ elif not has_script:
2315
+ self.stdin_code(name, lang, seg, prev, prev_inv, state, depth)
2316
+ return
2317
+ if name in ("xargs",):
2318
+ k = 0
2319
+ with_arg = {"-I", "-L", "-l", "-n", "-P", "-s", "-d", "-E", "-e", "-a",
2320
+ "--max-args", "--delimiter", "--arg-file", "--max-procs", "--replace",
2321
+ "--max-lines", "--max-chars", "--eof"}
2322
+ while k < len(args) and args[k].value.startswith("-") and not args[k].dynamic:
2323
+ k += 2 if args[k].value in with_arg else 1
2324
+ rest = args[k:] or [static_word("echo")]
2325
+ self.synthetic(rest + [wildcard_word()], seg, state, depth)
2326
+ return
2327
+ if name == "find":
2328
+ k = 0
2329
+ while k < len(args):
2330
+ v = args[k].value
2331
+ if v in ("-exec", "-execdir", "-ok", "-okdir"):
2332
+ j = k + 1
2333
+ while j < len(args) and args[j].value not in (";", "+"):
2334
+ j += 1
2335
+ if j > k + 1:
2336
+ self.synthetic(args[k + 1:j], seg, state, depth)
2337
+ k = j
2338
+ k += 1
2339
+ return
2340
+ if name == "watch":
2341
+ k = 0
2342
+ while k < len(args) and args[k].value.startswith("-"):
2343
+ k += 2 if args[k].value in ("-n", "--interval", "-d") else 1
2344
+ if k < len(args):
2345
+ if any(a.dynamic for a in args[k:]):
2346
+ self.opaque("`watch` runs a command built at run time", seg.text)
2347
+ else:
2348
+ self.analyze_text(" ".join(a.value for a in args[k:]), state.copy(), depth + 1)
2349
+ return
2350
+ if name in ("su", "runuser"):
2351
+ for k, a in enumerate(args):
2352
+ if a.value in ("-c", "--command") and k + 1 < len(args):
2353
+ c = args[k + 1]
2354
+ if c.dynamic:
2355
+ self.opaque("`su -c` runs a command built at run time", c.raw)
2356
+ else:
2357
+ self.analyze_text(c.value, state.copy(), depth + 1)
2358
+ return
2359
+ if name == "trap" and args:
2360
+ a = args[0]
2361
+ if a.dynamic:
2362
+ self.opaque("`trap` installs a command built at run time", a.raw)
2363
+ elif a.value not in ("-", "") and not a.value.startswith("-"):
2364
+ self.analyze_text(a.value, state.copy(), depth + 1)
2365
+ return
2366
+ if name == "alias":
2367
+ for a in args:
2368
+ if "=" in a.value:
2369
+ val = a.value.split("=", 1)[1]
2370
+ if a.dynamic:
2371
+ self.opaque("an alias is defined from a run-time value", a.raw)
2372
+ elif val:
2373
+ self.analyze_text(val, state.copy(), depth + 1)
2374
+ return
2375
+ if name in ("ssh", "mosh"):
2376
+ k = 0
2377
+ with_arg = set("-b -c -D -E -e -F -I -i -J -L -l -m -O -o -p -Q -R -S -W -w -B".split())
2378
+ while k < len(args) and args[k].value.startswith("-") and not args[k].dynamic:
2379
+ k += 2 if args[k].value in with_arg else 1
2380
+ rest = args[k + 1:]
2381
+ if rest:
2382
+ remote = state.copy()
2383
+ remote.cwd_known = False
2384
+ remote.sticky = True
2385
+ if any(a.dynamic for a in rest):
2386
+ self.opaque("`ssh` runs a remote command built at run time", seg.text)
2387
+ else:
2388
+ self.analyze_text(" ".join(a.value for a in rest), remote, depth + 1)
2389
+ return
2390
+ if name in ("npx", "bunx", "pnpx"):
2391
+ for k, a in enumerate(args):
2392
+ if a.value in ("-c", "--call") and k + 1 < len(args):
2393
+ c = args[k + 1]
2394
+ if c.dynamic:
2395
+ self.opaque("`npx -c` runs a command built at run time", c.raw)
2396
+ else:
2397
+ self.analyze_text(c.value, state.copy(), depth + 1)
2398
+
2399
+ def synthetic(self, words, seg, state, depth):
2400
+ s = Seg(seg.src, seg.start, False)
2401
+ s.end = seg.end
2402
+ s.words = list(words)
2403
+ s.sep = seg.sep
2404
+ self.eval_segment(s, None, None, state.copy(), depth + 1)
2405
+
2406
+ def shell_args(self, args):
2407
+ code_next = False
2408
+ k = 0
2409
+ while k < len(args):
2410
+ a = args[k]
2411
+ v = a.value
2412
+ if a.dynamic and not code_next:
2413
+ return None, a, args[k + 1:]
2414
+ if code_next:
2415
+ return a, None, args[k + 1:]
2416
+ if v == "--" or v == "-":
2417
+ k += 1
2418
+ break
2419
+ if v in ("-o", "+o", "-O", "+O", "--rcfile", "--init-file"):
2420
+ k += 2
2421
+ continue
2422
+ if v.startswith("--"):
2423
+ k += 1
2424
+ continue
2425
+ if len(v) > 1 and v[0] in "-+":
2426
+ if v[0] == "-" and "c" in v[1:]:
2427
+ code_next = True
2428
+ k += 1
2429
+ continue
2430
+ break
2431
+ if code_next:
2432
+ return (args[k] if k < len(args) else static_word("")), None, args[k + 1:]
2433
+ if k < len(args):
2434
+ return None, args[k], args[k + 1:]
2435
+ return None, None, []
2436
+
2437
+ def run_script(self, name, script, sargs, state, depth):
2438
+ if script.dynamic:
2439
+ self.opaque("`%s` runs a script whose path is computed at run time" % name, script.raw)
2440
+ return
2441
+ if self.path_key(script, state) in state.written:
2442
+ self.opaque("`%s` runs a file written earlier in this same command" % name,
2443
+ script.value)
2444
+ return
2445
+ if cmd_name(script.value) == "preflight.sh":
2446
+ self.preflight_args(sargs, state, depth)
2447
+ elif cmd_name(script.value) == "verify-run.sh":
2448
+ self.verify_args(sargs, state, depth)
2449
+
2450
+ def preflight_args(self, args, state, depth):
2451
+ """preflight.sh <report> "<cmd>"…: it truncates <report>, and runs each cmd via sh -c."""
2452
+ if not args:
2453
+ return
2454
+ self.check_path(args[0], state, "write", "preflight.sh's report argument")
2455
+ for a in args[1:]:
2456
+ if a.dynamic:
2457
+ self.opaque("preflight.sh runs a check command built at run time", a.raw)
2458
+ else:
2459
+ self.analyze_text(a.value, state.copy(), depth + 1)
2460
+
2461
+ # verify-run.sh run <id> --dev "<cmd>" --check "<name>=<cmd>" --migrate "<cmd>" …: every
2462
+ # command it is handed runs through a shell, so judge each one here — the script also asks
2463
+ # the gate itself, but its `--confirmed` flag is the lead's word, and a DENIED command must
2464
+ # stay denied whatever the flag says.
2465
+ VERIFY_CMD_FLAGS = {"--dev": False, "--ready": False, "--migrate": False,
2466
+ "--migrate-down": False, "--check": True}
2467
+
2468
+ def verify_args(self, args, state, depth):
2469
+ k = 0
2470
+ while k < len(args):
2471
+ flag = args[k].value
2472
+ if flag in self.VERIFY_CMD_FLAGS and k + 1 < len(args):
2473
+ a = args[k + 1]
2474
+ if a.dynamic:
2475
+ self.opaque("verify-run.sh runs a command built at run time", a.raw)
2476
+ else:
2477
+ cmd = a.value
2478
+ if self.VERIFY_CMD_FLAGS[flag] and "=" in cmd:
2479
+ cmd = cmd.split("=", 1)[1] # --check "<name>=<cmd>"
2480
+ if not (flag == "--ready" and re.match(r"^https?://", cmd.strip())):
2481
+ self.analyze_text(cmd, state.copy(), depth + 1)
2482
+ k += 2
2483
+ continue
2484
+ k += 1
2485
+
2486
+ def interp_code(self, name, args):
2487
+ lang = lang_of(name)
2488
+ k = 0
2489
+ while k < len(args):
2490
+ a = args[k]
2491
+ v = a.value
2492
+ if a.dynamic:
2493
+ return None, True
2494
+ if lang == "py":
2495
+ if v.startswith("-") and not v.startswith("--") and "c" in v[1:]:
2496
+ i = v.index("c", 1)
2497
+ rest = v[i + 1:]
2498
+ if rest:
2499
+ return static_word(rest), False
2500
+ return (args[k + 1] if k + 1 < len(args) else static_word("")), False
2501
+ if v in ("-m",) or (v.startswith("-m") and len(v) > 2):
2502
+ return None, True
2503
+ if v in ("-W", "-X", "-Q"):
2504
+ k += 2
2505
+ continue
2506
+ if v == "-":
2507
+ return None, False
2508
+ elif lang == "js":
2509
+ if v in ("-e", "--eval", "-p", "--print") or v.startswith("--eval=") \
2510
+ or v.startswith("--print="):
2511
+ if "=" in v:
2512
+ return static_word(v.split("=", 1)[1]), False
2513
+ return (args[k + 1] if k + 1 < len(args) else static_word("")), False
2514
+ if name == "deno" and v == "eval":
2515
+ return (args[k + 1] if k + 1 < len(args) else static_word("")), False
2516
+ if v in ("-r", "--require", "--import", "--loader", "-C", "--conditions"):
2517
+ k += 2
2518
+ continue
2519
+ if name in ("deno", "bun") and not v.startswith("-"):
2520
+ return None, True
2521
+ else:
2522
+ letters = {"php": "r", "ruby": "e"}.get(name, "eE")
2523
+ if v.startswith("-") and not v.startswith("--") and any(c in v[1:] for c in letters):
2524
+ j = min(v.index(c, 1) for c in letters if c in v[1:])
2525
+ rest = v[j + 1:]
2526
+ if rest and not rest.startswith("."):
2527
+ return static_word(rest), False
2528
+ return (args[k + 1] if k + 1 < len(args) else static_word("")), False
2529
+ if v == "--":
2530
+ return None, k + 1 < len(args)
2531
+ if not v.startswith("-"):
2532
+ return None, True
2533
+ k += 1
2534
+ return None, False
2535
+
2536
+ def code_check(self, lang, code, state, depth):
2537
+ if PROTECTED_NAME_RE.search(code):
2538
+ self.ask("inline code references a file the Cohorte gate depends on (gate config, "
2539
+ "settings or preflight stamp) — confirm it only reads it")
2540
+ if not SPAWN_RE[lang].search(code):
2541
+ return
2542
+ joined = re.sub(r"(['\"])\s*\+\s*\1", "", code)
2543
+ for m in STRING_LIT_RE.finditer(joined):
2544
+ lit = m.group(1) if m.group(1) is not None else m.group(2)
2545
+ if lit and " " in lit:
2546
+ self.analyze_text(lit, state.copy(), depth + 1)
2547
+ self.opaque("inline code starts processes", joined)
2548
+
2549
+ def stdin_code(self, name, lang, seg, prev, prev_inv, state, depth):
2550
+ def feed(text, static):
2551
+ if lang == "sh":
2552
+ if static:
2553
+ self.analyze_text(text, state.copy(), depth + 1)
2554
+ else:
2555
+ self.opaque("`%s` reads commands built at run time" % name, text)
2556
+ else:
2557
+ self.code_check(lang, text, state, depth)
2558
+
2559
+ for h in seg.heredocs:
2560
+ feed(h.body, True)
2561
+ return
2562
+ for r in seg.redirs:
2563
+ if r.op == "<<<":
2564
+ feed(r.target.raw if r.target.dynamic else r.target.value, not r.target.dynamic)
2565
+ return
2566
+ if r.op == "<":
2567
+ if r.target.dynamic or self.path_key(r.target, state) in state.written:
2568
+ self.opaque("`%s` reads commands from a file written or computed in this "
2569
+ "same command" % name, seg.text)
2570
+ return
2571
+ if prev is not None and prev.sep in ("|", "|&"):
2572
+ if prev_inv is not None and prev_inv.name in ("echo", "printf") \
2573
+ and not any(a.dynamic for a in prev_inv.args):
2574
+ vals = [a.value for a in prev_inv.args]
2575
+ if prev_inv.name == "echo":
2576
+ while vals and re.match(r"^-[neE]+$", vals[0]):
2577
+ vals.pop(0)
2578
+ text = " ".join(vals)
2579
+ else:
2580
+ text = vals[0] if vals else ""
2581
+ for v in vals[1:]:
2582
+ text = text.replace("%s", v, 1) if "%s" in text else text + " " + v
2583
+ text = text.replace("\\n", "\n")
2584
+ feed(text, True)
2585
+ else:
2586
+ self.opaque("`%s` executes whatever the pipe feeds it" % name,
2587
+ prev.text + " | " + seg.text)
2588
+
2589
+
2590
+ # ══ core/hooks/gate/analyze.py ═══════════════════════════════════════════════
2591
+ MAX_DEPTH = 6
2592
+ WRITE_OPS = {">", ">>", ">|", "&>", "&>>", "<>"}
2593
+
2594
+
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 = {}
2602
+
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 = []
2624
+
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)
2634
+ return
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)
2641
+
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)
2656
+
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)
2665
+
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
2705
+
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)
2720
+
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
2768
+
2758
2769
  # -- chain state -----------------------------------------------------------------
2759
2770
  def update_state(self, inv, seg, state, assigns):
2760
2771
  name, args = inv.name, inv.args