cohorte 3.1.1 → 3.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,38 @@ short, user-facing, most recent first. One `## <version> — <YYYY-MM-DD>` secti
7
7
  > They are history and are deliberately not rewritten — every command gained a `cohorte-` prefix
8
8
  > in 2.0.0.
9
9
 
10
+ ## 3.1.2 — 2026-11-16
11
+
12
+ - **A red test piped into `| tail` no longer passes the preflight.** A quiet variant such as
13
+ `npm test 2>&1 | tail -20` exits with `tail`'s status, so a failing suite stamped the preflight
14
+ GREEN and the review could reach SHIP on red code. `preflight.sh` and `verify-run.sh` now run every
15
+ check with `pipefail`; the doctrine's `| tail -40` fallback is written `set -o pipefail; …`; and
16
+ `cohorte doctor` warns about a stored command that pipes into `tail`/`head` without it. Found by
17
+ the new real-model end-to-end run.
18
+ - **A nightly real-model end-to-end run** (`/cohorte-build` then `/cohorte-review` on a toy repo,
19
+ asserting on the files they write) runs when the `ANTHROPIC_API_KEY` repository secret is set.
20
+ - **`cohorte sync` writes the pipeline's own permissions** (its scripts, read-only git, `git switch`,
21
+ `date`) into `.claude/settings.json`. `/cohorte-update-pipeline` used to Edit that file for them,
22
+ which the gate (rightly) asks about — a hard stop in a headless run. Found by running the update
23
+ on a real 2.x project.
24
+ - **`gate.hook_form: exec`** registers the gate without a shell (`python3` + an argument list), for
25
+ Windows teams without Git Bash. Opt-in: every teammate needs a recent Claude Code.
26
+ - **Ownership covers the workflows too — verified.** A subagent dispatched by a workflow
27
+ (`agent({ agentType })`, as the build, loop and refactor workflows do) reaches the gate with its
28
+ `agent_id` and `agent_type`, exactly like one dispatched by the lead (Claude Code 2.1.325).
29
+ - **The security-scan recipes are checked against the real tools** every week (gitleaks,
30
+ trufflehog, npm/pnpm audit, pip-audit, govulncheck, cargo audit).
31
+ - **Generated project CI runs `cohorte doctor`**, pinned to the project's core version, so a PR that
32
+ breaks the pipeline's wiring fails in CI.
33
+ - **The installed changelog is slimmer** (the current major's sections plus a link: 16 KB instead
34
+ of 127 KB).
35
+ - **Releases:** every publish is followed by an `npx cohorte@<version> install` from the registry;
36
+ Dependabot keeps the pinned actions current.
37
+ - **Internal:** `gate.py` is built from modules; no behaviour change. The source lives in
38
+ `core/hooks/gate/*.py`; `scripts/build-gate.mjs` concatenates it into the single committed
39
+ `core/hooks/gate.py` that installs and `cohorte sync` copy, and validate-core fails if the
40
+ two drift.
41
+
10
42
  ## 3.1.1 — 2026-11-16
11
43
 
12
44
  - **An install that fails half-way is rolled back.** `cohorte install` / `update` journal every file
@@ -74,8 +106,8 @@ short, user-facing, most recent first. One `## <version> — <YYYY-MM-DD>` secti
74
106
  worktree resolve against that worktree, and paths outside the project (`/dev/null`, `$TMPDIR`)
75
107
  are not judged. It is **on by default** from the first `cohorte sync` after upgrading (that sync
76
108
  also registers the hook for `NotebookEdit`). Verified on Claude Code 2.1.325: a subagent's
77
- `Write` reaches the hook with its `agent_id` and `agent_type`. Not verified yet for implementers
78
- dispatched by the *workflows* — if they lack those fields, their writes are judged as the lead's.
109
+ `Write` reaches the hook with its `agent_id` and `agent_type` — and, verified since (3.1.2), so
110
+ does one dispatched by a workflow.
79
111
  Before upgrading, check what each surface writes outside its tree (root `tests/`, a generated
80
112
  client, the root lockfile): `/cohorte-update-pipeline` proposes them as `owns_also` /
81
113
  `ownership.shared_writable`, and `ownership.enforce: false` turns the check off.
package/README.md CHANGED
@@ -85,9 +85,10 @@ The core never hardcodes stack facts. Two mechanisms keep it generic:
85
85
  - **Node ≥ 20 + npm** — for the `cohorte` CLI.
