@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,400 +0,0 @@
1
- // The stack is deliberately NOT torn down between verifies: a cold .NET start per task is the
2
- // difference between a loop people run and one they disable. Every subcommand acts in the tree
3
- // that owns the feature.
4
-
5
- import chalk from 'chalk';
6
- import { execFileSync } from 'child_process';
7
- import { existsSync, readFileSync } from 'fs';
8
- import { join, resolve } from 'path';
9
-
10
- import {
11
- bringUpE2e,
12
- composeProjectName,
13
- computeSourceStamp,
14
- decideIsolation,
15
- defaultExec,
16
- deleteStamp,
17
- getStackStatus,
18
- isDockerAvailable,
19
- isHostOnlyStack,
20
- lintComposeIsolation,
21
- resetE2eData,
22
- readStamp,
23
- resolveComposeFile,
24
- resolveSpecCommand,
25
- tearDownStack,
26
- } from '../../../framework/hooks/shared/e2e-check.js';
27
- import { isSecondaryWorktree } from '../../../framework/hooks/shared/git-paths.js';
28
- import { hostServicesStatus, stopHostServices } from '../../../framework/hooks/shared/host-services.js';
29
- import { buildComposeEnv } from '../../lib/e2e/compose-env.js';
30
- import { findWorktreeForFeature, resolvePrimaryRoot } from '../project/worktree.js';
31
- import { createHeavyGate, HeavyBusyError } from '../../lib/heavy/gate.js';
32
- import { afterHeavyRun } from '../../lib/heavy/cleanup.js';
33
- import { memoryBusyHint } from '../../lib/heavy/live-stacks.js';
34
- import { readHeavyConfig } from '../../../framework/hooks/shared/heavy-config.js';
35
- import { SESSION_MARK } from '../../../framework/hooks/shared/next-step.js';
36
-
37
- const EXIT_USAGE = 2;
38
- const EXIT_BUSY = 3;
39
-
40
- // No compose file and no e2e.hostServices is a usage error here, unlike in the verify node where
41
- // it is a graded skip. `composeFile` is null for a host-only stack.
42
- function resolveContext(featureName, { json = false, onMissing } = {}) {
43
- const root = resolvePrimaryRoot(process.cwd());
44
- const found = findWorktreeForFeature(featureName, root);
45
- const cwd = found?.path ?? root;
46
-
47
- const config = readConfig(cwd) ?? readConfig(root);
48
- const composeFile = resolveComposeFile(cwd, config);
49
-
50
- if (!composeFile && !isHostOnlyStack(config, composeFile)) {
51
- const message =
52
- `No compose file found in ${cwd} (compose.yaml, docker-compose.yml, …) and no e2e.hostServices. ` +
53
- 'Set e2e.composeFile in .morph/config/config.json if it lives elsewhere, ' +
54
- 'or declare the app in e2e.hostServices when it has no dependency to containerize.';
55
- if (onMissing) onMissing(message, cwd);
56
- else if (json) console.log(JSON.stringify({ error: message, tree: cwd }, null, 2));
57
- else console.error(chalk.red(`\n❌ ${message}\n`));
58
- return null;
59
- }
60
-
61
- const projectName = composeProjectName(featureName);
62
- const gitCommonDir = resolveGitCommonDir(cwd);
63
-
64
- return {
65
- cwd,
66
- root,
67
- tree: cwd,
68
- insideWorktree: isSecondaryWorktree(cwd),
69
- config,
70
- composeFile,
71
- projectName,
72
- gitCommonDir,
73
- env: buildEnv({ cwd, config, featureName, projectName, gitCommonDir }),
74
- };
75
- }
76
-
77
- // The port block comes from `buildComposeEnv`, so this command and the verify node agree by
78
- // construction.
79
- function buildEnv({ cwd, config, featureName, projectName, gitCommonDir }) {
80
- // The explicit key is the floor for a repo with no git common dir (no port layout).
81
- return {
82
- COMPOSE_PROJECT_NAME: projectName,
83
- ...buildComposeEnv({ cwd, config, featureName, gitCommonDir }),
84
- };
85
- }
86
-
87
- // `--fresh` drops the named volumes and reruns the auth seed: a preserved database would hand the
88
- // next suite stale rows and a storageState for a user that no longer exists.
89
- export async function e2eUpCommand(featureName, options = {}) {
90
- const ctx = resolveContext(featureName, options);
91
- if (!ctx) process.exit(EXIT_USAGE);
92
-
93
- // Isolation BEFORE the docker check: a compose that hardcodes host ports or container names
94
- // collides with a sibling worktree whatever we inject.
95
- const lint = ctx.composeFile ? lintComposeIsolation(readComposeText(ctx.cwd, ctx.composeFile)) : { findings: [] };
96
- const isolation = decideIsolation({ findings: lint.findings, insideWorktree: ctx.insideWorktree });
97
- if (isolation.status === 'fail') {
98
- if (options.json) {
99
- console.log(JSON.stringify(
100
- { error: 'compose-not-isolable', feature: featureName, tree: ctx.tree, composeFile: ctx.composeFile, reason: isolation.reason, findings: lint.findings },
101
- null, 2,
102
- ));
103
- } else {
104
- console.error(chalk.red(`\n❌ ${isolation.reason}`));
105
- for (const f of lint.findings) console.error(chalk.gray(` ${ctx.composeFile}:${f.line}: ${f.text}`));
106
- console.error('');
107
- }
108
- process.exit(1);
109
- }
110
- if (isolation.status === 'warn' && !options.json) {
111
- console.log(chalk.yellow(`⚠️ ${isolation.reason}`));
112
- }
113
-
114
- const exec = options._exec ?? defaultExec;
115
- if (ctx.composeFile && !isDockerAvailable(ctx.cwd, exec)) {
116
- console.error(chalk.red('\n❌ O Docker não está disponível nesta máquina, então o ambiente de teste não sobe.\n'));
117
- process.exit(EXIT_USAGE);
118
- }
119
-
120
- const gate = createHeavyGate({ projectPath: ctx.cwd, label: 'e2e up', feature: featureName });
121
- let result;
122
- try {
123
- gate.enter('e2e');
124
- result = bringUpE2e(ctx.cwd, {
125
- config: ctx.config,
126
- composeFile: ctx.composeFile,
127
- projectName: ctx.projectName,
128
- gitCommonDir: ctx.gitCommonDir,
129
- env: ctx.env,
130
- forceFresh: Boolean(options.fresh),
131
- }, exec);
132
- } catch (err) {
133
- if (!(err instanceof HeavyBusyError)) throw err;
134
- if (options.json) {
135
- console.log(JSON.stringify({ status: 'busy', feature: featureName, busy: { reason: err.reason, waitedMs: err.waitedMs } }, null, 2));
136
- }
137
- console.error(chalk.yellow(`\n⏳ O ambiente de teste não subiu: ${err.message}. Isso não é falha: a máquina estava ocupada e a fila já esperou o prazo dela.`));
138
- console.error(chalk.gray(` ${SESSION_MARK} não repita em laço; siga sem esta rodada e avise o usuário (\`morph-spec heavy status\`).\n`));
139
- const hint = memoryBusyHint(err, ctx.cwd);
140
- if (hint) console.error(chalk.yellow(`${hint}\n`));
141
- process.exit(EXIT_BUSY);
142
- } finally {
143
- gate.release();
144
- }
145
-
146
- const { auth, hostServices } = result;
147
- // A seedCommand that `mode` switches off is reported, never swallowed.
148
- const warnings = [];
149
- if (isolation.status === 'warn') warnings.push(isolation.reason);
150
- warnings.push(...result.warnings);
151
-
152
- const failed = result.status === 'fail';
153
- const payload = {
154
- feature: featureName,
155
- project: ctx.projectName,
156
- tree: ctx.tree,
157
- composeFile: ctx.composeFile,
158
- status: failed ? 'fail' : 'pass',
159
- reused: ctx.composeFile ? result.stack.reused : hostServices.reused,
160
- reason: result.reason,
161
- auth: { status: auth.status, reason: auth.reason },
162
- ...(hostServices.status === 'skip' ? {} : { hostServices: hostServices.services }),
163
- ...(warnings.length ? { warnings } : {}),
164
- ...(failed && result.output ? { output: result.output } : {}),
165
- };
166
-
167
- if (options.json) {
168
- console.log(JSON.stringify(payload, null, 2));
169
- } else if (failed) {
170
- console.error(chalk.red(`\n✗ ${result.reason}\n`));
171
- if (result.output) console.error(result.output);
172
- for (const w of result.warnings) console.error(chalk.yellow(`⚠️ ${w}`));
173
- } else {
174
- const how = !ctx.composeFile
175
- ? chalk.gray(`(${result.stack.reason})`)
176
- : result.stack.reused ? chalk.gray(`(${result.stack.reason})`) : chalk.gray('(montado agora)');
177
- console.log(chalk.green(`\n✓ Ambiente de teste no ar — ${ctx.projectName} ${how}`));
178
- console.log(chalk.gray(` Pasta: ${ctx.tree}`));
179
- for (const s of hostServices.services) {
180
- console.log(chalk.gray(` Serviço ${s.name}: pid ${s.pid} (${s.reused ? 'já estava rodando' : 'iniciado agora'}) — log ${s.log}`));
181
- }
182
- if (auth.reason) console.log(chalk.gray(` Login de teste: ${auth.reason}`));
183
- for (const w of result.warnings) console.log(chalk.yellow(`⚠️ ${w}`));
184
- console.log('');
185
- }
186
-
187
- process.exit(failed ? 1 : 0);
188
- }
189
-
190
- // Handed to the verifier so it never guesses `localhost:3000`: each feature owns a port block.
191
- // Mirrors what `playwright.config.ts` does: one rule, two readers.
192
- export function resolveBaseUrl(env = {}) {
193
- return env.PLAYWRIGHT_BASE_URL ?? `http://localhost:${env.PORT ?? 3000}`;
194
- }
195
-
196
- // Exit 0 only when up AND built from the code on disk, so it can gate a script.
197
- export async function e2eStatusCommand(featureName, options = {}) {
198
- const ctx = resolveContext(featureName, options);
199
- if (!ctx) process.exit(EXIT_USAGE);
200
-
201
- const exec = options._exec ?? defaultExec;
202
- const hostServices = ctx.gitCommonDir ? hostServicesStatus(ctx.gitCommonDir, ctx.projectName) : [];
203
- const status = ctx.composeFile
204
- ? getStackStatus(ctx.cwd, {
205
- composeFile: ctx.composeFile,
206
- projectName: ctx.projectName,
207
- env: ctx.env,
208
- }, exec)
209
- : {
210
- up: hostServices.length > 0 && hostServices.every((h) => h.alive),
211
- healthy: hostServices.length > 0 && hostServices.every((h) => h.alive && h.health !== false),
212
- services: [],
213
- };
214
-
215
- const stamp = computeSourceStamp(ctx.cwd, exec);
216
- const previous = ctx.gitCommonDir ? readStamp(ctx.gitCommonDir, ctx.projectName) : null;
217
- const fresh = Boolean(stamp && previous?.stamp === stamp);
218
- // Live processes say nothing about the schema: a reset that died after wiping the data left this mark.
219
- const dataBroken = Boolean(previous?.dataBroken);
220
- const healthy = status.healthy && !dataBroken;
221
-
222
- const spec = resolveSpecCommand(ctx.cwd, ctx.config, ctx.config?.project?.frontendPath);
223
-
224
- const payload = {
225
- feature: featureName,
226
- project: ctx.projectName,
227
- tree: ctx.tree,
228
- composeFile: ctx.composeFile,
229
- up: status.up,
230
- healthy,
231
- ...(dataBroken ? { dataBroken: true } : {}),
232
- fresh,
233
- baseUrl: resolveBaseUrl(ctx.env),
234
- builtAt: previous?.builtAt ?? null,
235
- specs: spec ? `${spec.command} ${spec.args.join(' ')}` : null,
236
- services: status.services.map((s) => ({
237
- name: s.Service ?? s.Name ?? null,
238
- state: s.State ?? null,
239
- health: s.Health || null,
240
- })),
241
- ...(hostServices.length ? { hostServices } : {}),
242
- };
243
-
244
- if (options.json) {
245
- console.log(JSON.stringify(payload, null, 2));
246
- } else {
247
- console.log('');
248
- console.log(chalk.bold(`Ambiente de teste — ${ctx.projectName}`));
249
- console.log(chalk.gray(`Pasta: ${ctx.tree}`));
250
- console.log(chalk.gray(`Compose: ${ctx.composeFile ?? 'nenhum (só serviços locais)'}`));
251
- console.log(chalk.gray(`Endereço: ${payload.baseUrl}`));
252
- console.log('');
253
- console.log(` No ar ${status.up ? chalk.green('sim') : chalk.gray('não')}`);
254
- console.log(` Funcionando ${healthy ? chalk.green('sim') : dataBroken
255
- ? chalk.red(`não — o último reset deixou os dados inutilizáveis: rode \`morph-spec e2e up ${featureName} --fresh\``)
256
- : chalk.gray('não')}`);
257
- console.log(
258
- ` Código em dia ${fresh ? chalk.green('sim') : chalk.yellow('não — o código mudou depois que o ambiente subiu')}`
259
- );
260
- console.log(` Testes do fluxo ${spec ? payload.specs : chalk.gray('nenhum (só o teste de fumaça)')}`);
261
- for (const s of payload.services) {
262
- console.log(chalk.gray(` · ${s.name}: ${s.state}${s.health ? ` / ${s.health}` : ''}`));
263
- }
264
- for (const h of hostServices) {
265
- const health = h.health === null ? 'sem checagem de saúde' : h.health ? 'funcionando' : 'com problema';
266
- console.log(chalk.gray(` · serviço ${h.name}: pid ${h.pid} ${h.alive ? 'rodando' : 'parado'} / ${health}`));
267
- }
268
- console.log('');
269
- }
270
-
271
- process.exit(status.up && healthy && fresh ? 0 : 1);
272
- }
273
-
274
- // Best-effort: a stack that will not come down must never block `finish`. The freshness stamp
275
- // goes regardless, or the next `up` would reuse a stack that is gone.
276
- export async function e2eDownCommand(featureName, options = {}) {
277
- const ctx = resolveContext(featureName, options);
278
- if (!ctx) process.exit(EXIT_USAGE);
279
-
280
- const hostServices = stopHostServices(ctx.gitCommonDir, ctx.projectName);
281
- const result = ctx.composeFile
282
- ? tearDownStack(ctx.cwd, {
283
- composeFile: ctx.composeFile,
284
- projectName: ctx.projectName,
285
- env: ctx.env,
286
- volumes: Boolean(options.volumes),
287
- }, options._exec ?? defaultExec)
288
- : { status: 'pass', output: '' };
289
- const stampDeleted = deleteStamp(ctx.gitCommonDir, ctx.projectName);
290
- const cleanup = afterHeavyRun({ projectPath: ctx.cwd, config: readHeavyConfig(ctx.cwd) });
291
-
292
- if (options.json) {
293
- console.log(JSON.stringify(
294
- {
295
- feature: featureName, project: ctx.projectName, tree: ctx.tree, status: result.status, stampDeleted, cleanup,
296
- ...(stoppedAnything(hostServices) ? { hostServices } : {}),
297
- },
298
- null, 2,
299
- ));
300
- } else {
301
- if (result.status === 'pass') {
302
- console.log(chalk.green(`\n✓ Ambiente de teste desligado — ${ctx.projectName}`));
303
- console.log(chalk.gray(` Pasta: ${ctx.tree}\n`));
304
- } else {
305
- console.log(chalk.yellow(`\n⚠️ O desligamento avisou um problema (não impede de seguir):\n${result.output}\n`));
306
- }
307
- if (hostServices.killed.length) console.log(chalk.gray(` Serviços locais parados: ${hostServices.killed.join(', ')}`));
308
- for (const w of hostServices.warnings) console.log(chalk.yellow(`⚠️ ${w}`));
309
- }
310
-
311
- process.exit(0);
312
- }
313
-
314
- // Between the verifier's flows: the next flow starts from the seeded state, not from the rows the
315
- // previous one left. Exit 1 only on fail; skip (nothing configured to reset) is exit 0.
316
- export async function e2eResetCommand(featureName, options = {}) {
317
- const emit = (payload) => {
318
- if (options.json) {
319
- console.log(JSON.stringify(payload, null, 2));
320
- } else if (payload.status === 'fail') {
321
- console.error(chalk.red(`\n✗ ${payload.reason}\n`));
322
- if (payload.output) console.error(payload.output);
323
- } else if (payload.status === 'skip') {
324
- console.log(chalk.gray(`\n○ Dados de teste não foram zerados: ${payload.reason}\n`));
325
- } else {
326
- const what = payload.reset.mode === 'command'
327
- ? `pelo e2e.resetCommand (${payload.reset.command})`
328
- : payload.reset.mode === 'volumes'
329
- ? `recriando ${payload.reset.services.join(', ')} (volumes ${payload.reset.volumes.join(', ')})`
330
- : 'sem apagar dados';
331
- console.log(chalk.green(`\n✓ Dados de teste zerados ${what}`));
332
- if (payload.auth.reason) console.log(chalk.gray(` Login de teste: ${payload.auth.reason}`));
333
- console.log('');
334
- }
335
- process.exit(payload.status === 'fail' ? 1 : 0);
336
- };
337
-
338
- const ctx = resolveContext(featureName, {
339
- ...options,
340
- onMissing: (message, tree) => emit({ feature: featureName, tree, status: 'fail', reason: message }),
341
- });
342
- if (!ctx) return;
343
-
344
- const result = resetE2eData(ctx.cwd, {
345
- config: ctx.config,
346
- composeFile: ctx.composeFile,
347
- projectName: ctx.projectName,
348
- gitCommonDir: ctx.gitCommonDir,
349
- env: ctx.env,
350
- }, options._exec ?? defaultExec);
351
-
352
- emit({
353
- feature: featureName,
354
- project: ctx.projectName,
355
- tree: ctx.tree,
356
- status: result.status,
357
- reason: result.reason,
358
- reset: result.reset,
359
- auth: result.auth,
360
- ...(result.status === 'fail' && result.output ? { output: result.output } : {}),
361
- });
362
- }
363
-
364
- function stoppedAnything({ killed, skipped, warnings }) {
365
- return killed.length + skipped.length + warnings.length > 0;
366
- }
367
-
368
- function readConfig(cwd) {
369
- try {
370
- const path = join(cwd, '.morph', 'config', 'config.json');
371
- if (!existsSync(path)) return null;
372
- return JSON.parse(readFileSync(path, 'utf8').replace(/^/, ''));
373
- } catch {
374
- return null;
375
- }
376
- }
377
-
378
- function readComposeText(cwd, composeFile) {
379
- try {
380
- return readFileSync(join(cwd, composeFile), 'utf8');
381
- } catch {
382
- return '';
383
- }
384
- }
385
-
386
- function resolveGitCommonDir(cwd) {
387
- try {
388
- const common = execFileSync('git', ['rev-parse', '--git-common-dir'], {
389
- cwd,
390
- stdio: 'pipe',
391
- encoding: 'utf-8',
392
- windowsHide: true,
393
- }).trim();
394
- return common ? resolve(cwd, common) : null;
395
- } catch {
396
- return null;
397
- }
398
- }
399
-
400
- export { defaultExec };
@@ -1,283 +0,0 @@
1
- // Bytes re-ingested is a deterministic proxy for cost, not a token count: hooks only see what
2
- // tools read off disk. `sessionUsage` is the exception, real hook-observed tokens.
3
-
4
- import chalk from 'chalk';
5
- import { loadTelemetry, loadTelemetryAllTrees, aggregateCost, dedupeEvents } from '../../lib/telemetry/telemetry-reader.js';
6
- import { computeMetrics } from '../../lib/telemetry/metrics.js';
7
-
8
- const BYTES_CAVEAT =
9
- 'Bytes re-ingeridos são um PROXY determinístico de custo (o que as ferramentas leram do disco) — NÃO são tokens reais. Hooks não enxergam o uso real de tokens do modelo.';
10
-
11
- const BY_MODES = ['phase'];
12
-
13
- function fmtBytes(n) {
14
- if (!n) return '0 B';
15
- if (n < 1024) return `${n} B`;
16
- if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
17
- return `${(n / 1024 / 1024).toFixed(1)} MB`;
18
- }
19
-
20
- function fmtDuration(s) {
21
- if (s === null || s === undefined) return '-';
22
- if (s < 60) return `${s.toFixed(1)}s`;
23
- const m = Math.floor(s / 60);
24
- const rem = Math.round(s % 60);
25
- return `${m}m${rem}s`;
26
- }
27
-
28
- function printBytesByKind(bytesByKind) {
29
- const entries = Object.entries(bytesByKind);
30
- if (!entries.length) {
31
- console.log(chalk.gray(' (0 bytes re-ingeridos — nenhum Read com bytes/kind neste escopo)'));
32
- return;
33
- }
34
- for (const [kind, bytes] of entries.sort((a, b) => b[1] - a[1])) {
35
- console.log(` ${chalk.yellow(kind.padEnd(14))} ${fmtBytes(bytes)}`);
36
- }
37
- }
38
-
39
- function printPhases(phases) {
40
- if (!phases.length) {
41
- console.log(chalk.gray('\nNenhum byte de Read com phase capturado.'));
42
- return;
43
- }
44
- for (const p of phases) {
45
- console.log('\n' + chalk.white.bold(`Fase ${p.phase}`) + chalk.gray(` · ${fmtBytes(p.bytesTotal)} total`));
46
- printBytesByKind(p.bytesByKind);
47
- }
48
- }
49
-
50
- function tokenLine(u) {
51
- return ` input=${u.inputTokens} output=${u.outputTokens} `
52
- + `cacheRead=${u.cacheReadTokens} cacheCreation=${u.cacheCreationTokens}`;
53
- }
54
-
55
- function printSessionUsage(summary) {
56
- const { sessionUsage, agentUsage, sessionUsageLegacySamples } = summary;
57
- if (sessionUsage) {
58
- console.log('\n' + chalk.white.bold('Tokens reais (sessões observadas)')
59
- + chalk.gray(` · ${sessionUsage.sessions} sessão(ões), ${sessionUsage.samples} amostra(s)`));
60
- console.log(tokenLine(sessionUsage));
61
- }
62
- if (agentUsage) {
63
- console.log('\n' + chalk.white.bold('Tokens reais (sub-agents)')
64
- + chalk.gray(` · ${agentUsage.agents} agente(s), ${agentUsage.samples} amostra(s)`));
65
- console.log(tokenLine(agentUsage));
66
- }
67
- if (sessionUsageLegacySamples > 0) {
68
- console.log(chalk.gray(` ${sessionUsageLegacySamples} amostra(s) SessionUsage antigas (sem delta) fora da soma: eram o total acumulado, repetido a cada Stop.`));
69
- }
70
- }
71
-
72
- function printSummary(summary) {
73
- console.log(`\n dispatches: ${summary.dispatches.count} (${summary.dispatches.promptChars} chars de prompt)`);
74
-
75
- console.log('\n' + chalk.white.bold('Bytes re-ingeridos por kind') + ` (${fmtBytes(summary.bytesTotal)} total)`);
76
- printBytesByKind(summary.bytesByKind);
77
-
78
- if (summary.tools.length) {
79
- console.log('\n' + chalk.white.bold('Mix de tools'));
80
- for (const t of summary.tools) console.log(` ${t.name.padEnd(16)} ${t.count}`);
81
- }
82
-
83
- printSessionUsage(summary);
84
- }
85
-
86
- function pct(r) {
87
- return r === null || r === undefined ? '-' : `${Math.round(r * 1000) / 10}%`;
88
- }
89
-
90
- function split(counts) {
91
- return `${counts.total} (orq ${counts.orchestrator} · sub ${counts.subagent}${counts.unknown ? ` · sem agente ${counts.unknown}` : ''})`;
92
- }
93
-
94
- function printMetricsBody(m) {
95
- const legacyShare = m.window.events ? m.coverage.legacy / m.window.events : 0;
96
- console.log(chalk.gray(`janela: ${m.window.from ?? '-'} → ${m.window.to ?? '-'} · ${m.window.events} eventos`
97
- + ` · ${pct(1 - legacyShare)} no esquema v2`));
98
- if (m.coverage.legacy) {
99
- console.log(chalk.gray(' eventos v1 não têm agente, exit code, duração nem janela de Read: entram como "sem agente" e rerun "unknown-*".'));
100
- }
101
-
102
- console.log('\n' + chalk.white.bold('Turnos e chamadas'));
103
- console.log(` turnos: ${m.turns ? split(m.turns) : 'desconhecido (nenhum PostToolBatch na janela)'}`);
104
- console.log(` chamadas de ferramenta: ${split(m.toolCalls)}`);
105
- console.log('\n' + chalk.white.bold('Tempo por classe de comando'));
106
- for (const [klass, t] of Object.entries(m.timeByClass).sort((a, b) => b[1].measuredMs - a[1].measuredMs)) {
107
- const unmeasured = t.unmeasured ? chalk.gray(` (${t.unmeasured} sem duração)`) : '';
108
- console.log(` ${klass.padEnd(12)} ${fmtDuration(t.measuredMs / 1000).padStart(8)} ${t.runs} execução(ões)${unmeasured}`);
109
- }
110
-
111
- const tov = m.testOutsideVerify;
112
- const timed = (t) => `${String(t.runs).padStart(4)}× ${fmtDuration(t.measuredMs / 1000).padStart(8)}`
113
- + (t.unmeasured ? chalk.gray(` (${t.unmeasured} sem duração)`) : '');
114
- console.log('\n' + chalk.white.bold('Teste fora do verify')
115
- + chalk.gray(` · de ${tov.total.runs} testes+verifies, ${fmtDuration(tov.total.measuredMs / 1000)} cronometrados`
116
- + (tov.total.unmeasured ? `, ${tov.total.unmeasured} sem duração` : '')));
117
- console.log(` agente de review rodando teste ${timed(tov.reviewTests)}`);
118
- console.log(chalk.gray(` ${tov.reviewTests.byPersona.runs}× pela persona morph-* (o que o hook test-budget reconhece);`
119
- + ' o resto veio de um nome de dispatch (ver-, rev-, gate3-…)'));
120
-
121
- console.log('\n' + chalk.white.bold('Rerun do mesmo comando em ≤10 min (mesma feature; o filtro de saída não conta)'));
122
- console.log(` total: ${pct(m.reruns.rate)} repetidas (${m.reruns.reruns}/${m.reruns.runs}) · ${pct(m.reruns.burstRate)} em rajada — testes, builds e verifies`);
123
- for (const [kind, r] of Object.entries(m.rerunsByKind).sort((a, b) => b[1].runs - a[1].runs)) {
124
- console.log(` ${kind.padEnd(22)} ${pct(r.rate).padStart(6)} repetidas ${pct(r.burstRate).padStart(6)} em rajada (${r.runs} execuções)`);
125
- }
126
- const classes = Object.entries(m.rerunClasses);
127
- if (classes.length) console.log(chalk.gray(` por quê: ${classes.map(([k, n]) => `${k} ${n}`).join(' · ')}`));
128
-
129
- console.log('\n' + chalk.white.bold('Releitura de arquivo (mesma janela, mesma feature)'));
130
- console.log(` ${pct(m.rereads.rate)} dos bytes lidos (${fmtBytes(m.rereads.redundantBytes)} de ${fmtBytes(m.rereads.bytes)}, ${m.rereads.reads} leituras)`);
131
- if (m.rereads.windowed < m.rereads.reads) {
132
- console.log(chalk.gray(` ${m.rereads.reads - m.rereads.windowed} leitura(s) sem janela gravada (v1) contam o arquivo inteiro: a taxa é um teto`));
133
- }
134
- for (const f of m.topRereads) {
135
- console.log(` ${fmtBytes(f.redundantBytes).padStart(9)} ${f.reads}× ${f.file}${chalk.gray(` [${f.feature ?? '-'}]`)}`);
136
- }
137
-
138
- console.log('\n' + chalk.white.bold('verify, git e reuso'));
139
- const perFeature = Object.entries(m.verify.byFeature).sort((a, b) => b[1] - a[1]);
140
- console.log(` verify por feature: mediana ${m.verify.median ?? '-'}`
141
- + (perFeature.length ? chalk.gray(` (${perFeature.slice(0, 5).map(([f, n]) => `${f} ${n}`).join(', ')})`) : ''));
142
- const repeats = Object.entries(m.verify.unchangedRepeats);
143
- if (repeats.length) {
144
- console.log(` verify de feature sobre a mesma árvore do anterior: ${repeats.reduce((n, [, v]) => n + v, 0)}`
145
- + chalk.gray(` (${repeats.map(([f, n]) => `${f} ${n}`).join(', ')})`));
146
- }
147
- if (m.dotnetFullSuite.runs) {
148
- const phases = Object.entries(m.dotnetFullSuite.byPhase).map(([p, v]) => `${p} ${v.withBuild}/${v.runs}`).join(' · ');
149
- console.log(` suíte .NET inteira que recompila (sem --no-build): ${m.dotnetFullSuite.withBuild}/${m.dotnetFullSuite.runs}`
150
- + chalk.gray(` (${phases})`));
151
- }
152
- console.log(` git status / diff: ${m.git.status} / ${m.git.diff}`);
153
- const trees = Object.entries(m.reuse.byTree);
154
- console.log(` reuse-validator: ${trees.length
155
- ? trees.map(([tree, s]) => `${tree} rodou ${s.ran}, pulou ${s.skipped}`).join(' · ')
156
- : 'nenhum evento Verify na janela'}`);
157
- for (const [reason, n] of Object.entries(m.reuse.skipReasons)) console.log(chalk.gray(` pulou ${n}×: ${reason}`));
158
- const gates = Object.entries(m.gates);
159
- if (!gates.length) {
160
- console.log(' gates: nenhum evento Gate na janela');
161
- return;
162
- }
163
- for (const [gate, g] of gates) {
164
- console.log(` gate ${gate}: ${g.decisions} decisões, ${g.paused} pausas (${g.pausedForHuman} para o humano) → ${g.approvedAfterPause} aprovadas como estavam, `
165
- + `${g.reworkedAfterPause} retrabalhadas${g.unapproved ? `, ${g.unapproved} desaprovações` : ''}`);
166
- for (const [signal, s] of Object.entries(g.bySignal)) {
167
- console.log(chalk.gray(` ${signal}: ${s.paused} pausas, ${s.approvedAfterPause} aprovadas como estavam, ${s.reworkedAfterPause} retrabalhadas`));
168
- }
169
- }
170
- }
171
-
172
- function printMetrics(feature, options, cwd) {
173
- const events = options.allTrees
174
- ? dedupeEvents(loadTelemetryAllTrees(cwd).flatMap((t) => t.events))
175
- : loadTelemetry(cwd);
176
- const metrics = computeMetrics(events, { feature, top: options.top });
177
-
178
- if (options.json) {
179
- console.log(JSON.stringify(metrics));
180
- return;
181
- }
182
- if (metrics.window.events === 0) {
183
- const scope = feature ? ` para a feature "${feature}"` : '';
184
- console.log(chalk.gray(`Telemetria vazia${scope} — nada a medir.`));
185
- return;
186
- }
187
- const scope = feature ? chalk.cyan(` · feature ${feature}`) : '';
188
- console.log(chalk.white.bold(`Medições do loop${options.allTrees ? ' — todas as árvores + finish-backup' : ''}`) + scope);
189
- printMetricsBody(metrics);
190
- }
191
-
192
- function printAllTrees(feature, options, cwd) {
193
- const treesData = loadTelemetryAllTrees(cwd);
194
- const perTree = treesData.map(({ tree, path, events }) => ({
195
- tree,
196
- path,
197
- ...aggregateCost(events, { feature }),
198
- }));
199
- const combined = aggregateCost(dedupeEvents(treesData.flatMap((t) => t.events)), { feature });
200
-
201
- if (options.json) {
202
- console.log(JSON.stringify({ allTrees: true, trees: perTree, combined }));
203
- return;
204
- }
205
-
206
- if (combined.total === 0) {
207
- const scope = feature ? ` para a feature "${feature}"` : '';
208
- console.log(chalk.gray(`Telemetria vazia${scope} em todas as árvores — nenhuma tem eventos capturados ainda.`));
209
- return;
210
- }
211
-
212
- console.log(chalk.white.bold(
213
- `Custo do harness (proxy determinística) — todas as árvores (${perTree.length} com eventos, ${combined.total} eventos no total)`
214
- ));
215
- console.log(chalk.gray(`⚠ ${BYTES_CAVEAT}`));
216
-
217
- for (const t of perTree) {
218
- console.log('\n' + chalk.cyan.bold(`── Árvore: ${t.tree}`) + chalk.gray(` — ${t.path}`));
219
- console.log(` ${t.total} eventos · `
220
- + `bytes: ${fmtBytes(t.bytesTotal)} · dispatches: ${t.dispatches.count}`);
221
- }
222
-
223
- console.log('\n' + chalk.white.bold('── Total agregado (todas as árvores)'));
224
- if (combined.features.length) {
225
- console.log(chalk.gray(`Features: ${combined.features.join(', ')}`));
226
- }
227
- if (options.by === 'phase') {
228
- printPhases(combined.phases);
229
- } else {
230
- printSummary(combined);
231
- }
232
- }
233
-
234
- export function costCommand(feature, options = {}) {
235
- if (options.by && !BY_MODES.includes(options.by)) {
236
- console.error(chalk.red(`\n❌ Invalid --by: "${options.by}"`));
237
- console.error(chalk.gray(`Valid modes: ${BY_MODES.join(', ')}\n`));
238
- process.exitCode = 1;
239
- return;
240
- }
241
-
242
- const cwd = options.cwd || process.cwd();
243
-
244
- if (options.metrics) {
245
- printMetrics(feature, options, cwd);
246
- return;
247
- }
248
-
249
- if (options.allTrees) {
250
- // No process.exit() here either, --json included.
251
- printAllTrees(feature, options, cwd);
252
- return;
253
- }
254
-
255
- const events = loadTelemetry(cwd);
256
- const summary = aggregateCost(events, { feature });
257
-
258
- if (options.json) {
259
- // No process.exit(): on Windows a piped stdout write is async, and exiting right after a
260
- // large console.log can truncate the output.
261
- console.log(JSON.stringify(summary));
262
- return;
263
- }
264
-
265
- if (summary.total === 0) {
266
- const scope = feature ? ` para a feature "${feature}"` : '';
267
- console.log(chalk.gray(`Telemetria vazia${scope} — nenhum evento capturado ainda em .morph/logs/events.jsonl.`));
268
- return;
269
- }
270
-
271
- const scope = feature ? chalk.cyan(` · feature ${feature}`) : '';
272
- console.log(chalk.white.bold(`Custo do harness (proxy determinística) — ${summary.total} eventos${scope}`));
273
- console.log(chalk.gray(`⚠ ${BYTES_CAVEAT}`));
274
- if (summary.features.length) {
275
- console.log(chalk.gray(`Features: ${summary.features.join(', ')}`));
276
- }
277
-
278
- if (options.by === 'phase') {
279
- printPhases(summary.phases);
280
- } else {
281
- printSummary(summary);
282
- }
283
- }