cohorte 3.0.0-dev.8 → 3.1.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 (251) hide show
  1. package/CHANGELOG.md +1637 -0
  2. package/README.md +322 -62
  3. package/bin/cli.js +213 -0
  4. package/bin/report.js +141 -0
  5. package/core/agents/cohorte-profile-reader.md +40 -0
  6. package/core/agents/cohorte-release.md +61 -0
  7. package/core/agents/cohorte-review.md +200 -0
  8. package/core/agents/implementer.template.md +154 -0
  9. package/core/commands/cohorte-align-ds.md +33 -0
  10. package/core/commands/cohorte-audit.md +74 -0
  11. package/core/commands/cohorte-brainstorm.md +73 -0
  12. package/core/commands/cohorte-build.md +248 -0
  13. package/core/commands/cohorte-doctor.md +135 -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 +122 -0
  20. package/core/commands/cohorte-retro.md +85 -0
  21. package/core/commands/cohorte-revert.md +104 -0
  22. package/core/commands/cohorte-review.md +239 -0
  23. package/core/commands/cohorte-ship.md +167 -0
  24. package/core/commands/cohorte-spec.md +114 -0
  25. package/core/commands/cohorte-update-pipeline.md +119 -0
  26. package/core/commands/cohorte-verify.md +106 -0
  27. package/core/hooks/gate.py +3236 -0
  28. package/core/templates/agent-handoff.md +34 -0
  29. package/core/templates/brainstorm-return.md +42 -0
  30. package/core/templates/decisions.template.md +42 -0
  31. package/core/templates/design-brief.md +37 -0
  32. package/core/templates/patch.template.md +95 -0
  33. package/core/templates/pr-body.md +25 -0
  34. package/core/templates/review-feedback.md +46 -0
  35. package/core/templates/spec.template.md +109 -0
  36. package/core/templates/steps/init-pipeline/01-detect-stack.md +53 -0
  37. package/core/templates/steps/init-pipeline/02-interview-gaps.md +78 -0
  38. package/core/templates/steps/init-pipeline/03-draft-profile.md +10 -0
  39. package/core/templates/steps/init-pipeline/04-write-render.md +95 -0
  40. package/core/templates/steps/init-pipeline/05-report.md +11 -0
  41. package/core/templates/steps/review-pr/01-pr-mode.md +54 -0
  42. package/core/workflows/audit.js +311 -0
  43. package/core/workflows/loop.js +692 -0
  44. package/core/workflows/refactor.js +398 -0
  45. package/core/workflows/review.js +505 -0
  46. package/install.ps1 +72 -0
  47. package/install.sh +69 -0
  48. package/lib/doctor.js +506 -0
  49. package/lib/install.js +386 -0
  50. package/lib/project.js +359 -0
  51. package/lib/render.js +121 -0
  52. package/lib/versions.js +145 -0
  53. package/lib/yaml.js +183 -0
  54. package/package.json +36 -17
  55. package/profile/PIPELINE.template.md +288 -0
  56. package/profile/SCHEMA.md +30 -0
  57. package/profile/cohorte.config.template.yaml +43 -0
  58. package/profile/schema/dead-agents.md +29 -0
  59. package/profile/schema/decisions.md +23 -0
  60. package/profile/schema/deferred.md +22 -0
  61. package/profile/schema/feature-diff.md +20 -0
  62. package/profile/schema/kanban.md +95 -0
  63. package/profile/schema/metrics.md +23 -0
  64. package/profile/schema/output-discipline.md +21 -0
  65. package/profile/schema/preflight.md +81 -0
  66. package/profile/schema/profile-block.md +103 -0
  67. package/profile/schema/project-kinds.md +89 -0
  68. package/profile/schema/readiness.md +17 -0
  69. package/profile/schema/reconcile.md +64 -0
  70. package/profile/schema/release-notes.md +29 -0
  71. package/profile/schema/rendering.md +48 -0
  72. package/profile/schema/retrieval.md +58 -0
  73. package/profile/schema/spec-status.md +79 -0
  74. package/profile/schema/specialization.md +41 -0
  75. package/profile/schema/verify.md +115 -0
  76. package/profile/schema/workflows.md +78 -0
  77. package/scripts/feature-diff.sh +118 -0
  78. package/scripts/kanban-move.sh +349 -0
  79. package/scripts/metrics/collect.mjs +542 -0
  80. package/scripts/metrics/prices.json +42 -0
  81. package/scripts/new-feature.sh.template +122 -0
  82. package/scripts/preflight.sh +114 -0
  83. package/scripts/remove-feature.sh.template +56 -0
  84. package/scripts/verify-run.sh +509 -0
  85. package/assets/manifest.json +0 -203
  86. package/assets/migrations/config/README.md +0 -12
  87. package/assets/migrations/state/0001_init.sql +0 -154
  88. package/assets/prompts/README.md +0 -11
  89. package/assets/prompts/agents/brainstormer.md +0 -3
  90. package/assets/prompts/agents/fixer.md +0 -7
  91. package/assets/prompts/agents/implementer.md +0 -12
  92. package/assets/prompts/agents/reviewer.md +0 -8
  93. package/assets/prompts/agents/security-reviewer.md +0 -7
  94. package/assets/prompts/agents/spec-author.md +0 -3
  95. package/assets/prompts/phases/build.md +0 -5
  96. package/assets/prompts/phases/review.md +0 -5
  97. package/assets/prompts/phases/test.md +0 -5
  98. package/assets/prompts/system.md +0 -11
  99. package/assets/schemas/agent-output.schema.json +0 -225
  100. package/assets/schemas/auth-status.schema.json +0 -87
  101. package/assets/schemas/command-result.schema.json +0 -192
  102. package/assets/schemas/commands.schema.json +0 -959
  103. package/assets/schemas/config.schema.json +0 -2281
  104. package/assets/schemas/doctor-report.schema.json +0 -104
  105. package/assets/schemas/events.schema.json +0 -8514
  106. package/assets/schemas/fake-script.schema.json +0 -549
  107. package/assets/schemas/inspect.schema.json +0 -3133
  108. package/assets/schemas/manifest.schema.json +0 -79
  109. package/assets/schemas/ownership.schema.json +0 -52
  110. package/assets/schemas/policy-verdict.schema.json +0 -282
  111. package/assets/schemas/project-model.schema.json +0 -783
  112. package/assets/schemas/project-status.schema.json +0 -217
  113. package/assets/schemas/reconcile-plan.schema.json +0 -154
  114. package/assets/schemas/run-diff.schema.json +0 -177
  115. package/assets/schemas/run-snapshot-manifest.schema.json +0 -2104
  116. package/assets/schemas/run-state.schema.json +0 -1755
  117. package/assets/schemas/runtime-capabilities.schema.json +0 -1545
  118. package/assets/schemas/sandbox-capabilities.schema.json +0 -116
  119. package/assets/schemas/skill.schema.json +0 -87
  120. package/assets/schemas/spec.schema.json +0 -202
  121. package/assets/schemas/tool-catalogue.schema.json +0 -655
  122. package/assets/schemas/trust-record.schema.json +0 -38
  123. package/assets/skills/README.md +0 -9
  124. package/assets/skills/inspect-surface.md +0 -4
  125. package/dist/agent-host.mjs +0 -2187
  126. package/dist/agent-host.mjs.map +0 -1
  127. package/dist/bundle-manifest.json +0 -128
  128. package/dist/chunks/__host-DgGPyco9.mjs +0 -18
  129. package/dist/chunks/__host-DgGPyco9.mjs.map +0 -1
  130. package/dist/chunks/align-ds-r_X_1aQ_.mjs +0 -93
  131. package/dist/chunks/align-ds-r_X_1aQ_.mjs.map +0 -1
  132. package/dist/chunks/approve-Cv135UqI.mjs +0 -19
  133. package/dist/chunks/approve-Cv135UqI.mjs.map +0 -1
  134. package/dist/chunks/audit-B4ZWQ_DI.mjs +0 -179
  135. package/dist/chunks/audit-B4ZWQ_DI.mjs.map +0 -1
  136. package/dist/chunks/auth-BT5oVp76.mjs +0 -132
  137. package/dist/chunks/auth-BT5oVp76.mjs.map +0 -1
  138. package/dist/chunks/auth-Dnlksuo5.mjs +0 -141
  139. package/dist/chunks/auth-Dnlksuo5.mjs.map +0 -1
  140. package/dist/chunks/brainstorm-SJwOIEif.mjs +0 -123
  141. package/dist/chunks/brainstorm-SJwOIEif.mjs.map +0 -1
  142. package/dist/chunks/build-C_-mbZfD.mjs +0 -19
  143. package/dist/chunks/build-C_-mbZfD.mjs.map +0 -1
  144. package/dist/chunks/cancel-KV_cpsqS.mjs +0 -15
  145. package/dist/chunks/cancel-KV_cpsqS.mjs.map +0 -1
  146. package/dist/chunks/canonical-C8UxeEmB.mjs +0 -57
  147. package/dist/chunks/canonical-C8UxeEmB.mjs.map +0 -1
  148. package/dist/chunks/catalogue-IaCJdfB8.mjs +0 -1549
  149. package/dist/chunks/catalogue-IaCJdfB8.mjs.map +0 -1
  150. package/dist/chunks/compose-DRKjQcn0.mjs +0 -7333
  151. package/dist/chunks/compose-DRKjQcn0.mjs.map +0 -1
  152. package/dist/chunks/config-Cqu5XQoP.mjs +0 -96
  153. package/dist/chunks/config-Cqu5XQoP.mjs.map +0 -1
  154. package/dist/chunks/contract-DjssDPpS.mjs +0 -335
  155. package/dist/chunks/contract-DjssDPpS.mjs.map +0 -1
  156. package/dist/chunks/contract-bQ9FJl4N.mjs +0 -123
  157. package/dist/chunks/contract-bQ9FJl4N.mjs.map +0 -1
  158. package/dist/chunks/deny-ClTxSvHJ.mjs +0 -15
  159. package/dist/chunks/deny-ClTxSvHJ.mjs.map +0 -1
  160. package/dist/chunks/diff-Qw0II0sj.mjs +0 -101
  161. package/dist/chunks/diff-Qw0II0sj.mjs.map +0 -1
  162. package/dist/chunks/discover-BZPolSZG.mjs +0 -21
  163. package/dist/chunks/discover-BZPolSZG.mjs.map +0 -1
  164. package/dist/chunks/doctor-DcDFPvQM.mjs +0 -222
  165. package/dist/chunks/doctor-DcDFPvQM.mjs.map +0 -1
  166. package/dist/chunks/fix-C9roGiQz.mjs +0 -82
  167. package/dist/chunks/fix-C9roGiQz.mjs.map +0 -1
  168. package/dist/chunks/fleet-yWHQY2ya.mjs +0 -297
  169. package/dist/chunks/fleet-yWHQY2ya.mjs.map +0 -1
  170. package/dist/chunks/gc-BBXlBF5w.mjs +0 -161
  171. package/dist/chunks/gc-BBXlBF5w.mjs.map +0 -1
  172. package/dist/chunks/init--FxxkrcT.mjs +0 -63
  173. package/dist/chunks/init--FxxkrcT.mjs.map +0 -1
  174. package/dist/chunks/inspect-Buby4cQD.mjs +0 -22
  175. package/dist/chunks/inspect-Buby4cQD.mjs.map +0 -1
  176. package/dist/chunks/intake-C1pesxCJ.mjs +0 -12
  177. package/dist/chunks/intake-C1pesxCJ.mjs.map +0 -1
  178. package/dist/chunks/logs-Giq5sUau.mjs +0 -25
  179. package/dist/chunks/logs-Giq5sUau.mjs.map +0 -1
  180. package/dist/chunks/loop-BWsUpyus.mjs +0 -212
  181. package/dist/chunks/loop-BWsUpyus.mjs.map +0 -1
  182. package/dist/chunks/migrate-DuYCAbE3.mjs +0 -33
  183. package/dist/chunks/migrate-DuYCAbE3.mjs.map +0 -1
  184. package/dist/chunks/models-Btp6X2YZ.mjs +0 -24
  185. package/dist/chunks/models-Btp6X2YZ.mjs.map +0 -1
  186. package/dist/chunks/obsidian-BHLkXx_H.mjs +0 -235
  187. package/dist/chunks/obsidian-BHLkXx_H.mjs.map +0 -1
  188. package/dist/chunks/patch-sAgVqjpx.mjs +0 -50
  189. package/dist/chunks/patch-sAgVqjpx.mjs.map +0 -1
  190. package/dist/chunks/pause-BASBfKLO.mjs +0 -16
  191. package/dist/chunks/pause-BASBfKLO.mjs.map +0 -1
  192. package/dist/chunks/policy-Du7WVBFX.mjs +0 -139
  193. package/dist/chunks/policy-Du7WVBFX.mjs.map +0 -1
  194. package/dist/chunks/providers-Dx78imKj.mjs +0 -19
  195. package/dist/chunks/providers-Dx78imKj.mjs.map +0 -1
  196. package/dist/chunks/reconcile-BHn66X3C.mjs +0 -50
  197. package/dist/chunks/reconcile-BHn66X3C.mjs.map +0 -1
  198. package/dist/chunks/refactor-DV3RfGjk.mjs +0 -153
  199. package/dist/chunks/refactor-DV3RfGjk.mjs.map +0 -1
  200. package/dist/chunks/render-DyZr5Lgi.mjs +0 -53
  201. package/dist/chunks/render-DyZr5Lgi.mjs.map +0 -1
  202. package/dist/chunks/resume-GJQRb2Eb.mjs +0 -15
  203. package/dist/chunks/resume-GJQRb2Eb.mjs.map +0 -1
  204. package/dist/chunks/retro-Dr-2RTNN.mjs +0 -78
  205. package/dist/chunks/retro-Dr-2RTNN.mjs.map +0 -1
  206. package/dist/chunks/retry-CLrUem1H.mjs +0 -15
  207. package/dist/chunks/retry-CLrUem1H.mjs.map +0 -1
  208. package/dist/chunks/review-ZsBqp3vZ.mjs +0 -35
  209. package/dist/chunks/review-ZsBqp3vZ.mjs.map +0 -1
  210. package/dist/chunks/run-BGabwbDL.mjs +0 -109
  211. package/dist/chunks/run-BGabwbDL.mjs.map +0 -1
  212. package/dist/chunks/run-tool-C3rAv4XF.mjs +0 -26
  213. package/dist/chunks/run-tool-C3rAv4XF.mjs.map +0 -1
  214. package/dist/chunks/scan-C5uDr7Yq.mjs +0 -167
  215. package/dist/chunks/scan-C5uDr7Yq.mjs.map +0 -1
  216. package/dist/chunks/schema-Bq9qtgsd.mjs +0 -583
  217. package/dist/chunks/schema-Bq9qtgsd.mjs.map +0 -1
  218. package/dist/chunks/send-BdnJ85Nz.mjs +0 -19
  219. package/dist/chunks/send-BdnJ85Nz.mjs.map +0 -1
  220. package/dist/chunks/ship-BizfUe62.mjs +0 -140
  221. package/dist/chunks/ship-BizfUe62.mjs.map +0 -1
  222. package/dist/chunks/shutdown-BM92Iyv2.mjs +0 -15
  223. package/dist/chunks/shutdown-BM92Iyv2.mjs.map +0 -1
  224. package/dist/chunks/skip-DZG5kpcH.mjs +0 -18
  225. package/dist/chunks/skip-DZG5kpcH.mjs.map +0 -1
  226. package/dist/chunks/spec-C2h3U64g.mjs +0 -65
  227. package/dist/chunks/spec-C2h3U64g.mjs.map +0 -1
  228. package/dist/chunks/spec-path-tptqR7W8.mjs +0 -10
  229. package/dist/chunks/spec-path-tptqR7W8.mjs.map +0 -1
  230. package/dist/chunks/src-Bfr1yzsn.mjs +0 -1689
  231. package/dist/chunks/src-Bfr1yzsn.mjs.map +0 -1
  232. package/dist/chunks/src-CPW2_Ons.mjs +0 -5487
  233. package/dist/chunks/src-CPW2_Ons.mjs.map +0 -1
  234. package/dist/chunks/src-Cu3TxNob.mjs +0 -783
  235. package/dist/chunks/src-Cu3TxNob.mjs.map +0 -1
  236. package/dist/chunks/src-DNsLSxgm.mjs +0 -928
  237. package/dist/chunks/src-DNsLSxgm.mjs.map +0 -1
  238. package/dist/chunks/src-DbS9gkJy.mjs +0 -117
  239. package/dist/chunks/src-DbS9gkJy.mjs.map +0 -1
  240. package/dist/chunks/src-yi5whv3n.mjs +0 -2118
  241. package/dist/chunks/src-yi5whv3n.mjs.map +0 -1
  242. package/dist/chunks/status-SMjiOMYy.mjs +0 -29
  243. package/dist/chunks/status-SMjiOMYy.mjs.map +0 -1
  244. package/dist/chunks/tail-BuhT-2PH.mjs +0 -25
  245. package/dist/chunks/tail-BuhT-2PH.mjs.map +0 -1
  246. package/dist/chunks/update-BXIppsbi.mjs +0 -16
  247. package/dist/chunks/update-BXIppsbi.mjs.map +0 -1
  248. package/dist/chunks/update-pipeline-Du-Gu1Pl.mjs +0 -56
  249. package/dist/chunks/update-pipeline-Du-Gu1Pl.mjs.map +0 -1
  250. package/dist/cli.mjs +0 -186
  251. package/dist/cli.mjs.map +0 -1
