cohorte 3.0.0-dev.7 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (229) hide show
  1. package/CHANGELOG.md +1532 -0
  2. package/README.md +106 -185
  3. package/bin/cli.js +212 -0
  4. package/bin/report.js +141 -0
  5. package/core/agents/cohorte-profile-reader.md +50 -0
  6. package/core/agents/cohorte-release.md +58 -0
  7. package/core/agents/cohorte-review.md +174 -0
  8. package/core/agents/implementer.template.md +146 -0
  9. package/core/commands/cohorte-align-ds.md +33 -0
  10. package/core/commands/cohorte-audit.md +67 -0
  11. package/core/commands/cohorte-brainstorm.md +73 -0
  12. package/core/commands/cohorte-build.md +241 -0
  13. package/core/commands/cohorte-doctor.md +133 -0
  14. package/core/commands/cohorte-fix.md +80 -0
  15. package/core/commands/cohorte-fleet.md +111 -0
  16. package/core/commands/cohorte-init-pipeline.md +30 -0
  17. package/core/commands/cohorte-intake.md +92 -0
  18. package/core/commands/cohorte-patch.md +118 -0
  19. package/core/commands/cohorte-refactor.md +57 -0
  20. package/core/commands/cohorte-retro.md +85 -0
  21. package/core/commands/cohorte-review.md +224 -0
  22. package/core/commands/cohorte-ship.md +155 -0
  23. package/core/commands/cohorte-spec.md +105 -0
  24. package/core/commands/cohorte-update-pipeline.md +115 -0
  25. package/core/hooks/gate.py +2931 -0
  26. package/core/templates/agent-handoff.md +34 -0
  27. package/core/templates/brainstorm-return.md +42 -0
  28. package/core/templates/decisions.template.md +42 -0
  29. package/core/templates/design-brief.md +37 -0
  30. package/core/templates/patch.template.md +86 -0
  31. package/core/templates/pr-body.md +25 -0
  32. package/core/templates/review-feedback.md +46 -0
  33. package/core/templates/spec.template.md +88 -0
  34. package/core/templates/steps/init-pipeline/01-detect-stack.md +44 -0
  35. package/core/templates/steps/init-pipeline/02-interview-gaps.md +55 -0
  36. package/core/templates/steps/init-pipeline/03-draft-profile.md +9 -0
  37. package/core/templates/steps/init-pipeline/04-write-render.md +91 -0
  38. package/core/templates/steps/init-pipeline/05-report.md +11 -0
  39. package/core/templates/steps/review-pr/01-pr-mode.md +54 -0
  40. package/core/workflows/audit.js +306 -0
  41. package/core/workflows/loop.js +687 -0
  42. package/core/workflows/refactor.js +291 -0
  43. package/core/workflows/review.js +491 -0
  44. package/install.ps1 +72 -0
  45. package/install.sh +69 -0
  46. package/lib/doctor.js +472 -0
  47. package/lib/install.js +377 -0
  48. package/lib/project.js +322 -0
  49. package/lib/render.js +121 -0
  50. package/lib/versions.js +145 -0
  51. package/lib/yaml.js +174 -0
  52. package/package.json +36 -17
  53. package/profile/PIPELINE.template.md +250 -0
  54. package/profile/SCHEMA.md +749 -0
  55. package/profile/cohorte.config.template.yaml +43 -0
  56. package/scripts/feature-diff.sh +118 -0
  57. package/scripts/kanban-move.sh +307 -0
  58. package/scripts/metrics/collect.mjs +542 -0
  59. package/scripts/metrics/prices.json +42 -0
  60. package/scripts/new-feature.sh.template +122 -0
  61. package/scripts/preflight.sh +114 -0
  62. package/scripts/remove-feature.sh.template +56 -0
  63. package/assets/manifest.json +0 -203
  64. package/assets/migrations/config/README.md +0 -12
  65. package/assets/migrations/state/0001_init.sql +0 -154
  66. package/assets/prompts/README.md +0 -11
  67. package/assets/prompts/agents/brainstormer.md +0 -3
  68. package/assets/prompts/agents/fixer.md +0 -7
  69. package/assets/prompts/agents/implementer.md +0 -12
  70. package/assets/prompts/agents/reviewer.md +0 -8
  71. package/assets/prompts/agents/security-reviewer.md +0 -7
  72. package/assets/prompts/agents/spec-author.md +0 -3
  73. package/assets/prompts/phases/build.md +0 -5
  74. package/assets/prompts/phases/review.md +0 -5
  75. package/assets/prompts/phases/test.md +0 -5
  76. package/assets/prompts/system.md +0 -11
  77. package/assets/schemas/agent-output.schema.json +0 -225
  78. package/assets/schemas/auth-status.schema.json +0 -87
  79. package/assets/schemas/command-result.schema.json +0 -192
  80. package/assets/schemas/commands.schema.json +0 -959
  81. package/assets/schemas/config.schema.json +0 -2281
  82. package/assets/schemas/doctor-report.schema.json +0 -104
  83. package/assets/schemas/events.schema.json +0 -8514
  84. package/assets/schemas/fake-script.schema.json +0 -549
  85. package/assets/schemas/inspect.schema.json +0 -3133
  86. package/assets/schemas/manifest.schema.json +0 -79
  87. package/assets/schemas/ownership.schema.json +0 -52
  88. package/assets/schemas/policy-verdict.schema.json +0 -282
  89. package/assets/schemas/project-model.schema.json +0 -783
  90. package/assets/schemas/project-status.schema.json +0 -217
  91. package/assets/schemas/reconcile-plan.schema.json +0 -154
  92. package/assets/schemas/run-diff.schema.json +0 -177
  93. package/assets/schemas/run-snapshot-manifest.schema.json +0 -2104
  94. package/assets/schemas/run-state.schema.json +0 -1755
  95. package/assets/schemas/runtime-capabilities.schema.json +0 -1545
  96. package/assets/schemas/sandbox-capabilities.schema.json +0 -116
  97. package/assets/schemas/skill.schema.json +0 -87
  98. package/assets/schemas/spec.schema.json +0 -202
  99. package/assets/schemas/tool-catalogue.schema.json +0 -655
  100. package/assets/schemas/trust-record.schema.json +0 -38
  101. package/assets/skills/README.md +0 -9
  102. package/assets/skills/inspect-surface.md +0 -4
  103. package/dist/agent-host.mjs +0 -2187
  104. package/dist/agent-host.mjs.map +0 -1
  105. package/dist/bundle-manifest.json +0 -128
  106. package/dist/chunks/__host-DgGPyco9.mjs +0 -18
  107. package/dist/chunks/__host-DgGPyco9.mjs.map +0 -1
  108. package/dist/chunks/align-ds-r_X_1aQ_.mjs +0 -93
  109. package/dist/chunks/align-ds-r_X_1aQ_.mjs.map +0 -1
  110. package/dist/chunks/approve-Cv135UqI.mjs +0 -19
  111. package/dist/chunks/approve-Cv135UqI.mjs.map +0 -1
  112. package/dist/chunks/audit-B4ZWQ_DI.mjs +0 -179
  113. package/dist/chunks/audit-B4ZWQ_DI.mjs.map +0 -1
  114. package/dist/chunks/auth-BT5oVp76.mjs +0 -132
  115. package/dist/chunks/auth-BT5oVp76.mjs.map +0 -1
  116. package/dist/chunks/auth-Dnlksuo5.mjs +0 -141
  117. package/dist/chunks/auth-Dnlksuo5.mjs.map +0 -1
  118. package/dist/chunks/brainstorm-DasVwI1D.mjs +0 -123
  119. package/dist/chunks/brainstorm-DasVwI1D.mjs.map +0 -1
  120. package/dist/chunks/build-crOld8gE.mjs +0 -19
  121. package/dist/chunks/build-crOld8gE.mjs.map +0 -1
  122. package/dist/chunks/cancel-KV_cpsqS.mjs +0 -15
  123. package/dist/chunks/cancel-KV_cpsqS.mjs.map +0 -1
  124. package/dist/chunks/canonical-C8UxeEmB.mjs +0 -57
  125. package/dist/chunks/canonical-C8UxeEmB.mjs.map +0 -1
  126. package/dist/chunks/catalogue-IaCJdfB8.mjs +0 -1549
  127. package/dist/chunks/catalogue-IaCJdfB8.mjs.map +0 -1
  128. package/dist/chunks/compose-DRKjQcn0.mjs +0 -7333
  129. package/dist/chunks/compose-DRKjQcn0.mjs.map +0 -1
  130. package/dist/chunks/config-Cqu5XQoP.mjs +0 -96
  131. package/dist/chunks/config-Cqu5XQoP.mjs.map +0 -1
  132. package/dist/chunks/contract-DjssDPpS.mjs +0 -335
  133. package/dist/chunks/contract-DjssDPpS.mjs.map +0 -1
  134. package/dist/chunks/contract-bQ9FJl4N.mjs +0 -123
  135. package/dist/chunks/contract-bQ9FJl4N.mjs.map +0 -1
  136. package/dist/chunks/deny-ClTxSvHJ.mjs +0 -15
  137. package/dist/chunks/deny-ClTxSvHJ.mjs.map +0 -1
  138. package/dist/chunks/diff-Qw0II0sj.mjs +0 -101
  139. package/dist/chunks/diff-Qw0II0sj.mjs.map +0 -1
  140. package/dist/chunks/discover-BZPolSZG.mjs +0 -21
  141. package/dist/chunks/discover-BZPolSZG.mjs.map +0 -1
  142. package/dist/chunks/doctor-DcDFPvQM.mjs +0 -222
  143. package/dist/chunks/doctor-DcDFPvQM.mjs.map +0 -1
  144. package/dist/chunks/fix-B_oGzGVn.mjs +0 -82
  145. package/dist/chunks/fix-B_oGzGVn.mjs.map +0 -1
  146. package/dist/chunks/fleet-yWHQY2ya.mjs +0 -297
  147. package/dist/chunks/fleet-yWHQY2ya.mjs.map +0 -1
  148. package/dist/chunks/gc-BBXlBF5w.mjs +0 -161
  149. package/dist/chunks/gc-BBXlBF5w.mjs.map +0 -1
  150. package/dist/chunks/init--FxxkrcT.mjs +0 -63
  151. package/dist/chunks/init--FxxkrcT.mjs.map +0 -1
  152. package/dist/chunks/inspect-Buby4cQD.mjs +0 -22
  153. package/dist/chunks/inspect-Buby4cQD.mjs.map +0 -1
  154. package/dist/chunks/intake-Dd1KVXnO.mjs +0 -12
  155. package/dist/chunks/intake-Dd1KVXnO.mjs.map +0 -1
  156. package/dist/chunks/logs-Giq5sUau.mjs +0 -25
  157. package/dist/chunks/logs-Giq5sUau.mjs.map +0 -1
  158. package/dist/chunks/loop-BWsUpyus.mjs +0 -212
  159. package/dist/chunks/loop-BWsUpyus.mjs.map +0 -1
  160. package/dist/chunks/migrate-DuYCAbE3.mjs +0 -33
  161. package/dist/chunks/migrate-DuYCAbE3.mjs.map +0 -1
  162. package/dist/chunks/models-Btp6X2YZ.mjs +0 -24
  163. package/dist/chunks/models-Btp6X2YZ.mjs.map +0 -1
  164. package/dist/chunks/obsidian-BHLkXx_H.mjs +0 -235
  165. package/dist/chunks/obsidian-BHLkXx_H.mjs.map +0 -1
  166. package/dist/chunks/patch-sAgVqjpx.mjs +0 -50
  167. package/dist/chunks/patch-sAgVqjpx.mjs.map +0 -1
  168. package/dist/chunks/pause-BASBfKLO.mjs +0 -16
  169. package/dist/chunks/pause-BASBfKLO.mjs.map +0 -1
  170. package/dist/chunks/policy-Du7WVBFX.mjs +0 -139
  171. package/dist/chunks/policy-Du7WVBFX.mjs.map +0 -1
  172. package/dist/chunks/providers-Dx78imKj.mjs +0 -19
  173. package/dist/chunks/providers-Dx78imKj.mjs.map +0 -1
  174. package/dist/chunks/reconcile-BHn66X3C.mjs +0 -50
  175. package/dist/chunks/reconcile-BHn66X3C.mjs.map +0 -1
  176. package/dist/chunks/refactor-CoNoqLZr.mjs +0 -153
  177. package/dist/chunks/refactor-CoNoqLZr.mjs.map +0 -1
  178. package/dist/chunks/render-DyZr5Lgi.mjs +0 -53
  179. package/dist/chunks/render-DyZr5Lgi.mjs.map +0 -1
  180. package/dist/chunks/resume-GJQRb2Eb.mjs +0 -15
  181. package/dist/chunks/resume-GJQRb2Eb.mjs.map +0 -1
  182. package/dist/chunks/retro-Dr-2RTNN.mjs +0 -78
  183. package/dist/chunks/retro-Dr-2RTNN.mjs.map +0 -1
  184. package/dist/chunks/retry-CLrUem1H.mjs +0 -15
  185. package/dist/chunks/retry-CLrUem1H.mjs.map +0 -1
  186. package/dist/chunks/review-ZsBqp3vZ.mjs +0 -35
  187. package/dist/chunks/review-ZsBqp3vZ.mjs.map +0 -1
  188. package/dist/chunks/run-NGAxdsIX.mjs +0 -105
  189. package/dist/chunks/run-NGAxdsIX.mjs.map +0 -1
  190. package/dist/chunks/run-tool-C3rAv4XF.mjs +0 -26
  191. package/dist/chunks/run-tool-C3rAv4XF.mjs.map +0 -1
  192. package/dist/chunks/scan-C5uDr7Yq.mjs +0 -167
  193. package/dist/chunks/scan-C5uDr7Yq.mjs.map +0 -1
  194. package/dist/chunks/schema-Bq9qtgsd.mjs +0 -583
  195. package/dist/chunks/schema-Bq9qtgsd.mjs.map +0 -1
  196. package/dist/chunks/send-BdnJ85Nz.mjs +0 -19
  197. package/dist/chunks/send-BdnJ85Nz.mjs.map +0 -1
  198. package/dist/chunks/ship-BizfUe62.mjs +0 -140
  199. package/dist/chunks/ship-BizfUe62.mjs.map +0 -1
  200. package/dist/chunks/shutdown-BM92Iyv2.mjs +0 -15
  201. package/dist/chunks/shutdown-BM92Iyv2.mjs.map +0 -1
  202. package/dist/chunks/skip-DZG5kpcH.mjs +0 -18
  203. package/dist/chunks/skip-DZG5kpcH.mjs.map +0 -1
  204. package/dist/chunks/spec-C2h3U64g.mjs +0 -65
  205. package/dist/chunks/spec-C2h3U64g.mjs.map +0 -1
  206. package/dist/chunks/spec-path-tptqR7W8.mjs +0 -10
  207. package/dist/chunks/spec-path-tptqR7W8.mjs.map +0 -1
  208. package/dist/chunks/src-Bfr1yzsn.mjs +0 -1689
  209. package/dist/chunks/src-Bfr1yzsn.mjs.map +0 -1
  210. package/dist/chunks/src-CPW2_Ons.mjs +0 -5487
  211. package/dist/chunks/src-CPW2_Ons.mjs.map +0 -1
  212. package/dist/chunks/src-Cu3TxNob.mjs +0 -783
  213. package/dist/chunks/src-Cu3TxNob.mjs.map +0 -1
  214. package/dist/chunks/src-DNsLSxgm.mjs +0 -928
  215. package/dist/chunks/src-DNsLSxgm.mjs.map +0 -1
  216. package/dist/chunks/src-DbS9gkJy.mjs +0 -117
  217. package/dist/chunks/src-DbS9gkJy.mjs.map +0 -1
  218. package/dist/chunks/src-yi5whv3n.mjs +0 -2118
  219. package/dist/chunks/src-yi5whv3n.mjs.map +0 -1
  220. package/dist/chunks/status-SMjiOMYy.mjs +0 -29
  221. package/dist/chunks/status-SMjiOMYy.mjs.map +0 -1
  222. package/dist/chunks/tail-BuhT-2PH.mjs +0 -25
  223. package/dist/chunks/tail-BuhT-2PH.mjs.map +0 -1
  224. package/dist/chunks/update-BXIppsbi.mjs +0 -16
  225. package/dist/chunks/update-BXIppsbi.mjs.map +0 -1
  226. package/dist/chunks/update-pipeline-Du-Gu1Pl.mjs +0 -56
  227. package/dist/chunks/update-pipeline-Du-Gu1Pl.mjs.map +0 -1
  228. package/dist/cli.mjs +0 -186
  229. package/dist/cli.mjs.map +0 -1