86
86
  - **Python ≥ 3.9** as `python3` — the gate hook every project commits runs on it. The hook is
87
87
  fail-closed: without Python, Claude Code refuses every Bash call in a Cohorte project.
88
- **Windows:** the committed hook is `python3 "$CLAUDE_PROJECT_DIR/.claude/hooks/cohorte-gate.py"`, so
89
- each teammate needs `python3` on `PATH` and Claude Code running hooks through a POSIX shell (Git
90
- Bash); this setup is not covered by CI yet.
88
+ **Windows:** the committed hook is `python3 "$CLAUDE_PROJECT_DIR/.claude/hooks/cohorte-gate.py"`, run
89
+ through a POSIX shell (Git Bash). Without one, set `gate.hook_form: exec` in `PIPELINE.md` and run
90
+ `cohorte sync`: the hook becomes `python3` + an argument list that Claude Code launches directly
91
+ (every teammate then needs a recent Claude Code). `python3` must be on `PATH` either way.
91
92
  - **Claude Code** — workflows (the opt-in deterministic runs) need ≥ 2.1.154; the hook's
92
93
  fail-closed `onFailure` setting is honoured from 2.1.295 (older clients ignore it and fail open).
93
94
  - **[`uv`](https://docs.astral.sh/uv/) + the Serena CLI** — _optional_, the default code-retrieval
@@ -353,6 +354,7 @@ core/
353
354
  agents/ # implementer.template.md (rendered per surface) + cohorte-review / -release / -profile-reader
354
355
  commands/ # the 16 /cohorte-* commands
355
356
  hooks/gate.py # the gate (copied into each project as .claude/hooks/cohorte-gate.py)
357
+ hooks/gate/ # its source modules — gate.py is built from them (scripts/build-gate.mjs)
356
358
  templates/ # handoff / brainstorm-return / design-brief / review-feedback / pr-body / spec + step files
357
359
  workflows/ # Workflow-runtime scripts: review / audit / refactor (opt-in variants) + loop (workflow-only)
358
360
  profile/
@@ -117,7 +117,7 @@ with its limit and what would trigger the upgrade — not in a comment, and not
117
117
 
118
118
  **Run commands bridled — always.** Your surface's `test_quiet_cmd`/`lint_quiet_cmd` in `PIPELINE.md`
119
119
  are the forms you execute (dot reporter / failures-only); when a quiet variant is empty or absent,
120
- run `<full cmd> 2>&1 | tail -40`. Never print a full runner log into your context — redirect to a
120
+ run `set -o pipefail; <full cmd> 2>&1 | tail -40` (without `pipefail` a red run through `| tail` exits 0). Never print a full runner log into your context — redirect to a
121
121
  file and grep it if you need more than the tail.
122
122
 
123
123
  ## Definition of done
@@ -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, analyze, preflight,
5
+ # 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,6 +1664,119 @@ def match_push(pat_args, cargs, pi):
1763
1664
  return res
1764
1665
 
1765
1666
 
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()
1722
+
1723
+ def _build_protected(self):
1724
+ write, delete = set(), set()
1725
+
1726
+ def add(s, p):
1727
+ s.add(os.path.normpath(p))
1728
+ s.add(os.path.realpath(p))
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
1743
+
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]
1777
+
1778
+
1779
+ # ══ core/hooks/gate/analyze.py ═══════════════════════════════════════════════
1766
1780
  # ── analysis ─────────────────────────────────────────────────────────────────
1767
1781
  PROTECTED_HINT_RE = re.compile(r"(^|/)\.claude(/|$)|gate-config\.json|preflight\.ok|"
1768
1782
  r"settings(\.local)?\.json|cohorte-gate\.py|pipeline\.json|"
@@ -2814,6 +2828,7 @@ class Analyzer(object):
2814
2828
  return t
2815
2829
 
2816
2830
 
2831
+ # ══ core/hooks/gate/preflight.py ═════════════════════════════════════════════
2817
2832
  # ── preflight phase gate ─────────────────────────────────────────────────────
2818
2833
  HEX_RE = re.compile(r"^[0-9a-f]{40}([0-9a-f]{24})?$")
2819
2834
  DIGEST_EXCLUDES = (".claude", "specs")
@@ -2969,7 +2984,8 @@ class Dispatch(object):
2969
2984
  "(PIPELINE.md gate.preflight)." % (sub, why))
2970
2985
 
2971
2986
 