package/lib/project.js ADDED
@@ -0,0 +1,359 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ // cohorte — wire ONE project, deterministically.
4
+ //
5
+ // node <core>/lib/project.js sync [root] # copy the gate, register its hook, pointer, .gitignore,
6
+ // # and .claude/profile.json (the parsed profile block)
7
+ // node <core>/lib/project.js unsync [root] # undo exactly what sync wrote
8
+ //
9
+ // Everything that describes a project lives in that project and is committed with it:
10
+ // PIPELINE.md, the surface agents, gate-config.json, the gate hook itself and its
11
+ // registration. The machine-wide install (`cohorte install`) only provides the commands
12
+ // and the generic core. A teammate who clones the repo therefore gets the gate even
13
+ // before installing Cohorte.
14
+ //
15
+ // This file is SELF-CONTAINED on purpose: the installer copies it to
16
+ // `~/.claude/cohorte/lib/project.js`, and `/cohorte-init-pipeline` runs it from there, so it
17
+ // must work without the `cohorte` binary on PATH (npx users). Its one sibling is `yaml.js` (the
18
+ // installer ships it next to this file), the same parser `cohorte doctor` uses — so sync and
19
+ // doctor cannot disagree about the profile. It is required lazily: a core missing it still wires
20
+ // the gate, and only `.claude/profile.json` is skipped, with a note saying why.
21
+
22
+ const fs = require('fs');
23
+ const path = require('path');
24
+ const { spawnSync } = require('child_process');
25
+
26
+ const GATE_FILE = path.join('.claude', 'hooks', 'cohorte-gate.py');
27
+ const PROFILE_FILE = path.join('.claude', 'profile.json');
28
+ const GATE_COMMAND = 'python3 "$CLAUDE_PROJECT_DIR/.claude/hooks/cohorte-gate.py"';
29
+ const GATE_MATCHER = 'Bash|Task|Agent';
30
+ const EDIT_MATCHER = 'Write|Edit|MultiEdit|NotebookEdit';
31
+ const INSTALL_HINT = 'npm i -g cohorte && cohorte install';
32
+ const IGNORE_LINES = ['.claude/preflight.ok', '.claude/pipeline-metrics.jsonl', 'specs/reports/'];
33
+ const IGNORE_HEADER = '# cohorte — local-only pipeline artifacts (never commit these)';
34
+ const MARKERS = ['Generated by the cohorte adapter', 'Generated by the cohorte installer'];
35
+ const COMMIT_LIST = '.claude/settings.json, .claude/hooks/cohorte-gate.py, .claude/pipeline.json, .claude/profile.json and .gitignore';
36
+
37
+ // --- where the shipped assets are -------------------------------------------
38
+ // Installed: <core>/lib/project.js, <core>/hooks/gate.py, <core>/pipeline/VERSION
39
+ // From source: <pkg>/lib/project.js, <pkg>/core/hooks/gate.py, <pkg>/package.json
40
+ function assets() {
41
+ const up = path.join(__dirname, '..');
42
+ const installed = fs.existsSync(path.join(up, 'pipeline', 'VERSION'));
43
+ const coreDir = installed ? up : path.join(up, 'core');
44
+ let version = null;
45
+ try {
46
+ version = installed
47
+ ? fs.readFileSync(path.join(up, 'pipeline', 'VERSION'), 'utf8').trim()
48
+ : JSON.parse(fs.readFileSync(path.join(up, 'package.json'), 'utf8')).version;
49
+ } catch { /* reported by the caller */ }
50
+ return {
51
+ gate: path.join(coreDir, 'hooks', 'gate.py'),
52
+ specTemplate: path.join(coreDir, 'templates', 'spec.template.md'),
53
+ templatesDir: path.join(coreDir, 'templates'),
54
+ version,
55
+ };
56
+ }
57
+
58
+ // --- JSON that is never clobbered ---------------------------------------------
59
+ class ProjectError extends Error {}
60
+
61
+ // Read a JSON object file. Absent ⇒ {}. Present but unparseable ⇒ throw: a settings file
62
+ // with a trailing comma or a BOM used to be silently replaced by a fresh one, taking the
63
+ // user's model, env and permissions with it.
64
+ function readJsonObject(file) {
65
+ let text;
66
+ try { text = fs.readFileSync(file, 'utf8'); } catch (e) {
67
+ if (e.code === 'ENOENT') return {};
68
+ throw new ProjectError(`cannot read ${file}: ${e.message}`);
69
+ }
70
+ if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);
71
+ if (!text.trim()) return {};
72
+ let data;
73
+ try { data = JSON.parse(text); } catch (e) {
74
+ throw new ProjectError(`${file} is not valid JSON (${e.message}). Fix it and re-run — `
75
+ + 'cohorte never rewrites a file it cannot parse.');
76
+ }
77
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
78
+ throw new ProjectError(`${file} must contain a JSON object — leaving it untouched.`);
79
+ }
80
+ return data;
81
+ }
82
+
83
+ function writeIfChanged(file, content, changes, label) {
84
+ let before = null;
85
+ try { before = fs.readFileSync(file, 'utf8'); } catch { /* new file */ }
86
+ if (before === content) return false;
87
+ fs.mkdirSync(path.dirname(file), { recursive: true });
88
+ fs.writeFileSync(file, content);
89
+ changes.push(`${before === null ? 'created' : 'updated'} ${label}`);
90
+ return true;
91
+ }
92
+
93
+ // --- the hook registration -----------------------------------------------------
94
+ // Ours: the 3.x command, or a 2.x registration of `.claude/hooks/gate.py` (what 2.x
95
+ // /cohorte-init-pipeline wrote: relative, $CLAUDE_PROJECT_DIR-anchored or absolute). Matching
96
+ // is on that exact path, never on a bare `gate.py` suffix — another tool's
97
+ // `~/tools/gate.py` is not ours to remove.
98
+ function isOurCommand(cmd) {
99
+ if (typeof cmd !== 'string') return false;
100
+ if (cmd.includes('cohorte-gate.py')) return true;
101
+ return /(^|["'\s/])\.claude\/hooks\/gate\.py(["'\s]|$)/.test(cmd.replace(/\\/g, '/'));
102
+ }
103
+
104
+ // Remove our hook objects from every PreToolUse group; drop a group only when it ends up
105
+ // empty, so a user's own hook sharing a matcher group survives.
106
+ function stripOurHooks(list) {
107
+ const out = [];
108
+ let removed = 0;
109
+ for (const group of Array.isArray(list) ? list : []) {
110
+ if (!group || typeof group !== 'object' || !Array.isArray(group.hooks)) { out.push(group); continue; }
111
+ const kept = group.hooks.filter((h) => !(h && isOurCommand(h.command)));
112
+ removed += group.hooks.length - kept.length;
113
+ if (kept.length) out.push(kept.length === group.hooks.length ? group : { ...group, hooks: kept });
114
+ }
115
+ return { list: out, removed };
116
+ }
117
+
118
+ function gateGroups() {
119
+ const hook = { type: 'command', command: GATE_COMMAND, onFailure: 'block' };
120
+ return [
121
+ { matcher: GATE_MATCHER, hooks: [hook] },
122
+ { matcher: EDIT_MATCHER, hooks: [{ ...hook }] },
123
+ ];
124
+ }
125
+
126
+ // 2.x allowlisted the pipeline scripts at their old homes. Point them at the 3.x core.
127
+ function migratePermissions(data) {
128
+ const allow = data.permissions && Array.isArray(data.permissions.allow) ? data.permissions.allow : null;
129
+ if (!allow) return false;
130
+ const next = [];
131
+ for (const rule of allow) {
132
+ let r = rule;
133
+ if (typeof r === 'string') {
134
+ r = r.replace('~/.claude/pipeline/scripts/', '~/.claude/cohorte/pipeline/scripts/');
135
+ if (/\(\s*(bash\s+)?\.claude\/pipeline\/scripts\//.test(r)) continue; // bundled core is gone
136
+ }
137
+ if (!next.includes(r)) next.push(r);
138
+ }
139
+ if (next.length === allow.length && next.every((r, i) => r === allow[i])) return false;
140
+ data.permissions.allow = next;
141
+ return true;
142
+ }
143
+
144
+ // --- 2.x bundled-core cleanup ----------------------------------------------------
145
+ function gitTrackedClean(root, rel) {
146
+ const r = spawnSync('git', ['-C', root, 'ls-files', '--error-unmatch', '--', rel], { stdio: 'ignore' });
147
+ if (r.status !== 0) return false;
148
+ const d = spawnSync('git', ['-C', root, 'diff', '--quiet', 'HEAD', '--', rel], { stdio: 'ignore' });
149
+ return d.status === 0;
150
+ }
151
+
152
+ function hasMarker(file) {
153
+ try { const t = fs.readFileSync(file, 'utf8'); return MARKERS.some((m) => t.includes(m)); } catch { return false; }
154
+ }
155
+
156
+ function walk(dir) {
157
+ let out = [];
158
+ let entries = [];
159
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return out; }
160
+ for (const e of entries) {
161
+ const p = path.join(dir, e.name);
162
+ out = e.isDirectory() ? out.concat(walk(p)) : out.concat([p]);
163
+ }
164
+ return out;
165
+ }
166
+
167
+ // A 2.x "bundled" install vendored the whole core into <repo>/.claude. 3.x never does:
168
+ // remove what is provably ours. A file git tracks unmodified is simply deleted (git
169
+ // keeps it); anything else is moved to .claude/cohorte-legacy-backup/ for the human.
170
+ function legacyBundled(root, A) {
171
+ const claude = path.join(root, '.claude');
172
+ if (!fs.existsSync(path.join(claude, 'pipeline', 'VERSION'))) return [];
173
+ const candidates = [];
174
+ candidates.push(...walk(path.join(claude, 'pipeline')));
175
+ for (const f of walk(path.join(claude, 'commands'))) {
176
+ if (/cohorte-[\w-]+\.md$/.test(f) && hasMarker(f)) candidates.push(f);
177
+ }
178
+ for (const n of ['review', 'release', 'profile-reader']) {
179
+ const f = path.join(claude, 'agents', `${n}.md`);
180
+ if (fs.existsSync(f) && hasMarker(f)) candidates.push(f);
181
+ }
182
+ const shipped = new Set(walk(A.templatesDir).map((f) => path.relative(A.templatesDir, f)));
183
+ for (const f of walk(path.join(claude, 'templates'))) {
184
+ if (shipped.has(path.relative(path.join(claude, 'templates'), f))) candidates.push(f);
185
+ }
186
+ for (const n of ['review', 'audit', 'refactor', 'loop']) {
187
+ const f = path.join(claude, 'workflows', `${n}.js`);
188
+ try { if (/name:\s*'cohorte-/.test(fs.readFileSync(f, 'utf8'))) candidates.push(f); } catch { /* absent */ }
189
+ }
190
+ const gate = path.join(claude, 'hooks', 'gate.py');
191
+ if (fs.existsSync(gate)) candidates.push(gate);
192
+
193
+ const moved = [];
194
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
195
+ for (const f of candidates) {
196
+ const rel = path.relative(root, f);
197
+ if (gitTrackedClean(root, rel)) {
198
+ fs.rmSync(f, { force: true });
199
+ moved.push(`removed ${rel} (2.x bundled core — still in git history)`);
200
+ } else {
201
+ const dest = path.join(claude, 'cohorte-legacy-backup', stamp, path.relative(claude, f));
202
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
203
+ fs.renameSync(f, dest);
204
+ moved.push(`moved ${rel} → ${path.relative(root, dest)} (2.x bundled core, not tracked or modified)`);
205
+ }
206
+ }
207
+ for (const d of ['pipeline', 'templates', 'workflows', 'commands', 'hooks']) pruneEmpty(path.join(claude, d));
208
+ return moved;
209
+ }
210
+
211
+ function pruneEmpty(dir) {
212
+ let entries;
213
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
214
+ for (const e of entries) if (e.isDirectory()) pruneEmpty(path.join(dir, e.name));
215
+ try { if (!fs.readdirSync(dir).length) fs.rmdirSync(dir); } catch { /* not empty */ }
216
+ }
217
+
218
+ // --- .gitignore -------------------------------------------------------------------
219
+ function ensureIgnored(root, changes) {
220
+ const file = path.join(root, '.gitignore');
221
+ let text = '';
222
+ try { text = fs.readFileSync(file, 'utf8'); } catch { /* new */ }
223
+ const have = new Set(text.split(/\r?\n/).map((l) => l.trim().replace(/^\/+/, '')));
224
+ const missing = IGNORE_LINES.filter((l) => !have.has(l) && !have.has(l.replace(/\/$/, '')));
225
+ if (!missing.length) return;
226
+ const sep = text && !text.endsWith('\n') ? '\n' : '';
227
+ const block = (text.includes(IGNORE_HEADER) ? '' : `${text ? '\n' : ''}${IGNORE_HEADER}\n`) + missing.join('\n') + '\n';
228
+ fs.writeFileSync(file, text + sep + block);
229
+ changes.push(`added ${missing.join(', ')} to .gitignore`);
230
+ }
231
+
232
+ // --- .claude/profile.json ----------------------------------------------------------
233
+ // The `yaml pipeline-profile` block of PIPELINE.md, parsed once here so every agent that needs only
234
+ // the machine block (implementers, the reviewer, the release agent, the workflows' profile-reader)
235
+ // reads a small JSON file instead of the whole profile. Committed, regenerated by every sync.
236
+ // Returns { text } to write, or { note } saying why nothing was written.
237
+ function profileJson(root) {
238
+ let md;
239
+ try { md = fs.readFileSync(path.join(root, 'PIPELINE.md'), 'utf8'); } catch {
240
+ return { note: 'PIPELINE.md not found — .claude/profile.json not written (run /cohorte-init-pipeline)' };
241
+ }
242
+ let yaml;
243
+ try { yaml = require('./yaml.js'); } catch {
244
+ return { note: `yaml.js missing next to ${__filename} — .claude/profile.json not written (reinstall cohorte)` };
245
+ }
246
+ let text = null;
247
+ try { text = yaml.profileJsonText(md); } catch { /* reported below */ }
248
+ if (!text) {
249
+ return { note: 'PIPELINE.md has no parseable `yaml pipeline-profile` block — .claude/profile.json not written'
250
+ + (fs.existsSync(path.join(root, PROFILE_FILE)) ? ' (the existing one was left as is and may be stale)' : '') };
251
+ }
252
+ return { text };
253
+ }
254
+
255
+ // --- sync / unsync -----------------------------------------------------------------
256
+ function sync(rootArg) {
257
+ const root = path.resolve(rootArg || process.cwd());
258
+ if (!fs.statSync(root).isDirectory()) throw new ProjectError(`${root} is not a directory`);
259
+ const A = assets();
260
+ if (!fs.existsSync(A.gate)) throw new ProjectError(`gate hook not found at ${A.gate} — reinstall cohorte`);
261
+ const changes = [];
262
+ const notes = [];
263
+
264
+ // Parse everything we will touch BEFORE writing anything: an invalid file aborts the
265
+ // whole sync rather than leaving the project half-wired.
266
+ const settingsPath = path.join(root, '.claude', 'settings.json');
267
+ const pointerPath = path.join(root, '.claude', 'pipeline.json');
268
+ const settings = readJsonObject(settingsPath);
269
+ const pointer = readJsonObject(pointerPath);
270
+
271
+ changes.push(...legacyBundled(root, A));
272
+
273
+ // 1. The gate itself, committed with the repo.
274
+ const gateText = fs.readFileSync(A.gate, 'utf8');
275
+ if (writeIfChanged(path.join(root, GATE_FILE), gateText, changes, GATE_FILE) && process.platform !== 'win32') {
276
+ try { fs.chmodSync(path.join(root, GATE_FILE), 0o755); } catch { /* optional */ }
277
+ }
278
+
279
+ // 2. Its registration — exactly one of ours, every foreign hook untouched.
280
+ if (!settings.hooks || typeof settings.hooks !== 'object' || Array.isArray(settings.hooks)) settings.hooks = {};
281
+ const { list } = stripOurHooks(settings.hooks.PreToolUse);
282
+ settings.hooks.PreToolUse = list.concat(gateGroups());
283
+ migratePermissions(settings);
284
+ writeIfChanged(settingsPath, JSON.stringify(settings, null, 2) + '\n', changes, '.claude/settings.json (gate hook)');
285
+
286
+ // 3. The pointer: tells a teammate (and /cohorte-doctor) which core this repo expects.
287
+ delete pointer.mode; // 3.x has a single mode
288
+ Object.assign(pointer, { pipeline: 'cohorte', core_version: A.version, install: INSTALL_HINT });
289
+ writeIfChanged(pointerPath, JSON.stringify(pointer, null, 2) + '\n', changes, '.claude/pipeline.json');
290
+
291
+ // 4. Local-only artifacts stay out of git.
292
+ ensureIgnored(root, changes);
293
+
294
+ // 5. The spec template /cohorte-spec copies from.
295
+ const specTpl = path.join(root, 'specs', '_template.md');
296
+ if (!fs.existsSync(specTpl) && fs.existsSync(A.specTemplate)) {
297
+ fs.mkdirSync(path.dirname(specTpl), { recursive: true });
298
+ fs.copyFileSync(A.specTemplate, specTpl);
299
+ changes.push('created specs/_template.md');
300
+ }
301
+
302
+ // 6. The parsed profile block, for agents that need only the machine block. Written AFTER
303
+ // PIPELINE.md: every command that edits the block re-runs sync so this file follows it.
304
+ const pj = profileJson(root);
305
+ if (pj.text) writeIfChanged(path.join(root, PROFILE_FILE), pj.text, changes, '.claude/profile.json');
306
+ else notes.push(pj.note);
307
+ return { root, version: A.version, changes, notes };
308
+ }
309
+
310
+ function unsync(rootArg) {
311
+ const root = path.resolve(rootArg || process.cwd());
312
+ const changes = [];
313
+ const settingsPath = path.join(root, '.claude', 'settings.json');
314
+ const settings = readJsonObject(settingsPath);
315
+ if (settings.hooks && Array.isArray(settings.hooks.PreToolUse)) {
316
+ const { list, removed } = stripOurHooks(settings.hooks.PreToolUse);
317
+ if (removed) {
318
+ if (list.length) settings.hooks.PreToolUse = list; else delete settings.hooks.PreToolUse;
319
+ if (!Object.keys(settings.hooks).length) delete settings.hooks;
320
+ fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n');
321
+ changes.push(`removed ${removed} gate hook registration(s) from .claude/settings.json`);
322
+ }
323
+ }
324
+ for (const rel of [GATE_FILE, path.join('.claude', 'pipeline.json'), PROFILE_FILE]) {
325
+ if (fs.existsSync(path.join(root, rel))) { fs.rmSync(path.join(root, rel)); changes.push(`removed ${rel}`); }
326
+ }
327
+ pruneEmpty(path.join(root, '.claude', 'hooks'));
328
+ const left = ['PIPELINE.md', '.claude/gate-config.json', '.claude/agents', 'specs', 'scripts/new-feature.sh',
329
+ 'scripts/remove-feature.sh'].filter((p) => fs.existsSync(path.join(root, p)));
330
+ return { root, changes, left };
331
+ }
332
+
333
+ module.exports = { sync, unsync, readJsonObject, stripOurHooks, isOurCommand, ProjectError, profileJson,
334
+ GATE_COMMAND, GATE_MATCHER, EDIT_MATCHER, GATE_FILE, PROFILE_FILE, IGNORE_LINES, COMMIT_LIST };
335
+
336
+ // --- CLI -----------------------------------------------------------------------------
337
+ if (require.main === module) {
338
+ const [verb, root] = process.argv.slice(2);
339
+ try {
340
+ if (verb === 'sync') {
341
+ const r = sync(root);
342
+ console.log(`cohorte sync — ${r.root} (core ${r.version})`);
343
+ for (const c of r.changes) console.log(` · ${c}`);
344
+ if (!r.changes.length) console.log(' · already in sync');
345
+ for (const n of r.notes) console.log(` ! ${n}`);
346
+ if (r.changes.length) console.log(` Commit ${COMMIT_LIST}.`);
347
+ } else if (verb === 'unsync') {
348
+ const r = unsync(root);
349
+ for (const c of r.changes) console.log(` · ${c}`);
350
+ if (r.left.length) console.log(` Project files kept (yours to delete): ${r.left.join(', ')}`);
351
+ } else {
352
+ console.error('usage: project.js sync|unsync [root]');
353
+ process.exit(2);
354
+ }
355
+ } catch (e) {
356
+ console.error(`error: ${e.message}`);
357
+ process.exit(1);
358
+ }
359
+ }
package/lib/render.js ADDED
@@ -0,0 +1,121 @@
1
+ 'use strict';
2
+ // cohorte — render the core prompts for Claude Code.
3
+ //
4
+ // The sources in core/commands/*.md and core/agents/*.md are written with a handful of
5
+ // path tokens (`<core>`, `<state>`, `<agents>`, …) so the prose never hardcodes where a
6
+ // machine keeps things. Rendering prepends one preamble that resolves every token, keeps
7
+ // only the frontmatter keys Claude Code understands (an unknown key is prose the model
8
+ // reads as an instruction), and leaves the body untouched.
9
+ //
10
+ // 3.0.0 made Claude Code the only target and dropped the capability conditionals that served
11
+ // the other coding agents: the last multi-runtime tree is on the `archive/multi-runtime` branch.
12
+
13
+ const os = require('os');
14
+ const path = require('path');
15
+
16
+ const COMMAND_KEYS = ['model', 'description', 'argument-hint', 'allowed-tools', 'disable-model-invocation'];
17
+ const AGENT_KEYS = ['name', 'description', 'tools', 'model'];
18
+
19
+ // The matcher the project hook is registered with. `Agent` is the subagent tool's name
20
+ // since Claude Code 2.1.63; `Task` is its former name, kept so an older client still
21
+ // delivers dispatches to the preflight phase gate.
22
+ const GATE_MATCHER = 'Bash|Task|Agent';
23
+
24
+ // Path as the human/model should see it: `~/…` reads better than an expanded homedir,
25
+ // and a project-relative path must stay relative (the agent's cwd is the repo).
26
+ function displayPath(p) {
27
+ if (!p) return null;
28
+ const home = os.homedir();
29
+ if (p === home) return '~';
30
+ if (p.startsWith(home + path.sep)) return '~/' + path.relative(home, p).split(path.sep).join('/');
31
+ return p.split(path.sep).join('/');
32
+ }
33
+
34
+ // A path a shell will expand even inside double quotes: `$HOME/…` rather than `~/…`.
35
+ function shellPath(p) {
36
+ const home = os.homedir();
37
+ if (p.startsWith(home + path.sep)) return '$HOME/' + path.relative(home, p).split(path.sep).join('/');
38
+ return p.split(path.sep).join('/');
39
+ }
40
+
41
+ /**
42
+ * The machine layout every rendered file is written against.
43
+ * @param {string} globalDir Claude Code's config dir (~/.claude, or $CLAUDE_CONFIG_DIR)
44
+ */
45
+ function layout(globalDir) {
46
+ const core = path.join(globalDir, 'cohorte');
47
+ return {
48
+ globalDir,
49
+ core,
50
+ commands: path.join(globalDir, 'commands'),
51
+ fixedAgents: path.join(globalDir, 'agents'),
52
+ workflows: path.join(globalDir, 'workflows'),
53
+ config: path.join(globalDir, 'cohorte.config.yaml'),
54
+ projectLib: path.join(core, 'lib', 'project.js'),
55
+ };
56
+ }
57
+
58
+ function preamble(L, { kind = 'command' } = {}) {
59
+ const core = displayPath(L.core);
60
+ const sync = `node "${shellPath(L.projectLib)}" sync .`;
61
+ const out = [];
62
+ out.push(`> **Cohorte — Claude Code.** Generated by the cohorte installer — do not edit this file;`);
63
+ out.push(`> edit \`core/${kind === 'agent' ? 'agents' : 'commands'}/\` in the cohorte source and re-install.`);
64
+ out.push('>');
65
+ out.push(`> - \`<core>\` = \`${core}\` — the pipeline's shared, machine-wide assets (\`pipeline/scripts/\`, \`pipeline/schema/<topic>.md\` — read only the one a step cites, \`templates/\`). Every \`<core>/…\` path below resolves there, and nowhere else.`);
66
+ out.push('> - `<state>` = `.claude/` in **this repo** — what the pipeline generates for this project (`gate-config.json`, `preflight.ok`, `pipeline-metrics.jsonl`, `pipeline.json`, `profile.json` — the parsed `PIPELINE.md` machine block).');
67
+ out.push('> - `<memory>` = `CLAUDE.md` — the project-instructions file at the repo root, loaded into every session here.');
68
+ out.push(`> - \`<config>\` = \`${displayPath(L.config)}\` — your user-level config (kanban boards, shared vault). One per human, never committed.`);
69
+ out.push('> - `<agents>` = `.claude/agents` in **this repo** — the surface agents rendered from `PIPELINE.md`, committed with the code. Never write a surface agent anywhere else.');
70
+ out.push(`> - \`<fixed-agents>\` = \`${displayPath(L.fixedAgents)}\` — the shipped \`cohorte-review\`, \`cohorte-release\` and \`cohorte-profile-reader\` agents.`);
71
+ out.push(`> - \`<workflows>\` = \`${displayPath(L.workflows)}\` — the shipped workflow scripts (\`cohorte-review.js\`, \`cohorte-audit.js\`, \`cohorte-refactor.js\`, \`cohorte-loop.js\`).`);
72
+ out.push('> - Dispatch: the `Agent` tool (formerly `Task`), `subagent_type: <name>`.');
73
+ out.push('> - **Gate** — `.claude/hooks/cohorte-gate.py` is committed in this repo and registered as a blocking `PreToolUse` hook in `.claude/settings.json`, reading `<state>/gate-config.json`. It fires whether or not you cooperate, and can deny outright or ask the human to confirm.');
74
+ out.push(`> - \`<sync>\` = \`${sync}\` — wires THIS repo deterministically: copies the gate, registers its hook, writes the \`<state>/pipeline.json\` pointer, \`<state>/profile.json\` and the \`.gitignore\` entries. Re-run it after any edit to \`PIPELINE.md\`'s machine block. Run it from the repo root; never hand-write those files.`);
75
+ return out.join('\n') + '\n';
76
+ }
77
+
78
+ function parseFrontmatter(text) {
79
+ if (!text.startsWith('---\n')) return { keys: [], body: text };
80
+ const end = text.indexOf('\n---\n', 3);
81
+ if (end === -1) return { keys: [], body: text };
82
+ const block = text.slice(4, end + 1);
83
+ const body = text.slice(end + 5);
84
+ const keys = [];
85
+ for (const line of block.split('\n')) {
86
+ const m = line.match(/^([A-Za-z][\w-]*):\s?(.*)$/);
87
+ // Continuation lines (a wrapped value) belong to the previous key.
88
+ if (!m) {
89
+ if (line.trim() && keys.length) keys[keys.length - 1][1] += '\n' + line;
90
+ continue;
91
+ }
92
+ keys.push([m[1], m[2]]);
93
+ }
94
+ return { keys, body };
95
+ }
96
+
97
+ function emitFrontmatter(keys) {
98
+ if (!keys.length) return '';
99
+ return '---\n' + keys.map(([k, v]) => `${k}: ${v}`).join('\n') + '\n---\n\n';
100
+ }
101
+
102
+ function render(source, L, allowed, kind) {
103
+ const { keys, body } = parseFrontmatter(source);
104
+ const kept = keys.filter(([k]) => allowed.includes(k));
105
+ return emitFrontmatter(kept) + preamble(L, { kind }) + '\n' + body.replace(/^\n+/, '');
106
+ }
107
+
108
+ const renderCommand = (source, L) => render(source, L, COMMAND_KEYS, 'command');
109
+ const renderAgent = (source, L) => render(source, L, AGENT_KEYS, 'agent');
110
+
111
+ module.exports = {
112
+ GATE_MATCHER,
113
+ layout,
114
+ displayPath,
115
+ shellPath,
116
+ preamble,
117
+ parseFrontmatter,
118
+ emitFrontmatter,
119
+ renderCommand,
120
+ renderAgent,
121
+ };
@@ -0,0 +1,145 @@
1
+ 'use strict';
2
+ // Freshness data: which core is installed where, and how it compares to npm latest.
3
+ // Dependency-free — reads VERSION files + the committed pointer, fetches the npm registry.
4
+
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const { spawnSync } = require('child_process');
8
+
9
+ function readTrimmed(file) {
10
+ try { return fs.readFileSync(file, 'utf8').trim(); } catch { return null; }
11
+ }
12
+
13
+ function readJson(file) {
14
+ try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; }
15
+ }
16
+
17
+ // A core rooted at `dir` (its `pipeline/VERSION`). 3.x: `<globalDir>/cohorte`. 2.x left one
18
+ // straight in `<globalDir>` (global mode) or in a repo's `.claude` (bundled mode).
19
+ function coreAt(dir) {
20
+ const version = readTrimmed(path.join(dir, 'pipeline', 'VERSION'));
21
+ return { present: version != null, version, dir };
22
+ }
23
+
24
+ // The committed per-repo pointer; names the core_version (and, on a 2.x repo, a mode).
25
+ function pointerAt(projectRoot) {
26
+ const ptr = readJson(path.join(projectRoot, '.claude', 'pipeline.json'));
27
+ if (!ptr || typeof ptr !== 'object') return { present: false };
28
+ return { present: true, mode: ptr.mode || null, core_version: ptr.core_version || null };
29
+ }
30
+
31
+ // Latest published version — registry fetch first, `npm view` as a fallback (it uses the
32
+ // user's configured registry/proxy, which works where a raw fetch may be blocked). Cached
33
+ // briefly so repeated calls don't hammer the network. null only if both fail.
34
+ let _cache = { value: null, at: 0 };
35
+ const CACHE_MS = 5 * 60 * 1000;
36
+ // Failures are cached too, briefly. Without this an offline machine paid the FULL
37
+ // 5s fetch timeout + 8s `npm view` timeout on every call — and /api/fleet calls
38
+ // this once per tracked project, so a batch of probes never finished.
39
+ const FAIL_CACHE_MS = 60 * 1000;
40
+
41
+ async function fetchRegistry(timeoutMs = 5000) {
42
+ const ctrl = new AbortController();
43
+ const t = setTimeout(() => ctrl.abort(), timeoutMs);
44
+ try {
45
+ const res = await fetch('https://registry.npmjs.org/cohorte/latest', {
46
+ signal: ctrl.signal,
47
+ headers: { accept: 'application/vnd.npm.install-v1+json' },
48
+ });
49
+ if (!res.ok) return null;
50
+ const body = await res.json();
51
+ return typeof body.version === 'string' ? body.version : null;
52
+ } catch {
53
+ return null;
54
+ } finally {
55
+ clearTimeout(t);
56
+ }
57
+ }
58
+
59
+ // Fallback only — spawnSync blocks the single-threaded server for up to its
60
+ // timeout, so it must stay behind latestNpm()'s cache + in-flight dedupe (at most
61
+ // one call a minute, and only when the registry fetch already failed).
62
+ function npmView() {
63
+ try {
64
+ // One static string on Windows (npm is npm.cmd — needs a shell; the
65
+ // shell+args-array combination is DEP0190-deprecated). Nothing dynamic.
66
+ const r = process.platform === 'win32'
67
+ ? spawnSync('npm view cohorte version', { encoding: 'utf8', timeout: 8000, shell: true })
68
+ : spawnSync('npm', ['view', 'cohorte', 'version'], { encoding: 'utf8', timeout: 8000 });
69
+ if (r.status === 0 && r.stdout) {
70
+ const v = r.stdout.trim();
71
+ return /^\d+\.\d+\.\d+/.test(v) ? v : null;
72
+ }
73
+ } catch { /* npm absent or slow */ }
74
+ return null;
75
+ }
76
+
77
+ let _inflight = null;
78
+ // `opts` bounds what a CALLER is willing to pay for the answer. The CLI's staleness
79
+ // notice runs at the tail of an install, where the default 5s fetch + 8s `npm view`
80
+ // fallback would make an OFFLINE install appear to hang for 13 seconds after it had
81
+ // already succeeded — so it asks for a short fetch and no fallback. The cache is
82
+ // shared across callers either way: a cheap lookup still serves an expensive one.
83
+ async function latestNpm({ timeoutMs = 5000, fallback = true } = {}) {
84
+ // Opt-out honoured by every caller (install notice, doctor, panels): offline machines and CI.
85
+ if (process.env.COHORTE_NO_VERSION_CHECK) return null;
86
+ const age = Date.now() - _cache.at;
87
+ if (_cache.at && age < (_cache.value ? CACHE_MS : FAIL_CACHE_MS)) return _cache.value;
88
+ // /api/fleet resolves N projects concurrently — without this, N lookups race and
89
+ // each pays the full timeout instead of sharing one.
90
+ if (_inflight) return _inflight;
91
+ _inflight = (async () => {
92
+ try {
93
+ const v = (await fetchRegistry(timeoutMs)) || (fallback ? npmView() : null);
94
+ _cache = { value: v || null, at: Date.now() };
95
+ return v || null;
96
+ } finally {
97
+ _inflight = null;
98
+ }
99
+ })();
100
+ return _inflight;
101
+ }
102
+
103
+ // Semver compare — returns -1|0|1 (a<b|a==b|a>b). A pre-release sorts before its release
104
+ // (3.0.0-dev.8 < 3.0.0), and between pre-releases the tags compare as strings.
105
+ function cmpSemver(a, b) {
106
+ if (!a || !b) return null;
107
+ const split = (v) => { const [core, pre] = String(v).split('-', 2); return [core.split('.').map(n => parseInt(n, 10) || 0), pre || null]; };
108
+ const [pa, ra] = split(a);
109
+ const [pb, rb] = split(b);
110
+ for (let i = 0; i < 3; i++) {
111
+ if ((pa[i] || 0) < (pb[i] || 0)) return -1;
112
+ if ((pa[i] || 0) > (pb[i] || 0)) return 1;
113
+ }
114
+ if (ra === rb) return 0;
115
+ if (!ra) return 1;
116
+ if (!rb) return -1;
117
+ return ra < rb ? -1 : 1;
118
+ }
119
+
120
+ async function versions({ projectRoot, globalDir, cliVersion, offline = false }) {
121
+ const global = coreAt(path.join(globalDir, 'cohorte'));
122
+ const pointer = pointerAt(projectRoot);
123
+ const latest = offline ? null : await latestNpm();
124
+ // 2.x layouts, reported so doctor can name the migration — never used to serve the project.
125
+ const legacyGlobal = coreAt(globalDir);
126
+ const legacyBundled = coreAt(path.join(projectRoot, '.claude'));
127
+
128
+ const installedVersion = global.present ? global.version : null;
129
+ return {
130
+ cli: cliVersion,
131
+ latest,
132
+ global,
133
+ // Kept for consumers of `doctor --json` (the Francois panel): 3.x has no bundled core.
134
+ bundled: { present: false, version: null, dir: path.join(projectRoot, '.claude') },
135
+ legacy: { global: legacyGlobal, bundled: legacyBundled },
136
+ pointer,
137
+ installMode: global.present ? 'global' : 'none',
138
+ installedVersion,
139
+ // -1 behind, 0 up-to-date, 1 ahead of registry (dev), null unknown
140
+ freshness: cmpSemver(installedVersion, latest),
141
+ globalFreshness: global.present ? cmpSemver(global.version, latest) : null,
142
+ };
143
+ }
144
+
145
+ module.exports = { versions, latestNpm, cmpSemver };