@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,971 +0,0 @@
1
- import { execFileSync } from 'child_process';
2
- import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs';
3
- import { join, resolve } from 'path';
4
-
5
- import { runBuildCheck, getBuildSteps, isDotnetStack } from '../../../framework/hooks/shared/build-check.js';
6
- import { changedPathsAgainst, detectDefaultBranch } from '../git/default-branch.js';
7
- import { resolveBaseRef } from '../git/branch-classifier.js';
8
- import { composeProjectName, runE2eCheck } from '../../../framework/hooks/shared/e2e-check.js';
9
- import { buildComposeEnv } from '../e2e/compose-env.js';
10
- import { e2eApplicability } from '../e2e/applicability.js';
11
- import {
12
- runTestSuite, parseTestCount, compareTestCount, resolveTestTimeout, discoverDotnetSolution, failureLines,
13
- } from '../tasks/test-runner.js';
14
- import {
15
- resolveTestNodes, parseTestFilter, nodeMatchesFilter, recordTestBaselines, morphConfigPath,
16
- } from '../tasks/test-nodes.js';
17
- import { runLinuxSuite, checkLinuxPreconditions } from '../tasks/linux-runner.js';
18
- import {
19
- EVAL_RUNNER, evalPreflight, evalNodeEnv, readEvalSummary, evalScenarioCount,
20
- evalFailureLines,
21
- evalEmptyRunProblem, evalColdCacheWarning,
22
- } from '../tasks/eval-node.js';
23
- import { runValidation } from './validation-runner.js';
24
- import { createHeavyGate } from '../heavy/gate.js';
25
- import { selectAffected } from '../verify/affected.js';
26
- import {
27
- cacheEntryFrom, planReuse, readVerifyCache, reusedEntry, writeVerifyCache,
28
- } from './verify-cache.js';
29
-
30
- const DEFAULT_BUILD_TIMEOUT = 1_800_000;
31
-
32
- const VALIDATOR_FEEDBACK_LIMIT = 10;
33
-
34
- const OUTPUT_TAIL_LINES = 20;
35
-
36
- /** A wrong invocation, not a red verification: `verify` exits 2 for it, 1 for "code not ready". */
37
- export class VerifyUsageError extends Error {
38
- constructor(message) {
39
- super(message);
40
- this.name = 'VerifyUsageError';
41
- this.code = 'verify-usage';
42
- }
43
- }
44
-
45
- /**
46
- * @throws {VerifyUsageError} on an invocation that cannot mean what was typed (exit 2)
47
- * @throws {HeavyBusyError} when no heavy slot (or RAM) freed within `heavy.waitTimeoutSec`
48
- */
49
- export async function runVerify(projectPath, featureName, options = {}) {
50
- const gate = options._heavyGate ?? createHeavyGate({ projectPath, feature: featureName });
51
- try {
52
- return await runVerifyGated(projectPath, featureName, applyAffectedScope(projectPath, options), gate);
53
- } finally {
54
- gate.release();
55
- }
56
- }
57
-
58
- export function withCpuShare(node, share) {
59
- if (!share || node.runner !== 'vitest' || /--max-?workers/i.test(node.command ?? '')) return node;
60
- return { ...node, command: `${node.command} --maxWorkers=${share}` };
61
- }
62
-
63
- // The complete run still runs each suite whole; it only leaves out a suite the feature diff cannot reach.
64
- // The same selection `--affected` uses, so what escalates it (migration, contract, shared code) keeps all.
65
- function outOfDiffSuites(projectPath, options) {
66
- if (options.filter || options.recordBaseline || options.refreshCache || options.linux || options.skipTests) return options;
67
- const nodes = resolveTestNodes(projectPath).nodes;
68
- const selection = selectAffected({ projectPath, nodes, deps: options._affectedDeps });
69
- if (selection.scope !== 'affected') return options;
70
- // A suite rooted at the project root reaches everything: only a suite with its own `cwd` is a slice.
71
- const kept = new Set(nodes.filter((n) => n.e2e || n.evals || n.runner === EVAL_RUNNER || !n.cwd || n.cwd === '.').map((n) => n.id));
72
- const outOfDiff = selection.skipped.filter((id) => !kept.has(id));
73
- return outOfDiff.length ? { ...options, outOfDiff } : options;
74
- }
75
-
76
- function applyAffectedScope(projectPath, options) {
77
- if (!options.affected) return outOfDiffSuites(projectPath, options);
78
- const conflict = [['filter', '--filter'], ['recordBaseline', '--record-baseline'], ['refreshCache', '--refresh-cache'], ['linux', '--linux']]
79
- .find(([key]) => options[key]);
80
- if (conflict) throw new VerifyUsageError(`--affected escolhe os testes sozinho; não combina com ${conflict[1]}`);
81
-
82
- const selection = selectAffected({ projectPath, nodes: resolveTestNodes(projectPath).nodes, deps: options._affectedDeps });
83
- if (selection.scope === 'full') return { ...options, escalatedBecause: selection.reason };
84
- // Every suite selected and none narrowed is the complete run: stamp it once, so the gate's run reuses it.
85
- const all = resolveTestNodes(projectPath).nodes;
86
- const whole = selection.skipped.length === 0 && selection.nodes.length === all.length
87
- && selection.nodes.every((n, i) => n.command === all[i].command);
88
- if (whole) return outOfDiffSuites(projectPath, { ...options, escalatedBecause: 'a seleção afetada já é a suíte inteira' });
89
- return {
90
- ...options,
91
- selection,
92
- skipE2e: true,
93
- skipBuild: options.skipBuild || selection.docsOnly,
94
- skipTests: options.skipTests || selection.nodes.length === 0,
95
- };
96
- }
97
-
98
- async function runVerifyGated(projectPath, featureName, options, gate) {
99
- const {
100
- timeout = DEFAULT_BUILD_TIMEOUT,
101
- skipTests = false,
102
- skipBuild = false,
103
- skipE2e = false,
104
- freshE2e = false,
105
- recordBaseline = false,
106
- refreshCache = false,
107
- linux = false,
108
- linuxImage = null,
109
- fingerprint = null,
110
- fresh = false,
111
- _runLinuxSuite = runLinuxSuite,
112
- _exec = undefined,
113
- _runBuildCheck = runBuildCheck,
114
- _runTestSuite = runTestSuite,
115
- _runValidation = runValidation,
116
- _runE2eCheck = runE2eCheck,
117
- _e2eApplicability = e2eApplicability,
118
- } = options;
119
-
120
- const stack = readStack(projectPath);
121
- const paths = readProjectPaths(projectPath);
122
-
123
- // Usage errors are judged before the build: paying for a build to discover a typo
124
- // is the worst ordering, and a refusal after the cache was touched leaves a half-rewritten tree.
125
- const resolvedPlan = resolveTestNodes(projectPath);
126
- const excluded = new Set(options.excludeNodes ?? []);
127
- const outOfDiff = new Set(options.outOfDiff ?? []);
128
- const scopedNodes = options.selection ? options.selection.nodes : resolvedPlan.nodes;
129
- const testPlan = { ...resolvedPlan, nodes: scopedNodes.filter((node) => !excluded.has(node.id) && !outOfDiff.has(node.id)) };
130
- const filter = parseTestFilter(options.filter);
131
- if (filter && !testPlan.nodes.some((node) => nodeMatchesFilter(node, filter))) {
132
- const declared = testPlan.nodes.map((node) => node.id).join(', ') || '(none)';
133
- throw new VerifyUsageError(
134
- `--filter "${filter.raw}" matched no test node — declared nodes: ${declared}`
135
- );
136
- }
137
-
138
- if (recordBaseline) {
139
- const problem = baselineTargetProblem(projectPath, testPlan, { skipTests });
140
- if (problem) throw new VerifyUsageError(problem);
141
- }
142
-
143
- if (refreshCache) {
144
- const problem = refreshCacheProblem(projectPath, testPlan, filter, { skipTests });
145
- if (problem) throw new VerifyUsageError(problem);
146
- }
147
-
148
- // Missing Docker is a usage error, never a skip: "could not check on Linux" must not read as green.
149
- if (linux) {
150
- const problem = checkLinuxPreconditions({
151
- projectPath, skipTests, ...(_exec ? { exec: _exec } : {}),
152
- });
153
- if (problem) throw new VerifyUsageError(problem);
154
-
155
- const evalNode = testPlan.nodes.find(
156
- (node) => node.runner === EVAL_RUNNER && nodeMatchesFilter(node, filter)
157
- );
158
- if (evalNode) {
159
- throw new VerifyUsageError(
160
- `--linux não executa o nó de eval "${evalNode.id}": o canal MORPH_EVAL_* carrega caminhos absolutos do host, `
161
- + 'e o container roda uma CÓPIA da árvore em /work. Rode o eval fora do container, '
162
- + `ou exclua-o com --filter (nós declarados: ${testPlan.nodes.map((n) => n.id).join(', ')}).`
163
- );
164
- }
165
- }
166
-
167
- const nodes = {};
168
- const feedback = [];
169
- if (options.escalatedBecause) feedback.push(`[verify] rodada completa: ${options.escalatedBecause}`);
170
- if (options.selection) {
171
- const kept = options.selection.nodes.map((n) => n.id).join(', ') || 'nenhuma';
172
- feedback.push(`[verify] rodada afetada, suítes: ${kept}; a completa roda uma vez antes da aprovação`);
173
- }
174
- if (excluded.size > 0) feedback.push(`[verify] provadas pelo CI da PR no finish: ${[...excluded].join(', ')}`);
175
- if (outOfDiff.size > 0) feedback.push(`[verify] suítes fora do diff da feature: ${[...outOfDiff].join(', ')}`);
176
-
177
- // Only a complete run feeds or reads the cache: a partial one proves nothing about the nodes it left out.
178
- const cacheDir = fingerprint && !filter && !skipTests && !skipBuild && !skipE2e && !recordBaseline
179
- && !refreshCache && !linux && !freshE2e && excluded.size === 0
180
- ? resolveGitCommonDir(projectPath)
181
- : null;
182
- const reuse = planReuse(cacheDir && !fresh ? readVerifyCache(cacheDir, featureName) : null, fingerprint);
183
-
184
- nodes.build = reuse.build
185
- ? reusedEntry(reuse.build)
186
- : await runBuildNode({ projectPath, stack, paths, timeout, skipBuild, gate, _runBuildCheck });
187
- appendBuildFeedback(feedback, nodes.build);
188
-
189
- // Only a TYPED --timeout reaches the tests: the build default would outrank
190
- // config.project.testTimeoutMs and the per-project scaling.
191
- const explicitTimeout = Number.isFinite(options.timeout) ? options.timeout : undefined;
192
- const stackNodes = [];
193
- const buildFacts = { solutionBuilt: builtDotnet(nodes.build), builtTargets: new Set() };
194
- nodes.tests = await runTestsNode({
195
- projectPath,
196
- testPlan,
197
- filter,
198
- skipTests: skipTests || (excluded.size > 0 && testPlan.nodes.length === 0),
199
- buildNode: nodes.build,
200
- timeout: explicitTimeout,
201
- refreshCache,
202
- linux,
203
- linuxImage,
204
- gate,
205
- stackNodes,
206
- reuse,
207
- buildFacts,
208
- _runTestSuite,
209
- _runLinuxSuite,
210
- _exec,
211
- });
212
- if (stackNodes.length === 0) appendTestsFeedback(feedback, nodes.tests);
213
-
214
- nodes.validators = await runValidatorsNode({ projectPath, featureName, _runValidation });
215
- appendValidatorsFeedback(feedback, nodes.validators);
216
-
217
- // A suite with `e2e: true` still to run needs the stack's env, which only a real run returns.
218
- const e2e = reuse.e2e && stackNodes.length === 0 && nodes.tests.status !== 'fail'
219
- ? { node: reusedEntry(reuse.e2e), stackEnv: null }
220
- : await runE2eNode({
221
- projectPath,
222
- featureName,
223
- skipE2e,
224
- freshE2e,
225
- buildNode: nodes.build,
226
- testsNode: nodes.tests,
227
- hasStackNodes: stackNodes.length > 0,
228
- gate,
229
- _runE2eCheck,
230
- _e2eApplicability,
231
- });
232
- nodes.e2e = e2e.node;
233
- appendE2eFeedback(feedback, nodes.e2e);
234
-
235
- if (stackNodes.length > 0) {
236
- nodes.tests = await runStackTestNodes({
237
- projectPath, testsNode: nodes.tests, stackNodes, e2eNode: nodes.e2e, stackEnv: e2e.stackEnv,
238
- timeout: explicitTimeout, gate, buildFacts, _runTestSuite,
239
- });
240
- appendTestsFeedback(feedback, nodes.tests);
241
- }
242
-
243
- const baseline = recordBaseline ? recordBaselineFrom(projectPath, nodes.tests) : null;
244
- if (baseline && !baseline.recorded) {
245
- feedback.push(`[baseline] não gravada: ${baseline.reason}`);
246
- }
247
- const lowered = baseline?.recorded ? baseline.updates.filter((u) => u.from !== null && u.to < u.from) : [];
248
- if (lowered.length > 0) {
249
- feedback.push(`[baseline] rebaixada: ${lowered.map((u) => `${u.id} (${u.from} → ${u.to})`).join(', ')}`);
250
- nodes.tests = acceptRecordedDrops(nodes.tests);
251
- }
252
-
253
- const status = Object.values(nodes).some((n) => n.status === 'fail') ? 'fail' : 'pass';
254
-
255
- if (cacheDir) writeVerifyCache(cacheDir, featureName, cacheEntryFrom(fingerprint, nodes));
256
-
257
- const reused = reusedNames(nodes);
258
- if (reused.length > 0) feedback.push(`[verify] aproveitado da rodada anterior na mesma árvore: ${reused.join(', ')}`);
259
- const flaky = flakyNames(nodes, reuse.retried);
260
- if (flaky.length > 0) feedback.push(`[verify] vermelho sem mudança de código, verde agora (instável): ${flaky.join(', ')}`);
261
-
262
- return {
263
- version: 1,
264
- feature: featureName,
265
- stack,
266
- status,
267
- scope: options.selection ? 'affected' : 'full',
268
- nodes,
269
- feedback,
270
- reused,
271
- flaky,
272
- ...(baseline ? { baseline } : {}),
273
- };
274
- }
275
-
276
- function reusedNames(nodes) {
277
- return [
278
- ...(nodes.build.reused ? ['build'] : []),
279
- ...(nodes.tests.runs || []).filter((run) => run.reused).map((run) => `tests/${run.id}`),
280
- ...(nodes.e2e.reused ? ['e2e'] : []),
281
- ];
282
- }
283
-
284
- function flakyNames(nodes, retried) {
285
- return [
286
- ...(nodes.tests.runs || []).filter((run) => run.status === 'pass' && retried.has(run.id)).map((run) => `tests/${run.id}`),
287
- ...(nodes.e2e.status === 'pass' && retried.has('e2e') ? ['e2e'] : []),
288
- ...(nodes.e2e.flakySpecs || []).map((spec) => `e2e: ${spec}`),
289
- ...(nodes.e2e.quarantinedSpecs || []).map((spec) => `e2e (quarentena): ${spec}`),
290
- ];
291
- }
292
-
293
- /**
294
- * A root `dotnet build` with no solution at the root fails MSB1003: build the
295
- * repository's single solution instead, or say which candidates and which key decide.
296
- */
297
- export function resolveDotnetBuild(projectPath, stack, paths = {}) {
298
- if (!stack || !isDotnetStack(stack.toLowerCase()) || paths.backendPath) return { paths, hint: null };
299
- const { target, candidates } = discoverDotnetSolution(projectPath);
300
- if (target === '.') return { paths, hint: null };
301
- if (target) return { paths: { ...paths, backendTarget: target }, hint: null };
302
- const found = candidates.length ? `candidatos: ${candidates.join(', ')}` : 'nenhum encontrado abaixo dela';
303
- return {
304
- paths,
305
- hint: `nenhum .sln/.slnx/.csproj na raiz (${found}): declare project.backendPath em .morph/config/config.json com a pasta da solução, relativa à raiz`,
306
- };
307
- }
308
-
309
- async function runBuildNode({ projectPath, stack, paths: declaredPaths = {}, timeout, skipBuild, gate, _runBuildCheck }) {
310
- if (skipBuild) {
311
- return { status: 'skip', command: null, durationMs: 0, reason: 'requested', output: '' };
312
- }
313
-
314
- const resolved = resolveDotnetBuild(projectPath, stack, declaredPaths);
315
- const { hint } = resolved;
316
- const paths = { ...resolved.paths, lintFiles: featureLintFiles(projectPath, stack, resolved.paths.frontendPath) };
317
- const steps = getBuildSteps(stack, { cwd: projectPath, frontendPath: paths.frontendPath, backendPath: paths.backendPath, backendTarget: paths.backendTarget, lintFiles: paths.lintFiles });
318
- if (steps.length === 0) {
319
- const reason = stack ? `no build command for stack "${stack}"` : 'no stack configured';
320
- return { status: 'skip', command: null, durationMs: 0, reason, output: '' };
321
- }
322
- const command = steps.map((s) => s.command).join(' && ');
323
-
324
- gate.enter('build');
325
- const start = Date.now();
326
- const result = await _runBuildCheck(projectPath, stack, timeout, paths);
327
- const durationMs = Date.now() - start;
328
-
329
- return {
330
- status: result.status,
331
- command,
332
- durationMs,
333
- reason: result.status === 'skip' ? 'no build command for stack' : null,
334
- output: [result.output, result.status === 'fail' ? hint : null].filter(Boolean).join('\n'),
335
- };
336
- }
337
-
338
- const LINTABLE = /\.(?:tsx?|jsx?|mjs|cjs)$/;
339
-
340
- /** The feature's own source files under the frontend, relative to it; `[]` when the base does not resolve. */
341
- export function featureLintFiles(projectPath, stack, frontendPath, { changed } = {}) {
342
- if (!/nextjs|react|vue|node/i.test(stack ?? '')) return [];
343
- const paths = changed ?? changedPathsAgainst(resolveBaseRef(detectDefaultBranch(projectPath), projectPath), projectPath);
344
- const prefix = frontendPath ? `${frontendPath.replace(/\\/g, '/').replace(/\/$/, '')}/` : '';
345
- return paths
346
- .filter((p) => LINTABLE.test(p) && p.startsWith(prefix) && existsSync(join(projectPath, p)))
347
- .map((p) => p.slice(prefix.length));
348
- }
349
-
350
- function appendBuildFeedback(feedback, buildNode) {
351
- if (buildNode.status !== 'fail') return;
352
- for (const line of linesOf(buildNode.output)) {
353
- feedback.push(`[build] ${line}`);
354
- }
355
- }
356
-
357
- // Every declared suite runs and appears in `runs[]`; the rollup stays an object
358
- // with `status` because verify.js and the persisted stamp read `nodes.tests.status`.
359
- async function runTestsNode({
360
- projectPath, testPlan, filter, skipTests, buildNode, timeout, refreshCache = false,
361
- linux = false, linuxImage = null, gate, stackNodes = [], reuse, buildFacts, _runTestSuite, _runLinuxSuite = runLinuxSuite, _exec,
362
- }) {
363
- const { nodes, source } = testPlan;
364
- const command = nodes.map((n) => n.command).filter(Boolean).join(' && ') || null;
365
- // A fresh `runs: []` per return — two rollups must never alias one array.
366
- const nothingRan = (reason) => ({
367
- status: 'skip', command, source, environment: null, runs: [], warnings: [],
368
- durationMs: 0, reason, output: '',
369
- });
370
-
371
- if (skipTests) return nothingRan('requested');
372
-
373
- if (buildNode.status === 'fail') {
374
- return nothingRan('build failed — test run would only add noise');
375
- }
376
-
377
- if (linux) {
378
- const { runs, environment } = await runNodesInLinux({
379
- projectPath, nodes, filter, timeout, linuxImage, gate, _runLinuxSuite, _exec,
380
- });
381
- return rollUpTestRuns(runs, { command, source, environment });
382
- }
383
-
384
- const declaredOrder = new Map(nodes.map((node, index) => [node.id, index]));
385
- const redFirst = [...nodes].sort((a, b) => reuse.redFirst.has(b.id) - reuse.redFirst.has(a.id));
386
-
387
- // A round chasing a red suite stays serial: it must be able to stop at the first one.
388
- const together = reuse.redFirst.size > 0
389
- ? []
390
- : nodes.filter((node) => node.parallel && !node.e2e && !reuse.tests.has(node.id));
391
- const finished = new Map(await Promise.all(together.map(async (node) => [node.id, await runOneTestNode({
392
- projectPath, node, filter, timeout, refreshCache, gate, buildFacts, _runTestSuite,
393
- })])));
394
-
395
- const runs = [];
396
- let stillRed = null;
397
- for (const node of redFirst) {
398
- if (reuse.tests.has(node.id)) {
399
- runs.push(reusedEntry(reuse.tests.get(node.id)));
400
- continue;
401
- }
402
- if (finished.has(node.id)) {
403
- runs.push(finished.get(node.id));
404
- continue;
405
- }
406
- if (stillRed) {
407
- runs.push({ ...emptyRunEntry(node), reason: `adiado: ${stillRed} segue vermelho` });
408
- continue;
409
- }
410
- if (node.e2e && !preDecideRun({ node, filter, projectPath, refreshCache })) {
411
- stackNodes.push(node);
412
- runs.push(emptyRunEntry(node));
413
- continue;
414
- }
415
- const run = await runOneTestNode({
416
- projectPath, node, filter, timeout, refreshCache, gate, buildFacts, _runTestSuite,
417
- });
418
- runs.push(run);
419
- if (run.status === 'fail' && reuse.redFirst.has(node.id)) stillRed = node.id;
420
- }
421
-
422
- runs.sort((a, b) => declaredOrder.get(a.id) - declaredOrder.get(b.id));
423
- return rollUpTestRuns(runs, { command, source });
424
- }
425
-
426
- // No stack, no run: the skip carries the e2e verdict as reason AND warning, so the
427
- // suite never disappears behind a green rollup.
428
- const builtDotnet = (buildNode) => buildNode.status === 'pass' && /\bdotnet build\b/.test(buildNode.command ?? '');
429
-
430
- async function runStackTestNodes({ projectPath, testsNode, stackNodes, e2eNode, stackEnv, timeout, gate, buildFacts, _runTestSuite }) {
431
- const byId = new Map(stackNodes.map((node) => [node.id, node]));
432
- const runs = [];
433
- for (const run of testsNode.runs) {
434
- const node = byId.get(run.id);
435
- if (!node) { runs.push(run); continue; }
436
- if (e2eNode.status !== 'pass') {
437
- const reason = `a stack do e2e não está de pé (e2e: ${e2eNode.status}${e2eNode.reason ? ` — ${e2eNode.reason}` : ''}): nó e2e: true não roda sem ela`;
438
- runs.push({ ...run, reason, warnings: [reason] });
439
- continue;
440
- }
441
- runs.push(await runOneTestNode({ projectPath, node, filter: null, timeout, gate, env: stackEnv, buildFacts, _runTestSuite }));
442
- }
443
- return rollUpTestRuns(runs, { command: testsNode.command, source: testsNode.source, environment: testsNode.environment });
444
- }
445
-
446
- // Pre-decisions run before the container exists, so a filtered node is never written
447
- // into its script; results go through the same `judgeRun()` as the host path.
448
- async function runNodesInLinux({
449
- projectPath, nodes, filter, timeout, linuxImage, gate, _runLinuxSuite, _exec,
450
- }) {
451
- const decided = new Map();
452
- const toRun = [];
453
- for (const node of nodes) {
454
- const pre = preDecideRun({ node, filter, projectPath });
455
- if (pre) decided.set(node.id, pre);
456
- else toRun.push(node);
457
- }
458
-
459
- // One container, one clock: the sum of each node's local timeout.
460
- const containerTimeout = toRun.reduce(
461
- (sum, node) => sum + resolveTestTimeout(projectPath, node, timeout), 0
462
- ) || undefined;
463
-
464
- if (toRun.length > 0) gate.enter('tests');
465
- const suite = await _runLinuxSuite({
466
- projectPath,
467
- nodes: toRun,
468
- image: linuxImage || undefined,
469
- timeout: containerTimeout,
470
- ...(_exec ? { exec: _exec } : {}),
471
- });
472
-
473
- const byId = new Map((suite.results || []).map((r) => [r.id, r]));
474
- const runs = nodes.map((node) => {
475
- if (decided.has(node.id)) return decided.get(node.id);
476
- const raw = byId.get(node.id);
477
- if (!raw) {
478
- return { ...emptyRunEntry(node), status: 'fail', reason: 'o container não reportou este nó' };
479
- }
480
- if (raw.skipped) {
481
- return { ...emptyRunEntry(node), reason: raw.reason };
482
- }
483
- const result = raw.exitCode === null
484
- // No exit code is NOT a pass: the container died before this node reported.
485
- ? { passed: false, output: raw.output || '', reason: raw.reason, exitCode: null }
486
- : { passed: raw.exitCode === 0, output: raw.output || '', exitCode: raw.exitCode };
487
- const logPath = writeFailedRunLog(projectPath, node, result);
488
- return judgeRun({ node, result, durationMs: raw.durationMs ?? 0, logPath });
489
- });
490
-
491
- return { runs, environment: suite.environment };
492
- }
493
-
494
- async function runOneTestNode({
495
- projectPath, node, filter, timeout, refreshCache = false, gate, env = null, buildFacts = {}, _runTestSuite,
496
- }) {
497
- const decided = preDecideRun({ node, filter, projectPath, refreshCache });
498
- if (decided) return decided;
499
-
500
- const evalChannel = node.runner === EVAL_RUNNER
501
- ? evalNodeEnv(node, projectPath, { refresh: refreshCache })
502
- : null;
503
- // The summary path is fixed per node id and pid: a file left by an earlier run
504
- // would be read as this run's and hide an empty run behind the old count.
505
- if (evalChannel) discardFile(evalChannel.summaryPath);
506
-
507
- gate.enter('tests');
508
- const start = Date.now();
509
- const childEnv = env || evalChannel ? { ...(env || {}), ...(evalChannel?.env || {}) } : null;
510
- const result = await _runTestSuite(projectPath, {
511
- timeout, node: withCpuShare(node, gate.cpuShare), ...buildFacts, background: node.parallel === true, ...(childEnv ? { env: childEnv } : {}),
512
- });
513
- const durationMs = Date.now() - start;
514
- const logPath = writeFailedRunLog(projectPath, node, result);
515
- const entry = judgeRun({ node, result, durationMs, logPath });
516
- if (!evalChannel) return entry;
517
-
518
- const judged = judgeEvalRun(entry, node, evalChannel.summaryPath);
519
- discardFile(evalChannel.summaryPath);
520
- return judged;
521
- }
522
-
523
- // Fail-open: a log that cannot be written must not change the verdict.
524
- function writeFailedRunLog(projectPath, node, result) {
525
- if (result.passed || result.skipped || !result.output) return null;
526
- const relPath = `.morph/logs/verify-tests-${String(node.id).replace(/[^\w.-]/g, '_')}.log`;
527
- try {
528
- mkdirSync(join(projectPath, '.morph', 'logs'), { recursive: true });
529
- writeFileSync(join(projectPath, relPath), result.output);
530
- return relPath;
531
- } catch {
532
- return null;
533
- }
534
- }
535
-
536
- function discardFile(path) {
537
- try { rmSync(path, { force: true }); } catch { /* the next run removes it first */ }
538
- }
539
-
540
- // The scenario count comes ONLY from the summary (the dotnet extractor counts xunit
541
- // cases, another unit); no readable summary is null, UNKNOWN, never 0.
542
- function judgeEvalRun(entry, node, summaryPath) {
543
- const summary = readEvalSummary(summaryPath);
544
- const warnings = [...(entry.warnings || [])];
545
-
546
- const cold = evalColdCacheWarning(summary);
547
- if (cold) warnings.push(cold);
548
-
549
- const count = evalScenarioCount(summary);
550
- const verdict = compareTestCount(count, node.expectedCount);
551
- if (verdict.warning) warnings.push(verdict.warning);
552
-
553
- // Named failures go into `output` (feedback prefers it to `reason`), prepended
554
- // rather than replacing it because a runner crash also lives in that tail.
555
- const named = evalFailureLines(summary);
556
- const withNames = named.length > 0
557
- ? { ...entry, output: [...named, ...(entry.output ? [entry.output] : [])].join('\n') }
558
- : entry;
559
-
560
- const empty = evalEmptyRunProblem(summary);
561
- if (empty) {
562
- return { ...withNames, status: 'fail', count, warnings, reason: empty };
563
- }
564
-
565
- if (entry.status === 'pass' && verdict.verdict === 'drop') {
566
- return { ...withNames, status: 'fail', count, warnings, reason: verdict.reason, countDrop: true };
567
- }
568
- if (verdict.verdict === 'drop') warnings.push(verdict.reason);
569
-
570
- return { ...withNames, count, warnings };
571
- }
572
-
573
- function emptyRunEntry(node) {
574
- return {
575
- id: node.id,
576
- command: node.command,
577
- cwd: node.cwd,
578
- runner: node.runner,
579
- expectedCount: node.expectedCount,
580
- // null is UNKNOWN, never 0.
581
- count: null,
582
- status: 'skip',
583
- durationMs: 0,
584
- reason: null,
585
- warnings: [],
586
- output: '',
587
- };
588
- }
589
-
590
- // Verdicts decided before execution, shared by the host loop and `--linux` so both
591
- // refuse for the same reason with the same words; null means the node must run.
592
- function preDecideRun({ node, filter, projectPath = '.', refreshCache = false }) {
593
- const entry = emptyRunEntry(node);
594
-
595
- if (node.status) {
596
- return { ...entry, status: node.status, reason: node.reason };
597
- }
598
-
599
- // After the pre-decided verdict on purpose: an invalid node costs no clock and
600
- // still reddens the gate even when filtered out.
601
- if (!nodeMatchesFilter(node, filter)) {
602
- return { ...entry, reason: `filtered out (--filter ${filter.raw})` };
603
- }
604
-
605
- // A cache miss is a fail, never a skip: a skip would be green over nothing.
606
- if (node.runner === EVAL_RUNNER) {
607
- const pre = evalPreflight(projectPath, node, { refresh: refreshCache });
608
- if (pre.status) return { ...entry, status: pre.status, reason: pre.reason };
609
- }
610
-
611
- return null;
612
- }
613
-
614
- // The single count rule for host and container runs; a second copy makes them disagree.
615
- function judgeRun({ node, result, durationMs, logPath = null }) {
616
- const entry = emptyRunEntry(node);
617
-
618
- if (result.skipped) {
619
- return { ...entry, durationMs, reason: result.reason || 'no test command detected' };
620
- }
621
-
622
- const logLine = logPath ? [`log completo: ${logPath}`] : [];
623
-
624
- // A truncated log tail reads like a passing run cut mid-sentence: lead with the timeout.
625
- if (result.timedOut) {
626
- const tail = tailLines(result.output, OUTPUT_TAIL_LINES);
627
- return {
628
- ...entry,
629
- status: 'fail',
630
- durationMs,
631
- timedOut: true,
632
- reason: result.message,
633
- output: [result.message, ...logLine, tail].filter(Boolean).join('\n'),
634
- };
635
- }
636
-
637
- // Parsed from the FULL output, before truncation to a tail.
638
- const parsed = parseTestCount(result.output, node.runner);
639
- const count = parsed ? parsed.total : null;
640
-
641
- // An eval node's unit is the SCENARIO, compared only by `judgeEvalRun`; the
642
- // extractor's xunit-case count against that baseline would fail green runs.
643
- const verdict = compareTestCount(count, node.runner === EVAL_RUNNER ? null : node.expectedCount);
644
- const warnings = verdict.warning ? [verdict.warning] : [];
645
-
646
- // Only a drop fails a node; a rise never does, or failing on growth teaches deleting tests.
647
- if (verdict.verdict === 'drop' && result.passed) {
648
- return { ...entry, status: 'fail', durationMs, count, warnings, reason: verdict.reason, output: '', countDrop: true };
649
- }
650
- if (verdict.verdict === 'drop') warnings.push(verdict.reason);
651
-
652
- // Without a baseline, zero is the floor: a green run over no test is a suite that stopped running.
653
- if (result.passed && count === 0 && !node.allowEmpty && node.runner !== EVAL_RUNNER && !Number.isInteger(node.expectedCount)) {
654
- return { ...entry, status: 'fail', durationMs, count, warnings, reason: 'suíte verde sem nenhum teste executado', output: '' };
655
- }
656
-
657
- if (result.passed) {
658
- return { ...entry, status: 'pass', durationMs, count, warnings, reason: result.reason ?? null, output: '' };
659
- }
660
-
661
- // The failing test sits thousands of lines above a TAP summary, never in the tail.
662
- const failed = failureLines(result.output);
663
- return {
664
- ...entry,
665
- status: 'fail',
666
- durationMs,
667
- count,
668
- warnings,
669
- // `test-build-failed` / `stale-binary`: refused before any test ran.
670
- reason: result.reason ?? failureSummary(failed),
671
- output: [
672
- ...failed.map((name) => `falhou: ${name}`),
673
- ...logLine,
674
- tailLines(result.output, OUTPUT_TAIL_LINES),
675
- ].filter(Boolean).join('\n'),
676
- };
677
- }
678
-
679
- function failureSummary(failed) {
680
- if (failed.length === 0) return null;
681
- const more = failed.length > 3 ? ` (+${failed.length - 3})` : '';
682
- return `falhou: ${failed.slice(0, 3).join('; ')}${more}`;
683
- }
684
-
685
- function acceptRecordedDrops(testsNode) {
686
- const runs = testsNode.runs.map(({ countDrop, ...run }) => (countDrop ? { ...run, status: 'pass', reason: null } : run));
687
- return rollUpTestRuns(runs, { command: testsNode.command, source: testsNode.source, environment: testsNode.environment });
688
- }
689
-
690
- // Any red run reddens the rollup; one green run among skips is a pass.
691
- function rollUpTestRuns(runs, { command, source, environment = null }) {
692
- const failed = runs.filter((r) => r.status === 'fail');
693
- const status = failed.length > 0
694
- ? 'fail'
695
- : runs.some((r) => r.status === 'pass') ? 'pass' : 'skip';
696
-
697
- const node = {
698
- status,
699
- command,
700
- durationMs: runs.reduce((sum, r) => sum + (r.durationMs || 0), 0),
701
- reason: null,
702
- output: failed.map((r) => r.output).filter(Boolean).join('\n'),
703
- source,
704
- // null is the local host; a container run is named so feature.json says what was proven.
705
- environment,
706
- warnings: runs.flatMap((r) => (r.warnings || []).map((w) => `${r.id}: ${w}`)),
707
- runs,
708
- };
709
-
710
- if (status === 'fail') node.reason = failed[0].reason ?? null;
711
- else if (status === 'skip') {
712
- node.reason = runs.length === 1 ? runs[0].reason : 'every test node was skipped';
713
- }
714
- if (runs.some((r) => r.timedOut)) node.timedOut = true;
715
-
716
- return node;
717
- }
718
-
719
- function appendTestsFeedback(feedback, testsNode) {
720
- // Warnings print whatever the verdict: a stale baseline lives on a GREEN node.
721
- for (const run of testsNode.runs || []) {
722
- for (const warning of run.warnings || []) {
723
- feedback.push(`[tests/${run.id}] warning: ${warning}`);
724
- }
725
- }
726
- if (testsNode.status !== 'fail') return;
727
- for (const run of testsNode.runs || []) {
728
- if (run.status !== 'fail') continue;
729
- for (const line of linesOf(run.output || run.reason || '')) {
730
- feedback.push(`[tests/${run.id}] ${line}`);
731
- }
732
- }
733
- }
734
-
735
- // The missing credential is judged per node by `evalPreflight`, not here.
736
- function refreshCacheProblem(projectPath, testPlan, filter, { skipTests }) {
737
- if (skipTests) {
738
- return '--refresh-cache com --skip-tests: as duas flags se anulam — a regravação da cache É a suíte de eval';
739
- }
740
-
741
- const evalNodes = testPlan.nodes.filter((node) => node.runner === EVAL_RUNNER);
742
- if (evalNodes.length === 0) {
743
- const declared = testPlan.nodes.map((node) => node.id).join(', ') || '(nenhum)';
744
- return `--refresh-cache sem nenhum nó \`runner: "evals"\` declarado em project.tests[] — nós declarados: ${declared}`;
745
- }
746
-
747
- if (!evalNodes.some((node) => nodeMatchesFilter(node, filter))) {
748
- return `--refresh-cache com --filter "${filter.raw}", que não casa nenhum nó de eval`
749
- + ` (nós de eval: ${evalNodes.map((node) => node.id).join(', ')})`;
750
- }
751
-
752
- return null;
753
- }
754
-
755
- // Never creates config.json nor a `project.tests[]` entry: fallback nodes have no
756
- // declaration to update, and inventing one is not this command's job.
757
- function baselineTargetProblem(projectPath, testPlan, { skipTests }) {
758
- if (skipTests) {
759
- return '--record-baseline com --skip-tests não mede nada — uma baseline vem de uma execução, não de uma omissão';
760
- }
761
- if (!existsSync(morphConfigPath(projectPath))) {
762
- return `--record-baseline não tem onde gravar: ${morphConfigPath(projectPath)} não existe `
763
- + '(e não será criado — declare project.tests[] antes)';
764
- }
765
- if (testPlan.source !== 'config-tests') {
766
- return '--record-baseline exige project.tests[] declarado em .morph/config/config.json — '
767
- + `os nós de "${testPlan.source}" são sintetizados pelo fallback e não têm entrada onde gravar`;
768
- }
769
- return null;
770
- }
771
-
772
- // Only a run with EVERY node green records: a red run would freeze the regression,
773
- // a partial one would claim counts for nodes nobody measured. A count drop on a run that
774
- // exited 0 is the one red it accepts: lowering the number is how deleting tests passes.
775
- function recordBaselineFrom(projectPath, testsNode) {
776
- const runs = testsNode.runs || [];
777
- const refuse = (reason) => ({ recorded: false, reason, updates: [], removed: [] });
778
-
779
- if (runs.length === 0) return refuse('nenhum nó de teste executou');
780
-
781
- const notGreen = runs.filter((r) => r.status !== 'pass' && !r.countDrop);
782
- if (notGreen.length > 0) {
783
- const named = notGreen.map((r) => `${r.id} (${r.status}${r.reason ? `: ${r.reason}` : ''})`).join('; ');
784
- return refuse(
785
- `execução não está inteiramente verde — ${named}. `
786
- + 'Gravar baseline de execução vermelha ou parcial congela a regressão'
787
- );
788
- }
789
-
790
- return recordTestBaselines(projectPath, runs.map((r) => ({ id: r.id, count: r.count })));
791
- }
792
-
793
- async function runValidatorsNode({ projectPath, featureName, _runValidation }) {
794
- const start = Date.now();
795
-
796
- // runValidation() prints progress to stdout, which would corrupt verify's JSON.
797
- const originalLog = console.log;
798
- const originalWarn = console.warn;
799
- let validationResult;
800
- try {
801
- console.log = () => {};
802
- console.warn = () => {};
803
- validationResult = await _runValidation(projectPath, featureName);
804
- } finally {
805
- console.log = originalLog;
806
- console.warn = originalWarn;
807
- }
808
-
809
- const durationMs = Date.now() - start;
810
-
811
- const skipped = validationResult?.skipped ?? [];
812
-
813
- if (validationResult && validationResult._skipReason) {
814
- return {
815
- status: 'skip',
816
- ran: [],
817
- skipped,
818
- reason: validationResult._skipReason,
819
- issues: [],
820
- durationMs,
821
- };
822
- }
823
-
824
- return {
825
- status: validationResult.passed === false ? 'fail' : 'pass',
826
- ran: Object.keys(validationResult.results || {}),
827
- skipped,
828
- reason: null,
829
- issues: validationResult.issues || [],
830
- durationMs,
831
- };
832
- }
833
-
834
- function appendValidatorsFeedback(feedback, validatorsNode) {
835
- // A validator that could not check is invisible in a green node otherwise.
836
- if (validatorsNode.status !== 'skip') {
837
- for (const s of validatorsNode.skipped || []) {
838
- if (s.unavailable) feedback.push(`[validators/${s.validator}] não rodou: ${s.reason}`);
839
- }
840
- }
841
- const issues = validatorsNode.issues || [];
842
- const ordered = [
843
- ...issues.filter((i) => i.level === 'error'),
844
- ...issues.filter((i) => i.level !== 'error'),
845
- ].slice(0, VALIDATOR_FEEDBACK_LIMIT);
846
- for (const issue of ordered) {
847
- const location = issue.file ? ` (${issue.file}${issue.line ? ':' + issue.line : ''})` : '';
848
- feedback.push(`[validators/${issue.validator ?? 'unknown'}] ${issue.message}${location}`);
849
- }
850
- }
851
-
852
- const skippedE2e = (reason) => ({ node: { status: 'skip', command: null, durationMs: 0, reason, output: '' }, stackEnv: null });
853
-
854
- async function runE2eNode({
855
- projectPath, featureName, skipE2e, freshE2e, buildNode, testsNode, hasStackNodes, gate, _runE2eCheck, _e2eApplicability,
856
- }) {
857
- if (buildNode.status === 'fail') return skippedE2e('build failed — the stack could not come up anyway');
858
- if (testsNode?.status === 'fail') return skippedE2e('tests failed — the e2e does not run over a red suite');
859
-
860
- const config = readConfig(projectPath);
861
- // An `e2e: true` test node is the backend's proof against the stack: it always brings the stack up.
862
- if (!skipE2e && !hasStackNodes) {
863
- const applicability = _e2eApplicability(projectPath, featureName, config);
864
- if (!applicability.applicable) return skippedE2e(applicability.reason);
865
- }
866
- const gitCommonDir = resolveGitCommonDir(projectPath);
867
- // Without the port block, two worktrees verifying at once collide on host ports.
868
- const env = buildComposeEnv({ cwd: projectPath, config, featureName, gitCommonDir });
869
-
870
- const start = Date.now();
871
- const result = _runE2eCheck(projectPath, {
872
- config,
873
- featureName,
874
- gitCommonDir,
875
- env,
876
- skipRequested: skipE2e,
877
- forceFresh: freshE2e,
878
- beforeHeavy: () => gate.enter('e2e'),
879
- countSpecs: (output) => parseTestCount(output, 'playwright')?.total ?? null,
880
- // Cold-starting a .NET container per verify is too slow; `e2e down` and `finish` tear it down.
881
- keepUp: true,
882
- });
883
- const durationMs = Date.now() - start;
884
-
885
- return {
886
- node: {
887
- status: result.status,
888
- command: result.command ?? null,
889
- durationMs,
890
- reason: result.reason ?? null,
891
- output: tailLines(result.output || '', OUTPUT_TAIL_LINES),
892
- count: Number.isInteger(result.count) ? result.count : null,
893
- warnings: Array.isArray(result.warnings) ? result.warnings : [],
894
- flakySpecs: result.flakySpecs ?? [],
895
- quarantinedSpecs: result.quarantinedSpecs ?? [],
896
- },
897
- stackEnv: { COMPOSE_PROJECT_NAME: composeProjectName(featureName), ...env },
898
- };
899
- }
900
-
901
- function appendE2eFeedback(feedback, e2eNode) {
902
- for (const warning of e2eNode.warnings || []) {
903
- feedback.push(`[e2e] warning: ${warning}`);
904
- }
905
- if (e2eNode.status !== 'fail') return;
906
- if (e2eNode.reason) feedback.push(`[e2e] ${e2eNode.reason}`);
907
- for (const line of linesOf(e2eNode.output)) {
908
- feedback.push(`[e2e] ${line}`);
909
- }
910
- }
911
-
912
- // Never the stack-profile default: it falls back to dotnet and would fire
913
- // `dotnet build` on a greenfield JS project.
914
- function readStack(projectPath) {
915
- try {
916
- const configPath = join(projectPath, '.morph', 'config', 'config.json');
917
- if (!existsSync(configPath)) return null;
918
- const config = JSON.parse(readFileSync(configPath, 'utf8'));
919
- return config?.project?.stack ?? null;
920
- } catch {
921
- return null;
922
- }
923
- }
924
-
925
- function readProjectPaths(projectPath) {
926
- try {
927
- const configPath = join(projectPath, '.morph', 'config', 'config.json');
928
- if (!existsSync(configPath)) return {};
929
- const config = JSON.parse(readFileSync(configPath, 'utf8'));
930
- const { frontendPath, backendPath } = config?.project ?? {};
931
- return { frontendPath, backendPath };
932
- } catch {
933
- return {};
934
- }
935
- }
936
-
937
- function readConfig(projectPath) {
938
- try {
939
- const configPath = join(projectPath, '.morph', 'config', 'config.json');
940
- if (!existsSync(configPath)) return null;
941
- return JSON.parse(readFileSync(configPath, 'utf8').replace(/^/, ''));
942
- } catch {
943
- return null;
944
- }
945
- }
946
-
947
- // The e2e freshness stamp lives in the common dir: shared by every worktree and
948
- // never dirties `git status`. Fail-open: no git costs a rebuild, never a crash.
949
- function resolveGitCommonDir(projectPath) {
950
- try {
951
- const common = execFileSync('git', ['rev-parse', '--git-common-dir'], {
952
- cwd: projectPath,
953
- stdio: 'pipe',
954
- encoding: 'utf-8',
955
- windowsHide: true,
956
- }).trim();
957
- return common ? resolve(projectPath, common) : null;
958
- } catch {
959
- return null;
960
- }
961
- }
962
-
963
- function linesOf(text) {
964
- const trimmed = (text || '').trim();
965
- return trimmed ? trimmed.split('\n') : [];
966
- }
967
-
968
- function tailLines(text, n) {
969
- const lines = linesOf(text);
970
- return lines.slice(-n).join('\n');
971
- }