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
@@ -0,0 +1,542 @@
1
+ #!/usr/bin/env node
2
+ // collect.mjs — reconstruct per-command cost and runtime from Claude Code's own transcripts.
3
+ //
4
+ // node scripts/metrics/collect.mjs [projectRoot] [--json] [--runs] [--since=ISO] [--days=N]
5
+ //
6
+ // WHY THIS EXISTS
7
+ // `.claude/pipeline-metrics.jsonl` is written by the model itself (each command file tells
8
+ // it to append a line). That makes it unreliable — a command that ends early, errors, or
9
+ // simply forgets writes nothing, and it can never report tokens because the model does not
10
+ // know its own usage. Claude Code, meanwhile, already logs every API response it makes to
11
+ // ~/.claude/projects/<slug>/<sessionId>.jsonl with exact `usage` and timestamps, and every
12
+ // subagent to <sessionId>/subagents/agent-<id>.jsonl. That is ground truth, it needs no
13
+ // cooperation from the model, and it is retroactive: this script works on runs that already
14
+ // happened. Nothing here writes to the pipeline — it is a pure reader.
15
+ //
16
+ // THREE THINGS THAT ARE EASY TO GET WRONG, HANDLED HERE
17
+ // 1. One API response is written as SEVERAL transcript lines (one per content block:
18
+ // thinking, text, tool_use, tool_use), and EACH line repeats the full `usage` object.
19
+ // Summing lines inflates tokens ~1.8x. We dedupe by message.id.
20
+ // 2. Feature work happens in git worktrees, whose cwd hashes to a DIFFERENT project slug.
21
+ // Scanning only the main checkout's slug silently drops most of a multi-surface run. We match
22
+ // sessions by their recorded `cwd` against `git worktree list`.
23
+ // 3. Subagent spend lives in a separate file tree and is invisible in the parent
24
+ // transcript. For cohorte that is the majority of the cost, so we walk subagents/ and
25
+ // attribute each agent to the command segment that spawned it (via meta.toolUseId,
26
+ // falling back to timestamp containment for agents spawned by the Workflow runner).
27
+
28
+ import fs from 'node:fs';
29
+ import path from 'node:path';
30
+ import os from 'node:os';
31
+ import { execFileSync } from 'node:child_process';
32
+ import { fileURLToPath } from 'node:url';
33
+
34
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
35
+ const PRICES = JSON.parse(fs.readFileSync(path.join(HERE, 'prices.json'), 'utf8'));
36
+
37
+ // A gap longer than this between two API responses is the human thinking, reading, or away
38
+ // — not the command working. `wall` keeps it, `active` drops it. Without the split, a
39
+ // command left open over lunch reports a two-hour runtime and poisons every median.
40
+ const IDLE_GAP_S = 120;
41
+
42
+ // A prompt this short with no command in it ("continue", "go", "ok next") is the human
43
+ // steering a run that is already going, not starting a new one. Without this, a single
44
+ // /cohorte-review driven by three "continue"s reports as one /cohorte-review plus three anonymous chat
45
+ // runs, and three quarters of its cost lands under (chat).
46
+ const CONTINUATION_MAX_CHARS = 40;
47
+
48
+ // Commands are recognised two ways. `<command-name>` is emitted only when the whole prompt
49
+ // IS the slash command; in practice people write "move on branding-ramp and /cohorte-review", which
50
+ // the harness records as ordinary prose. So we also look for an inline mention, checked
51
+ // against the real command list rather than any /token — otherwise a file path like
52
+ // /usr/bin or a URL fragment would invent commands that were never run.
53
+ function knownCommands() {
54
+ const names = new Set();
55
+ for (const dir of [path.join(HERE, '..', '..', 'core', 'commands'),
56
+ path.join(process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude'), 'commands')]) {
57
+ try {
58
+ for (const f of fs.readdirSync(dir)) if (/^cohorte-[\w-]+\.md$/.test(f)) names.add(f.slice(0, -3));
59
+ } catch {}
60
+ }
61
+ // Fallback for a collector run outside the package (e.g. copied into a repo on its own).
62
+ if (!names.size) {
63
+ for (const n of ['cohorte-brainstorm', 'cohorte-spec', 'cohorte-build', 'cohorte-review',
64
+ 'cohorte-fix', 'cohorte-ship', 'cohorte-audit', 'cohorte-refactor',
65
+ 'cohorte-align-ds', 'cohorte-doctor', 'cohorte-patch', 'cohorte-intake',
66
+ 'cohorte-fleet', 'cohorte-retro',
67
+ 'cohorte-init-pipeline', 'cohorte-update-pipeline']) names.add(n);
68
+ }
69
+ // Retired commands. The list above is read from the shipped core, so a command that is
70
+ // removed stops being recognised — and every run of it already in the transcripts silently
71
+ // reclassifies as (chat), rewriting history and inflating the catch-all bucket. Keep the
72
+ // names here so past runs stay attributed to what actually ran.
73
+ //
74
+ // 2.0.0 prefixed every command with `cohorte-`, which retires all 13 bare names at once:
75
+ // months of transcripts say `/build`, and without these they would all reclassify to (chat)
76
+ // — the largest instance of exactly the bug this list exists to prevent. `drive`/`loop` are
77
+ // both here because the driver was `/loop` → `/drive` (1.6.0) → `/cohorte-loop` (2.0.0), and
78
+ // `cohorte-loop` joins them now that 2.2.0 retired the driver outright.
79
+ for (const n of ['cycle', 'smoke', 'drive', 'loop', 'cohorte-loop',
80
+ 'brainstorm', 'spec', 'build', 'review',
81
+ 'fix', 'ship', 'audit', 'refactor', 'align-ds', 'doctor',
82
+ 'init-pipeline', 'update-pipeline']) names.add(n);
83
+ return names;
84
+ }
85
+ const COMMANDS = knownCommands();
86
+
87
+ // An invocation is a short instruction that is mostly the command ("move on branding-ramp
88
+ // and /cohorte-review"). A long prompt that happens to name one is someone TALKING ABOUT the
89
+ // command — a bug report, a design discussion, a pasted transcript. Counting those as runs
90
+ // inflates a command's run count and cost with conversation that never invoked it, which is
91
+ // exactly what happened in cohorte's own repo while this pipeline was being discussed.
92
+ // Only inline mentions are length-gated; an explicit <command-name> is always an invocation.
93
+ const MENTION_MAX_CHARS = 120;
94
+
95
+ function commandIn(text) {
96
+ const explicit = /<command-name>\s*(\/?[\w:-]+)\s*<\/command-name>/.exec(text);
97
+ if (explicit) return explicit[1].replace(/^\//, '');
98
+ if (text.trim().length > MENTION_MAX_CHARS) return null;
99
+ // Last mention wins: "finish /cohorte-build then /cohorte-review" ends on the one being asked for.
100
+ let found = null;
101
+ for (const m of text.matchAll(/(?:^|\s)\/([a-z][a-z0-9-]{2,})\b/g)) {
102
+ if (COMMANDS.has(m[1])) found = m[1];
103
+ }
104
+ return found;
105
+ }
106
+
107
+ // ── paths ────────────────────────────────────────────────────────────────────────────────
108
+
109
+ const norm = (p) => String(p || '').replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase();
110
+
111
+ function git(args, cwd) {
112
+ try {
113
+ return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
114
+ } catch { return ''; }
115
+ }
116
+
117
+ // Every checkout that belongs to this repo: the main one plus every live feature worktree.
118
+ // A cohorte run spreads its surfaces across worktrees, so this set is what makes a feature
119
+ // add up instead of reporting only whatever the human happened to type in the main window.
120
+ function repoCheckouts(root) {
121
+ const out = new Set([norm(root)]);
122
+ const common = git(['rev-parse', '--git-common-dir'], root).trim();
123
+ if (common) out.add(norm(path.resolve(root, common, '..')));
124
+ for (const line of git(['worktree', 'list', '--porcelain'], root).split(/\r?\n/)) {
125
+ if (line.startsWith('worktree ')) out.add(norm(line.slice(9)));
126
+ }
127
+ return out;
128
+ }
129
+
130
+ const projectsDir = () =>
131
+ path.join(process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude'), 'projects');
132
+
133
+ // Read only the head of a transcript to decide whether it belongs to this repo. Transcripts
134
+ // run to tens of MB and most of them belong to other projects; fully parsing every file to
135
+ // find the handful that match turns a 2-second command into a 2-minute one.
136
+ function sessionCwd(file) {
137
+ let fd;
138
+ try {
139
+ fd = fs.openSync(file, 'r');
140
+ const buf = Buffer.alloc(65536);
141
+ const n = fs.readSync(fd, buf, 0, buf.length, 0);
142
+ const m = /"cwd"\s*:\s*"((?:[^"\\]|\\.)*)"/.exec(buf.subarray(0, n).toString('utf8'));
143
+ return m ? JSON.parse(`"${m[1]}"`) : null;
144
+ } catch { return null; }
145
+ finally { if (fd !== undefined) try { fs.closeSync(fd); } catch {} }
146
+ }
147
+
148
+ function findSessions(checkouts) {
149
+ const root = projectsDir();
150
+ let dirs;
151
+ try { dirs = fs.readdirSync(root, { withFileTypes: true }); }
152
+ catch { return []; }
153
+
154
+ const found = [];
155
+ for (const d of dirs) {
156
+ if (!d.isDirectory()) continue;
157
+ const dir = path.join(root, d.name);
158
+ let files;
159
+ try { files = fs.readdirSync(dir); } catch { continue; }
160
+ for (const f of files) {
161
+ if (!f.endsWith('.jsonl')) continue;
162
+ const file = path.join(dir, f);
163
+ const cwd = sessionCwd(file);
164
+ if (!cwd) continue;
165
+ // A worktree's cwd can be a SUBDIRECTORY of the checkout (an agent cd'd into a
166
+ // package), so prefix-match rather than compare for equality.
167
+ const c = norm(cwd);
168
+ if (![...checkouts].some((k) => c === k || c.startsWith(k + '/'))) continue;
169
+ found.push({ file, dir: path.join(dir, path.basename(f, '.jsonl')), cwd });
170
+ }
171
+ }
172
+ return found;
173
+ }
174
+
175
+ // ── pricing ──────────────────────────────────────────────────────────────────────────────
176
+
177
+ function rates(model, speed) {
178
+ let best = null;
179
+ for (const key of Object.keys(PRICES.models)) {
180
+ if (String(model || '').startsWith(key) && (!best || key.length > best.length)) best = key;
181
+ }
182
+ if (!best) return null;
183
+ const entry = PRICES.models[best];
184
+ return (speed === 'fast' && entry.fast) ? entry.fast : entry;
185
+ }
186
+
187
+ const emptyTokens = () => ({ input: 0, output: 0, cacheWrite5m: 0, cacheWrite1h: 0, cacheRead: 0 });
188
+
189
+ function addUsage(acc, usage, model, speed) {
190
+ // `<synthetic>` messages are harness-authored (API error notices, interrupt markers).
191
+ // They carry a usage block but cost nothing — billing them invents spend.
192
+ if (model === '<synthetic>') return;
193
+ const cc = usage.cache_creation || {};
194
+ let w5 = cc.ephemeral_5m_input_tokens || 0;
195
+ const w1 = cc.ephemeral_1h_input_tokens || 0;
196
+ // Older transcripts carry only the flat total with no TTL breakdown. Bill it as 5m —
197
+ // the cheaper of the two, so an unknown-TTL run under-reports rather than inflates.
198
+ if (!w5 && !w1) w5 = usage.cache_creation_input_tokens || 0;
199
+
200
+ const t = { input: usage.input_tokens || 0, output: usage.output_tokens || 0,
201
+ cacheWrite5m: w5, cacheWrite1h: w1, cacheRead: usage.cache_read_input_tokens || 0 };
202
+ for (const k of Object.keys(t)) acc.tokens[k] += t[k];
203
+
204
+ const r = rates(model, speed);
205
+ if (!r) { acc.unpriced.add(model || 'unknown'); return; }
206
+ const m = PRICES.multipliers;
207
+ acc.cost += (
208
+ t.input * r.input +
209
+ t.output * r.output +
210
+ t.cacheWrite5m * r.input * m.cacheWrite5m +
211
+ t.cacheWrite1h * r.input * m.cacheWrite1h +
212
+ t.cacheRead * r.input * m.cacheRead
213
+ ) / 1e6;
214
+
215
+ const byModel = acc.models[model] || (acc.models[model] = emptyTokens());
216
+ for (const k of Object.keys(t)) byModel[k] += t[k];
217
+ }
218
+
219
+ // ── transcript parsing ───────────────────────────────────────────────────────────────────
220
+
221
+ const userText = (msg) => {
222
+ const c = msg && msg.content;
223
+ if (typeof c === 'string') return c;
224
+ if (!Array.isArray(c)) return '';
225
+ return c.filter((b) => b && b.type === 'text').map((b) => b.text || '').join('\n');
226
+ };
227
+
228
+ const isToolResultTurn = (msg) =>
229
+ Array.isArray(msg && msg.content) && msg.content.some((b) => b && b.type === 'tool_result');
230
+
231
+ function newSegment(label, ts) {
232
+ return {
233
+ label, startTs: ts, endTs: ts,
234
+ tokens: emptyTokens(), cost: 0, models: {}, unpriced: new Set(),
235
+ activeS: 0, lastTs: ts, turns: 0, continuations: 0,
236
+ toolUseIds: new Set(), agents: [],
237
+ };
238
+ }
239
+
240
+ // One segment = one command invocation (or one free-form chat turn). Boundaries are user
241
+ // turns that are NOT tool results — a tool result is the harness feeding the loop, not the
242
+ // human starting something new.
243
+ function parseSession(file) {
244
+ const segments = [];
245
+ let seg = null;
246
+ const seenMessageIds = new Set();
247
+
248
+ let raw;
249
+ try { raw = fs.readFileSync(file, 'utf8'); } catch { return segments; }
250
+
251
+ for (const line of raw.split(/\r?\n/)) {
252
+ if (!line) continue;
253
+ let e;
254
+ try { e = JSON.parse(line); } catch { continue; }
255
+ const ts = e.timestamp ? Date.parse(e.timestamp) : NaN;
256
+
257
+ if (e.type === 'user') {
258
+ const msg = e.message || {};
259
+ if (isToolResultTurn(msg) || e.isMeta || e.isSidechain) continue;
260
+ const text = userText(msg);
261
+ const cmd = commandIn(text);
262
+ // Not every user-role turn is the human starting something. The harness injects
263
+ // turns mid-run — a local-command echo, and (critically for cohorte) a
264
+ // <task-notification> when a background agent finishes. Those arrive DURING a
265
+ // a /cohorte-build; treating them as boundaries chops one command into several
266
+ // cheap-looking fragments and strands the agent spend in the wrong segment.
267
+ if (!cmd && /<(local-command-(stdout|stderr)|task-notification|system-reminder)>/.test(text)) continue;
268
+ // A short steer with no command keeps the current run open rather than opening a new
269
+ // one — see CONTINUATION_MAX_CHARS.
270
+ if (!cmd && seg && text.trim().length <= CONTINUATION_MAX_CHARS) { seg.continuations += 1; continue; }
271
+ seg = newSegment(cmd ? '/' + cmd : '(chat)', ts);
272
+ segments.push(seg);
273
+ continue;
274
+ }
275
+
276
+ if (e.type !== 'assistant' || !seg) continue;
277
+ const msg = e.message || {};
278
+
279
+ // Dedupe: the same API response is written once per content block, each copy carrying
280
+ // the full usage. See header note 1 — this is the single biggest correctness trap.
281
+ const id = msg.id;
282
+ if (id && seenMessageIds.has(id)) {
283
+ for (const b of msg.content || []) if (b && b.type === 'tool_use' && b.id) seg.toolUseIds.add(b.id);
284
+ if (!Number.isNaN(ts)) seg.endTs = Math.max(seg.endTs, ts);
285
+ continue;
286
+ }
287
+ if (id) seenMessageIds.add(id);
288
+
289
+ if (msg.usage) addUsage(seg, msg.usage, msg.model, msg.usage.speed);
290
+ for (const b of msg.content || []) if (b && b.type === 'tool_use' && b.id) seg.toolUseIds.add(b.id);
291
+
292
+ seg.turns += 1;
293
+ if (!Number.isNaN(ts)) {
294
+ const gap = (ts - seg.lastTs) / 1000;
295
+ if (gap > 0 && gap <= IDLE_GAP_S) seg.activeS += gap;
296
+ seg.lastTs = ts;
297
+ seg.endTs = Math.max(seg.endTs, ts);
298
+ }
299
+ }
300
+ return segments;
301
+ }
302
+
303
+ // ── subagents ────────────────────────────────────────────────────────────────────────────
304
+
305
+ function readSubagents(sessionDir) {
306
+ const dir = path.join(sessionDir, 'subagents');
307
+ let files;
308
+ try { files = fs.readdirSync(dir); } catch { return []; }
309
+
310
+ const agents = [];
311
+ for (const f of files) {
312
+ if (!f.endsWith('.jsonl')) continue;
313
+ const base = f.slice(0, -'.jsonl'.length);
314
+ let meta = {};
315
+ try { meta = JSON.parse(fs.readFileSync(path.join(dir, base + '.meta.json'), 'utf8')); } catch {}
316
+
317
+ const acc = { tokens: emptyTokens(), cost: 0, models: {}, unpriced: new Set() };
318
+ let startTs = Infinity, endTs = -Infinity, turns = 0;
319
+ const seen = new Set();
320
+
321
+ let raw;
322
+ try { raw = fs.readFileSync(path.join(dir, f), 'utf8'); } catch { continue; }
323
+ for (const line of raw.split(/\r?\n/)) {
324
+ if (!line) continue;
325
+ let e;
326
+ try { e = JSON.parse(line); } catch { continue; }
327
+ if (e.type !== 'assistant') continue;
328
+ const msg = e.message || {};
329
+ if (msg.id && seen.has(msg.id)) continue;
330
+ if (msg.id) seen.add(msg.id);
331
+ if (msg.usage) addUsage(acc, msg.usage, msg.model, msg.usage.speed);
332
+ turns += 1;
333
+ const ts = e.timestamp ? Date.parse(e.timestamp) : NaN;
334
+ if (!Number.isNaN(ts)) { startTs = Math.min(startTs, ts); endTs = Math.max(endTs, ts); }
335
+ }
336
+
337
+ agents.push({
338
+ id: base.replace(/^agent-/, ''),
339
+ agentType: meta.agentType || 'unknown',
340
+ description: meta.description || '',
341
+ toolUseId: meta.toolUseId || null,
342
+ spawnDepth: meta.spawnDepth ?? null,
343
+ turns, startTs, endTs, ...acc,
344
+ });
345
+ }
346
+ return agents;
347
+ }
348
+
349
+ function attachAgents(segments, agents) {
350
+ for (const a of agents) {
351
+ // Preferred link: the Task/Agent tool_use that spawned it. Workflow-spawned agents can
352
+ // carry a toolUseId the parent transcript never recorded, so fall back to which segment
353
+ // was running when the agent started.
354
+ let seg = a.toolUseId ? segments.find((s) => s.toolUseIds.has(a.toolUseId)) : null;
355
+ if (!seg && Number.isFinite(a.startTs)) {
356
+ seg = segments.find((s) => a.startTs >= s.startTs && a.startTs <= s.endTs + 5 * 60_000);
357
+ }
358
+ if (!seg) continue;
359
+ seg.agents.push(a);
360
+ for (const k of Object.keys(seg.tokens)) seg.tokens[k] += a.tokens[k];
361
+ seg.cost += a.cost;
362
+ for (const [m, t] of Object.entries(a.models)) {
363
+ const dst = seg.models[m] || (seg.models[m] = emptyTokens());
364
+ for (const k of Object.keys(t)) dst[k] += t[k];
365
+ }
366
+ for (const m of a.unpriced) seg.unpriced.add(m);
367
+ if (Number.isFinite(a.endTs)) seg.endTs = Math.max(seg.endTs, a.endTs);
368
+ // Agents run in parallel, so their wall time is not additive and cannot be folded into
369
+ // the parent's `active`. Segment `wall` already covers them via endTs; agent runtime is
370
+ // reported separately per command as agentWallS.
371
+ }
372
+ }
373
+
374
+ // ── rollup ───────────────────────────────────────────────────────────────────────────────
375
+
376
+ const pct = (arr, p) => {
377
+ if (!arr.length) return 0;
378
+ const s = [...arr].sort((a, b) => a - b);
379
+ return s[Math.min(s.length - 1, Math.floor((p / 100) * s.length))];
380
+ };
381
+
382
+ function rollup(segments) {
383
+ const by = new Map();
384
+ for (const s of segments) {
385
+ let g = by.get(s.label);
386
+ if (!g) {
387
+ g = { command: s.label, runs: 0, continuations: 0, tokens: emptyTokens(), cost: 0, models: {},
388
+ wall: [], active: [], agentCounts: [], agentWall: [], turns: [], unpriced: new Set() };
389
+ by.set(s.label, g);
390
+ }
391
+ g.runs += 1;
392
+ g.continuations += s.continuations;
393
+ for (const k of Object.keys(s.tokens)) g.tokens[k] += s.tokens[k];
394
+ g.cost += s.cost;
395
+ for (const [m, t] of Object.entries(s.models)) {
396
+ const dst = g.models[m] || (g.models[m] = emptyTokens());
397
+ for (const k of Object.keys(t)) dst[k] += t[k];
398
+ }
399
+ for (const m of s.unpriced) g.unpriced.add(m);
400
+ g.wall.push(Math.max(0, (s.endTs - s.startTs) / 1000) || 0);
401
+ g.active.push(s.activeS);
402
+ g.turns.push(s.turns);
403
+ g.agentCounts.push(s.agents.length);
404
+ g.agentWall.push(s.agents.reduce((n, a) => n + (Number.isFinite(a.endTs) ? (a.endTs - a.startTs) / 1000 : 0), 0));
405
+ }
406
+
407
+ return [...by.values()]
408
+ .map((g) => ({
409
+ command: g.command,
410
+ runs: g.runs,
411
+ continuations: g.continuations,
412
+ cost: { total: g.cost, perRun: g.cost / g.runs },
413
+ tokens: g.tokens,
414
+ tokensPerRun: Object.fromEntries(Object.entries(g.tokens).map(([k, v]) => [k, Math.round(v / g.runs)])),
415
+ wallS: { p50: pct(g.wall, 50), p90: pct(g.wall, 90), total: g.wall.reduce((a, b) => a + b, 0) },
416
+ activeS: { p50: pct(g.active, 50), p90: pct(g.active, 90) },
417
+ agents: { perRunP50: pct(g.agentCounts, 50), total: g.agentCounts.reduce((a, b) => a + b, 0),
418
+ serialWallP50S: pct(g.agentWall, 50) },
419
+ turnsP50: pct(g.turns, 50),
420
+ models: g.models,
421
+ unpriced: [...g.unpriced],
422
+ }))
423
+ .sort((a, b) => b.cost.total - a.cost.total);
424
+ }
425
+
426
+ // ── output ───────────────────────────────────────────────────────────────────────────────
427
+
428
+ const fmtUsd = (n) => (n < 0.01 && n > 0 ? '<$0.01' : '$' + n.toFixed(2));
429
+ const fmtTok = (n) => (n >= 1e6 ? (n / 1e6).toFixed(1) + 'M' : n >= 1e3 ? Math.round(n / 1e3) + 'k' : String(n));
430
+ const fmtDur = (s) => (s >= 3600 ? (s / 3600).toFixed(1) + 'h' : s >= 60 ? Math.round(s / 60) + 'm' : Math.round(s) + 's');
431
+
432
+ function table(rows) {
433
+ const head = ['COMMAND', 'RUNS', '$/RUN', '$ TOTAL', 'TOK/RUN', 'OUT/RUN', 'WALL p50', 'ACTIVE p50', 'AGENTS p50'];
434
+ const body = rows.map((r) => [
435
+ r.command,
436
+ String(r.runs),
437
+ fmtUsd(r.cost.perRun),
438
+ fmtUsd(r.cost.total),
439
+ fmtTok(Object.values(r.tokensPerRun).reduce((a, b) => a + b, 0)),
440
+ fmtTok(r.tokensPerRun.output),
441
+ fmtDur(r.wallS.p50),
442
+ fmtDur(r.activeS.p50),
443
+ String(r.agents.perRunP50),
444
+ ]);
445
+ const w = head.map((h, i) => Math.max(h.length, ...body.map((b) => b[i].length)));
446
+ const line = (cells) => cells.map((c, i) => (i === 0 ? c.padEnd(w[i]) : c.padStart(w[i]))).join(' ');
447
+ return [line(head), w.map((n) => '-'.repeat(n)).join(' '), ...body.map(line)].join('\n');
448
+ }
449
+
450
+ // ── main ─────────────────────────────────────────────────────────────────────────────────
451
+
452
+ function main(argv) {
453
+ const args = argv.slice(2);
454
+ const flag = (name) => args.includes('--' + name);
455
+ const opt = (name) => {
456
+ const hit = args.find((a) => a.startsWith(`--${name}=`));
457
+ return hit ? hit.slice(name.length + 3) : null;
458
+ };
459
+ const root = path.resolve(args.find((a) => !a.startsWith('--')) || process.cwd());
460
+
461
+ // A malformed filter must fail loudly: NaN used to skip the filter, so `--days=abc`
462
+ // silently reported all time.
463
+ let since = null;
464
+ if (opt('since') !== null) {
465
+ since = Date.parse(opt('since'));
466
+ if (Number.isNaN(since)) { console.error(`error: --since=${opt('since')} is not a date (use ISO 8601, e.g. 2026-11-01)`); process.exit(2); }
467
+ }
468
+ if (opt('days') !== null) {
469
+ const days = Number(opt('days'));
470
+ if (!Number.isFinite(days) || days <= 0) { console.error(`error: --days=${opt('days')} must be a positive number`); process.exit(2); }
471
+ since = Date.now() - days * 86400_000;
472
+ }
473
+
474
+ const checkouts = repoCheckouts(root);
475
+ const sessions = findSessions(checkouts);
476
+
477
+ let segments = [];
478
+ for (const s of sessions) {
479
+ const segs = parseSession(s.file);
480
+ attachAgents(segs, readSubagents(s.dir));
481
+ segments.push(...segs);
482
+ }
483
+ if (since) segments = segments.filter((s) => s.startTs >= since);
484
+ // A segment with no API call is a typo or an interrupted prompt, not a run.
485
+ segments = segments.filter((s) => s.turns > 0);
486
+
487
+ const rows = rollup(segments);
488
+ const totals = {
489
+ sessions: sessions.length,
490
+ runs: segments.length,
491
+ cost: rows.reduce((n, r) => n + r.cost.total, 0),
492
+ agents: rows.reduce((n, r) => n + r.agents.total, 0),
493
+ };
494
+
495
+ // The headline figures as a Francois extension `stat-row` payload — four tiles, no
496
+ // table. Deliberately ahead of the --json branch: --panel is a shape, not a filter,
497
+ // and passing both should never print two documents.
498
+ // See github.com/TheBidouilleAgency/francois-plugin-cohorte.
499
+ if (flag('panel')) {
500
+ const window = opt('days') ? `last ${opt('days')} days` : since ? 'since ' + new Date(since).toISOString().slice(0, 10) : 'all time';
501
+ const top = rows[0];
502
+ process.stdout.write(JSON.stringify({ tiles: [
503
+ { label: 'Cost', value: fmtUsd(totals.cost), sublabel: window },
504
+ { label: 'Runs', value: String(totals.runs), sublabel: `${totals.sessions} sessions` },
505
+ { label: 'Subagents', value: String(totals.agents) },
506
+ ...(top ? [{ label: 'Priciest', value: top.command, sublabel: fmtUsd(top.cost.total) }] : []),
507
+ ] }) + '\n');
508
+ return 0;
509
+ }
510
+
511
+ if (flag('json')) {
512
+ const out = { generatedAt: new Date().toISOString(), projectRoot: root,
513
+ checkouts: [...checkouts], pricesUpdated: PRICES.updated, totals, commands: rows };
514
+ if (flag('runs')) {
515
+ out.runs = segments.map((s) => ({
516
+ command: s.label, startedAt: new Date(s.startTs).toISOString(),
517
+ wallS: Math.max(0, (s.endTs - s.startTs) / 1000), activeS: s.activeS,
518
+ turns: s.turns, continuations: s.continuations, cost: s.cost, tokens: s.tokens,
519
+ agents: s.agents.map((a) => ({ type: a.agentType, description: a.description,
520
+ cost: a.cost, tokens: a.tokens, turns: a.turns })),
521
+ }));
522
+ }
523
+ process.stdout.write(JSON.stringify(out, null, 2) + '\n');
524
+ return 0;
525
+ }
526
+
527
+ if (!sessions.length) {
528
+ console.log(`No Claude Code transcripts found for ${root} under ${projectsDir()}.`);
529
+ return 0;
530
+ }
531
+ console.log(`cohorte metrics — ${root}`);
532
+ console.log(`${totals.runs} runs across ${totals.sessions} sessions, ${totals.agents} subagents, ${fmtUsd(totals.cost)} total`
533
+ + (since ? ` (since ${new Date(since).toISOString().slice(0, 10)})` : ''));
534
+ console.log(`prices as of ${PRICES.updated}; wall excludes nothing, active drops gaps > ${IDLE_GAP_S}s\n`);
535
+ console.log(table(rows));
536
+
537
+ const unpriced = [...new Set(rows.flatMap((r) => r.unpriced))];
538
+ if (unpriced.length) console.log(`\nnot in prices.json (counted, not costed): ${unpriced.join(', ')}`);
539
+ return 0;
540
+ }
541
+
542
+ process.exit(main(process.argv));
@@ -0,0 +1,42 @@
1
+ {
2
+ "_comment": [
3
+ "USD per million tokens, Anthropic first-party API rates. Bedrock/Vertex are",
4
+ "partner-priced and are NOT covered here — a run on those platforms will be",
5
+ "costed at first-party rates and slightly misreported.",
6
+ "Cache rates are derived from `input` via `multipliers` (write 1.25x for the 5m",
7
+ "TTL, 2x for 1h, read 0.1x) rather than restated per model, so a price change",
8
+ "is a one-line edit. `fast` is the fast-mode premium (usage.speed === 'fast').",
9
+ "Model lookup is longest-prefix, so dated ids (claude-haiku-4-5-20251001) hit",
10
+ "their base entry without needing a row of their own.",
11
+ "Sonnet 5 is $2/$10: the introductory rate became the standard rate on 2026-08-20.",
12
+ "The $3/$15 increase once scheduled for 2026-09-01 was cancelled and must not",
13
+ "be reinstated. Sonnet 4.6 and earlier stay at $3/$15 — same tier, different price."
14
+ ],
15
+ "updated": "2026-08-22",
16
+ "multipliers": {
17
+ "cacheWrite5m": 1.25,
18
+ "cacheWrite1h": 2.0,
19
+ "cacheRead": 0.1
20
+ },
21
+ "models": {
22
+ "claude-fable-5": { "input": 10, "output": 50 },
23
+ "claude-mythos-5": { "input": 10, "output": 50 },
24
+ "claude-opus-5": {
25
+ "input": 5,
26
+ "output": 25,
27
+ "fast": { "input": 10, "output": 50 }
28
+ },
29
+ "claude-opus-4-8": {
30
+ "input": 5,
31
+ "output": 25,
32
+ "fast": { "input": 10, "output": 50 }
33
+ },
34
+ "claude-opus-4-7": { "input": 5, "output": 25 },
35
+ "claude-opus-4-6": { "input": 5, "output": 25 },
36
+ "claude-opus-4-5": { "input": 5, "output": 25 },
37
+ "claude-sonnet-5": { "input": 2, "output": 10 },
38
+ "claude-sonnet-4-6": { "input": 3, "output": 15 },
39
+ "claude-sonnet-4-5": { "input": 3, "output": 15 },
40
+ "claude-haiku-4-5": { "input": 1, "output": 5 }
41
+ }
42
+ }