cohorte 3.1.1 → 3.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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;
@@ -345,6 +367,51 @@ function checkHooks(projectRoot, globalDir) {
345
367
  return mk('hooks', 'Gate hook', 'ok', `registered once (${shell[0].matcher} + Write|Edit|MultiEdit|NotebookEdit), committed`);
346
368
  }
347
369
 
370
+ // Claude Code ignores a project's permissions.allow until its folder is trusted (the dialog an
371
+ // interactive `claude` shows once). Under `claude -p` — CI, and tools such as francois that drive
372
+ // Claude Code headless — nothing ever shows that dialog, so every pipeline script and test command
373
+ // prompts (or is refused) instead of running. Hooks still run: the gate is unaffected. The answer
374
+ // lives on the user store (`<config>/.claude.json`, or `~/.claude.json` without CLAUDE_CONFIG_DIR),
375
+ // keyed by the git root and honoured from any ancestor folder.
376
+ function claudeUserStore(globalDir) {
377
+ if (process.env.CLAUDE_CONFIG_DIR) return path.join(process.env.CLAUDE_CONFIG_DIR, '.claude.json');
378
+ return path.join(require('os').homedir(), '.claude.json');
379
+ }
380
+
381
+ const realOr = (p) => { try { return fs.realpathSync(p); } catch { return path.resolve(p); } };
382
+
383
+ // Trusted folders, as written and resolved (macOS: /var ⇄ /private/var, /tmp ⇄ /private/tmp).
384
+ function trustedBy(projects, dirs) {
385
+ const trusted = new Map();
386
+ for (const [k, node] of Object.entries(projects || {})) {
387
+ if (node && node.hasTrustDialogAccepted === true) { trusted.set(path.resolve(k), k); trusted.set(realOr(k), k); }
388
+ }
389
+ for (const start of dirs) {
390
+ for (let d = path.resolve(start); ; d = path.dirname(d)) {
391
+ if (trusted.has(d)) return trusted.get(d);
392
+ if (path.dirname(d) === d) break;
393
+ }
394
+ }
395
+ return null;
396
+ }
397
+
398
+ function checkTrust(projectRoot, globalDir) {
399
+ const store = readJson(claudeUserStore(globalDir));
400
+ if (!store) return mk('trust', 'Folder trust', 'skip', 'no Claude Code user store found (never run on this machine?)');
401
+ const top = spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd: projectRoot, encoding: 'utf8' });
402
+ const root = top.status === 0 && top.stdout.trim() ? path.resolve(top.stdout.trim()) : path.resolve(projectRoot);
403
+ const by = trustedBy(store.projects, [root, realOr(root), projectRoot]);
404
+ if (by) {
405
+ const self = [root, realOr(root), path.resolve(projectRoot)].some((d) => realOr(by) === realOr(d));
406
+ return mk('trust', 'Folder trust', 'ok', self ? 'trusted' : `trusted through ${by}`);
407
+ }
408
+ const settings = readJson(path.join(projectRoot, '.claude', 'settings.json'));
409
+ const n = (settings && settings.permissions && Array.isArray(settings.permissions.allow)) ? settings.permissions.allow.length : 0;
410
+ return mk('trust', 'Folder trust', 'warn',
411
+ `not trusted — under \`claude -p\` (CI, francois, scripts) Claude Code ignores the ${n} permissions.allow rule(s), so every pipeline script prompts or is refused (the gate itself still runs)`,
412
+ `run \`claude\` once in ${root} (or a parent folder) and accept the trust dialog`);
413
+ }
414
+
348
415
  function checkRetrieval(profile, projectRoot) {
349
416
  const provider = profile && profile.retrieval && profile.retrieval.provider;
350
417
  if (!provider || provider === 'none' || String(provider).startsWith('<')) {
@@ -474,6 +541,8 @@ async function state({ projectRoot, globalDir, cliVersion, offline }) {
474
541
  checkLocalArtifacts(projectRoot, ['.claude']),
475
542
  isProject ? checkHooks(projectRoot, globalDir)
476
543
  : mk('hooks', 'Gate hook', 'skip', 'not a cohorte project yet (no PIPELINE.md / .claude/pipeline.json)'),
544
+ isProject ? checkTrust(projectRoot, globalDir)
545
+ : mk('trust', 'Folder trust', 'skip', 'not a cohorte project yet'),
477
546
  checkRetrieval(profile, projectRoot),
478
547
  checkDesign(profile, projectRoot),
479
548
  checkIsolation(profile, projectRoot),
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.3",
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**
@@ -230,14 +230,43 @@ fi
230
230
 
231
231
  # Serialize the read-modify-write: parallel worktrees (/cohorte-fleet, the loop workflow) move
232
232
  # cards on ONE board, and two concurrent rewrites used to lose one of the moves.
233
- # Where flock(1) exists (Linux), the kernel holds the lock and drops it if we die; the lock file
234
- # lives in $TMPDIR keyed by the board's path, never next to the board in the human's vault.
235
- # Elsewhere (macOS has no flock) an atomic `mkdir` is the lock and the holder's PID marks it: a
236
- # lock is stale only when that process is gone, never by age. COHORTE_KANBAN_NO_FLOCK=1 forces
237
- # the fallback (tests).
233
+ # A kernel lock whenever possible: flock(2) on fd 9, held by this shell until it exits — the
234
+ # kernel drops it if we die, so there is no stale lock to break. flock(1) where it exists (Linux);
235
+ # otherwise python3 takes it on the INHERITED fd 9 (a flock belongs to the open file, which this
236
+ # shell keeps open after python exits) — python3 is there wherever cohorte runs, the gate needs it.
237
+ # The lock file lives in $TMPDIR keyed by the board's physical path (`./Tasks.md`, an absolute
238
+ # path and a symlinked vault serialize together), never next to the board in the human's vault.
239
+ # Last resort, neither available: an atomic `mkdir` with the holder's PID (stale only when that
240
+ # process is gone; breaking it is serialized under `<lock>.break`).
241
+ # COHORTE_KANBAN_LOCK=flock|python|mkdir forces one (tests); COHORTE_KANBAN_NO_FLOCK=1 skips flock(1).
242
+ board_key="$(cd "$(dirname "$board")" && pwd -P)/$(basename "$board")"
238
243
  lock="${board}.lock"
239
- if [ -z "${COHORTE_KANBAN_NO_FLOCK:-}" ] && command -v flock >/dev/null 2>&1; then
240
- flockfile="${TMPDIR:-/tmp}/cohorte-kanban-$(printf '%s' "$board" | cksum | cut -d' ' -f1).lock"
244
+ flockfile="${TMPDIR:-/tmp}/cohorte-kanban-$(printf '%s' "$board_key" | cksum | cut -d' ' -f1).lock"
245
+ lock_kind=${COHORTE_KANBAN_LOCK:-}
246
+ if [ -z "$lock_kind" ]; then
247
+ if [ -z "${COHORTE_KANBAN_NO_FLOCK:-}" ] && command -v flock >/dev/null 2>&1; then lock_kind=flock
248
+ elif python3 -c 'import fcntl' >/dev/null 2>&1; then lock_kind=python
249
+ else lock_kind=mkdir
250
+ fi
251
+ fi
252
+ if [ "$lock_kind" = python ]; then
253
+ exec 9>"$flockfile"
254
+ if ! python3 -c 'import errno, fcntl, sys, time
255
+ end = time.time() + 30
256
+ while True:
257
+ try:
258
+ fcntl.flock(9, fcntl.LOCK_EX | fcntl.LOCK_NB)
259
+ sys.exit(0)
260
+ except OSError as e:
261
+ if e.errno not in (errno.EAGAIN, errno.EACCES, errno.EWOULDBLOCK):
262
+ raise
263
+ if time.time() > end:
264
+ sys.exit(1)
265
+ time.sleep(0.02)'; then
266
+ echo "error: board is locked by another move ($flockfile) — retry" >&2
267
+ exit 4
268
+ fi
269
+ elif [ "$lock_kind" = flock ]; then
241
270
  exec 9>"$flockfile"
242
271
  if ! flock -w 30 9; then
243
272
  echo "error: board is locked by another move ($flockfile) — retry" >&2
@@ -248,11 +277,22 @@ else
248
277
  until mkdir "$lock" 2>/dev/null; do
249
278
  holder=$(cat "$lock/pid" 2>/dev/null || true)
250
279
  if [ -n "$holder" ] && ! kill -0 "$holder" 2>/dev/null; then
251
- # Dead holder. Remove only if it is still THAT lock (another waiter may have replaced it).
252
- if [ "$(cat "$lock/pid" 2>/dev/null || true)" = "$holder" ]; then
253
- rm -f "$lock/pid"; rmdir "$lock" 2>/dev/null || true
280
+ # Dead holder. One breaker at a time; under that, remove the lock only if it still names
281
+ # the same dead holder — then nobody else can have replaced it (only a breaker or its
282
+ # owner removes a lock, and the owner is dead).
283
+ if mkdir "$lock.break" 2>/dev/null; then
284
+ echo $$ > "$lock.break/pid"
285
+ if [ "$(cat "$lock/pid" 2>/dev/null || true)" = "$holder" ]; then
286
+ rm -f "$lock/pid"; rmdir "$lock" 2>/dev/null || true
287
+ fi
288
+ rm -f "$lock.break/pid"; rmdir "$lock.break" 2>/dev/null || true
289
+ continue
290
+ fi
291
+ # Another waiter is breaking it — unless that breaker died mid-way too.
292
+ breaker=$(cat "$lock.break/pid" 2>/dev/null || true)
293
+ if [ -n "$breaker" ] && ! kill -0 "$breaker" 2>/dev/null; then
294
+ rm -f "$lock.break/pid"; rmdir "$lock.break" 2>/dev/null || true
254
295
  fi
255
- continue
256
296
  fi
257
297
  waited=$((waited + 1))
258
298
  if [ "$waited" -gt 300 ]; then
@@ -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"