package/lib/install.js ADDED
@@ -0,0 +1,377 @@
1
+ 'use strict';
2
+ // cohorte — the machine-wide install: commands, fixed agents, workflows and the generic core.
3
+ //
4
+ // <globalDir> = ~/.claude (or $CLAUDE_CONFIG_DIR)
5
+ // commands/cohorte-*.md the 16 slash commands
6
+ // agents/cohorte-*.md cohorte-review, cohorte-release, cohorte-profile-reader
7
+ // workflows/cohorte-*.js review / audit / refactor / loop
8
+ // cohorte/ the generic core: pipeline/, templates/, hooks/gate.py, lib/project.js
9
+ // cohorte/manifest.json every file above, with the hash it was written with
10
+ // cohorte.config.yaml YOUR config (seeded once, never in the manifest)
11
+ //
12
+ // Ownership rules, each one a bug that shipped in 2.x:
13
+ // - nothing outside the manifest is ever deleted (2.x rm'd any ~/.claude/commands/review.md);
14
+ // - a file we would overwrite that the user changed is backed up first;
15
+ // - no hook is registered machine-wide — the gate lives in each project (lib/project.js);
16
+ // - a settings.json that does not parse aborts the run instead of being reset.
17
+
18
+ const fs = require('fs');
19
+ const os = require('os');
20
+ const path = require('path');
21
+ const crypto = require('crypto');
22
+ const R = require('./render.js');
23
+ const { readJsonObject, ProjectError } = require('./project.js');
24
+
25
+ const pkgRoot = path.join(__dirname, '..');
26
+ const VERSION = JSON.parse(fs.readFileSync(path.join(pkgRoot, 'package.json'), 'utf8')).version;
27
+ const MANIFEST = path.join('cohorte', 'manifest.json');
28
+
29
+ const sha = (s) => crypto.createHash('sha256').update(s).digest('hex');
30
+ const readMaybe = (p) => { try { return fs.readFileSync(p); } catch { return null; } };
31
+ const stamp = () => new Date().toISOString().replace(/[:.]/g, '-');
32
+ const toPosix = (p) => p.split(path.sep).join('/');
33
+
34
+ function walk(dir) {
35
+ let out = [];
36
+ let entries = [];
37
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return out; }
38
+ for (const e of entries) {
39
+ if (e.name === '__pycache__' || e.name.endsWith('.pyc')) continue;
40
+ const p = path.join(dir, e.name);
41
+ out = e.isDirectory() ? out.concat(walk(p)) : out.concat([p]);
42
+ }
43
+ return out;
44
+ }
45
+
46
+ function pruneEmpty(dir, stopAt) {
47
+ let entries;
48
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
49
+ for (const e of entries) if (e.isDirectory()) pruneEmpty(path.join(dir, e.name), stopAt);
50
+ if (dir === stopAt) return;
51
+ try { if (!fs.readdirSync(dir).length) fs.rmdirSync(dir); } catch { /* not empty */ }
52
+ }
53
+
54
+ // --- what this version installs ------------------------------------------------
55
+ // rel path (under globalDir) → { content: Buffer|string, mode? }
56
+ function desiredFiles(globalDir) {
57
+ const L = R.layout(globalDir);
58
+ const files = new Map();
59
+ const put = (rel, content, mode) => files.set(toPosix(rel), { content, mode });
60
+ const core = path.join(pkgRoot, 'core');
61
+
62
+ for (const f of fs.readdirSync(path.join(core, 'commands')).sort()) {
63
+ if (!f.endsWith('.md')) continue;
64
+ put(path.join('commands', f), R.renderCommand(fs.readFileSync(path.join(core, 'commands', f), 'utf8'), L));
65
+ }
66
+ for (const f of fs.readdirSync(path.join(core, 'agents')).sort()) {
67
+ if (!f.endsWith('.md')) continue;
68
+ const src = fs.readFileSync(path.join(core, 'agents', f), 'utf8');
69
+ // The implementer is rendered per SURFACE later, by /cohorte-init-pipeline, into the
70
+ // project's .claude/agents. Ship its rendered template, never an agent named after it.
71
+ if (f.endsWith('.template.md')) put(path.join('cohorte', 'pipeline', f), R.renderAgent(src, L));
72
+ else put(path.join('agents', f), R.renderAgent(src, L));
73
+ }
74
+ for (const f of fs.readdirSync(path.join(core, 'workflows')).sort()) {
75
+ if (f.endsWith('.js')) put(path.join('workflows', `cohorte-${f}`), fs.readFileSync(path.join(core, 'workflows', f)));
76
+ }
77
+ put(path.join('cohorte', 'hooks', 'gate.py'), fs.readFileSync(path.join(core, 'hooks', 'gate.py')), 0o755);
78
+ for (const f of walk(path.join(core, 'templates'))) {
79
+ put(path.join('cohorte', 'templates', path.relative(path.join(core, 'templates'), f)), fs.readFileSync(f));
80
+ }
81
+ for (const f of ['PIPELINE.template.md', 'SCHEMA.md', 'cohorte.config.template.yaml']) {
82
+ put(path.join('cohorte', 'pipeline', f), fs.readFileSync(path.join(pkgRoot, 'profile', f)));
83
+ }
84
+ // A `<x>.sh` with an `<x>.sh.template` sibling is rendered per project by
85
+ // /cohorte-init-pipeline, so only the template ships; every other `.sh` is executable.
86
+ const scripts = fs.readdirSync(path.join(pkgRoot, 'scripts'));
87
+ for (const f of scripts.sort()) {
88
+ const isTemplate = f.endsWith('.sh.template');
89
+ const isShipped = f.endsWith('.sh') && !scripts.includes(`${f}.template`);
90
+ if (!isTemplate && !isShipped) continue;
91
+ put(path.join('cohorte', 'pipeline', 'scripts', f), fs.readFileSync(path.join(pkgRoot, 'scripts', f)),
92
+ isShipped ? 0o755 : undefined);
93
+ }
94
+ put(path.join('cohorte', 'pipeline', 'CHANGELOG.md'), fs.readFileSync(path.join(pkgRoot, 'CHANGELOG.md')));
95
+ put(path.join('cohorte', 'pipeline', 'VERSION'), VERSION + '\n');
96
+ put(path.join('cohorte', 'lib', 'project.js'), fs.readFileSync(path.join(pkgRoot, 'lib', 'project.js')));
97
+ return files;
98
+ }
99
+
100
+ function readManifest(globalDir) {
101
+ try {
102
+ const m = JSON.parse(fs.readFileSync(path.join(globalDir, MANIFEST), 'utf8'));
103
+ return m && typeof m.files === 'object' ? m : { files: {} };
104
+ } catch { return { files: {} }; }
105
+ }
106
+
107
+ // --- 2.x global installs ------------------------------------------------------------
108
+ // 2.x wrote its core straight into ~/.claude (pipeline/, templates/, workflows/review.js,
109
+ // hooks/gate.py, agents/review.md …) and registered `python3 "~/.claude/hooks/gate.py"` in
110
+ // the GLOBAL settings.json. That registration must go BEFORE its file moves: a registered
111
+ // hook whose script is missing makes python exit 2, which Claude Code reads as "block" —
112
+ // every Bash call in every session on the machine would be refused.
113
+ function legacyGateCommandMatches(cmd, globalDir) {
114
+ if (typeof cmd !== 'string') return false;
115
+ const norm = (s) => s.replace(/\\/g, '/');
116
+ const target = norm(path.join(globalDir, 'hooks', 'gate.py'));
117
+ const home = norm(os.homedir());
118
+ const c = norm(cmd).replace(/\$HOME|\$\{HOME\}|~(?=\/)/g, home);
119
+ return c.includes(target);
120
+ }
121
+
122
+ function removeLegacyGlobalHook(globalDir, report) {
123
+ const settingsPath = path.join(globalDir, 'settings.json');
124
+ if (!fs.existsSync(settingsPath)) return;
125
+ const data = readJsonObject(settingsPath); // throws on invalid JSON — nothing written yet
126
+ const pre = data.hooks && Array.isArray(data.hooks.PreToolUse) ? data.hooks.PreToolUse : null;
127
+ if (!pre) return;
128
+ let removed = 0;
129
+ const kept = [];
130
+ for (const g of pre) {
131
+ if (!g || !Array.isArray(g.hooks)) { kept.push(g); continue; }
132
+ const hooks = g.hooks.filter((h) => !(h && legacyGateCommandMatches(h.command, globalDir)));
133
+ removed += g.hooks.length - hooks.length;
134
+ if (hooks.length) kept.push(hooks.length === g.hooks.length ? g : { ...g, hooks });
135
+ }
136
+ if (!removed) return;
137
+ if (kept.length) data.hooks.PreToolUse = kept; else delete data.hooks.PreToolUse;
138
+ if (data.hooks && !Object.keys(data.hooks).length) delete data.hooks;
139
+ fs.writeFileSync(settingsPath, JSON.stringify(data, null, 2) + '\n');
140
+ report.push(`removed the 2.x machine-wide gate hook from ${R.displayPath(settingsPath)} (the gate now lives in each project)`);
141
+ // That hook was the ONLY gate of every 2.x global-mode project: until `cohorte sync` runs in
142
+ // each one, they are ungated. Say so, and name the ones Claude Code knows about.
143
+ const projects = knownCohorteProjects(globalDir);
144
+ report.push('! 2.x projects have NO gate until you wire them: run /cohorte-update-pipeline (or `cohorte sync <path>`) in each'
145
+ + (projects.length ? `:\n${projects.map((p) => ` cohorte sync "${p}"`).join('\n')}` : '.'));
146
+ }
147
+
148
+ // Projects Claude Code has opened (~/.claude.json `projects`) that carry a cohorte pointer or
149
+ // gate config but no 3.x project gate yet.
150
+ function knownCohorteProjects(globalDir) {
151
+ const out = [];
152
+ for (const f of [path.join(os.homedir(), '.claude.json'), path.join(globalDir, '.claude.json')]) {
153
+ let data;
154
+ try { data = JSON.parse(fs.readFileSync(f, 'utf8')); } catch { continue; }
155
+ for (const p of Object.keys((data && data.projects) || {})) {
156
+ if (out.includes(p)) continue;
157
+ const c = path.join(p, '.claude');
158
+ if ((fs.existsSync(path.join(c, 'pipeline.json')) || fs.existsSync(path.join(c, 'gate-config.json')))
159
+ && !fs.existsSync(path.join(c, 'hooks', 'cohorte-gate.py'))) out.push(p);
160
+ }
161
+ }
162
+ return out.sort();
163
+ }
164
+
165
+ const LEGACY_TEMPLATES = [
166
+ 'agent-handoff.md', 'brainstorm-return.md', 'decisions.template.md', 'design-brief.md',
167
+ 'patch.template.md', 'pr-body.md', 'review-feedback.md', 'spec.template.md',
168
+ 'research-brief.md', 'questionnaire-blueprint.md', 'questionnaire-declaration.md',
169
+ 'questionnaire-verdict.md', 'questionnaire-domain-brief.md',
170
+ ];
171
+ const LEGACY_BARE_COMMANDS = ['align-ds', 'audit', 'brainstorm', 'build', 'doctor', 'drive', 'fix',
172
+ 'init-pipeline', 'refactor', 'review', 'ship', 'spec', 'update-pipeline', 'cycle', 'loop', 'smoke',
173
+ 'research', 'questionnaire'];
174
+ const MARKERS = ['Generated by the cohorte adapter', 'Generated by the cohorte installer'];
175
+
176
+ const text = (p) => { try { return fs.readFileSync(p, 'utf8'); } catch { return null; } };
177
+ const looksCohorte = (p) => { const t = text(p); return t != null && (MARKERS.some((m) => t.includes(m)) || /PIPELINE\.md/.test(t)); };
178
+
179
+ // What a 2.x (or 1.x) global install left in ~/.claude that is PROVABLY ours: a
180
+ // `pipeline/VERSION`-stamped core, files carrying our marker, or 1.x command names whose
181
+ // body is pipeline doctrine. A user's own `review.md` that never mentions PIPELINE.md is
182
+ // not touched. Surface agents a 2.x global init rendered here are NOT moved — live
183
+ // projects still dispatch them; they are reported instead.
184
+ function legacyGlobalCandidates(globalDir) {
185
+ const out = [];
186
+ const add = (rel) => { if (fs.existsSync(path.join(globalDir, rel))) out.push(rel); };
187
+ const hasCore = fs.existsSync(path.join(globalDir, 'pipeline', 'VERSION'));
188
+ if (hasCore) for (const f of walk(path.join(globalDir, 'pipeline'))) out.push(path.relative(globalDir, f));
189
+ const gate = path.join(globalDir, 'hooks', 'gate.py');
190
+ if (fs.existsSync(gate) && (hasCore || /gate-config\.json/.test(text(gate) || ''))) add(path.join('hooks', 'gate.py'));
191
+ for (const n of ['tdd_gate.py']) if (hasCore) add(path.join('hooks', n));
192
+ if (hasCore) {
193
+ for (const t of LEGACY_TEMPLATES) add(path.join('templates', t));
194
+ for (const d of ['init-pipeline', 'research', 'questionnaire']) {
195
+ for (const f of walk(path.join(globalDir, 'templates', 'steps', d))) out.push(path.relative(globalDir, f));
196
+ }
197
+ }
198
+ for (const n of ['review', 'audit', 'refactor', 'loop', 'cycle']) {
199
+ const rel = path.join('workflows', `${n}.js`);
200
+ const t = text(path.join(globalDir, rel));
201
+ if (t && (/name:\s*'cohorte-/.test(t) || (hasCore && n === 'cycle'))) out.push(rel);
202
+ }
203
+ for (const n of ['review', 'release', 'profile-reader', 'smoke', 'questionnaire-researcher',
204
+ 'research-agent', 'questionnaire-architect', 'questionnaire-writer', 'questionnaire-validator']) {
205
+ const rel = path.join('agents', `${n}.md`);
206
+ if (looksCohorte(path.join(globalDir, rel))) out.push(rel);
207
+ }
208
+ for (const n of LEGACY_BARE_COMMANDS) {
209
+ const rel = path.join('commands', `${n}.md`);
210
+ if (looksCohorte(path.join(globalDir, rel))) out.push(rel);
211
+ }
212
+ // Retired prefixed commands (e.g. cohorte-loop.md, 2.2.0) carry the marker.
213
+ for (const f of walk(path.join(globalDir, 'commands'))) {
214
+ const rel = path.relative(globalDir, f);
215
+ if (/^cohorte-[\w-]+\.md$/.test(path.basename(f)) && path.dirname(rel) === 'commands') {
216
+ if (!fs.existsSync(path.join(pkgRoot, 'core', 'commands', path.basename(f))) && looksCohorte(f)) out.push(rel);
217
+ }
218
+ }
219
+ return [...new Set(out.map(toPosix))];
220
+ }
221
+
222
+ function legacySurfaceAgents(globalDir) {
223
+ const out = [];
224
+ for (const f of walk(path.join(globalDir, 'agents'))) {
225
+ const t = text(f) || '';
226
+ if (/Dispatched by \/cohorte-build/.test(t) && MARKERS.some((m) => t.includes(m))) out.push(path.basename(f));
227
+ }
228
+ return out;
229
+ }
230
+
231
+ function migrateLegacy(globalDir, report) {
232
+ const candidates = legacyGlobalCandidates(globalDir);
233
+ const settingsPath = path.join(globalDir, 'settings.json');
234
+ const hookPresent = fs.existsSync(settingsPath) && (text(settingsPath) || '').includes('gate.py');
235
+ if (!candidates.length && !hookPresent) return;
236
+ removeLegacyGlobalHook(globalDir, report);
237
+ if (!candidates.length) return;
238
+ const backup = path.join(globalDir, 'cohorte', 'legacy-backup', stamp());
239
+ for (const rel of candidates) {
240
+ const from = path.join(globalDir, rel);
241
+ const to = path.join(backup, rel);
242
+ fs.mkdirSync(path.dirname(to), { recursive: true });
243
+ fs.renameSync(from, to);
244
+ }
245
+ for (const d of ['pipeline', 'templates', 'workflows', 'hooks']) pruneEmpty(path.join(globalDir, d));
246
+ report.push(`moved ${candidates.length} file(s) of the 2.x core out of ${R.displayPath(globalDir)} → ${R.displayPath(backup)}`);
247
+ const surface = legacySurfaceAgents(globalDir);
248
+ if (surface.length) {
249
+ report.push(`left in place: 2.x surface agents in ${R.displayPath(path.join(globalDir, 'agents'))} (${surface.join(', ')}). ` +
250
+ 'They belong in each project now: run /cohorte-update-pipeline in every project that uses them, then delete these.');
251
+ }
252
+ }
253
+
254
+ // --- config ---------------------------------------------------------------------------
255
+ async function seedConfig(globalDir, { ask } = {}, report) {
256
+ const cfg = path.join(globalDir, 'cohorte.config.yaml');
257
+ if (fs.existsSync(cfg)) return;
258
+ const legacy = path.join(globalDir, 'thebidouille.config.yaml');
259
+ if (fs.existsSync(legacy)) { report.push(`kept legacy ${R.displayPath(legacy)} (still read as a fallback)`); return; }
260
+ let t = fs.readFileSync(path.join(pkgRoot, 'profile', 'cohorte.config.template.yaml'), 'utf8');
261
+ if (ask) {
262
+ const vault = await ask(' · absolute path to your shared Obsidian vault for the kanban mirror (Enter to skip): ');
263
+ if (vault) {
264
+ t = t.split('\n').map((line) => {
265
+ const i = line.indexOf('# cfg:vault_path');
266
+ if (i === -1) return line;
267
+ const m = line.slice(0, i).match(/^(\s*[\w.]+:\s*)/);
268
+ return m ? `${m[1]}"${vault}" ${line.slice(i)}` : line;
269
+ }).join('\n');
270
+ }
271
+ }
272
+ fs.mkdirSync(globalDir, { recursive: true });
273
+ fs.writeFileSync(cfg, t);
274
+ report.push(`seeded ${R.displayPath(cfg)}`);
275
+ }
276
+
277
+ // --- install / update ----------------------------------------------------------------
278
+ async function install(globalDir, opts = {}) {
279
+ const report = [];
280
+ const warnings = [];
281
+ // Refuse before touching anything if the settings file we may have to edit is broken.
282
+ const settingsPath = path.join(globalDir, 'settings.json');
283
+ if (fs.existsSync(settingsPath)) readJsonObject(settingsPath);
284
+
285
+ migrateLegacy(globalDir, report);
286
+
287
+ const old = readManifest(globalDir);
288
+ const want = desiredFiles(globalDir);
289
+ const backupDir = path.join(globalDir, 'cohorte', 'backup', stamp());
290
+ const manifest = { version: VERSION, files: {} };
291
+ let written = 0;
292
+
293
+ for (const [rel, { content, mode }] of want) {
294
+ const dest = path.join(globalDir, rel);
295
+ const buf = Buffer.isBuffer(content) ? content : Buffer.from(content);
296
+ const cur = readMaybe(dest);
297
+ const newHash = sha(buf);
298
+ if (cur && sha(cur) !== newHash) {
299
+ const known = old.files[rel];
300
+ // A 2.x install has no manifest, but every file it rendered carries our marker.
301
+ const ours2x = !known && MARKERS.some((m) => cur.toString('utf8').includes(m));
302
+ // Modified since we wrote it, or a file we never wrote that sits on our name.
303
+ if (!ours2x && (!known || known !== sha(cur))) {
304
+ const to = path.join(backupDir, rel);
305
+ fs.mkdirSync(path.dirname(to), { recursive: true });
306
+ fs.copyFileSync(dest, to);
307
+ warnings.push(`${rel} differed from what cohorte installed — your copy is saved in ${R.displayPath(to)}`);
308
+ }
309
+ }
310
+ if (!cur || sha(cur) !== newHash) {
311
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
312
+ fs.writeFileSync(dest, buf);
313
+ written++;
314
+ }
315
+ if (mode && process.platform !== 'win32') { try { fs.chmodSync(dest, mode); } catch { /* optional */ } }
316
+ manifest.files[rel] = newHash;
317
+ }
318
+
319
+ // Files the previous version installed and this one does not: delete them when they are
320
+ // exactly as we wrote them, keep (and say so) when the user changed them.
321
+ let removed = 0;
322
+ for (const [rel, hash] of Object.entries(old.files)) {
323
+ if (want.has(rel)) continue;
324
+ const dest = path.join(globalDir, rel);
325
+ const cur = readMaybe(dest);
326
+ if (!cur) continue;
327
+ if (sha(cur) === hash) { fs.rmSync(dest); removed++; }
328
+ else warnings.push(`kept ${rel}: no longer shipped, but you modified it`);
329
+ }
330
+ for (const d of ['cohorte', 'workflows']) pruneEmpty(path.join(globalDir, d), path.join(globalDir, d));
331
+
332
+ fs.mkdirSync(path.join(globalDir, 'cohorte'), { recursive: true });
333
+ fs.writeFileSync(path.join(globalDir, MANIFEST), JSON.stringify(manifest, null, 2) + '\n');
334
+ await seedConfig(globalDir, opts, report);
335
+
336
+ report.unshift(`${old.version ? `updated ${old.version} → ${VERSION}` : `installed ${VERSION}`}: `
337
+ + `${want.size} files (${written} written${removed ? `, ${removed} retired file(s) removed` : ''})`);
338
+ return { report, warnings, version: VERSION, previous: old.version || null };
339
+ }
340
+
341
+ // --- uninstall ----------------------------------------------------------------------------
342
+ function uninstall(globalDir, { purge = false } = {}) {
343
+ const report = [];
344
+ const warnings = [];
345
+ const settingsPath = path.join(globalDir, 'settings.json');
346
+ if (fs.existsSync(settingsPath)) readJsonObject(settingsPath);
347
+ removeLegacyGlobalHook(globalDir, report);
348
+
349
+ const m = readManifest(globalDir);
350
+ let removed = 0;
351
+ for (const [rel, hash] of Object.entries(m.files)) {
352
+ const dest = path.join(globalDir, rel);
353
+ const cur = readMaybe(dest);
354
+ if (!cur) continue;
355
+ if (sha(cur) === hash) { fs.rmSync(dest); removed++; }
356
+ else warnings.push(`kept ${rel}: you modified it`);
357
+ }
358
+ fs.rmSync(path.join(globalDir, MANIFEST), { force: true });
359
+ pruneEmpty(path.join(globalDir, 'cohorte'));
360
+ pruneEmpty(path.join(globalDir, 'workflows'));
361
+ if (removed) report.push(`removed ${removed} installed file(s)`);
362
+ const leftovers = legacyGlobalCandidates(globalDir);
363
+ 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 ? '…' : ''}`);
364
+ if (fs.existsSync(path.join(globalDir, 'cohorte'))) {
365
+ warnings.push(`${R.displayPath(path.join(globalDir, 'cohorte'))} still holds backups or files you changed — review and delete it yourself`);
366
+ }
367
+ const cfg = path.join(globalDir, 'cohorte.config.yaml');
368
+ if (fs.existsSync(cfg)) {
369
+ if (purge) { fs.rmSync(cfg); report.push(`removed ${R.displayPath(cfg)}`); }
370
+ else report.push(`kept your config ${R.displayPath(cfg)} (--purge removes it)`);
371
+ }
372
+ const surface = legacySurfaceAgents(globalDir);
373
+ if (surface.length) warnings.push(`2.x surface agents remain in ${R.displayPath(path.join(globalDir, 'agents'))}: ${surface.join(', ')}`);
374
+ return { report, warnings };
375
+ }
376
+
377
+ module.exports = { install, uninstall, desiredFiles, legacyGlobalCandidates, VERSION, ProjectError };