@polymorphism-tech/morph-spec 10.12.1 → 11.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 (323) hide show
  1. package/CLAUDE.md +27 -57
  2. package/README.md +53 -338
  3. package/bin/morph-spec.js +22 -373
  4. package/docs/CHEATSHEET.md +37 -166
  5. package/docs/QUICKSTART.md +14 -74
  6. package/framework/CLAUDE.md +15 -26
  7. package/framework/MORPH.md +34 -101
  8. package/framework/agents.json +12 -9
  9. package/framework/commands/morph-apply.md +5 -5
  10. package/framework/commands/morph-infra.md +1 -1
  11. package/framework/docs/CLI.md +74 -886
  12. package/framework/evals/review-checklist.md +14 -14
  13. package/framework/hooks/README.md +21 -189
  14. package/framework/hooks/claude-code/core/README.md +2 -5
  15. package/framework/hooks/claude-code/core/conventional-commit.js +2 -2
  16. package/framework/hooks/claude-code/core/denylist.json +3 -3
  17. package/framework/hooks/claude-code/core/graph-refresh-kick.js +2 -2
  18. package/framework/hooks/claude-code/core/masked-exit.js +6 -6
  19. package/framework/hooks/claude-code/core/pre-bash-denylist.js +2 -2
  20. package/framework/hooks/claude-code/core/protect-spec-files.js +17 -61
  21. package/framework/hooks/claude-code/core/stack-changed.js +35 -0
  22. package/framework/hooks/claude-code/core/validate-completion.js +32 -87
  23. package/framework/hooks/shared/{heavy-command.js → command-kind.js} +6 -79
  24. package/framework/hooks/shared/command-tokens.js +0 -139
  25. package/framework/hooks/shared/contract.js +14 -0
  26. package/framework/hooks/shared/feature-slug.js +21 -0
  27. package/framework/hooks/shared/frontend-locations.js +0 -1
  28. package/framework/hooks/shared/git-paths.js +0 -15
  29. package/framework/hooks/shared/graph-freshness.js +0 -19
  30. package/framework/hooks/shared/hook-response.js +0 -7
  31. package/framework/hooks/shared/morph-cli.js +2 -81
  32. package/framework/hooks/shared/owner-words.js +2 -120
  33. package/framework/hooks/shared/payload-utils.js +0 -39
  34. package/framework/hooks/shared/report-progress.js +7 -101
  35. package/framework/hooks/statusline.js +16 -60
  36. package/framework/mcp/registry.json +2 -2
  37. package/framework/rules/ai-agents-standards.md +1 -1
  38. package/framework/rules/asaas-standards.md +1 -1
  39. package/framework/rules/ef-standards.md +1 -1
  40. package/framework/rules/gsap-standards.md +1 -1
  41. package/framework/rules/hangfire-standards.md +1 -1
  42. package/framework/rules/implement-report.md +3 -3
  43. package/framework/rules/neon-auth-standards.md +1 -1
  44. package/framework/rules/nextjs-standards.md +1 -1
  45. package/framework/rules/plan-grammar.md +15 -13
  46. package/framework/rules/resend-standards.md +1 -1
  47. package/framework/rules/ui-design.md +5 -1
  48. package/framework/schemas/config.schema.json +95 -310
  49. package/framework/skills/README.md +12 -32
  50. package/framework/skills/core/create-umbraco-lp/SKILL.md +1 -1
  51. package/framework/skills/core/migrate-lp-to-umbraco/SKILL.md +1 -1
  52. package/framework/skills/core/morph-apply/SKILL.md +21 -46
  53. package/framework/skills/core/morph-plan/SKILL.md +28 -63
  54. package/framework/skills/core/morph-uiux/SKILL.md +23 -25
  55. package/framework/{templates/docs/ui-mockups.md → skills/core/morph-uiux/references/mockups.md} +4 -4
  56. package/framework/standards/STANDARDS.json +10 -11
  57. package/framework/standards/STANDARDS.meta.json +1 -1
  58. package/framework/standards/ai-agents/evals-with-cache.md +18 -32
  59. package/framework/standards/ai-agents/observability-patterns.md +2 -2
  60. package/framework/standards/architecture/code-comments.md +2 -5
  61. package/framework/standards/architecture/engineering-lens.md +1 -1
  62. package/framework/standards/backend/dotnet/testing.md +4 -4
  63. package/framework/standards/frontend/nextjs/lint.md +24 -10
  64. package/framework/standards/frontend/nextjs/testing.md +2 -2
  65. package/framework/standards/infrastructure/docker/local-compose-isolation.md +14 -30
  66. package/framework/templates/CLAUDE.md.core.guide.md +2 -2
  67. package/framework/templates/README.md +1 -1
  68. package/framework/templates/REGISTRY.json +3 -33
  69. package/framework/templates/docs/plan.md +3 -2
  70. package/framework/templates/dotnet/ai-kit/README.md +2 -4
  71. package/framework/templates/dotnet/ai-kit/src/Morph.AiKit/Evals/EvalCacheMissException.cs +1 -1
  72. package/framework/templates/dotnet/ai-kit/src/Morph.AiKit/Evals/EvalFixture.cs +1 -1
  73. package/package.json +1 -2
  74. package/src/commands/graph/explain.js +2 -1
  75. package/src/commands/graph/status.js +2 -1
  76. package/src/commands/mcp/mcp-setup.js +1 -2
  77. package/src/commands/project/doctor.js +13 -342
  78. package/src/commands/project/env.js +21 -52
  79. package/src/commands/project/init-contract.js +47 -0
  80. package/src/commands/project/init.js +36 -66
  81. package/src/commands/project/stack-scan.js +1 -1
  82. package/src/commands/project/update.js +16 -53
  83. package/src/commands/validation/check.js +128 -0
  84. package/src/commands/validation/plan-check.js +41 -64
  85. package/src/commands/validation/prove-red.js +1 -1
  86. package/src/core/paths/output-schema.js +0 -22
  87. package/src/core/templates/template-renderer.js +0 -14
  88. package/src/lib/ai/ai-project-scan.js +1 -6
  89. package/src/lib/check/attempts.js +38 -0
  90. package/src/lib/check/signals.js +145 -0
  91. package/src/lib/config/project-config.js +13 -0
  92. package/src/lib/contract/apply.js +62 -0
  93. package/src/lib/contract/defaults.js +96 -0
  94. package/src/lib/contract/merge.js +79 -0
  95. package/src/lib/contract/ports.js +43 -0
  96. package/src/lib/contract/scan.js +102 -0
  97. package/src/lib/detectors/claude-config-detector.js +7 -0
  98. package/src/lib/{procs → detectors}/mcp-config.js +1 -37
  99. package/src/lib/diff/diff-lines.js +64 -0
  100. package/src/lib/generators/architecture-scanner.js +1 -1
  101. package/src/lib/generators/scaffold-generator.js +0 -7
  102. package/src/lib/git/default-branch.js +0 -122
  103. package/src/lib/graph/diff-tree.js +2 -1
  104. package/src/lib/graph/god-nodes.js +2 -1
  105. package/src/lib/graph/graphify-runtime.js +0 -1
  106. package/src/lib/graph/graphifyignore.js +1 -1
  107. package/src/lib/graph/sanitize.js +2 -8
  108. package/src/lib/installers/memory-installer.js +15 -30
  109. package/src/lib/installers/stack-sync.js +16 -9
  110. package/src/lib/plan/checks.js +20 -64
  111. package/src/lib/plan/media.js +1 -1
  112. package/src/lib/plan/plan-parser.js +5 -5
  113. package/src/lib/review-reports.js +3 -77
  114. package/src/lib/scan/worktree-dirs.js +3 -0
  115. package/src/lib/specs/adr-index.js +2 -2
  116. package/src/lib/stack/dotnet-build-ignores.js +10 -2
  117. package/src/lib/stack/stack-scan.js +2 -2
  118. package/src/lib/stack-filter.js +3 -2
  119. package/src/lib/tests-audit/audit.js +1 -1
  120. package/src/scripts/setup-infra.js +6 -59
  121. package/src/utils/agents-installer.js +13 -37
  122. package/src/utils/atomic-json.js +27 -0
  123. package/src/utils/file-copier.js +24 -24
  124. package/src/utils/hooks-installer.js +9 -107
  125. package/claude-plugin.json +0 -14
  126. package/framework/commands/morph-archive.md +0 -46
  127. package/framework/commands/morph-hotfix.md +0 -17
  128. package/framework/commands/morph-preflight.md +0 -180
  129. package/framework/commands/morph-review.md +0 -15
  130. package/framework/commands/morph-status.md +0 -37
  131. package/framework/hooks/claude-code/core/block-destructive-worktree-removal.js +0 -80
  132. package/framework/hooks/claude-code/core/block-raw-worktree-add.js +0 -72
  133. package/framework/hooks/claude-code/core/enforce-phase-writes.js +0 -100
  134. package/framework/hooks/claude-code/core/gate-guard.js +0 -148
  135. package/framework/hooks/claude-code/core/heavy-gate.js +0 -78
  136. package/framework/hooks/claude-code/core/heavy-release.js +0 -23
  137. package/framework/hooks/claude-code/core/loop-detect.js +0 -79
  138. package/framework/hooks/claude-code/core/state-sync.js +0 -214
  139. package/framework/hooks/claude-code/core/telemetry-log.js +0 -259
  140. package/framework/hooks/claude-code/core/test-budget.js +0 -29
  141. package/framework/hooks/claude-code/core/worktree-context.js +0 -249
  142. package/framework/hooks/claude-code/core/worktree-create.js +0 -119
  143. package/framework/hooks/claude-code/core/worktree-env-inject.js +0 -68
  144. package/framework/hooks/claude-code/core/worktree-remove.js +0 -55
  145. package/framework/hooks/shared/build-check.js +0 -120
  146. package/framework/hooks/shared/claim-registry.js +0 -125
  147. package/framework/hooks/shared/e2e-check.js +0 -1022
  148. package/framework/hooks/shared/feature-locator.js +0 -82
  149. package/framework/hooks/shared/gate-event.js +0 -18
  150. package/framework/hooks/shared/gate-question.js +0 -20
  151. package/framework/hooks/shared/heavy-config.js +0 -113
  152. package/framework/hooks/shared/heavy-holders.js +0 -85
  153. package/framework/hooks/shared/heavy-slots.js +0 -280
  154. package/framework/hooks/shared/host-services.js +0 -440
  155. package/framework/hooks/shared/next-step.js +0 -181
  156. package/framework/hooks/shared/redact-secrets.js +0 -44
  157. package/framework/hooks/shared/reparse-scan.js +0 -40
  158. package/framework/hooks/shared/state-reader.js +0 -220
  159. package/framework/hooks/shared/state-writer.js +0 -112
  160. package/framework/hooks/shared/telemetry-logger.js +0 -101
  161. package/framework/hooks/shared/transcript-usage.js +0 -58
  162. package/framework/hooks/shared/worktree-root.js +0 -71
  163. package/framework/phases.json +0 -92
  164. package/framework/schemas/feature.schema.json +0 -242
  165. package/framework/skills/core/morph-apply/references/hotfix.md +0 -46
  166. package/framework/skills/core/morph-apply/references/machine.md +0 -30
  167. package/framework/skills/core/morph-apply/references/review.md +0 -77
  168. package/framework/skills/core/morph-plan/references/critique.md +0 -51
  169. package/framework/skills/core/morph-plan/references/interview.md +0 -37
  170. package/framework/templates/state.template.json +0 -17
  171. package/src/commands/dashboard/dashboard.js +0 -74
  172. package/src/commands/e2e/e2e.js +0 -400
  173. package/src/commands/observability/cost.js +0 -283
  174. package/src/commands/project/branch.js +0 -129
  175. package/src/commands/project/claim.js +0 -132
  176. package/src/commands/project/doctor-procs.js +0 -162
  177. package/src/commands/project/fleet.js +0 -66
  178. package/src/commands/project/heavy.js +0 -81
  179. package/src/commands/project/install-plugin-cmd.js +0 -27
  180. package/src/commands/project/status.js +0 -61
  181. package/src/commands/project/worktree.js +0 -1234
  182. package/src/commands/state/advance.js +0 -248
  183. package/src/commands/state/approve.js +0 -303
  184. package/src/commands/state/archive.js +0 -231
  185. package/src/commands/state/auto-approval.js +0 -67
  186. package/src/commands/state/create.js +0 -274
  187. package/src/commands/state/delete.js +0 -192
  188. package/src/commands/state/finish.js +0 -1247
  189. package/src/commands/state/gate-check.js +0 -244
  190. package/src/commands/state/gate-decision.js +0 -122
  191. package/src/commands/state/list.js +0 -244
  192. package/src/commands/state/next.js +0 -24
  193. package/src/commands/state/recap.js +0 -80
  194. package/src/commands/state/report-check.js +0 -244
  195. package/src/commands/state/retype.js +0 -110
  196. package/src/commands/validation/verify.js +0 -421
  197. package/src/core/state/feature-identity.js +0 -10
  198. package/src/core/state/gate-order.js +0 -23
  199. package/src/core/state/lifecycle-audit.js +0 -171
  200. package/src/core/state/state-manager.js +0 -523
  201. package/src/core/templates/template-seed.js +0 -21
  202. package/src/core/work-types.js +0 -44
  203. package/src/dashboard/app/App.jsx +0 -84
  204. package/src/dashboard/app/components/ActivityFeed.jsx +0 -166
  205. package/src/dashboard/app/components/CommandPalette.jsx +0 -144
  206. package/src/dashboard/app/components/DetailPanel.jsx +0 -43
  207. package/src/dashboard/app/components/EntityLink.jsx +0 -42
  208. package/src/dashboard/app/components/ErrorBoundary.jsx +0 -47
  209. package/src/dashboard/app/components/FlowGraph.jsx +0 -19
  210. package/src/dashboard/app/components/GatePauses.jsx +0 -116
  211. package/src/dashboard/app/components/KnowledgeMarkdown.jsx +0 -42
  212. package/src/dashboard/app/components/Markdown.jsx +0 -38
  213. package/src/dashboard/app/components/PhaseRail.jsx +0 -100
  214. package/src/dashboard/app/components/SearchFilter.jsx +0 -36
  215. package/src/dashboard/app/components/SessionMap.jsx +0 -77
  216. package/src/dashboard/app/components/Sidebar.jsx +0 -147
  217. package/src/dashboard/app/hooks/useMorphQuery.js +0 -44
  218. package/src/dashboard/app/hooks/usePref.js +0 -34
  219. package/src/dashboard/app/lib/format.js +0 -69
  220. package/src/dashboard/app/lib/phases.js +0 -75
  221. package/src/dashboard/app/lib/project.js +0 -38
  222. package/src/dashboard/app/main.jsx +0 -13
  223. package/src/dashboard/app/pages/Activity.jsx +0 -28
  224. package/src/dashboard/app/pages/AgentMap.jsx +0 -363
  225. package/src/dashboard/app/pages/FeatureDetail.jsx +0 -579
  226. package/src/dashboard/app/pages/Features.jsx +0 -393
  227. package/src/dashboard/app/pages/Guide.jsx +0 -145
  228. package/src/dashboard/app/pages/HookInspector.jsx +0 -444
  229. package/src/dashboard/app/pages/PhasePipeline.jsx +0 -273
  230. package/src/dashboard/app/pages/Portfolio.jsx +0 -190
  231. package/src/dashboard/app/pages/RulesMap.jsx +0 -285
  232. package/src/dashboard/app/pages/SkillsLibrary.jsx +0 -468
  233. package/src/dashboard/app/pages/Standards.jsx +0 -392
  234. package/src/dashboard/app/styles/index.css +0 -187
  235. package/src/dashboard/index.html +0 -14
  236. package/src/dashboard/package.json +0 -32
  237. package/src/dashboard/scanner/activity-scanner.js +0 -321
  238. package/src/dashboard/scanner/agents-scanner.js +0 -67
  239. package/src/dashboard/scanner/docs-scanner.js +0 -34
  240. package/src/dashboard/scanner/feature-status.js +0 -7
  241. package/src/dashboard/scanner/features-scanner.js +0 -397
  242. package/src/dashboard/scanner/hooks-scanner.js +0 -96
  243. package/src/dashboard/scanner/index.js +0 -21
  244. package/src/dashboard/scanner/phases-scanner.js +0 -14
  245. package/src/dashboard/scanner/portfolio.js +0 -129
  246. package/src/dashboard/scanner/project-api.js +0 -160
  247. package/src/dashboard/scanner/rules-scanner.js +0 -46
  248. package/src/dashboard/scanner/skills-scanner.js +0 -104
  249. package/src/dashboard/scanner/standards-scanner.js +0 -38
  250. package/src/dashboard/vite-plugin-morph-data.js +0 -120
  251. package/src/dashboard/vite.config.js +0 -26
  252. package/src/lib/ci/ci-verify.js +0 -30
  253. package/src/lib/ci/github-ci.js +0 -52
  254. package/src/lib/ci/pr-checks.js +0 -76
  255. package/src/lib/e2e/applicability.js +0 -39
  256. package/src/lib/e2e/compose-env.js +0 -80
  257. package/src/lib/e2e/stack-teardown.js +0 -96
  258. package/src/lib/git/branch-classifier.js +0 -104
  259. package/src/lib/git/evidence-staleness.js +0 -40
  260. package/src/lib/git/gh.js +0 -15
  261. package/src/lib/git/pending-prs.js +0 -58
  262. package/src/lib/git/pr-files.js +0 -31
  263. package/src/lib/git/pr-index.js +0 -39
  264. package/src/lib/git/tree-fingerprint.js +0 -58
  265. package/src/lib/git/tree-state.js +0 -125
  266. package/src/lib/heavy/cleanup.js +0 -72
  267. package/src/lib/heavy/gate.js +0 -168
  268. package/src/lib/heavy/live-stacks.js +0 -64
  269. package/src/lib/heavy/reclaim.js +0 -107
  270. package/src/lib/heavy/watchdog.js +0 -46
  271. package/src/lib/next-step.js +0 -12
  272. package/src/lib/plan/critique.js +0 -67
  273. package/src/lib/plan/plan-template.js +0 -18
  274. package/src/lib/procs/classify.js +0 -91
  275. package/src/lib/procs/list.js +0 -124
  276. package/src/lib/procs/prune.js +0 -47
  277. package/src/lib/procs/wslconfig.js +0 -70
  278. package/src/lib/projects/registry.js +0 -121
  279. package/src/lib/recap/piper.js +0 -36
  280. package/src/lib/recap/recap.js +0 -259
  281. package/src/lib/review-confirmation.js +0 -66
  282. package/src/lib/risk/diff-risk.js +0 -137
  283. package/src/lib/risk-detector.js +0 -638
  284. package/src/lib/specs/design-seed.js +0 -18
  285. package/src/lib/specs/screen-checklist.js +0 -315
  286. package/src/lib/stack/stack-profile.js +0 -69
  287. package/src/lib/tasks/eval-node.js +0 -293
  288. package/src/lib/tasks/linux-runner.js +0 -200
  289. package/src/lib/tasks/test-nodes.js +0 -414
  290. package/src/lib/tasks/test-runner.js +0 -569
  291. package/src/lib/telemetry/metrics.js +0 -384
  292. package/src/lib/telemetry/telemetry-reader.js +0 -276
  293. package/src/lib/telemetry/verify-event.js +0 -57
  294. package/src/lib/validators/code-budget/code-budget-validator.js +0 -170
  295. package/src/lib/validators/contracts/contract-compliance-validator.js +0 -219
  296. package/src/lib/validators/nextjs/next-component-validator.js +0 -142
  297. package/src/lib/validators/packages/package-validator.js +0 -310
  298. package/src/lib/validators/reuse/reuse-validator.js +0 -202
  299. package/src/lib/validators/reuse/symbol-scanner.js +0 -64
  300. package/src/lib/validators/validation-runner.js +0 -188
  301. package/src/lib/validators/verify-cache.js +0 -63
  302. package/src/lib/validators/verify-runner.js +0 -971
  303. package/src/lib/verify/affected.js +0 -143
  304. package/src/lib/verify/detached.js +0 -159
  305. package/src/lib/view/feature-html.js +0 -480
  306. package/src/lib/view/feature-page.client.js +0 -109
  307. package/src/lib/view/feature-page.css +0 -278
  308. package/src/lib/view/feature-view.js +0 -113
  309. package/src/lib/view/flow-layers.js +0 -79
  310. package/src/lib/view/flow-svg.js +0 -63
  311. package/src/lib/view/tokens.css +0 -18
  312. package/src/lib/work-type-detector.js +0 -81
  313. package/src/lib/worktree/dirs.js +0 -3
  314. package/src/lib/worktree/docker-audit.js +0 -175
  315. package/src/lib/worktree/env-allocator.js +0 -177
  316. package/src/lib/worktree/feature-truth.js +0 -145
  317. package/src/lib/worktree/finish-backup.js +0 -529
  318. package/src/lib/worktree/fleet-scanner.js +0 -223
  319. package/src/lib/worktree/ignored-triage.js +0 -136
  320. package/src/lib/worktree/vscode-settings.js +0 -112
  321. package/src/lib/worktree/worktree-audit.js +0 -323
  322. package/src/lib/worktree/worktree-include.js +0 -44
  323. package/src/scripts/install-plugin.js +0 -114