2972
- # ── entry points ─────────────────────────────────────────────────────────────
2987
+ # ══ core/hooks/gate/evaluate.py ══════════════════════════════════════════════
2988
+ # ── evaluation ───────────────────────────────────────────────────────────────
2973
2989
  DISPATCH_TOOLS = {"Task", "Agent"}
2974
2990
  EDIT_TOOLS = {"Write", "Edit", "MultiEdit", "NotebookEdit"}
2975
2991
  GATED_TOOLS = {"Bash"} | DISPATCH_TOOLS | EDIT_TOOLS
@@ -3083,6 +3099,8 @@ def evaluate(payload):
3083
3099
  return level, "Cohorte gate: " + reason
3084
3100
 
3085
3101
 
3102
+ # ══ core/hooks/gate/main.py ══════════════════════════════════════════════════
3103
+ # ── entry points ─────────────────────────────────────────────────────────────
3086
3104
  def emit(decision, reason):
3087
3105
  sys.stdout.write(json.dumps({"hookSpecificOutput": {
3088
3106
  "hookEventName": "PreToolUse",
@@ -32,7 +32,8 @@ Ask ONLY what you couldn't confidently detect. Batch related questions. Cover:
32
32
  jest, `-q` pytest, `--quiet` eslint/ruff — whatever the detected runner supports). These land in
33
33
  `test_quiet_cmd`/`lint_quiet_cmd` + `commands.test_quiet`/`lint_quiet` and are what agents and the
34
34
  `/cohorte-review` pre-flight actually run (`<core>/pipeline/schema/output-discipline.md`). If the human declines or
35
- the runner has no such flag, leave `""` — consumers then fall back to `<cmd> 2>&1 | tail -40`.
35
+ the runner has no such flag, leave `""` — consumers then fall back to `set -o pipefail; <cmd> 2>&1 | tail -40`.
36
+ Never store a quiet variant that pipes into `tail`/`head` without `set -o pipefail;` in front.
36
37
  - **Security scans** (only if Phase 1 found an auditor or a secret scanner). Propose the detected
37
38
  commands from `<core>/pipeline/schema/preflight.md` §Security scans as one multi-select. Fill
38
39
  in `--default <default_branch>`. If `CLAUDE_CONFIG_DIR` is set, use its literal value in place
@@ -24,13 +24,10 @@
24
24
  `allow` list of the project's read-only / verification commands** so agents don't stall on
25
25
  permission prompts — including mid-workflow, where nobody is watching a prompt: the detected
26
26
  per-surface `test_cmd`/`lint_cmd`/`typecheck_cmd`/`build_cmd` **and their `*_quiet_cmd`
27
- variants** and repo-wide `commands.*` equivalents as `Bash(<cmd>:*)` rules, plus read-only git —
28
- `Bash(git status:*)`, `Bash(git diff:*)`, `Bash(git log:*)`, `Bash(git rev-parse:*)`, plus
29
- `Bash(git switch:*)` and `Bash(date:*)` (the refactor workflow cuts its branch and dates its spec) — plus the
30
- shipped pipeline scripts (`Bash(<core>/pipeline/scripts/:*)` — preflight, kanban-move;
31
- a prefix rule matches a command *starting* with that path, so a `bash <path>`
32
- invocation would need its own entry), and the
33
- retrieval provider's MCP tools when wired (e.g. `mcp__serena`). Never allowlist anything matching
27
+ variants** and repo-wide `commands.*` equivalents as `Bash(<cmd>:*)` rules, and the
28
+ retrieval provider's MCP tools when wired (e.g. `mcp__serena`). The pipeline's own rules — its
29
+ scripts (`Bash(<core>/pipeline/scripts/:*)`), read-only git, `git switch`, `date` — are written by
30
+ `<sync>` (step 8), never by hand: the gate asks before any edit of `settings.json`. Never allowlist anything matching
34
31
  a `gate.ask`/`gate.deny` pattern. Mention the human can widen it later with
35
32
  `/fewer-permission-prompts`) + the PostToolUse formatter hook (detected formatter). Do **not**
36
33
  write the gate hook here — step 8 (`<sync>`) registers it.
@@ -83,6 +80,12 @@
83
80
  `commands.install`, then `commands.lint` · `commands.typecheck` · `commands.test` (+ per-surface
84
81
  `build_cmd`s that are non-empty). Derive the setup steps from the detected stack — mirror what a
85
82
  sibling workflow does if one exists. `/cohorte-ship` watches these checks before the merge.
83
+ Add one more step, so a PR that breaks the pipeline's own wiring (gate unregistered or not
84
+ committed, stale `profile.json`, a surface without its agent, a tracked preflight stamp) fails
85
+ in CI instead of in someone's session — pin it to this repo's `core_version`:
86
+ `npx -y cohorte@<core_version> install && npx -y cohorte@<core_version> doctor`
87
+ (with `COHORTE_NO_VERSION_CHECK: 1` in its `env`; `doctor` exits 1 on any bad check). On an
88
+ existing workflow, offer to add just that step. `/cohorte-update-pipeline` bumps the pin.
86
89
  11. **Design system:** if `design.enabled` with a snapshot dir, note that `/cohorte-align-ds` is active; else the
87
90
  `/cohorte-align-ds` command will no-op with a clear message.
88
91
  12. **Kanban** (only if the human opted in at Phase 2): wire it per `<core>/pipeline/schema/kanban.md`, writing into the
package/lib/doctor.js CHANGED
@@ -90,6 +90,20 @@ function checkCore(v, isProject) {
90
90
  return mk('core', 'Core & pointer', 'ok', `core ${v.installedVersion}${tail}`);
91
91
  }
92
92
 
93
+ // A stored command that pipes into tail/head loses its exit status unless pipefail is set: the
94
+ // preflight and verify-run.sh set it, but an agent's own Bash call does not.
95
+ function maskedPipes(profile) {
96
+ const out = [];
97
+ const look = (where, v) => {
98
+ if (typeof v === 'string' && /\|\s*(tail|head)\b/.test(v) && !/pipefail/.test(v)) out.push(where);
99
+ };
100
+ for (const [k, v] of Object.entries((profile && profile.commands) || {})) look(`commands.${k}`, v);
101
+ for (const s of (profile && profile.surfaces) || []) {
102
+ for (const k of ['test_cmd', 'test_quiet_cmd', 'lint_cmd', 'lint_quiet_cmd', 'typecheck_cmd', 'build_cmd']) look(`${s.key}.${k}`, s[k]);
103
+ }
104
+ return out;
105
+ }
106
+
93
107
  function checkProfile(profile, hasPipelineMd) {
94
108
  if (!hasPipelineMd) {
95
109
  return mk('profile', 'Profile (PIPELINE.md)', 'bad', 'PIPELINE.md not found',
@@ -101,6 +115,12 @@ function checkProfile(profile, hasPipelineMd) {
101
115
  '/cohorte-init-pipeline (or fix the fenced yaml block)');
102
116
  }
103
117
  const n = (profile.surfaces || []).length;
118
+ const masked = maskedPipes(profile);
119
+ if (masked.length) {
120
+ return mk('profile', 'Profile (PIPELINE.md)', 'warn',
121
+ `${masked.join(', ')} pipe(s) into tail/head without pipefail — an agent running it sees exit 0 on a red run`,
122
+ 'prefix it with `set -o pipefail; ` or use the runner\'s quiet flag (--reporter=dot, -q)');
123
+ }
104
124
  return mk('profile', 'Profile (PIPELINE.md)', n ? 'ok' : 'warn',
105
125
  `${profile.name || 'unnamed'} · ${n} surface${n === 1 ? '' : 's'}`,
106
126
  n ? undefined : 'add at least one surface to §surfaces');
@@ -275,7 +295,9 @@ function gateEntries(settingsPath, isOurs) {
275
295
  const out = [];
276
296
  for (const g of list) {
277
297
  for (const h of (g && Array.isArray(g.hooks) ? g.hooks : [])) {
278
- if (h && isOurs(String(h.command || '').replace(/\\/g, '/'))) out.push({ matcher: String(g.matcher || ''), command: h.command });
298
+ // Shell form keeps the whole line in `command`; exec form splits it into `command` + `args`.
299
+ const line = [h && h.command, ...((h && Array.isArray(h.args)) ? h.args : [])].filter(Boolean).join(' ');
300
+ if (h && isOurs(String(line).replace(/\\/g, '/'))) out.push({ matcher: String(g.matcher || ''), command: line });
279
301
  }
280
302
  }
281
303
  return out;
package/lib/install.js CHANGED
@@ -102,7 +102,7 @@ function desiredFiles(globalDir) {
102
102
  put(path.join('cohorte', 'pipeline', 'scripts', f), fs.readFileSync(path.join(pkgRoot, 'scripts', f)),
103
103
  isShipped ? 0o755 : undefined);
104
104
  }
105
- put(path.join('cohorte', 'pipeline', 'CHANGELOG.md'), fs.readFileSync(path.join(pkgRoot, 'CHANGELOG.md')));
105
+ put(path.join('cohorte', 'pipeline', 'CHANGELOG.md'), installedChangelog());
106
106
  put(path.join('cohorte', 'pipeline', 'VERSION'), VERSION + '\n');
107
107
  put(path.join('cohorte', 'lib', 'project.js'), fs.readFileSync(path.join(pkgRoot, 'lib', 'project.js')));
108
108
  // project.js requires its sibling yaml.js (lazily) to write .claude/profile.json.
@@ -110,6 +110,20 @@ function desiredFiles(globalDir) {
110
110
  return files;
111
111
  }
112
112
 
113
+ // /cohorte-update-pipeline prints "What's new" from the installed changelog, between the old and the
114
+ // new version. Only the current major line is ever needed there (an upgrade from 2.x lands on 3.0.0,
115
+ // whose section is the migration guide), so the installed copy keeps the 3.x sections and points at
116
+ // the full history instead of shipping ~120 KB of it into every machine's core.
117
+ function installedChangelog() {
118
+ const full = fs.readFileSync(path.join(pkgRoot, 'CHANGELOG.md'), 'utf8');
119
+ const major = VERSION.split('.')[0];
120
+ const at = full.search(/^## \d+\.\d+\.\d+/m);
121
+ const head = at === -1 ? full : full.slice(0, at);
122
+ const sections = full.slice(at === -1 ? full.length : at).split(/^(?=## \d)/m);
123
+ const keep = sections.filter((s) => s.startsWith(`## ${major}.`));
124
+ return head + keep.join('') + `\n---\n\nOlder releases: https://github.com/TheBidouilleAgency/cohorte/blob/main/CHANGELOG.md\n`;
125
+ }
126
+
113
127
  function readManifest(globalDir) {
114
128
  try {
115
129
  const m = JSON.parse(fs.readFileSync(path.join(globalDir, MANIFEST), 'utf8'));
package/lib/project.js CHANGED
@@ -48,6 +48,8 @@ function assets() {
48
48
  : JSON.parse(fs.readFileSync(path.join(up, 'package.json'), 'utf8')).version;
49
49
  } catch { /* reported by the caller */ }
50
50
  return {
51
+ // Where the commands read the scripts from: this core when installed, else the machine's.
52
+ installedCore: installed ? up : path.join(process.env.CLAUDE_CONFIG_DIR || path.join(require('os').homedir(), '.claude'), 'cohorte'),
51
53
  gate: path.join(coreDir, 'hooks', 'gate.py'),
52
54
  specTemplate: path.join(coreDir, 'templates', 'spec.template.md'),
53
55
  templatesDir: path.join(coreDir, 'templates'),
@@ -101,6 +103,14 @@ function isOurCommand(cmd) {
101
103
  return /(^|["'\s/])\.claude\/hooks\/gate\.py(["'\s]|$)/.test(cmd.replace(/\\/g, '/'));
102
104
  }
103
105
 
106
+ // A hook entry is ours in either form: shell (`command` holds the whole line) or exec
107
+ // (`command` is the interpreter, `args` holds the script path).
108
+ function isOurHook(h) {
109
+ if (!h || typeof h !== 'object') return false;
110
+ if (isOurCommand(h.command)) return true;
111
+ return Array.isArray(h.args) && h.args.some((a) => isOurCommand(String(a)));
112
+ }
113
+
104
114
  // Remove our hook objects from every PreToolUse group; drop a group only when it ends up
105
115
  // empty, so a user's own hook sharing a matcher group survives.
106
116
  function stripOurHooks(list) {
@@ -108,21 +118,46 @@ function stripOurHooks(list) {
108
118
  let removed = 0;
109
119
  for (const group of Array.isArray(list) ? list : []) {
110
120
  if (!group || typeof group !== 'object' || !Array.isArray(group.hooks)) { out.push(group); continue; }
111
- const kept = group.hooks.filter((h) => !(h && isOurCommand(h.command)));
121
+ const kept = group.hooks.filter((h) => !isOurHook(h));
112
122
  removed += group.hooks.length - kept.length;
113
123
  if (kept.length) out.push(kept.length === group.hooks.length ? group : { ...group, hooks: kept });
114
124
  }
115
125
  return { list: out, removed };
116
126
  }
117
127
 
118
- function gateGroups() {
119
- const hook = { type: 'command', command: GATE_COMMAND, onFailure: 'block' };
128
+ // `shell` (default): one command line, expanded by a POSIX shell — works on every Claude Code that
129
+ // runs hooks. `exec` (`gate.hook_form: exec` in the profile): the interpreter plus an `args` list,
130
+ // with `${CLAUDE_PROJECT_DIR}` substituted by Claude Code itself — no shell involved, which is what
131
+ // Windows teams without Git Bash need. Verified on Claude Code 2.1.325; an older client that does
132
+ // not know `args` would run a bare `python3`, so every teammate must be on a recent version.
133
+ function gateGroups(form = 'shell') {
134
+ const hook = form === 'exec'
135
+ ? { type: 'command', command: 'python3', args: ['${CLAUDE_PROJECT_DIR}/.claude/hooks/cohorte-gate.py'], onFailure: 'block' }
136
+ : { type: 'command', command: GATE_COMMAND, onFailure: 'block' };
120
137
  return [
121
138
  { matcher: GATE_MATCHER, hooks: [hook] },
122
139
  { matcher: EDIT_MATCHER, hooks: [{ ...hook }] },
123
140
  ];
124
141
  }
125
142
 
143
+ // The permissions the PIPELINE itself needs (its scripts, the branch it cuts, read-only git):
144
+ // written by sync, deterministically, so no command has to Edit settings.json for them — the
145
+ // gate asks before any edit of that file, which is a hard stop in a headless run.
146
+ function pipelineAllow(coreDir) {
147
+ const os = require('os');
148
+ const home = os.homedir();
149
+ const scripts = path.join(coreDir, 'pipeline', 'scripts');
150
+ const shown = scripts.startsWith(home + path.sep) ? '~/' + path.relative(home, scripts).split(path.sep).join('/') : scripts.split(path.sep).join('/');
151
+ return [`Bash(${shown}/:*)`, 'Bash(git status:*)', 'Bash(git diff:*)', 'Bash(git log:*)',
152
+ 'Bash(git rev-parse:*)', 'Bash(git switch:*)', 'Bash(date:*)'];
153
+ }
154
+
155
+ function ensureAllow(data, rules) {
156
+ if (!data.permissions || typeof data.permissions !== 'object' || Array.isArray(data.permissions)) data.permissions = {};
157
+ if (!Array.isArray(data.permissions.allow)) data.permissions.allow = [];
158
+ for (const r of rules) if (!data.permissions.allow.includes(r)) data.permissions.allow.push(r);
159
+ }
160
+
126
161
  // 2.x allowlisted the pipeline scripts at their old homes. Point them at the 3.x core.
127
162
  function migratePermissions(data) {
128
163
  const allow = data.permissions && Array.isArray(data.permissions.allow) ? data.permissions.allow : null;
@@ -276,11 +311,16 @@ function sync(rootArg) {
276
311
  try { fs.chmodSync(path.join(root, GATE_FILE), 0o755); } catch { /* optional */ }
277
312
  }
278
313
 
279
- // 2. Its registration — exactly one of ours, every foreign hook untouched.
314
+ // 2. Its registration — exactly one of ours, every foreign hook untouched, in the form the
315
+ // profile asks for (`gate.hook_form`, default shell).
316
+ const pj = profileJson(root);
317
+ let form = 'shell';
318
+ try { form = (JSON.parse(pj.text || '{}').gate || {}).hook_form === 'exec' ? 'exec' : 'shell'; } catch { /* default */ }
280
319
  if (!settings.hooks || typeof settings.hooks !== 'object' || Array.isArray(settings.hooks)) settings.hooks = {};
281
320
  const { list } = stripOurHooks(settings.hooks.PreToolUse);
282
- settings.hooks.PreToolUse = list.concat(gateGroups());
321
+ settings.hooks.PreToolUse = list.concat(gateGroups(form));
283
322
  migratePermissions(settings);
323
+ ensureAllow(settings, pipelineAllow(A.installedCore));
284
324
  writeIfChanged(settingsPath, JSON.stringify(settings, null, 2) + '\n', changes, '.claude/settings.json (gate hook)');
285
325
 
286
326
  // 3. The pointer: tells a teammate (and /cohorte-doctor) which core this repo expects.
@@ -301,7 +341,6 @@ function sync(rootArg) {
301
341
 
302
342
  // 6. The parsed profile block, for agents that need only the machine block. Written AFTER
303
343
  // PIPELINE.md: every command that edits the block re-runs sync so this file follows it.
304
- const pj = profileJson(root);
305
344
  if (pj.text) writeIfChanged(path.join(root, PROFILE_FILE), pj.text, changes, '.claude/profile.json');
306
345
  else notes.push(pj.note);
307
346
  return { root, version: A.version, changes, notes };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cohorte",
3
- "version": "3.1.1",
3
+ "version": "3.1.2",
4
4
  "description": "Multi-agent development pipeline for Claude Code — install it once, run /cohorte-init-pipeline in a repo, and it adapts to that project's stack.",
5
5
  "bin": {
6
6
  "cohorte": "bin/cli.js"
@@ -14,9 +14,12 @@
14
14
  "!scripts/new-feature.sh",
15
15
  "!scripts/remove-feature.sh",
16
16
  "!scripts/demo",
17
+ "!scripts/ci",
17
18
  "!scripts/test-*.mjs",
18
19
  "!scripts/validate-core.mjs",
20
+ "!scripts/build-gate.mjs",
19
21
  "!core/hooks/__pycache__",
22
+ "!core/hooks/gate",
20
23
  "!**/*.pyc",
21
24
  "install.sh",
22
25
  "install.ps1",
@@ -68,7 +68,7 @@ surfaces:
68
68
  test_cmd: pnpm --filter api test
69
69
  # Bridled variants — what agents actually RUN (dot reporter / failures-only /
70
70
  # --quiet), so a green run costs lines, not pages. "" ⇒ callers fall back to
71
- # `<cmd> 2>&1 | tail -40`. /cohorte-init-pipeline asks for these; never store a bare
71
+ # `set -o pipefail; <cmd> 2>&1 | tail -40`. /cohorte-init-pipeline asks for these; never store a bare
72
72
  # `pnpm test` as the thing agents execute.
73
73
  test_quiet_cmd: pnpm --filter api test --reporter=dot
74
74
  lint_cmd: pnpm --filter api lint
@@ -13,8 +13,12 @@ context. The profile therefore stores **two forms of each noisy command**:
13
13
  Rules for every consumer (implementers, preflight, `/cohorte-audit` gates, workflow agents):
14
14
 
15
15
  1. Run the quiet variant when set.
16
- 2. Quiet variant empty/absent (older profile) ⇒ run `<full cmd> 2>&1 | tail -40` — never the bare
17
- command into your context.
16
+ 2. Quiet variant empty/absent (older profile) ⇒ run `set -o pipefail; <full cmd> 2>&1 | tail -40` —
17
+ never the bare command into your context. **Never drop the `pipefail`:** a pipeline's exit status
18
+ is its last command's, so without it a red run through `| tail` exits 0 and reads as green.
19
+ (`preflight.sh` and `verify-run.sh` always run checks with pipefail; your own Bash calls do not.)
20
+ 4. Prefer a runner's own quiet flag (`--reporter=dot`, `-q`, `--silent`) to a `| tail` when you store
21
+ a quiet variant: it keeps the runner's exit status without relying on the caller's shell options.
18
22
  3. Need the full log? Redirect it to a file and grep it; never print it.
19
23
 
20
24
  `/cohorte-init-pipeline` **asks** for these variants (detected defaults offered first) instead of silently
@@ -78,6 +78,7 @@ generic pipeline uses it, so a stateless agent can read/regenerate the profile c
78
78
  | `gate.preflight.enabled` | bool | hooks/gate.py, review | Phase gate: review dispatches need a fresh preflight stamp. See §Preflight (`<core>/pipeline/schema/preflight.md`). |
79
79
  | `gate.preflight.agents[]` | list | hooks/gate.py | `subagent_type`s the stamp gates (default `[cohorte-review]`; `review` still accepted). |
80
80
  | `gate.preflight.max_age_minutes` | number | hooks/gate.py | Stamp freshness window (default 30). |
81
+ | `gate.hook_form` | enum | sync | `shell` (default) — the hook is one command line run by a POSIX shell. `exec` — `python3` + an `args` list, `${CLAUDE_PROJECT_DIR}` substituted by Claude Code, no shell: for Windows teams without Git Bash. Needs a recent Claude Code on every machine (verified on 2.1.325). |
81
82
 
82
83
  ## Prose sections
83
84
 
@@ -22,7 +22,7 @@ files automatically. It works because every generated artifact is a **determinis
22
22
  `<agents>/<agent>.md` from the current `implementer.template.md` per §Rendering (`<core>/pipeline/schema/rendering.md`). Safe by
23
23
  doctrine: rendered agents are regenerable artifacts — hand-written rules belong in `PIPELINE.md`
24
24
  §Conventions (which reconcile never touches), NOT in agent files, where they'd be clobbered here.
25
- 3. **Additive settings patch.** Run `<sync>` (it owns the gate hook, the pointer,
25
+ 3. **Additive settings patch.** Run `<sync>` (it owns the gate hook, the pipeline's own `allow` rules, the pointer,
26
26
  `<state>/profile.json` and the `.gitignore` entries — so it runs AFTER step 1's top-up, and again
27
27
  if anything later edits the machine block), then bring `<state>/gate-config.json` and the `settings.json` permissions up
28
28
  to the current init spec (missing `allow` entries): add what's missing, never remove or rewrite
@@ -40,6 +40,8 @@ files automatically. It works because every generated artifact is a **determinis
40
40
  as "this is still sending", which is the one thing it must not imply. This is the single
41
41
  exception to "never rewrite the config": a targeted deletion of a block the core no longer
42
42
  defines, never a re-seed.
43
+ 5b. **CI doctor pin.** If `.github/workflows/*.yml` runs `npx -y cohorte@<x> doctor`, bump `<x>` (both
44
+ occurrences) to the installed core version.
43
45
  6. **Kanban sync.** Run the §Kanban reconcile (`<core>/pipeline/schema/kanban.md`): link/create the project's board if configured, verify
44
46
  its columns, and backfill/sync cards from `specs/*.md`.
45
47
  7. **Spec-template top-up.** `specs/_template.md` is seeded once at install and then **never**
@@ -9,7 +9,8 @@
9
9
  #
10
10
  # preflight.sh <report-file> "<cmd>" ["<cmd>"...]
11
11
  #
12
- # - Each command runs through `sh -c`, all output appended to <report-file> — the bulk
12
+ # - Each command runs through `bash -o pipefail -c` (sh with pipefail when bash is absent), all
13
+ # output appended to <report-file> — a `| tail` in a check can no longer hide its failure; the bulk
13
14
  # never enters the calling agent's context.
14
15
  # - First failure: prints the last 40 lines of the report raw to stderr and exits 1.
15
16
  # The caller must stop there — no agents.
@@ -31,12 +32,21 @@ shift
31
32
  mkdir -p "$(dirname "$report")" 2>/dev/null || true
32
33
  : > "$report"
33
34
 
35
+ # pipefail: a quiet variant is often `<runner> 2>&1 | tail -20`, and without it a pipeline's status
36
+ # is tail's — a red test run stamped GREEN (found by the real-model end-to-end run). bash when it
37
+ # exists; otherwise sh, which honours `set -o pipefail` on dash ≥ 0.5.11, busybox and bash-as-sh.
38
+ if command -v bash >/dev/null 2>&1; then
39
+ run_check() { bash -o pipefail -c "$1"; }
40
+ else
41
+ run_check() { sh -c "set -o pipefail 2>/dev/null; $1"; }
42
+ fi
43
+
34
44
  n=0
35
45
  for cmd in "$@"; do
36
46
  [ -n "$cmd" ] || continue
37
47
  n=$((n + 1))
38
48
  printf '\n$ %s\n' "$cmd" >> "$report"
39
- if ! sh -c "$cmd" >> "$report" 2>&1; then
49
+ if ! run_check "$cmd" >> "$report" 2>&1; then
40
50
  echo "PREFLIGHT FAIL — $cmd" >&2
41
51
  echo "--- last 40 lines of $report ---" >&2
42
52
  tail -40 "$report" >&2
@@ -90,7 +90,8 @@ rollback_check() {
90
90
  # was SIGKILLed (no trap runs) is reaped by `stop` or by the next run from that list.
91
91
  spawn() { # spawn <logfile> <cmd> — sets $spawned to the group leader's pid
92
92
  set -m
93
- sh -c "$2" > "$1" 2>&1 < /dev/null &
93
+ # pipefail: a check written `<runner> 2>&1 | tail -20` must fail when the runner fails.
94
+ bash -o pipefail -c "$2" > "$1" 2>&1 < /dev/null &
94
95
  spawned=$!
95
96
  set +m
96
97
  remember "$spawned"