cohorte 3.1.0 → 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,55 @@ 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
+
42
+ ## 3.1.1 — 2026-11-16
43
+
44
+ - **An install that fails half-way is rolled back.** `cohorte install` / `update` journal every file
45
+ they write or retire and put the tree back as it was if anything fails mid-run (a full disk, a
46
+ path that is a directory, a permission). Empty folders of yours under `~/.claude/commands` or
47
+ `~/.claude/agents` are never pruned.
48
+ - **The lead commands read `.claude/profile.json`** (16 of 18 commands), falling back to the
49
+ `PIPELINE.md` block when it is absent; prose sections (§Conventions, §Personas) are still read
50
+ from `PIPELINE.md`.
51
+ - **`/cohorte-ship` clears the feature's report buffer after the merge** (`specs/reports/<id>.*`,
52
+ the brainstorm return, the verify evidence) — with `rm -f`/`rmdir`, which every gate allows.
53
+ - **`new-feature.sh` / `remove-feature.sh` validate their input:** the feature id must be kebab-case,
54
+ and an unknown option is an error instead of being ignored. Re-render them with
55
+ `/cohorte-update-pipeline`.
56
+ - **Releases:** every GitHub Action is pinned to a commit SHA, the Discord notification fires only
57
+ after a successful npm publish, and the docs site builds on pull requests.
58
+
10
59
  ## 3.1.0 — 2026-11-16
11
60
 
12
61
  - **The schema is split: one file per topic, each command loads only what it cites.**
@@ -57,8 +106,8 @@ short, user-facing, most recent first. One `## <version> — <YYYY-MM-DD>` secti
57
106
  worktree resolve against that worktree, and paths outside the project (`/dev/null`, `$TMPDIR`)
58
107
  are not judged. It is **on by default** from the first `cohorte sync` after upgrading (that sync
59
108
  also registers the hook for `NotebookEdit`). Verified on Claude Code 2.1.325: a subagent's
60
- `Write` reaches the hook with its `agent_id` and `agent_type`. Not verified yet for implementers
61
- 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.
62
111
  Before upgrading, check what each surface writes outside its tree (root `tests/`, a generated
63
112
  client, the root lockfile): `/cohorte-update-pipeline` proposes them as `owns_also` /
64
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
@@ -7,7 +7,7 @@ allowed-tools: Read, Write, Edit, Bash, Grep, Glob, DesignSync
7
7
  Bring the code UI kit back in line with the **design system** — the source of truth. Direction is
8
8
  **design → code**.
9
9
 
10
- > Read `PIPELINE.md` §`design` first. **If `design.enabled` is false, stop immediately** and tell the
10
+ > Read `.claude/profile.json` §`design` first (the parsed `pipeline-profile` block; absent ⇒ read that block in `PIPELINE.md`). **If `design.enabled` is false, stop immediately** and tell the
11
11
  > human this project has no design system configured (nothing to align). Otherwise proceed with the
12
12
  > profile's `provider`, `design_system_project`, `snapshot_dir`, `ui_kit_path`, `tokens_path`.
13
13
 
@@ -7,7 +7,7 @@ argument-hint: [path or domain, default = whole repo]
7
7
  You are the **lead**. Audit **$ARGUMENTS** (default: whole repo) to drive it to a clean base. Read +
8
8
  analyze only — no fixes (those go through `/cohorte-refactor`).
9
9
 
10
- > Read `PIPELINE.md` §`commands` (the mechanical gates), `surfaces`, and §Conventions — plus
10
+ > Read `.claude/profile.json` `commands` (the mechanical gates) and `surfaces` (the parsed `pipeline-profile` block; absent ⇒ read that block in `PIPELINE.md`), and `PIPELINE.md` §Conventions — plus
11
11
  > `specs/_decisions.md` §Live if it exists (`<core>/pipeline/schema/decisions.md`): those standing decisions are part
12
12
  > of the rulebook you audit against, and code that contradicts one is a finding like any other.