@@ -1,384 +0,0 @@
1
- // Every number degrades to null when the stream lacks its field: a v1 event never counts as a zero.
2
- // A rerun is the same producer command (before the output filter) in the same feature within 10 minutes.
3
-
4
- import { ingestedBytes } from './telemetry-reader.js';
5
- import { producerOf } from '../../../framework/hooks/shared/command-tokens.js';
6
- import { isFailedToolCall } from '../../../framework/hooks/shared/telemetry-logger.js';
7
- import { GATE_EVENT, GATE_STEPS } from '../../../framework/hooks/shared/gate-event.js';
8
- import { QUEUE_FULL_EXIT, REVIEW_AGENT_TYPES, morphVerifyCall, testRunKind } from '../../../framework/hooks/shared/heavy-command.js';
9
-
10
- export const RERUN_WINDOW_MS = 10 * 60 * 1000;
11
-
12
- const RERUN_CLASSES = new Set(['test', 'build', 'verify']);
13
- const READ_ONLY = new Set(['grep', 'rg', 'sed', 'ls', 'cat', 'find', 'head', 'tail', 'wc', 'tree', 'awk']);
14
- const TOOL_EVENTS = new Set(['PostToolUse', 'PostToolUseFailure']);
15
- const NO_FEATURE = '\u0000';
16
-
17
- // `morph-spec verify` inside a commit message is not a verify run.
18
- function executedText(command) {
19
- const beforeHeredoc = command.split('<<', 1)[0];
20
- return beforeHeredoc.replace(/"(?:[^"\\]|\\.)*"|'[^']*'/g, (q) => q[0] + ' '.repeat(q.length - 2) + q[0]);
21
- }
22
-
23
- /** Searched anywhere in the command, most specific first, so `cd x && dotnet test` is a test. */
24
- export function classifyCommand(command) {
25
- const cmd = String(command || '');
26
- if (/\bmorph-spec(?:\.js)?\s+verify\s+[^\s;&|)]+/.test(executedText(cmd))) return { kind: 'verify', klass: 'verify' };
27
- if (/\bdotnet\s+test\b/.test(cmd)) {
28
- if (/--list-tests\b/.test(cmd)) return { kind: 'dotnet-test-list', klass: 'test' };
29
- return { kind: /--filter\b/.test(cmd) ? 'dotnet-test-filtered' : 'dotnet-test-full', klass: 'test' };
30
- }
31
- if (/\b(?:(?:npm|pnpm|yarn)\s+(?:run\s+)?test|vitest|jest|node\s+--test|run-tests\.mjs)\b/.test(cmd)) {
32
- return { kind: 'js-test', klass: 'test' };
33
- }
34
- if (/\b(?:dotnet\s+build|(?:npm|pnpm|yarn)\s+(?:run\s+)?build|next\s+build|tsc)\b/.test(cmd)) {
35
- return { kind: 'build', klass: 'build' };
36
- }
37
- if (/\b(?:morph-spec\s+e2e|playwright\s+test|docker\s+compose\s+up)\b/.test(cmd)) return { kind: 'e2e', klass: 'e2e' };
38
- const git = /\bgit\s+(?:-C\s+(?:"[^"]*"|\S+)\s+)?([a-z][a-z-]*)/.exec(cmd);
39
- if (git) return { kind: `git-${git[1]}`, klass: 'git' };
40
- const morph = /\bmorph-spec\s+([a-z][a-z-]*)/.exec(cmd);
41
- if (morph) return { kind: `morph-spec-${morph[1]}`, klass: 'morph-spec' };
42
- const first = cmd.trim().split(/\s+/, 1)[0];
43
- if (READ_ONLY.has(first)) return { kind: first, klass: 'read' };
44
- return { kind: 'other', klass: 'other' };
45
- }
46
-
47
- /** `git status` and `git diff` occurrences — `git status && git diff` is two calls. */
48
- function gitCalls(command) {
49
- const text = executedText(String(command || ''));
50
- const count = (sub) => (text.match(new RegExp(`\\bgit\\s+(?:-C\\s+(?:"[^"]*"|\\S+)\\s+)?${sub}\\b`, 'g')) || []).length;
51
- return { status: count('status'), diff: count('diff') };
52
- }
53
-
54
- function median(values) {
55
- const v = values.filter((x) => Number.isFinite(x)).sort((a, b) => a - b);
56
- if (!v.length) return null;
57
- const mid = Math.floor(v.length / 2);
58
- return v.length % 2 ? v[mid] : (v[mid - 1] + v[mid]) / 2;
59
- }
60
-
61
- function rate(part, whole) {
62
- return whole ? Math.round((part / whole) * 1000) / 1000 : null;
63
- }
64
-
65
- function isV2(e) {
66
- return Number.isInteger(e.schemaVersion) && e.schemaVersion >= 2;
67
- }
68
-
69
- function whoOf(e) {
70
- if (e.agentId) return 'subagent';
71
- return isV2(e) ? 'orchestrator' : 'unknown';
72
- }
73
-
74
- function newCounters() {
75
- return {
76
- toolCalls: { total: 0, orchestrator: 0, subagent: 0, unknown: 0 },
77
- turns: { total: 0, orchestrator: 0, subagent: 0, unknown: 0 },
78
- timeByClass: {},
79
- reruns: { runs: 0, reruns: 0, inBursts: 0 },
80
- git: { status: 0, diff: 0 },
81
- reads: { reads: 0, bytes: 0, redundantBytes: 0, windowed: 0 },
82
- };
83
- }
84
-
85
- const newTimeSlot = () => ({ runs: 0, measuredMs: 0, unmeasured: 0 });
86
-
87
- function addRun(slot, durationMs) {
88
- slot.runs += 1;
89
- if (Number.isFinite(durationMs)) slot.measuredMs += durationMs;
90
- else slot.unmeasured += 1;
91
- }
92
-
93
- // `agent_type` carries the dispatch name when one is given (`ver-c`, `gate3-motor`), not the persona,
94
- // so the metric also reads Gate 3 names; `byPersona` is the part the test-budget hook recognizes.
95
- const REVIEW_NAME = /^(?:ver|rev|sec|g3|gate3|eval|review|reviewer|security)\d*-/;
96
- const isReviewAgent = (type) => REVIEW_AGENT_TYPES.has(type) || type === 'morph-evaluator' || REVIEW_NAME.test(String(type ?? ''));
97
-
98
- // A run refused by the full heavy queue ran no test.
99
- function testOutsideVerify(bashEvents) {
100
- const out = { total: newTimeSlot(), reviewTests: { ...newTimeSlot(), byPersona: newTimeSlot() } };
101
- for (const e of bashEvents) {
102
- if (e.event === 'PostToolUseFailure' && e.exitCode === QUEUE_FULL_EXIT) continue;
103
- if (!morphVerifyCall(e.command) && !testRunKind(e.command)) continue;
104
- addRun(out.total, e.durationMs);
105
- if (!e.agentId || !isReviewAgent(e.agentType)) continue;
106
- addRun(out.reviewTests, e.durationMs);
107
- if (REVIEW_AGENT_TYPES.has(e.agentType)) addRun(out.reviewTests.byPersona, e.durationMs);
108
- }
109
- return out;
110
- }
111
-
112
- function finishCounters(c, turnsObserved) {
113
- return {
114
- toolCalls: c.toolCalls,
115
- turns: turnsObserved ? c.turns : null,
116
- timeByClass: c.timeByClass,
117
- reruns: { ...c.reruns, rate: rate(c.reruns.reruns, c.reruns.runs), burstRate: rate(c.reruns.inBursts, c.reruns.runs) },
118
- git: c.git,
119
- rereads: { ...c.reads, rate: rate(c.reads.redundantBytes, c.reads.bytes) },
120
- };
121
- }
122
-
123
- // Edits in between and a changed output filter need no exit code; the pass/fail split does, so a masked
124
- // or v1 exit code falls back to "after an edit or not".
125
- function rerunClass(prev, current, editsBetween) {
126
- if (isV2(prev) && prev.outcome === 'timeout') return 'timeout';
127
- if (editsBetween === 0 && prev.command !== current.command) return 'refilter';
128
- if (!isV2(prev) || !isV2(current) || prev.exitMasked || current.exitMasked) {
129
- return editsBetween > 0 ? 'unknown-after-edit' : 'unknown-no-edit';
130
- }
131
- const prevFailed = prev.outcome === 'error' || (Number.isInteger(prev.exitCode) && prev.exitCode !== 0);
132
- const nowFailed = current.outcome === 'error' || (Number.isInteger(current.exitCode) && current.exitCode !== 0);
133
- if (prevFailed) {
134
- if (editsBetween > 0) return 'fix-loop';
135
- return nowFailed ? 'retry' : 'flake';
136
- }
137
- return editsBetween > 0 ? 're-verify' : 'redundant';
138
- }
139
-
140
- function reuseStateOf(e) {
141
- const skipped = (e.nodes?.validators?.skipped || []).find((s) => s?.validator === 'reuse');
142
- if (skipped) return { state: 'skipped', reason: skipped.reason || null };
143
- if ((e.nodes?.validators?.ran || []).includes('reuse')) return { state: 'ran', reason: null };
144
- return { state: 'absent', reason: null };
145
- }
146
-
147
- const newGateSlot = () => ({ decisions: 0, paused: 0, pausedForHuman: 0, pausedUnattributed: 0, autoPassed: 0, approvedAfterPause: 0, reworkedAfterPause: 0, unapproved: 0, bySignal: {} });
148
-
149
- // A pause stays open until the next approve or a decision that no longer pauses on the same signal:
150
- // re-running gate-check over the same unchanged pause is not rework.
151
- function trackGate(gates, open, e) {
152
- if (!e.gate || !GATE_STEPS.includes(e.step)) return;
153
- const slot = gates[e.gate] ||= newGateSlot();
154
- const key = `${e.feature || ''}\u0000${e.gate}`;
155
- const pending = open.get(key);
156
- const bySignal = (signal) => slot.bySignal[signal || 'desconhecido'] ||= { paused: 0, pausedForHuman: 0, pausedUnattributed: 0, approvedAfterPause: 0, reworkedAfterPause: 0 };
157
- const credit = (field) => {
158
- slot[field] += 1;
159
- bySignal(pending.signal)[field] += 1;
160
- };
161
-
162
- if (e.step === 'unapprove') {
163
- slot.unapproved += 1;
164
- return;
165
- }
166
- if (e.step === 'approve') {
167
- if (pending) credit('approvedAfterPause');
168
- open.delete(key);
169
- return;
170
- }
171
- slot.decisions += 1;
172
- const resolver = e.resolver ?? 'human';
173
- if (pending && e.pause && e.signal === pending.signal) {
174
- // Same signal, new owner: the session ran out of attempts and the pause escalated to the human.
175
- if (pending.resolver === 'session' && resolver === 'human') {
176
- slot.pausedForHuman += 1;
177
- bySignal(pending.signal).pausedForHuman += 1;
178
- }
179
- pending.resolver = resolver;
180
- return;
181
- }
182
- if (pending) credit(e.source === 'manual' && !e.pause ? 'approvedAfterPause' : 'reworkedAfterPause');
183
- if (e.pause) {
184
- slot.paused += 1;
185
- bySignal(e.signal).paused += 1;
186
- if (resolver === 'human') {
187
- slot.pausedForHuman += 1;
188
- bySignal(e.signal).pausedForHuman += 1;
189
- }
190
- // Written before the resolver existed: counted as human above, but nobody recorded who cleared it.
191
- if (e.resolver === undefined) {
192
- slot.pausedUnattributed += 1;
193
- bySignal(e.signal).pausedUnattributed += 1;
194
- }
195
- open.set(key, { signal: e.signal, resolver });
196
- } else {
197
- slot.autoPassed += 1;
198
- open.delete(key);
199
- }
200
- }
201
-
202
- /** The returned shape is documented in framework/docs/CLI.md, "cost --metrics". */
203
- export function computeMetrics(events, opts = {}) {
204
- const top = Number.isInteger(opts.top) && opts.top > 0 ? opts.top : 10;
205
- const scoped = (events || []).filter((e) => e && typeof e === 'object' && (!opts.feature || e.feature === opts.feature));
206
-
207
- const global = newCounters();
208
- const byFeature = new Map();
209
- const lastRun = new Map();
210
- const editCount = new Map();
211
- const readsSeen = new Set();
212
- const files = new Map();
213
- const rerunClasses = {};
214
- const rerunByKind = {};
215
- const verifyByFeature = {};
216
- const fullSuite = { runs: 0, withBuild: 0, byPhase: {} };
217
- const lastFingerprint = new Map();
218
- const unchangedRepeats = {};
219
- const reuse = { runs: 0, byTree: {}, skipReasons: {} };
220
- const gates = {};
221
- const openPauses = new Map();
222
- const testBash = [];
223
- let v2 = 0;
224
- let legacy = 0;
225
- let turnsObserved = false;
226
- let from = null;
227
- let to = null;
228
-
229
- const featureCounters = (key) => {
230
- if (!byFeature.has(key)) byFeature.set(key, newCounters());
231
- return byFeature.get(key);
232
- };
233
- for (const e of scoped) {
234
- if (isV2(e)) v2 += 1; else legacy += 1;
235
- if (e.ts) {
236
- from ??= e.ts;
237
- to = e.ts;
238
- }
239
- const fkey = e.feature || NO_FEATURE;
240
-
241
- const sinks = [global, featureCounters(fkey)];
242
-
243
- if (e.event === 'ToolBatch') {
244
- turnsObserved = true;
245
- for (const c of sinks) { c.turns.total += 1; c.turns[whoOf(e)] += 1; }
246
- continue;
247
- }
248
-
249
- if (e.event === GATE_EVENT) {
250
- trackGate(gates, openPauses, e);
251
- continue;
252
- }
253
-
254
- if (e.event === 'Verify') {
255
- if (e.fingerprint && e.persisted !== false) {
256
- if (lastFingerprint.get(fkey) === e.fingerprint) {
257
- unchangedRepeats[e.feature || '(sem feature)'] = (unchangedRepeats[e.feature || '(sem feature)'] || 0) + 1;
258
- }
259
- lastFingerprint.set(fkey, e.fingerprint);
260
- }
261
- reuse.runs += 1;
262
- const tree = e.tree || 'unknown';
263
- const { state, reason } = reuseStateOf(e);
264
- const slot = reuse.byTree[tree] ||= { ran: 0, skipped: 0, absent: 0 };
265
- slot[state] += 1;
266
- if (reason) reuse.skipReasons[reason] = (reuse.skipReasons[reason] || 0) + 1;
267
- continue;
268
- }
269
-
270
- if (!TOOL_EVENTS.has(e.event) || !e.tool) continue;
271
- for (const c of sinks) { c.toolCalls.total += 1; c.toolCalls[whoOf(e)] += 1; }
272
-
273
- if (e.tool === 'Write' || e.tool === 'Edit') {
274
- if (!isFailedToolCall(e)) editCount.set(fkey, (editCount.get(fkey) || 0) + 1);
275
- continue;
276
- }
277
-
278
- if (e.tool === 'Read') {
279
- const bytes = ingestedBytes(e);
280
- if (bytes === null || !e.target) continue;
281
- const window = `${fkey}\u0000${e.target}\u0000${e.offset || 1}\u0000${e.limit || 0}`;
282
- const redundant = readsSeen.has(window) ? bytes : 0;
283
- readsSeen.add(window);
284
- for (const c of sinks) {
285
- c.reads.reads += 1;
286
- c.reads.bytes += bytes;
287
- c.reads.redundantBytes += redundant;
288
- if (Number.isFinite(e.bytesRead)) c.reads.windowed += 1;
289
- }
290
- const fileKey = `${fkey}\u0000${e.target}`;
291
- const file = files.get(fileKey) || { feature: e.feature ?? null, file: e.target, reads: 0, bytes: 0, redundantBytes: 0 };
292
- file.reads += 1;
293
- file.bytes += bytes;
294
- file.redundantBytes += redundant;
295
- files.set(fileKey, file);
296
- continue;
297
- }
298
-
299
- if (e.tool !== 'Bash' && e.tool !== 'PowerShell') continue;
300
- if (e.tool === 'Bash' && typeof e.command === 'string') testBash.push(e);
301
- const { kind, klass } = classifyCommand(e.command);
302
- const git = gitCalls(e.command);
303
- for (const c of sinks) {
304
- addRun(c.timeByClass[klass] ||= newTimeSlot(), e.durationMs);
305
- c.git.status += git.status;
306
- c.git.diff += git.diff;
307
- }
308
-
309
- if (kind === 'dotnet-test-full') {
310
- const rebuilds = !/--no-build\b/.test(e.command);
311
- const phase = fullSuite.byPhase[e.phase || '-'] ||= { runs: 0, withBuild: 0 };
312
- fullSuite.runs += 1;
313
- phase.runs += 1;
314
- if (rebuilds) { fullSuite.withBuild += 1; phase.withBuild += 1; }
315
- }
316
-
317
- if (klass === 'verify') {
318
- const name = e.feature || '(sem feature)';
319
- verifyByFeature[name] = (verifyByFeature[name] || 0) + 1;
320
- }
321
-
322
- if (!RERUN_CLASSES.has(klass) || typeof e.command !== 'string') continue;
323
- const runKey = `${fkey}\u0000${producerOf(e.command)}`;
324
- const prev = lastRun.get(runKey);
325
- const edits = editCount.get(fkey) || 0;
326
- const t = Date.parse(e.ts ?? '');
327
- const isRerun = Boolean(prev) && Number.isFinite(t) && t - prev.t <= RERUN_WINDOW_MS;
328
- const kindSlot = rerunByKind[kind] ||= { runs: 0, reruns: 0, inBursts: 0 };
329
- kindSlot.runs += 1;
330
- for (const c of sinks) c.reruns.runs += 1;
331
- const run = { t: Number.isFinite(t) ? t : 0, edits, event: e, sinks, kindSlot, inBurst: false };
332
- if (isRerun) {
333
- kindSlot.reruns += 1;
334
- for (const c of sinks) c.reruns.reruns += 1;
335
- // A burst counts its first run too; that one is only known once the
336
- // second arrives, so it is credited to where it ran, late.
337
- for (const r of prev.inBurst ? [run] : [prev, run]) {
338
- r.inBurst = true;
339
- r.kindSlot.inBursts += 1;
340
- for (const c of r.sinks) c.reruns.inBursts += 1;
341
- }
342
- const why = rerunClass(prev.event, e, edits - prev.edits);
343
- rerunClasses[why] = (rerunClasses[why] || 0) + 1;
344
- }
345
- lastRun.set(runKey, run);
346
- }
347
-
348
- const featureRows = [...byFeature.entries()]
349
- .filter(([key]) => key !== NO_FEATURE)
350
- .map(([feature, c]) => ({
351
- feature,
352
- ...finishCounters(c, turnsObserved),
353
- verify: verifyByFeature[feature] || 0,
354
- }))
355
- .sort((a, b) => b.toolCalls.total - a.toolCalls.total || a.feature.localeCompare(b.feature));
356
-
357
- const byKind = {};
358
- for (const [kind, slot] of Object.entries(rerunByKind)) {
359
- byKind[kind] = { ...slot, rate: rate(slot.reruns, slot.runs), burstRate: rate(slot.inBursts, slot.runs) };
360
- }
361
-
362
- return {
363
- scope: { feature: opts.feature ?? null },
364
- window: { from, to, events: scoped.length },
365
- coverage: { v2, legacy },
366
- ...finishCounters(global, turnsObserved),
367
- rerunsByKind: byKind,
368
- rerunClasses,
369
- topRereads: [...files.values()]
370
- .filter((f) => f.redundantBytes > 0)
371
- .sort((a, b) => b.redundantBytes - a.redundantBytes || a.file.localeCompare(b.file))
372
- .slice(0, top),
373
- verify: {
374
- byFeature: verifyByFeature,
375
- median: median(featureRows.map((f) => f.verify).filter((n) => n > 0)),
376
- unchangedRepeats,
377
- },
378
- dotnetFullSuite: fullSuite,
379
- testOutsideVerify: testOutsideVerify(testBash),
380
- reuse,
381
- gates,
382
- features: featureRows,
383
- };
384
- }
@@ -1,276 +0,0 @@
1
- import { readFileSync, existsSync, readdirSync } from 'fs';
2
- import { join, basename } from 'path';
3
- import { parseWorktreeList, resolvePrimaryRoot } from '../../commands/project/worktree.js';
4
- import { resolveGitCommonDir } from '../../../framework/hooks/shared/git-paths.js';
5
- import { isFailedToolCall } from '../../../framework/hooks/shared/telemetry-logger.js';
6
-
7
- const LOGS_DIR = join('.morph', 'logs');
8
- const EVENTS_FILE = join(LOGS_DIR, 'events.jsonl');
9
- const EVENTS_LOG = /^events(-.+)?\.jsonl$/;
10
- // Caches a finish backup may hold; none of them contains a log.
11
- const BACKUP_SKIP_DIRS = new Set(['node_modules', '.next', 'bin', 'obj', 'TestResults', 'graphify-out', '.git']);
12
-
13
- // The same line arrives through the live log, its rotated archives and every finish backup. v2 events
14
- // carry an `eventId`; a v1 event is identical only to a byte-identical copy of itself.
15
- function dedupeKey(event) {
16
- return event.eventId ? `id:${event.eventId}` : `raw:${JSON.stringify(event)}`;
17
- }
18
-
19
- function eventTime(event) {
20
- const t = Date.parse(event.ts ?? '');
21
- return Number.isNaN(t) ? 0 : t;
22
- }
23
-
24
- /** Stable sort, so events sharing a timestamp keep their write order. */
25
- export function dedupeEvents(events) {
26
- const seen = new Set();
27
- const out = [];
28
- for (const e of events || []) {
29
- if (!e || typeof e !== 'object') continue;
30
- const key = dedupeKey(e);
31
- if (seen.has(key)) continue;
32
- seen.add(key);
33
- out.push(e);
34
- }
35
- return out.sort((a, b) => eventTime(a) - eventTime(b));
36
- }
37
-
38
- function readJsonlFile(path, out) {
39
- try {
40
- if (!existsSync(path)) return;
41
- for (const line of readFileSync(path, 'utf-8').split('\n')) {
42
- const trimmed = line.trim();
43
- if (!trimmed) continue;
44
- try { out.push(JSON.parse(trimmed)); } catch {}
45
- }
46
- } catch {}
47
- }
48
-
49
- function archiveFiles(sessionsDir) {
50
- try {
51
- return readdirSync(sessionsDir)
52
- .filter((name) => name.startsWith('events-') && EVENTS_LOG.test(name))
53
- .sort()
54
- .map((name) => join(sessionsDir, name));
55
- } catch {
56
- return [];
57
- }
58
- }
59
-
60
- /** Live log plus, by default, the rotated archives: the live file alone loses everything past 5 MB. */
61
- export function loadTelemetry(projectPath, { archives = true } = {}) {
62
- const root = projectPath || process.cwd();
63
- const events = [];
64
- if (archives) for (const file of archiveFiles(join(root, LOGS_DIR, 'sessions'))) readJsonlFile(file, events);
65
- readJsonlFile(join(root, EVENTS_FILE), events);
66
- return dedupeEvents(events);
67
- }
68
-
69
- function collectBackupLogs(dir, depth, out) {
70
- if (depth < 0) return;
71
- let entries;
72
- try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
73
- for (const entry of entries) {
74
- const full = join(dir, entry.name);
75
- if (entry.isDirectory()) {
76
- if (!BACKUP_SKIP_DIRS.has(entry.name)) collectBackupLogs(full, depth - 1, out);
77
- } else if (EVENTS_LOG.test(entry.name) && /[\\/]\.morph[\\/]logs([\\/]sessions)?$/.test(dir)) {
78
- out.push(full);
79
- }
80
- }
81
- }
82
-
83
- /** Logs `finish` saved before tearing a worktree down: once it is gone, they are the feature's only telemetry. */
84
- export function loadFinishBackupTelemetry(cwd = process.cwd()) {
85
- const common = resolveGitCommonDir(cwd);
86
- if (!common) return null;
87
- const base = join(common, 'morph-spec', 'finish-backup');
88
- const files = [];
89
- collectBackupLogs(base, 6, files);
90
- if (!files.length) return null;
91
- const events = [];
92
- for (const file of files.sort()) readJsonlFile(file, events);
93
- return { path: base, events: dedupeEvents(events) };
94
- }
95
-
96
- /** Labels the primary worktree `'root'`, the others by directory basename. Outside git, a single root entry. */
97
- export function loadTelemetryAllTrees(cwd = process.cwd()) {
98
- const root = resolvePrimaryRoot(cwd);
99
- const entries = parseWorktreeList(root);
100
- const trees = entries.length ? entries : [{ path: root }];
101
-
102
- const out = [];
103
- for (const t of trees) {
104
- const eventsPath = join(t.path, EVENTS_FILE);
105
- if (!existsSync(eventsPath)) continue;
106
- out.push({
107
- tree: t.path === root ? 'root' : basename(t.path),
108
- path: t.path,
109
- events: loadTelemetry(t.path),
110
- });
111
- }
112
- const backup = loadFinishBackupTelemetry(root);
113
- if (backup) out.push({ tree: 'finish-backup', path: backup.path, events: backup.events });
114
- return out;
115
- }
116
-
117
- function rank(map) {
118
- return [...map.entries()]
119
- .map(([name, count]) => ({ name, count }))
120
- .sort((a, b) => b.count - a.count || a.name.localeCompare(b.name));
121
- }
122
-
123
- export function aggregateTelemetry(events, opts = {}) {
124
- const scoped = opts.feature
125
- ? (events || []).filter(e => e.feature === opts.feature)
126
- : (events || []);
127
-
128
- const skills = new Map();
129
- const personas = new Map();
130
- const standards = new Map();
131
- const tools = new Map();
132
- const features = new Set();
133
- const prompts = [];
134
-
135
- for (const e of scoped) {
136
- if (e.tool) tools.set(e.tool, (tools.get(e.tool) || 0) + 1);
137
- if (e.feature) features.add(e.feature);
138
-
139
- if (e.tool === 'Skill' && e.skill) {
140
- skills.set(e.skill, (skills.get(e.skill) || 0) + 1);
141
- } else if ((e.tool === 'Agent' || e.tool === 'Task') && e.persona) {
142
- personas.set(e.persona, (personas.get(e.persona) || 0) + 1);
143
- }
144
-
145
- if (e.kind === 'standard' && e.target) {
146
- standards.set(e.target, (standards.get(e.target) || 0) + 1);
147
- }
148
-
149
- if (e.tool === 'UserPrompt' && typeof e.prompt === 'string') {
150
- prompts.push({ ts: e.ts, source: 'user', feature: e.feature ?? null, phase: e.phase ?? null, text: e.prompt });
151
- } else if ((e.tool === 'Agent' || e.tool === 'Task') && typeof e.prompt === 'string' && e.prompt) {
152
- prompts.push({ ts: e.ts, source: 'agent', feature: e.feature ?? null, phase: e.phase ?? null, text: e.prompt });
153
- }
154
- }
155
-
156
- return {
157
- total: scoped.length,
158
- skills: rank(skills),
159
- personas: rank(personas),
160
- standards: rank(standards).map(({ name, count }) => ({ path: name, count })),
161
- tools: rank(tools),
162
- prompts,
163
- features: [...features],
164
- };
165
- }
166
-
167
- // Bytes re-ingested is a proxy for cost, never a token count.
168
-
169
- function mapToObj(map) {
170
- const out = {};
171
- for (const key of [...map.keys()].sort()) out[key] = map.get(key);
172
- return out;
173
- }
174
-
175
- function sumValues(map) {
176
- let total = 0;
177
- for (const v of map.values()) total += v;
178
- return total;
179
- }
180
-
181
- // Prefers `promptChars` over `prompt.length`: the prompt is truncated on write. Session and agent usage sum
182
- // only their `delta`, never the running total; they are `null` when nothing summable was seen.
183
- const SESSION_USAGE_KEYS = ['inputTokens', 'outputTokens', 'cacheReadTokens', 'cacheCreationTokens'];
184
-
185
- /** Bytes a Read put in context: its window when known, else the file size. */
186
- export function ingestedBytes(e) {
187
- if (isFailedToolCall(e)) return null;
188
- if (Number.isFinite(e.bytesRead)) return e.bytesRead;
189
- if (Number.isFinite(e.bytes)) return e.bytes;
190
- return null;
191
- }
192
-
193
- export function aggregateCost(events, opts = {}) {
194
- const scoped = opts.feature
195
- ? (events || []).filter(e => e.feature === opts.feature)
196
- : (events || []);
197
-
198
- const features = new Set();
199
- const toolCounts = new Map();
200
- const bytesByKindGlobal = new Map();
201
- const dispatches = { count: 0, promptChars: 0 };
202
- const phaseBytes = new Map();
203
- const newUsageBucket = () => ({
204
- totals: { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheCreationTokens: 0 },
205
- ids: new Set(),
206
- samples: 0,
207
- legacy: 0,
208
- });
209
- const usage = { session: newUsageBucket(), agent: newUsageBucket() };
210
-
211
- for (const e of scoped) {
212
- if (!e || typeof e !== 'object') continue;
213
- if (e.feature) features.add(e.feature);
214
-
215
- if (e.event === 'SessionUsage' || e.event === 'AgentUsage') {
216
- const bucket = e.event === 'SessionUsage' ? usage.session : usage.agent;
217
- // Only a delta can be summed: the top-level numbers are the transcript's
218
- // running total, and v1 samples (no delta) repeat it on every Stop.
219
- if (!e.delta || typeof e.delta !== 'object') {
220
- bucket.legacy += 1;
221
- continue;
222
- }
223
- bucket.samples += 1;
224
- bucket.ids.add(e.event === 'SessionUsage' ? (e.sessionId ?? 'default') : e.agentId);
225
- for (const key of SESSION_USAGE_KEYS) {
226
- if (Number.isFinite(e.delta[key])) bucket.totals[key] += e.delta[key];
227
- }
228
- continue;
229
- }
230
-
231
- if (e.tool) toolCounts.set(e.tool, (toolCounts.get(e.tool) || 0) + 1);
232
-
233
- const read = ingestedBytes(e);
234
- if (read !== null) {
235
- const kind = e.kind || 'unknown';
236
- bytesByKindGlobal.set(kind, (bytesByKindGlobal.get(kind) || 0) + read);
237
- if (e.phase) {
238
- if (!phaseBytes.has(e.phase)) phaseBytes.set(e.phase, new Map());
239
- const m = phaseBytes.get(e.phase);
240
- m.set(kind, (m.get(kind) || 0) + read);
241
- }
242
- }
243
-
244
- const hasPromptChars = typeof e.promptChars === 'number' && Number.isFinite(e.promptChars);
245
- if ((e.tool === 'Agent' || e.tool === 'Task') && (hasPromptChars || (typeof e.prompt === 'string' && e.prompt))) {
246
- const chars = hasPromptChars ? e.promptChars : e.prompt.length;
247
- dispatches.count += 1;
248
- dispatches.promptChars += chars;
249
- }
250
- }
251
-
252
- const phases = [...phaseBytes.entries()]
253
- .map(([phase, kindMap]) => ({
254
- phase,
255
- bytesByKind: mapToObj(kindMap),
256
- bytesTotal: sumValues(kindMap),
257
- }))
258
- .sort((a, b) => a.phase.localeCompare(b.phase));
259
-
260
- return {
261
- total: scoped.length,
262
- features: [...features],
263
- bytesByKind: mapToObj(bytesByKindGlobal),
264
- bytesTotal: sumValues(bytesByKindGlobal),
265
- dispatches,
266
- sessionUsage: usage.session.samples > 0
267
- ? { ...usage.session.totals, sessions: usage.session.ids.size, samples: usage.session.samples }
268
- : null,
269
- sessionUsageLegacySamples: usage.session.legacy,
270
- agentUsage: usage.agent.samples > 0
271
- ? { ...usage.agent.totals, agents: usage.agent.ids.size, samples: usage.agent.samples }
272
- : null,
273
- tools: rank(toolCounts),
274
- phases,
275
- };
276
- }