@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,569 +0,0 @@
1
- import { exec as execCallback, execSync, execFileSync } from 'child_process';
2
- import { existsSync, readFileSync, readdirSync, realpathSync } from 'fs';
3
- import { join, resolve, relative, isAbsolute } from 'path';
4
- import { globSync } from 'glob';
5
-
6
- import { WORKTREES_DIR, LEGACY_WORKTREES_DIR } from '../../commands/project/worktree.js';
7
- import { getBuildSteps } from '../../../framework/hooks/shared/build-check.js';
8
- import { CONFIG_FILE_NAME } from '../../core/state/state-manager.js';
9
-
10
- // Per chained project: a fixed cap timed a long `a && b` chain out for being long, not broken.
11
- export const DEFAULT_TEST_TIMEOUT_PER_PROJECT = 1_800_000;
12
- const TEST_OUTPUT_MAX_BUFFER = 256 * 1024 * 1024;
13
-
14
- /**
15
- * Fallback test command when the project declared no nodes; `projectCount` scales the timeout.
16
- * `source`: 'config' | 'dotnet-root' | 'dotnet-scan' | 'npm' | 'none'.
17
- */
18
- export function resolveTestPlan(projectPath = '.') {
19
- const config = readMorphConfig(projectPath);
20
- const configured = config?.project?.testCommand;
21
- if (configured && typeof configured === 'string') {
22
- return { command: configured, projectCount: 1, source: 'config' };
23
- }
24
-
25
- try {
26
- const entries = readdirSync(projectPath);
27
- const hasDotnetProject = entries.some(
28
- (entry) => entry.endsWith('.sln') || entry.endsWith('.csproj')
29
- );
30
- if (hasDotnetProject) {
31
- return { command: 'dotnet test', projectCount: 1, source: 'dotnet-root' };
32
- }
33
- } catch {
34
- }
35
-
36
- const testProjects = collectDotnetTestProjects(projectPath);
37
- if (testProjects.length > 0) {
38
- return {
39
- // No `--nologo` (VSTest-only: MTP forwards it and dies with exit 5, zero tests)
40
- // and no `--project` (MTP-only): positional path and `-v q` work in both modes.
41
- command: testProjects.map((p) => `dotnet test "${p}" -v q`).join(' && '),
42
- projectCount: testProjects.length,
43
- source: 'dotnet-scan',
44
- };
45
- }
46
-
47
- const packageJsonPath = join(projectPath, 'package.json');
48
- if (existsSync(packageJsonPath)) {
49
- try {
50
- const pkg = JSON.parse(readFileSync(packageJsonPath, 'utf8'));
51
- if (pkg?.scripts?.test) {
52
- return { command: 'npm test', projectCount: 1, source: 'npm' };
53
- }
54
- } catch {
55
- }
56
- }
57
-
58
- return { command: null, projectCount: 0, source: 'none' };
59
- }
60
-
61
- // A linked worktree is another feature's checkout: scanning it doubles the clock and
62
- // reports on code outside the tree. The glob ignore covers the convention dirs;
63
- // `git worktree list` covers worktrees created anywhere else (fail-open).
64
- function collectDotnetTestProjects(projectPath) {
65
- let matches;
66
- try {
67
- matches = globSync('**/*Tests.csproj', {
68
- cwd: projectPath,
69
- ignore: [
70
- '**/bin/**',
71
- '**/obj/**',
72
- '**/node_modules/**',
73
- `${WORKTREES_DIR}/**`,
74
- `${LEGACY_WORKTREES_DIR}/**`,
75
- ],
76
- });
77
- } catch {
78
- return [];
79
- }
80
-
81
- const linked = listLinkedWorktreePaths(projectPath);
82
- if (linked.length > 0) {
83
- matches = matches.filter(
84
- (p) => !linked.some((wt) => isInside(canonicalPath(resolve(projectPath, p)), wt))
85
- );
86
- }
87
-
88
- return matches.sort();
89
- }
90
-
91
- // Git prints the long path; the tree may be addressed by its 8.3 short form (`MORPHT~1`).
92
- // `path.resolve` does not expand that alias, only `realpathSync.native` does.
93
- export function canonicalPath(p) {
94
- try {
95
- return realpathSync.native(p);
96
- } catch {
97
- return resolve(p);
98
- }
99
- }
100
-
101
- function listLinkedWorktreePaths(projectPath) {
102
- let out;
103
- try {
104
- out = execFileSync('git', ['worktree', 'list', '--porcelain'], {
105
- cwd: projectPath,
106
- stdio: 'pipe',
107
- encoding: 'utf8',
108
- windowsHide: true,
109
- });
110
- } catch {
111
- return [];
112
- }
113
-
114
- const self = canonicalPath(projectPath);
115
- return out
116
- .split('\n')
117
- .filter((line) => line.startsWith('worktree '))
118
- .map((line) => canonicalPath(line.slice('worktree '.length).trim()))
119
- .filter((p) => p && p !== self);
120
- }
121
-
122
- /** True when `child` is `parent` or lives under it. */
123
- export function isInside(child, parent) {
124
- const rel = relative(parent, child);
125
- return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
126
- }
127
-
128
- /** The parsed config, or null when absent OR malformed — both mean "fall back", never "fail". */
129
- export function readMorphConfig(projectPath) {
130
- const configPath = join(projectPath, CONFIG_FILE_NAME);
131
- if (!existsSync(configPath)) return null;
132
- try {
133
- return JSON.parse(readFileSync(configPath, 'utf8'));
134
- } catch {
135
- return null;
136
- }
137
- }
138
-
139
- /** Precedence: CLI override > node `timeoutMs` > config `testTimeoutMs` > default × chained projects. */
140
- export function resolveTestTimeout(projectPath, node, override) {
141
- if (Number.isFinite(override) && override > 0) return override;
142
-
143
- if (Number.isFinite(node?.timeoutMs) && node.timeoutMs > 0) return node.timeoutMs;
144
-
145
- const configured = readMorphConfig(projectPath)?.project?.testTimeoutMs;
146
- if (Number.isFinite(configured) && configured > 0) return configured;
147
-
148
- return DEFAULT_TEST_TIMEOUT_PER_PROJECT * Math.max(1, node?.projectCount ?? 1);
149
- }
150
-
151
- // Heuristic: only names WHICH chain link was running when the clock ran out.
152
- function countCompletedRuns(output) {
153
- const matches = (output || '').match(
154
- /(?:^|\n)\s*(?:Aprovado|Passed|Failed|Reprovado|Com falha|Erro)!/gi
155
- );
156
- return matches ? matches.length : 0;
157
- }
158
-
159
- const NO_BUILD_FLAG = /(^|\s)--no-build(\s|$)/;
160
- const DOTNET_COMMAND = /^\s*dotnet\s/;
161
-
162
- // `[]` is the safe answer: nothing compiled here, so a `--no-build` in the same command is refused.
163
- export function extractCsprojTargets(command) {
164
- if (typeof command !== 'string') return [];
165
- const found = [];
166
- const token = /"([^"]+\.csproj)"|'([^']+\.csproj)'|(\S+\.csproj)/gi;
167
- let match;
168
- while ((match = token.exec(command)) !== null) {
169
- found.push(match[1] ?? match[2] ?? match[3]);
170
- }
171
- return [...new Set(found)];
172
- }
173
-
174
- /** Declared `build`, else the csproj the command names; only `runner: 'dotnet'` prebuilds. */
175
- export function resolveTestBuildTargets(node) {
176
- if (node?.runner !== 'dotnet') return [];
177
- if (Array.isArray(node.build) && node.build.length > 0) return node.build;
178
- return extractCsprojTargets(node.command);
179
- }
180
-
181
- function singleDotnetBuildable(files) {
182
- const solutions = files.filter((f) => /\.slnx?$/i.test(f));
183
- const projects = files.filter((f) => /\.csproj$/i.test(f));
184
- if (solutions.length) return solutions.length === 1 ? solutions[0] : null;
185
- return projects.length === 1 ? projects[0] : null;
186
- }
187
-
188
- const DOTNET_SCAN_SKIPPED = new Set([WORKTREES_DIR, LEGACY_WORKTREES_DIR, 'node_modules', 'bin', 'obj']);
189
- const DOTNET_SCAN_DEPTH = 6;
190
-
191
- function dotnetBuildablesUnder(root, rel = '', depth = 0, found = []) {
192
- let entries;
193
- try { entries = readdirSync(join(root, rel), { withFileTypes: true }); } catch { return found; }
194
- for (const e of entries) {
195
- const path = rel ? `${rel}/${e.name}` : e.name;
196
- if (e.isFile() && /\.(?:slnx?|csproj)$/i.test(e.name)) found.push(path);
197
- else if (e.isDirectory() && depth < DOTNET_SCAN_DEPTH && !e.name.startsWith('.') && !DOTNET_SCAN_SKIPPED.has(e.name)) {
198
- dotnetBuildablesUnder(root, path, depth + 1, found);
199
- }
200
- }
201
- return found;
202
- }
203
-
204
- /**
205
- * The repo's single .sln/.slnx, else its single .csproj. `target` is `.` when the root
206
- * already has one, `null` for zero or several (listed in `candidates`).
207
- */
208
- export function discoverDotnetSolution(root) {
209
- let rootEntries;
210
- try { rootEntries = readdirSync(root); } catch { return { target: null, candidates: [] }; }
211
- if (rootEntries.some((e) => /\.(?:slnx?|csproj)$/i.test(e))) return { target: '.', candidates: [] };
212
- const all = dotnetBuildablesUnder(root).sort();
213
- const solutions = all.filter((f) => /\.slnx?$/i.test(f));
214
- const pool = solutions.length ? solutions : all;
215
- const single = singleDotnetBuildable(pool);
216
- return { target: single, candidates: pool };
217
- }
218
-
219
- // Derived from build-check.js, the single spelling of "dotnet build". `--no-restore` is
220
- // dropped: a test project outside the solution may never have been restored.
221
- export function dotnetBuildCommandFor(target, projectPath) {
222
- const base = getBuildSteps('dotnet', { cwd: projectPath || '.' })[0]?.command;
223
- if (!base) return null;
224
- const [verb, subcommand, ...flags] = base.split(/\s+/);
225
- const kept = flags.filter((flag) => flag !== '--no-restore');
226
- return `${verb} ${subcommand} "${target}"${kept.length ? ` ${kept.join(' ')}` : ''}`;
227
- }
228
-
229
- // Runs only with declared `build[]` or `--no-build`: a plain `dotnet test` builds
230
- // itself, and pre-compiling it would double the clock of the hot path.
231
- function runTestPrebuild({ node, cwd, exec, timeout, projectPath, builtTargets = new Set() }) {
232
- if (node.runner !== 'dotnet') return { built: false, failure: null };
233
-
234
- const declared = Array.isArray(node.build) ? node.build : [];
235
- if (declared.length === 0 && !NO_BUILD_FLAG.test(node.command)) {
236
- return { built: false, failure: null };
237
- }
238
-
239
- const targets = resolveTestBuildTargets(node);
240
- const outputs = [];
241
-
242
- for (const target of targets) {
243
- const key = `${cwd}\0${target}`;
244
- if (builtTargets.has(key)) continue;
245
- const command = dotnetBuildCommandFor(target, projectPath);
246
- if (!command) return { built: false, failure: null };
247
- try {
248
- exec(command, { cwd, timeout, encoding: 'utf8', stdio: 'pipe' });
249
- builtTargets.add(key);
250
- } catch (err) {
251
- outputs.push(`[${command}]\n${(err.stdout || '') + (err.stderr || '')}`);
252
- return {
253
- built: false,
254
- failure: {
255
- passed: false,
256
- buildFailed: true,
257
- reason: 'test-build-failed',
258
- output: outputs.join('\n\n'),
259
- exitCode: err.status ?? 1,
260
- timeoutMs: timeout,
261
- },
262
- };
263
- }
264
- }
265
-
266
- return { built: targets.length > 0, failure: null };
267
- }
268
-
269
- const VSTEST_SUMMARY = /^\s*(?:Aprovado|Passed|Com falha|Failed|Reprovado|Erro)!/i;
270
- // `\S+` spans `ção`, and a mis-decoded version of it, without naming a byte.
271
- const MTP_SUMMARY_HEADER = /^(?:Test run summary|Resumo da execu\S+ de teste):/;
272
- const MTP_TOTAL = /^\s+total:\s*(\d+)\s*$/;
273
- const MTP_FAILED = /^\s+(?:failed|falhou):\s*(\d+)\s*$/;
274
- const MTP_PASSED = /^\s+(?:succeeded|conclu\S*\s+com\s+\S*xito):\s*(\d+)\s*$/;
275
-
276
- function mtpSummaryBlock(lines, from) {
277
- const block = { total: null, passed: 0, failed: 0 };
278
- for (let i = from; i < lines.length && /^(?:\s|$)/.test(lines[i]); i++) {
279
- const line = lines[i];
280
- let m;
281
- if ((m = MTP_TOTAL.exec(line))) block.total = Number(m[1]);
282
- else if ((m = MTP_FAILED.exec(line))) block.failed = Number(m[1]);
283
- else if ((m = MTP_PASSED.exec(line))) block.passed = Number(m[1]);
284
- }
285
- return block;
286
- }
287
-
288
- // SUM of every VSTest line and MTP block: a chained `a && b` prints one summary per
289
- // invocation, and reading only one invents a count drop. MTP prints ONE aggregated
290
- // block per invocation; an unmeasured locale is UNKNOWN, never 0.
291
- function parseDotnetCount(output) {
292
- const lines = output.split('\n');
293
- let seen = false;
294
- const sum = { total: 0, passed: 0, failed: 0 };
295
- const add = (total, passed, failed) => {
296
- seen = true;
297
- sum.total += total;
298
- sum.passed += passed;
299
- sum.failed += failed;
300
- };
301
-
302
- for (const line of lines.filter((l) => VSTEST_SUMMARY.test(l))) {
303
- const total = /\b(?:Total de testes|Total)\s*:\s*(\d+)/i.exec(line);
304
- if (!total) continue;
305
- const passed = /\b(?:Aprovado|Passed)\s*:\s*(\d+)/i.exec(line);
306
- const failed = /\b(?:Com falha|Failed|Reprovado)\s*:\s*(\d+)/i.exec(line);
307
- add(Number(total[1]), passed ? Number(passed[1]) : 0, failed ? Number(failed[1]) : 0);
308
- }
309
-
310
- lines.forEach((line, i) => {
311
- if (!MTP_SUMMARY_HEADER.test(line)) return;
312
- const block = mtpSummaryBlock(lines, i + 1);
313
- if (block.total !== null) add(block.total, block.passed, block.failed);
314
- });
315
-
316
- return seen ? sum : null;
317
- }
318
-
319
- function lastSummaryValue(output, key) {
320
- const re = new RegExp(`^\\s*[#ℹ]\\s*${key}\\s+(\\d+)\\s*$`, 'gim');
321
- let match;
322
- let value = null;
323
- while ((match = re.exec(output)) !== null) value = Number(match[1]);
324
- return value;
325
- }
326
-
327
- function parseNodeTestCount(output) {
328
- const total = lastSummaryValue(output, 'tests');
329
- if (total === null) return null;
330
- return {
331
- total,
332
- passed: lastSummaryValue(output, 'pass') ?? 0,
333
- failed: lastSummaryValue(output, 'fail') ?? 0,
334
- };
335
- }
336
-
337
- // `Tests`, never `Test Files`: the file-count line above has the same shape.
338
- function parseVitestCount(output) {
339
- const line = output.split('\n').find((l) => /^\s*Tests\s{1,}\d/.test(l));
340
- if (!line) return null;
341
- const passed = /(\d+)\s+passed/i.exec(line);
342
- const failed = /(\d+)\s+failed/i.exec(line);
343
- if (!passed && !failed) return null;
344
- const declaredTotal = /\((\d+)\)\s*$/.exec(line.trim());
345
- const p = passed ? Number(passed[1]) : 0;
346
- const f = failed ? Number(failed[1]) : 0;
347
- return { total: declaredTotal ? Number(declaredTotal[1]) : p + f, passed: p, failed: f };
348
- }
349
-
350
- function parseJestCount(output) {
351
- const line = output.split('\n').find((l) => /^\s*Tests:\s/.test(l));
352
- if (!line) return null;
353
- const total = /(\d+)\s+total/i.exec(line);
354
- if (!total) return null;
355
- const passed = /(\d+)\s+passed/i.exec(line);
356
- const failed = /(\d+)\s+failed/i.exec(line);
357
- return {
358
- total: Number(total[1]),
359
- passed: passed ? Number(passed[1]) : 0,
360
- failed: failed ? Number(failed[1]) : 0,
361
- };
362
- }
363
-
364
- const ANSI_PATTERN = /\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\))/g;
365
-
366
- /** Strips CSI/SGR and OSC sequences; non-string input is returned unchanged, never coerced. */
367
- export function stripAnsi(text) {
368
- if (typeof text !== 'string') return text;
369
- return text.replace(ANSI_PATTERN, '');
370
- }
371
-
372
- function parsePlaywrightCount(output) {
373
- const passed = /^\s*(\d+)\s+passed\b/im.exec(output);
374
- const failed = /^\s*(\d+)\s+failed\b/im.exec(output);
375
- if (!passed && !failed) return null;
376
- const p = passed ? Number(passed[1]) : 0;
377
- const f = failed ? Number(failed[1]) : 0;
378
- return { total: p + f, passed: p, failed: f };
379
- }
380
-
381
- const COUNT_EXTRACTORS = {
382
- dotnet: parseDotnetCount,
383
- // Counts xunit cases, not scenarios: `judgeEvalRun` replaces it with the summary
384
- // file's scenario count (or null), and `judgeRun` never compares it to `expectedCount`.
385
- evals: parseDotnetCount,
386
- 'node-test': parseNodeTestCount,
387
- vitest: parseVitestCount,
388
- jest: parseJestCount,
389
- playwright: parsePlaywrightCount,
390
- none: () => null,
391
- };
392
-
393
- /**
394
- * Returns null when the summary is unreadable: null is UNKNOWN, never zero, or a
395
- * missing regex would fabricate a count drop against every baseline.
396
- */
397
- export function parseTestCount(output, runner) {
398
- if (typeof output !== 'string' || !output) return null;
399
- const extractor = COUNT_EXTRACTORS[runner];
400
- if (!extractor) return null;
401
- // Strip ANSI before EVERY extractor: an SGR code inside a summary line defeats the anchored regexes.
402
- return extractor(stripAnsi(output));
403
- }
404
-
405
- const FAILURE_LINES_MAX = 10;
406
- const TAP_NOT_OK = /^(\s*)not ok \d+ - (.+?)\s*$/;
407
- const TAP_DIRECTIVE = /\s#\s*(?:TODO|SKIP)\b/i;
408
- const VITEST_FAIL = /^\s*FAIL\s+(.+?)\s*$/;
409
- const VITEST_CROSS = /^\s*[×✗]\s+(.+?)(?:\s+\d+(?:\.\d+)?\s*m?s)?\s*$/;
410
- // The duration suffix is required: it separates a test line from the summary's `failed: 1` / `Failed!`.
411
- const DOTNET_FAILED = /^\s*(?:failed|com falha)\s+(\S.*?)\s*(?:\[[^\]]*\]|\([^)]*\))\s*$/i;
412
-
413
- function tapLeafFailures(lines) {
414
- const seen = [];
415
- for (const line of lines) {
416
- const match = TAP_NOT_OK.exec(line);
417
- if (!match || TAP_DIRECTIVE.test(match[2])) continue;
418
- const depth = match[1].length;
419
- // TAP prints a subtest's result before its parent's: deeper unclaimed entries above are its children.
420
- const children = seen.filter((e) => !e.claimed && e.depth > depth);
421
- for (const child of children) child.claimed = true;
422
- seen.push({ depth, name: match[2], leaf: children.length === 0, claimed: false });
423
- }
424
- return seen.filter((e) => e.leaf).map((e) => e.name);
425
- }
426
-
427
- function captures(lines, pattern) {
428
- return lines.map((line) => pattern.exec(line)?.[1]).filter(Boolean);
429
- }
430
-
431
- /** Failed test names anywhere in the output (TAP leaves, vitest, dotnet), deduplicated, at most 10; [] when no form matches. */
432
- export function failureLines(output) {
433
- if (typeof output !== 'string' || !output) return [];
434
- const lines = stripAnsi(output).split(/\r?\n/);
435
- const vitestFiles = captures(lines, VITEST_FAIL);
436
- const names = [
437
- ...tapLeafFailures(lines),
438
- ...(vitestFiles.length > 0 ? vitestFiles : captures(lines, VITEST_CROSS)),
439
- ...captures(lines, DOTNET_FAILED),
440
- ];
441
- return [...new Set(names)].slice(0, FAILURE_LINES_MAX);
442
- }
443
-
444
- /**
445
- * Asymmetric on purpose: only a drop fails (non-null `reason`); a rise only warns,
446
- * or every new test would redden the gate and teach deleting tests.
447
- */
448
- export function compareTestCount(count, expectedCount) {
449
- const answer = (verdict, reason = null, warning = null) => ({ verdict, reason, warning });
450
-
451
- // A declared `0` is a real baseline; only null means "none recorded".
452
- if (!Number.isInteger(expectedCount)) return answer('no-baseline');
453
-
454
- if (!Number.isInteger(count)) {
455
- return answer('unknown', null,
456
- `contagem desconhecida — a baseline ${expectedCount} não pôde ser comparada`);
457
- }
458
-
459
- if (count < expectedCount) {
460
- return answer('drop', `count-drop: esperado ${expectedCount}, executado ${count}`);
461
- }
462
-
463
- if (count > expectedCount) {
464
- return answer('rise', null,
465
- `baseline desatualizada (${expectedCount} → ${count}); rode verify --record-baseline`);
466
- }
467
-
468
- return answer('match');
469
- }
470
-
471
- /**
472
- * Runs ONE node; resolving the list of nodes belongs to `resolveTestNodes()`.
473
- * `opts.env` is layered over `process.env` (the eval channel `MORPH_EVAL_*` travels there).
474
- */
475
- export function runTestSuite(projectPath = '.', opts = {}) {
476
- const node = opts.node;
477
- const cmd = node?.command;
478
-
479
- if (!cmd) {
480
- return {
481
- skipped: true,
482
- reason: node?.reason || 'No testCommand configured and no known project file detected',
483
- };
484
- }
485
-
486
- const exec = opts._execSync ?? execSync;
487
- const timeout = resolveTestTimeout(projectPath, node, opts.timeout);
488
- const projectCount = node.projectCount ?? 1;
489
- const cwd = resolve(projectPath, node.cwd || '.');
490
-
491
- // Prebuild BEFORE judging `--no-build`: the build is what makes the flag legal.
492
- const prebuild = runTestPrebuild({ node, cwd, exec, timeout, projectPath, builtTargets: opts.builtTargets });
493
- if (prebuild.failure) return prebuild.failure;
494
-
495
- // `--no-build` without a build here would run a stale assembly. The command is never
496
- // rewritten: a silent fix would make the reported `command` a lie about what ran.
497
- if (DOTNET_COMMAND.test(cmd) && NO_BUILD_FLAG.test(cmd) && !prebuild.built && !opts.solutionBuilt) {
498
- return {
499
- passed: false,
500
- buildFailed: false,
501
- reason: 'stale-binary: --no-build sem build dos projetos de teste nesta invocação',
502
- output: '',
503
- exitCode: null,
504
- timeoutMs: timeout,
505
- };
506
- }
507
-
508
- // Layered OVER process.env: a child that lost PATH fails for reasons unrelated to the suite.
509
- const env = opts.env ? { ...process.env, ...opts.env } : undefined;
510
-
511
- const execOptions = {
512
- cwd,
513
- timeout,
514
- encoding: 'utf8',
515
- stdio: 'pipe',
516
- // Node's 1 MiB default kills a large suite mid-run (ENOBUFS), which then reads as a red suite.
517
- maxBuffer: TEST_OUTPUT_MAX_BUFFER,
518
- ...(env ? { env } : {}),
519
- };
520
- const passed = (output) => ({ passed: true, output: output ?? '', exitCode: 0, timeoutMs: timeout });
521
- const failed = (err) => {
522
- // A spawn failure or a kill leaves both streams empty; its own error is then the only lead.
523
- const output = (err.stdout || '') + (err.stderr || '')
524
- || [err.code, err.signal, err.message].filter(Boolean).join(' ');
525
-
526
- // A timeout is NOT a red suite: the command was interrupted, so no verdict exists.
527
- if (err.code === 'ETIMEDOUT' || err.killed === true) {
528
- const total = Math.max(1, projectCount);
529
- const at = Math.min(countCompletedRuns(output) + 1, total);
530
- const where = total > 1 ? ` na execução ${at} de ${total}` : '';
531
- return {
532
- passed: false,
533
- timedOut: true,
534
- timeoutMs: timeout,
535
- buildFailed: false,
536
- message: `timeout após ${timeout} ms${where} — nenhum teste falhou, o comando foi interrompido`,
537
- output,
538
- exitCode: err.status ?? null,
539
- };
540
- }
541
-
542
- const BUILD_FAIL = /Build FAILED|error MSB\d+|error CS\d+|Could not find.*\.csproj/i;
543
- const buildFailed = BUILD_FAIL.test(output);
544
- return {
545
- passed: false,
546
- buildFailed,
547
- output,
548
- exitCode: err.status ?? 1,
549
- timeoutMs: timeout,
550
- };
551
- };
552
-
553
- if (opts.background) return runInBackground(cmd, execOptions).then(passed, failed);
554
- try {
555
- return passed(exec(cmd, execOptions));
556
- } catch (err) {
557
- return failed(err);
558
- }
559
- }
560
-
561
- // `exec` reports the exit code in `err.code`; the shared handler reads `err.status`, as from execSync.
562
- function runInBackground(cmd, options) {
563
- return new Promise((resolvePromise, reject) => {
564
- execCallback(cmd, options, (err, stdout, stderr) => {
565
- if (!err) return resolvePromise(stdout);
566
- return reject(Object.assign(err, { stdout, stderr, status: Number.isInteger(err.code) ? err.code : null }));
567
- });
568
- });
569
- }