13
13
  >
@@ -13,7 +13,7 @@ metrics line, no kanban move. It exists to refresh what the loop workflow's prec
13
13
  (`readiness.json` newer than the spec, the contract on disk) without a full build — the loop then
14
14
  builds itself. Say which mode you ran in your last line.
15
15
 
16
- > Read `PIPELINE.md` §`pipeline-profile` first: the `surfaces` list (how many implementers to
16
+ > Read `.claude/profile.json` first (the parsed `pipeline-profile` block; absent ⇒ read that block in `PIPELINE.md`): the `surfaces` list (how many implementers to
17
17
  > dispatch + their agent names), `contract` (mechanism + path), and the `design` flag. _Skip the
18
18
  > re-read if it's already in your context this session and unmodified since._
19
19
  >
@@ -188,7 +188,7 @@ the prompt-cache prefix. Never paste a diff into a dispatch — the agent comput
188
188
  tree. For each surface in `surfaces`:
189
189
 
190
190
  > `subagent_type: <surface.agent>` — "Implement the **<surface.key>** surface for feature `$ARGUMENTS`.
191
- > Read `PIPELINE.md` first. Spec: `specs/$ARGUMENTS.md`. Contract: `<contract.path>/$ARGUMENTS.<ext>`
191
+ > Read `.claude/profile.json` first (your surface's commands and flags). Spec: `specs/$ARGUMENTS.md`. Contract: `<contract.path>/$ARGUMENTS.<ext>`
192
192
  > (import read-only). Work test-first. Touch only `<surface.path>`. Need the current state of your
193
193
  > tree? Compute it yourself: `<core>/pipeline/scripts/feature-diff.sh --default <default_branch> --patch -- <surface.path>`. Return the handoff in the
194
194
  > format your agent instructions define. Design files: <the spec's `design_files` links — each
@@ -8,7 +8,7 @@ You are the **lead**. Run the fix loop for feature **$ARGUMENTS** — the scoped
8
8
  `REVISE`/`BLOCK` verdict. The full `/cohorte-spec` (Mode B) + `/cohorte-build` path still exists for review returns
9
9
  that change the *contract*; `/cohorte-fix` is for everything else.
10
10
 
11
- > Read `PIPELINE.md` §`pipeline-profile` first: `surfaces` (paths + agent names) and `contract`.
11
+ > Read `.claude/profile.json` first (the parsed `pipeline-profile` block; absent ⇒ read that block in `PIPELINE.md`): `surfaces` (paths + agent names) and `contract`.
12
12
  > _Skip the re-read if it's already in your context this session and unmodified since._
13
13
  >
14
14
  > **Kanban** (`<core>/pipeline/schema/kanban.md`): on ingest, run
@@ -17,7 +17,7 @@ worktree's session**, supervised like any other; the fleet plans, watches and re
17
17
  lives in `specs/reports/fleet.json` (the main checkout's gitignored buffer — this repo's
18
18
  multi-*feature* flight plan).
19
19
 
20
- > Read `PIPELINE.md` §`pipeline-profile` first: `surfaces` (paths — the overlap analysis keys
20
+ > Read `.claude/profile.json` first (the parsed `pipeline-profile` block; absent ⇒ read that block in `PIPELINE.md`): `surfaces` (paths — the overlap analysis keys
21
21
  > on them), `contract`, `vcs.default_branch`, and the `isolation` block. _Skip the re-read if
22
22
  > already in context and unmodified since._ **`isolation.enabled: false` ⇒ stop at `plan`**:
23
23
  > N features in one checkout is a merge-conflict generator with extra steps — name the fix
@@ -8,7 +8,7 @@ client email, a support thread, a stack trace, a half-idea — and today a human
8
8
  hand before anything can start. Your job is that distillation: read the raw material, decide
9
9
  which door it enters through, and stage a handoff the next command can consume verbatim.
10
10
 
11
- > Read `PIPELINE.md` §`pipeline-profile` first — `name`, `one_liner`, `surfaces` (to guess which
11
+ > Read `.claude/profile.json` first (the parsed `pipeline-profile` block; absent ⇒ read that block in `PIPELINE.md`) — `name`, `one_liner`, `surfaces` (to guess which
12
12
  > surface a symptom lives in) and `ui_language`. _Skip the re-read if it's already in your
13
13
  > context this session and unmodified since._ Read `specs/_decisions.md` §Live if it exists —
14
14
  > an incoming request that contradicts a settled decision must be flagged as such, not triaged
@@ -12,7 +12,7 @@ cycle at input price on every turn.
12
12
 
13
13
  Bug (may be empty): **$ARGUMENTS**
14
14
 
15
- > Read `PIPELINE.md` §`pipeline-profile` first: `surfaces` (paths — this is what you map the bug onto)
15
+ > Read `.claude/profile.json` first (the parsed `pipeline-profile` block; absent ⇒ read that block in `PIPELINE.md`): `surfaces` (paths — this is what you map the bug onto)
16
16
  > and `vcs`. _Skip the re-read if it's already in your context this session and unmodified since._
17
17
  > Do NOT read `specs/_decisions.md`: a bug fix decides nothing transverse, and the journal is for
18
18
  > decisions that outlive a feature.
@@ -6,8 +6,8 @@ argument-hint: <domain…> (one or more surface keys, "shared", or "all")
6
6
 
7
7
  You are the **lead**. Refactor domain **$ARGUMENTS** to match `PIPELINE.md`, using the `/cohorte-audit` backlog.
8
8
 
9
- > Read `PIPELINE.md` §`surfaces` (map the domain → a surface + its agent + commands), §`contract`
10
- > and §`vcs` (§4's branch).
9
+ > Read `.claude/profile.json` `surfaces` (map the domain → a surface + its agent + commands), `contract`
10
+ > and `vcs` (§4's branch) (the parsed `pipeline-profile` block; absent ⇒ read that block in `PIPELINE.md`).
11
11
  >
12
12
  > **Kanban** (`<core>/pipeline/schema/kanban.md`): §4 runs
13
13
  > `<core>/pipeline/scripts/kanban-move.sh auto <spec id> ready --title "[refactor] <domains>"`. `auto`
@@ -11,7 +11,7 @@ each surface agent at render time. This command closes that loop: findings → p
11
11
  ratified rules → re-rendered agents. The next build then never produces the finding again —
12
12
  which is cheaper than any number of review rounds catching it.
13
13
 
14
- > Read `PIPELINE.md` §`pipeline-profile` (`surfaces`, and skim the existing §Conventions
14
+ > Read `.claude/profile.json` `surfaces` (the parsed `pipeline-profile` block; absent ⇒ read that block in `PIPELINE.md`), and skim `PIPELINE.md`'s existing §Conventions
15
15
  > stanzas — a rule that already exists is a finding about *enforcement*, not a missing rule)
16
16
  > and `specs/_decisions.md` §Live. _Skip the re-read if already in context and unmodified._
17
17
 
@@ -6,7 +6,7 @@ argument-hint: <feature_id> | --pr <num>
6
6
 
7
7
  You are the **lead**. Dispatch the review for feature **$ARGUMENTS**.
8
8
 
9
- > Read `PIPELINE.md` §`vcs.default_branch` (diff base) and the `surfaces`/`contract`/`commands` fields.
9
+ > Read `.claude/profile.json` `vcs.default_branch` (diff base) and the `surfaces`/`contract`/`commands` fields (the parsed `pipeline-profile` block; absent ⇒ read that block in `PIPELINE.md`).
10
10
  > _Skip the re-read if it's already in your context this session and unmodified since._
11
11
  >
12
12
  > **Kanban** (`<core>/pipeline/schema/kanban.md`): run
@@ -101,8 +101,8 @@ reviewed surface:
101
101
  Keep the dispatch prompt **byte-identical across features and rounds** except the variable block,
102
102
  which sits at the END so every repeat hits the prompt-cache prefix:
103
103
 
104
- > `subagent_type: cohorte-review` — "Review one feature surface against its frozen spec. Read `PIPELINE.md`
105
- > first (flags + the §Conventions/§Testing slice for your scope). Check spec conformance first, then
104
+ > `subagent_type: cohorte-review` — "Review one feature surface against its frozen spec. Read `.claude/profile.json`
105
+ > first (flags), then `PIPELINE.md`'s §Conventions/§Testing slice for your scope. Check spec conformance first, then
106
106
  > correctness, security, conventions, RBAC/mobile-first _if the profile enables them_, and TDD
107
107
  > coverage. Your dispatch names a staged diff file — read it FIRST; open a full source file only when
108
108
  > a finding demands it. Emit the REVIEW REPORT in the capped format your agent instructions define —
@@ -6,7 +6,7 @@ argument-hint: <feature_id>
6
6
 
7
7
  You are the **lead**. Ship feature **$ARGUMENTS**. This is the outward-facing gate.
8
8
 
9
- > Read `PIPELINE.md` §`vcs` (host, remote, default_branch, feature_branch_prefix) **and
9
+ > Read `.claude/profile.json` `vcs` (host, remote, default_branch, feature_branch_prefix) (the parsed `pipeline-profile` block; absent ⇒ read that block in `PIPELINE.md`) **and
10
10
  > §`release_notes`** — §2b below is skipped or required based on it, and skipping it when it is
11
11
  > required opens a PR that CI fails on arrival.
12
12
  >
@@ -122,7 +122,7 @@ See `<core>/pipeline/schema/release-notes.md`.
122
122
 
123
123
  Spawn one agent (`subagent_type: cohorte-release`):
124
124
  "Release feature `$ARGUMENTS` on branch
125
- `<the branch §1 resolved>`. Read `PIPELINE.md` §vcs first. Spec: `specs/$ARGUMENTS.md` (already
125
+ `<the branch §1 resolved>`. Read `.claude/profile.json` `vcs` first. Spec: `specs/$ARGUMENTS.md` (already
126
126
  `status: shipped` — stage it). Write conventional commit(s), push (no force), open the PR (use `gh` if
127
127
  `host: github` + available; else emit the compare URL + drafted PR body from `<core>/templates/pr-body.md`).
128
128
  Stage **all** the feature's changes including `specs/$ARGUMENTS.md` and, if `release_notes.enabled`, the
@@ -162,6 +162,11 @@ under the `shipped` heading — never re-read the whole board into context.
162
162
  `scripts/remove-feature.sh $ARGUMENTS` (add `--drop-db` to also drop the feature db; kept by
163
163
  default). It removes the worktree, deletes the merged branch, frees the slot. Never run it before
164
164
  the merge is confirmed, and only with the human's go-ahead (the gate will ask anyway).
165
+ - **Clear the report buffer** once the merge is confirmed (never before — `/cohorte-fix` and a
166
+ re-review read it): in the main checkout, one Bash call —
167
+ `rm -f specs/reports/$ARGUMENTS.verify/* 2>/dev/null; rmdir specs/reports/$ARGUMENTS.verify 2>/dev/null; rm -f specs/reports/$ARGUMENTS.* specs/reports/$ARGUMENTS-brainstorm.md`
168
+ (plain `rm -f` + `rmdir`, never `rm -rf`, which many profiles' gate denies).
169
+ These are gitignored, derived files: the spec, its `## Remediation` history and the merged code keep
170
+ everything worth keeping. Say how many files went.
165
171
  - Feature closed — **recommend a `/clear`** before starting the next one; nothing from this session
166
- is needed again (spec `merged`, board updated). `specs/reports/$ARGUMENTS.*` is a gitignored
167
- buffer and can be deleted now.
172
+ is needed again (spec `merged`, board updated, buffer cleared).
@@ -7,8 +7,8 @@ You run the **spec** step in the main thread — interactive, with the human. Pa
7
7
 
8
8
  **$ARGUMENTS**
9
9
 
10
- > Read `PIPELINE.md` first: `contract` (mechanism/path — so §5 names the right schema types),
11
- > `design.enabled` (whether §8 matters), and §Conventions. Use `specs/_template.md` as the section list.
10
+ > Read `.claude/profile.json` first (the parsed `pipeline-profile` block; absent ⇒ read that block in `PIPELINE.md`): `contract` (mechanism/path — so §5 names the right schema types),
11
+ > `design.enabled` (whether §8 matters); then `PIPELINE.md` §Conventions. Use `specs/_template.md` as the section list.
12
12
  >
13
13
  > **Decision journal** (`<core>/pipeline/schema/decisions.md`): read `specs/_decisions.md` §Live if it exists — one
14
14
  > line per standing decision, so it is cheap. It is the ONLY place the project's transverse rules
@@ -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
@@ -43,6 +43,12 @@ function walk(dir) {
43
43
  return out;
44
44
  }
45
45
 
46
+ // Remove `dir` itself when empty — never anything inside it. For the user's shared dirs
47
+ // (commands/, agents/): an empty folder of theirs under them is not ours to delete.
48
+ function rmdirIfEmpty(dir) {
49
+ try { if (!fs.readdirSync(dir).length) fs.rmdirSync(dir); } catch { /* absent or not empty */ }
50
+ }
51
+
46
52
  function pruneEmpty(dir, stopAt) {
47
53
  let entries;
48
54
  try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
@@ -96,7 +102,7 @@ function desiredFiles(globalDir) {
96
102
  put(path.join('cohorte', 'pipeline', 'scripts', f), fs.readFileSync(path.join(pkgRoot, 'scripts', f)),
97
103
  isShipped ? 0o755 : undefined);
98
104
  }
99
- put(path.join('cohorte', 'pipeline', 'CHANGELOG.md'), fs.readFileSync(path.join(pkgRoot, 'CHANGELOG.md')));
105
+ put(path.join('cohorte', 'pipeline', 'CHANGELOG.md'), installedChangelog());
100
106
  put(path.join('cohorte', 'pipeline', 'VERSION'), VERSION + '\n');
101
107
  put(path.join('cohorte', 'lib', 'project.js'), fs.readFileSync(path.join(pkgRoot, 'lib', 'project.js')));
102
108
  // project.js requires its sibling yaml.js (lazily) to write .claude/profile.json.
@@ -104,6 +110,20 @@ function desiredFiles(globalDir) {
104
110
  return files;
105
111
  }
106
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
+
107
127
  function readManifest(globalDir) {
108
128
  try {
109
129
  const m = JSON.parse(fs.readFileSync(path.join(globalDir, MANIFEST), 'utf8'));
@@ -297,42 +317,61 @@ async function install(globalDir, opts = {}) {
297
317
  const manifest = { version: VERSION, files: {} };
298
318
  let written = 0;
299
319
 
300
- for (const [rel, { content, mode }] of want) {
301
- const dest = path.join(globalDir, rel);
302
- const buf = Buffer.isBuffer(content) ? content : Buffer.from(content);
303
- const cur = readMaybe(dest);
304
- const newHash = sha(buf);
305
- if (cur && sha(cur) !== newHash) {
306
- const known = old.files[rel];
307
- // A 2.x install has no manifest, but every file it rendered carries our marker.
308
- const ours2x = !known && MARKERS.some((m) => cur.toString('utf8').includes(m));
309
- // Modified since we wrote it, or a file we never wrote that sits on our name.
310
- if (!ours2x && (!known || known !== sha(cur))) {
311
- const to = path.join(backupDir, rel);
312
- fs.mkdirSync(path.dirname(to), { recursive: true });
313
- fs.copyFileSync(dest, to);
314
- warnings.push(`${rel} differed from what cohorte installed — your copy is saved in ${R.displayPath(to)}`);
320
+ // Every change below is journaled (path + previous bytes, or null when the file is new), so an
321
+ // error half-way — a full disk, a path that is a directory, a permission — puts the tree back as
322
+ // it was instead of leaving half a release next to the previous manifest.
323
+ const journal = [];
324
+ const remember = (dest, prev) => journal.push({ dest, prev });
325
+ let removed = 0;
326
+ try {
327
+ for (const [rel, { content, mode }] of want) {
328
+ const dest = path.join(globalDir, rel);
329
+ const buf = Buffer.isBuffer(content) ? content : Buffer.from(content);
330
+ const cur = readMaybe(dest);
331
+ const newHash = sha(buf);
332
+ if (cur && sha(cur) !== newHash) {
333
+ const known = old.files[rel];
334
+ // A 2.x install has no manifest, but every file it rendered carries our marker.
335
+ const ours2x = !known && MARKERS.some((m) => cur.toString('utf8').includes(m));
336
+ // Modified since we wrote it, or a file we never wrote that sits on our name.
337
+ if (!ours2x && (!known || known !== sha(cur))) {
338
+ const to = path.join(backupDir, rel);
339
+ fs.mkdirSync(path.dirname(to), { recursive: true });
340
+ fs.copyFileSync(dest, to);
341
+ warnings.push(`${rel} differed from what cohorte installed — your copy is saved in ${R.displayPath(to)}`);
342
+ }
343
+ }
344
+ if (!cur || sha(cur) !== newHash) {
345
+ remember(dest, cur);
346
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
347
+ fs.writeFileSync(dest, buf);
348
+ written++;
315
349
  }
350
+ if (mode && process.platform !== 'win32') { try { fs.chmodSync(dest, mode); } catch { /* optional */ } }
351
+ manifest.files[rel] = newHash;
316
352
  }
317
- if (!cur || sha(cur) !== newHash) {
318
- fs.mkdirSync(path.dirname(dest), { recursive: true });
319
- fs.writeFileSync(dest, buf);
320
- written++;
353
+
354
+ // Files the previous version installed and this one does not: delete them when they are
355
+ // exactly as we wrote them, keep (and say so) when the user changed them.
356
+ for (const [rel, hash] of Object.entries(old.files)) {
357
+ if (want.has(rel)) continue;
358
+ const dest = path.join(globalDir, rel);
359
+ const cur = readMaybe(dest);
360
+ if (!cur) continue;
361
+ if (sha(cur) === hash) { remember(dest, cur); fs.rmSync(dest); removed++; }
362
+ else warnings.push(`kept ${rel}: no longer shipped, but you modified it`);
321
363
  }
322
- if (mode && process.platform !== 'win32') { try { fs.chmodSync(dest, mode); } catch { /* optional */ } }
323
- manifest.files[rel] = newHash;
324
- }
325
364
 
326
- // Files the previous version installed and this one does not: delete them when they are
327
- // exactly as we wrote them, keep (and say so) when the user changed them.
328
- let removed = 0;
329
- for (const [rel, hash] of Object.entries(old.files)) {
330
- if (want.has(rel)) continue;
331
- const dest = path.join(globalDir, rel);
332
- const cur = readMaybe(dest);
333
- if (!cur) continue;
334
- if (sha(cur) === hash) { fs.rmSync(dest); removed++; }
335
- else warnings.push(`kept ${rel}: no longer shipped, but you modified it`);
365
+ } catch (e) {
366
+ for (const { dest, prev } of journal.reverse()) {
367
+ try {
368
+ if (prev === null || prev === undefined) fs.rmSync(dest, { force: true });
369
+ else { fs.mkdirSync(path.dirname(dest), { recursive: true }); fs.writeFileSync(dest, prev); }
370
+ } catch { /* best effort — keep restoring the rest */ }
371
+ }
372
+ for (const d of ['cohorte', 'workflows']) pruneEmpty(path.join(globalDir, d));
373
+ for (const d of ['commands', 'agents']) rmdirIfEmpty(path.join(globalDir, d));
374
+ throw new ProjectError(`install failed and was rolled back (${journal.length} change(s) undone): ${e.message}`);
336
375
  }
337
376
  for (const d of ['cohorte', 'workflows']) pruneEmpty(path.join(globalDir, d), path.join(globalDir, d));
338
377
 
@@ -366,7 +405,8 @@ function uninstall(globalDir, { purge = false } = {}) {
366
405
  pruneEmpty(path.join(globalDir, 'cohorte'));
367
406
  // Empty dirs install created (commands/, agents/, workflows/): harmless to remove, and left
368
407
  // behind they make an uninstall look incomplete.
369
- for (const d of ['workflows', 'commands', 'agents']) pruneEmpty(path.join(globalDir, d));
408
+ pruneEmpty(path.join(globalDir, 'workflows'));
409
+ for (const d of ['commands', 'agents']) rmdirIfEmpty(path.join(globalDir, d));
370
410
  if (removed) report.push(`removed ${removed} installed file(s)`);
371
411
  const leftovers = legacyGlobalCandidates(globalDir);
372
412
  if (leftovers.length) warnings.push(`2.x files still present (run \`cohorte update\` first to migrate them, then uninstall): ${leftovers.slice(0, 5).join(', ')}${leftovers.length > 5 ? '…' : ''}`);
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.0",
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**
@@ -19,10 +19,16 @@
19
19
  set -euo pipefail
20
20
 
21
21
  id="${1:-}"
22
- if [[ -z "$id" ]]; then
22
+ if [[ -z "$id" || $# -gt 1 ]]; then
23
23
  echo "usage: scripts/new-feature.sh <feature_id>" >&2
24
24
  exit 1
25
25
  fi
26
+ # The id becomes a branch name, a directory, a database name and a slot key: kebab-case only
27
+ # (what /cohorte-spec assigns), so nothing downstream has to quote or escape it.
28
+ if [[ ! "$id" =~ ^[a-z0-9][a-z0-9-]{0,62}$ ]]; then
29
+ echo "error: feature id \"$id\" must be kebab-case (a-z, 0-9, -; at most 63 chars), as /cohorte-spec assigns it" >&2
30
+ exit 2
31
+ fi
26
32
 
27
33
  repo_root="$(git -C "$(dirname "${BASH_SOURCE[0]}")" rev-parse --show-toplevel)"
28
34
  branch="__BRANCH_PREFIX__${id}"
@@ -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
@@ -14,11 +14,20 @@ set -euo pipefail
14
14
 
15
15
  id="${1:-}"
16
16
  drop_db="no"
17
- [[ "${2:-}" == "--drop-db" ]] && drop_db="yes"
18
-
19
- if [[ -z "$id" ]]; then
20
- echo "usage: scripts/remove-feature.sh <feature_id> [--drop-db]" >&2
21
- exit 1
17
+ usage() { echo "usage: scripts/remove-feature.sh <feature_id> [--drop-db]" >&2; exit 1; }
18
+ [[ -n "$id" ]] || usage
19
+ shift
20
+ # Every flag is parsed: an unknown one (a typo'd --drop-db, a --force this script never had) used
21
+ # to be ignored silently, so the teardown ran with options the human did not get.
22
+ for arg in "$@"; do
23
+ case "$arg" in
24
+ --drop-db) drop_db="yes" ;;
25
+ *) echo "error: unknown option \"$arg\"" >&2; usage ;;
26
+ esac
27
+ done
28
+ if [[ ! "$id" =~ ^[a-z0-9][a-z0-9-]{0,62}$ ]]; then
29
+ echo "error: feature id \"$id\" must be kebab-case (a-z, 0-9, -)" >&2
30
+ exit 2
22
31
  fi
23
32
 
24
33
  repo_root="$(git -C "$(dirname "${BASH_SOURCE[0]}")" rev-parse --show-toplevel)"
@@ -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"