@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,1022 +0,0 @@
1
- // Uses the project's OWN compose file, never a generated one: what is verified is what ships.
2
-
3
- import { execFileSync } from 'child_process';
4
- import { createHash } from 'crypto';
5
- import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'fs';
6
- import { join } from 'path';
7
-
8
- import { E2E_SPEC_LOCATIONS } from './frontend-locations.js';
9
- import { isSecondaryWorktree } from './git-paths.js';
10
- import { hostServicesStatus, startHostServices, stopHostServices } from './host-services.js';
11
- import { resolveSpawn } from './spawn-command.js';
12
-
13
- // Docker's own resolution order.
14
- const COMPOSE_CANDIDATES = [
15
- 'compose.yaml',
16
- 'compose.yml',
17
- 'docker-compose.yaml',
18
- 'docker-compose.yml',
19
- ];
20
-
21
- const PLAYWRIGHT_CONFIGS = [
22
- 'playwright.config.ts',
23
- 'playwright.config.js',
24
- 'playwright.config.mjs',
25
- ];
26
-
27
- export const DEFAULT_HEALTH_TIMEOUT = 180_000;
28
-
29
- export const DEFAULT_SPEC_TIMEOUT = 300_000;
30
-
31
- const HEALTH_POLL_MS = 2_000;
32
-
33
- const OUTPUT_TAIL_LINES = 20;
34
-
35
- /** Never throws. @returns {{ code: number, output: string }} */
36
- export function defaultExec(file, args, opts = {}) {
37
- const spawn = resolveSpawn(file, args, { cwd: opts.cwd });
38
- try {
39
- const stdout = execFileSync(spawn.file, spawn.args, {
40
- cwd: opts.cwd,
41
- shell: spawn.shell,
42
- timeout: opts.timeout,
43
- encoding: 'utf-8',
44
- stdio: ['pipe', 'pipe', 'pipe'],
45
- env: opts.env ? { ...process.env, ...opts.env } : process.env,
46
- windowsHide: true,
47
- });
48
- return { code: 0, output: stdout || '' };
49
- } catch (err) {
50
- const output = `${err.stdout || ''}${err.stderr || ''}` || err.message || '';
51
- // `status` is null for a missing binary or a timeout: both are failures, never a pass.
52
- return { code: typeof err.status === 'number' ? err.status : 1, output };
53
- }
54
- }
55
-
56
- export function resolveComposeFile(cwd, config) {
57
- const configured = config?.e2e?.composeFile;
58
- if (configured) {
59
- return existsSync(join(cwd, configured)) ? configured : null;
60
- }
61
- return COMPOSE_CANDIDATES.find((name) => existsSync(join(cwd, name))) ?? null;
62
- }
63
-
64
- /** `null` is not a failure: it degrades the node to a smoke check. */
65
- export function resolveSpecCommand(cwd, config, frontendPath) {
66
- const configured = config?.e2e?.command;
67
- if (configured) {
68
- const [command, ...args] = configured.split(' ').filter(Boolean);
69
- return { command, args, cwd };
70
- }
71
-
72
- for (const dir of specSearchDirs(cwd, frontendPath)) {
73
- const hasConfig = PLAYWRIGHT_CONFIGS.some((name) => existsSync(join(dir, name)));
74
- // The config is versioned but the toolchain is not: `npx playwright` in a fresh
75
- // worktree would fetch an unrelated package.
76
- if (hasConfig && existsSync(join(dir, 'node_modules'))) {
77
- return { command: 'npx', args: ['playwright', 'test'], cwd: dir };
78
- }
79
- }
80
- return null;
81
- }
82
-
83
- function specSearchDirs(cwd, frontendPath) {
84
- return frontendPath ? [join(cwd, frontendPath), cwd] : E2E_SPEC_LOCATIONS.map((loc) => join(cwd, loc));
85
- }
86
-
87
- function hasPlaywrightConfig(dir) {
88
- return PLAYWRIGHT_CONFIGS.some((name) => existsSync(join(dir, name)));
89
- }
90
-
91
- // Configs `resolveSpecCommand` did not run (searched dir without node_modules,
92
- // or a first-level dir outside the search): each is a smoke pass hiding specs.
93
- export function findUnrunPlaywrightConfigs(cwd, frontendPath) {
94
- const searched = frontendPath ? [frontendPath, '.'] : [...E2E_SPEC_LOCATIONS];
95
- const norm = (rel) => rel.replace(/\\/g, '/').replace(/^\.\/|\/$/g, '') || '.';
96
- const searchedSet = new Set(searched.map(norm));
97
- let firstLevel = [];
98
- try {
99
- firstLevel = readdirSync(cwd, { withFileTypes: true })
100
- .filter((e) => e.isDirectory() && e.name !== 'node_modules' && !e.name.startsWith('.'))
101
- .map((e) => e.name);
102
- } catch { }
103
-
104
- const found = [];
105
- const seen = new Set();
106
- for (const rel of [...searched.map(norm), ...firstLevel]) {
107
- if (seen.has(rel)) continue;
108
- seen.add(rel);
109
- const dir = join(cwd, rel);
110
- if (!hasPlaywrightConfig(dir)) continue;
111
- if (!searchedSet.has(rel)) found.push({ dir: rel, why: 'not-searched' });
112
- else if (!existsSync(join(dir, 'node_modules'))) found.push({ dir: rel, why: 'no-node-modules' });
113
- }
114
- return found;
115
- }
116
-
117
- function unrunConfigWarning({ dir, why }) {
118
- const where = dir === '.' ? 'na raiz' : `em ${dir}/`;
119
- const cause = why === 'no-node-modules'
120
- ? 'sem node_modules ao lado'
121
- : 'fora de project.frontendPath e dos locais conhecidos';
122
- const fix = dir === '.' ? 'instale as dependências' : `declare project.frontendPath: "${dir}" e instale as dependências`;
123
- return `playwright.config.* ${where} não rodou (${cause}) — o nó e2e ficou só no smoke; ${fix}`;
124
- }
125
-
126
- export function composeProjectName(featureName) {
127
- const slug = String(featureName ?? '')
128
- .toLowerCase()
129
- .replace(/[^a-z0-9]+/g, '-')
130
- .replace(/^-+|-+$/g, '');
131
- return `morph-${slug || 'default'}`;
132
- }
133
-
134
- const FIXED_PORT_SHORT_RE = /^\s*-\s*["']?(?:[\d.]+:)?\d{1,5}:\d{1,5}(?:\/(?:tcp|udp))?["']?\s*$/;
135
-
136
- const FIXED_PORT_LONG_RE = /^\s*published:\s*["']?\d{1,5}["']?\s*$/;
137
-
138
- const CONTAINER_NAME_RE = /^\s*container_name:\s*\S/;
139
-
140
- // The two things COMPOSE_PROJECT_NAME cannot isolate. Line-based because a hook has no YAML
141
- // parser; flow lists (`ports: ["3000:3000"]`) are a known miss that costs a clash, never a false fail.
142
- export function lintComposeIsolation(composeText) {
143
- const findings = [];
144
- const lines = typeof composeText === 'string' ? composeText.split(/\r?\n/) : [];
145
-
146
- lines.forEach((raw, i) => {
147
- const line = stripYamlComment(raw);
148
- if (!line.trim()) return;
149
- if (FIXED_PORT_SHORT_RE.test(line) || FIXED_PORT_LONG_RE.test(line)) {
150
- findings.push({ kind: 'fixed-port', line: i + 1, text: line.trim() });
151
- } else if (CONTAINER_NAME_RE.test(line)) {
152
- findings.push({ kind: 'container-name', line: i + 1, text: line.trim() });
153
- }
154
- });
155
-
156
- return { isolable: findings.length === 0, findings };
157
- }
158
-
159
- function stripYamlComment(line) {
160
- let quote = null;
161
- for (let i = 0; i < line.length; i++) {
162
- const ch = line[i];
163
- if (quote) {
164
- if (ch === quote) quote = null;
165
- } else if (ch === '"' || ch === "'") {
166
- quote = ch;
167
- } else if (ch === '#' && (i === 0 || /\s/.test(line[i - 1]))) {
168
- return line.slice(0, i);
169
- }
170
- }
171
- return line;
172
- }
173
-
174
- // Fails only inside a worktree, where a second stack collides with the primary's; at the root
175
- // fixed ports have nothing to collide with.
176
- export function decideIsolation({ findings = [], insideWorktree = false } = {}) {
177
- if (!findings.length) return { status: 'ok', reason: null };
178
-
179
- const ports = findings.filter((f) => f.kind === 'fixed-port').length;
180
- const names = findings.filter((f) => f.kind === 'container-name').length;
181
- const reason =
182
- `compose-not-isolable: ${ports} fixed host port(s)/${names} container_name — ` +
183
- 'two worktrees would collide on the host; use ${PORT:-3000}:3000 / ' +
184
- '${POSTGRES_PORT:-5432}:5432 and drop container_name';
185
-
186
- return { status: insideWorktree ? 'fail' : 'warn', reason };
187
- }
188
-
189
- // HEAD alone would let a stack built before an uncommitted edit read as fresh: status and diff
190
- // make any edit move the stamp. `.morph/` stays out, config.json aside: the verify's own commits
191
- // must not rebuild a stack whose source did not change. `null` outside a git repo.
192
- export function computeSourceStamp(cwd, exec = defaultExec) {
193
- const head = exec('git', ['rev-parse', 'HEAD'], { cwd });
194
- if (head.code !== 0) return null;
195
-
196
- const tree = exec('git', ['ls-tree', 'HEAD'], { cwd });
197
- const status = exec('git', ['status', '--porcelain', ...OUTSIDE_MORPH], { cwd });
198
- const diff = exec('git', ['diff', 'HEAD', ...OUTSIDE_MORPH], { cwd });
199
- const entries = tree.code === 0
200
- ? tree.output.split('\n').filter((line) => line.split('\t')[1] !== '.morph').join('\n')
201
- : head.output.trim();
202
-
203
- return createHash('sha1')
204
- .update(entries)
205
- .update('\0')
206
- .update(status.code === 0 ? status.output : '')
207
- .update('\0')
208
- .update(diff.code === 0 ? diff.output : '')
209
- .update('\0')
210
- .update(readConfigText(cwd))
211
- .digest('hex');
212
- }
213
-
214
- const OUTSIDE_MORPH = ['--', '.', ':(exclude).morph'];
215
-
216
- function readConfigText(cwd) {
217
- try {
218
- return readFileSync(join(cwd, '.morph', 'config', 'config.json'), 'utf8');
219
- } catch {
220
- return '';
221
- }
222
- }
223
-
224
- export function stampPath(gitCommonDir, projectName) {
225
- return join(gitCommonDir, 'morph-spec', `e2e-stamp-${projectName}.json`);
226
- }
227
-
228
- export function readStamp(gitCommonDir, projectName) {
229
- try {
230
- const raw = readFileSync(stampPath(gitCommonDir, projectName), 'utf8').replace(/^/, '');
231
- const parsed = JSON.parse(raw);
232
- return typeof parsed?.stamp === 'string' ? parsed : null;
233
- } catch {
234
- return null;
235
- }
236
- }
237
-
238
- export function writeStamp(gitCommonDir, projectName, stamp, extra = {}) {
239
- const dir = join(gitCommonDir, 'morph-spec');
240
- mkdirSync(dir, { recursive: true });
241
- const target = stampPath(gitCommonDir, projectName);
242
- const tmp = `${target}.tmp.${process.pid}`;
243
- const body = { version: 1, project: projectName, stamp, builtAt: new Date().toISOString(), ...extra };
244
- writeFileSync(tmp, `${JSON.stringify(body, null, 2)}\n`, 'utf8');
245
- renameSync(tmp, target);
246
- }
247
-
248
- // Lives in the stamp so that whatever drops the stamp (down, a fresh up) drops the mark with it.
249
- function setDataBroken(gitCommonDir, projectName, broken) {
250
- if (!gitCommonDir) return;
251
- const previous = readStamp(gitCommonDir, projectName);
252
- if (Boolean(previous?.dataBroken) === broken) return;
253
- try {
254
- writeStamp(gitCommonDir, projectName, previous?.stamp ?? '', {
255
- builtAt: previous?.builtAt ?? new Date().toISOString(),
256
- ...(broken ? { dataBroken: true } : {}),
257
- });
258
- } catch {
259
- }
260
- }
261
-
262
- export function isDataBroken(gitCommonDir, projectName) {
263
- return Boolean(gitCommonDir && readStamp(gitCommonDir, projectName)?.dataBroken);
264
- }
265
-
266
- // A stamp that outlives its containers would let the next `up` reuse a stack that no longer exists.
267
- export function deleteStamp(gitCommonDir, projectName) {
268
- if (!gitCommonDir) return false;
269
- try {
270
- unlinkSync(stampPath(gitCommonDir, projectName));
271
- return true;
272
- } catch {
273
- return false;
274
- }
275
- }
276
-
277
- // True only when EVERY service built here mounts the project ROOT: a sidecar mounting `./e2e`
278
- // still runs its baked image. Uncertainty answers false, which costs one layer-cached rebuild.
279
- export function usesBindMount(composeConfig, cwd) {
280
- const services = composeConfig?.services;
281
- if (!services || typeof services !== 'object') return false;
282
-
283
- const normalizedCwd = normalizeMountPath(cwd);
284
- const built = Object.values(services).filter(
285
- (service) => service && service.build !== undefined && service.build !== null,
286
- );
287
- if (built.length === 0) return false;
288
-
289
- return built.every((service) => mountsProjectRoot(service, normalizedCwd));
290
- }
291
-
292
- function normalizeMountPath(path) {
293
- return String(path ?? '')
294
- .replace(/\\/g, '/')
295
- .replace(/\/+$/, '');
296
- }
297
-
298
- // Anchored on the ':' before the absolute container path: the first ':' is the drive on Windows.
299
- function shortVolumeSource(spec) {
300
- const match = /^(.+):(\/[^:]*)(:[A-Za-z,]+)?$/.exec(spec);
301
- return match ? match[1] : null;
302
- }
303
-
304
- function mountsProjectRoot(service, normalizedCwd) {
305
- const volumes = Array.isArray(service?.volumes) ? service.volumes : [];
306
- return volumes.some((vol) => {
307
- if (typeof vol !== 'string' && vol?.type && vol.type !== 'bind') return false;
308
- const source = typeof vol === 'string' ? shortVolumeSource(vol) : vol?.source;
309
- if (!source) return false;
310
- return normalizeMountPath(source) === normalizedCwd;
311
- });
312
- }
313
-
314
- // Compose emits a JSON array or NDJSON depending on its version.
315
- export function parseComposePs(raw) {
316
- const text = (raw || '').trim();
317
- if (!text) return [];
318
-
319
- try {
320
- const parsed = JSON.parse(text);
321
- return Array.isArray(parsed) ? parsed : [parsed];
322
- } catch {
323
- return text
324
- .split('\n')
325
- .map((line) => line.trim())
326
- .filter(Boolean)
327
- .map((line) => {
328
- try {
329
- return JSON.parse(line);
330
- } catch {
331
- return null;
332
- }
333
- })
334
- .filter(Boolean);
335
- }
336
- }
337
-
338
- export function isServiceHealthy(service) {
339
- const state = String(service?.State ?? '').toLowerCase();
340
- if (state !== 'running') return false;
341
- const health = String(service?.Health ?? '').toLowerCase();
342
- return health === '' || health === 'healthy';
343
- }
344
-
345
- export function getStackStatus(cwd, { composeFile, projectName, env } = {}, exec = defaultExec) {
346
- const result = exec('docker', [...composeArgs(composeFile, projectName), 'ps', '--format', 'json'], {
347
- cwd,
348
- env,
349
- });
350
- if (result.code !== 0) return { up: false, healthy: false, services: [] };
351
-
352
- const services = parseComposePs(result.output);
353
- const running = services.filter((s) => String(s?.State ?? '').toLowerCase() === 'running');
354
- return {
355
- up: running.length > 0,
356
- healthy: services.length > 0 && services.every(isServiceHealthy),
357
- services,
358
- };
359
- }
360
-
361
- function composeArgs(composeFile, projectName) {
362
- const args = ['compose'];
363
- if (composeFile) args.push('-f', composeFile);
364
- if (projectName) args.push('-p', projectName);
365
- return args;
366
- }
367
-
368
- export function isDockerAvailable(cwd, exec = defaultExec) {
369
- return exec('docker', ['version', '--format', '{{.Server.Version}}'], { cwd }).code === 0;
370
- }
371
-
372
- // A configured `e2e.composeFile` that is missing never degrades to host-only: the database it
373
- // declares would silently never come up.
374
- export function isHostOnlyStack(config, composeFile) {
375
- if (composeFile || config?.e2e?.composeFile) return false;
376
- const services = config?.e2e?.hostServices;
377
- return Array.isArray(services) && services.length > 0;
378
- }
379
-
380
- // Declaring the docker integration without a compose file fails instead of skipping: as a skip,
381
- // every project without compose would pass e2e forever.
382
- export function decideApplicability({
383
- composeFile,
384
- integrations = [],
385
- hostOnly = false,
386
- skipRequested = false,
387
- }) {
388
- if (skipRequested) {
389
- return { run: false, status: 'skip', reason: 'requested' };
390
- }
391
-
392
- if (!composeFile) {
393
- if (integrations.map((i) => String(i).toLowerCase()).includes('docker')) {
394
- return {
395
- run: false,
396
- status: 'fail',
397
- reason:
398
- 'project declares the "docker" integration but no compose file was found — ' +
399
- 'e2e verification was never set up (add one, or set e2e.composeFile in config.json)',
400
- };
401
- }
402
- if (hostOnly) return { run: true };
403
- return { run: false, status: 'skip', reason: 'project does not containerize (no compose file)' };
404
- }
405
-
406
- return { run: true };
407
- }
408
-
409
- // Reuses a warm stack only when it provably serves current code; anything uncertain rebuilds,
410
- // which the layer cache makes cheap.
411
- export function bringUpStack(
412
- cwd,
413
- { composeFile, projectName, gitCommonDir, env, forceFresh = false, healthTimeout = DEFAULT_HEALTH_TIMEOUT, stamp: knownStamp } = {},
414
- exec = defaultExec,
415
- ) {
416
- const base = composeArgs(composeFile, projectName);
417
- const stamp = knownStamp === undefined ? computeSourceStamp(cwd, exec) : knownStamp;
418
- const status = getStackStatus(cwd, { composeFile, projectName, env }, exec);
419
-
420
- const decision = decideReuse({ cwd, base, env, stamp, status, gitCommonDir, projectName, forceFresh, exec });
421
-
422
- if (decision.reuse) {
423
- return { status: 'pass', reused: true, output: '', reason: decision.reason };
424
- }
425
-
426
- // "Fresh" covers the DATA too: `--build` alone keeps the postgres volume and the previous
427
- // run's rows. Volumes and the stamp go together.
428
- if (forceFresh) {
429
- tearDownStack(cwd, { composeFile, projectName, env, volumes: true }, exec);
430
- deleteStamp(gitCommonDir, projectName);
431
- }
432
-
433
- const upArgs = [...base, 'up', '-d', '--wait'];
434
- if (decision.rebuild) upArgs.push('--build');
435
-
436
- const up = exec('docker', upArgs, { cwd, env, timeout: healthTimeout });
437
- if (up.code !== 0) {
438
- return {
439
- status: 'fail',
440
- reused: false,
441
- output: tailLines(up.output, OUTPUT_TAIL_LINES),
442
- reason: 'stack failed to start',
443
- };
444
- }
445
-
446
- const health = waitForHealthy(cwd, { composeFile, projectName, env, timeout: healthTimeout }, exec);
447
- if (!health.healthy) {
448
- return {
449
- status: 'fail',
450
- reused: false,
451
- output: health.output,
452
- reason: 'stack came up but never reported healthy',
453
- };
454
- }
455
-
456
- if (gitCommonDir && stamp) {
457
- try {
458
- writeStamp(gitCommonDir, projectName, stamp);
459
- } catch {
460
- }
461
- }
462
-
463
- return { status: 'pass', reused: false, output: '', reason: null };
464
- }
465
-
466
- function decideReuse({ cwd, base, env, stamp, status, gitCommonDir, projectName, forceFresh, exec }) {
467
- if (forceFresh) return { reuse: false, rebuild: true };
468
- if (!status.up || !status.healthy) return { reuse: false, rebuild: true };
469
-
470
- const configJson = exec('docker', [...base, 'config', '--format', 'json'], { cwd, env });
471
- if (configJson.code === 0) {
472
- try {
473
- if (usesBindMount(JSON.parse(configJson.output), cwd)) {
474
- return { reuse: true, reason: 'reused warm stack (source is bind-mounted)' };
475
- }
476
- } catch {
477
- }
478
- }
479
-
480
- if (!gitCommonDir || !stamp) return { reuse: false, rebuild: true };
481
-
482
- const previous = readStamp(gitCommonDir, projectName);
483
- if (previous?.stamp === stamp) {
484
- return { reuse: true, reason: 'reused warm stack (source unchanged since build)' };
485
- }
486
- return { reuse: false, rebuild: true };
487
- }
488
-
489
- function waitForHealthy(cwd, { composeFile, projectName, env, timeout }, exec) {
490
- const deadline = Date.now() + timeout;
491
- let last = { up: false, healthy: false, services: [] };
492
-
493
- // `up --wait` returns the moment a service without a healthcheck starts.
494
- do {
495
- last = getStackStatus(cwd, { composeFile, projectName, env }, exec);
496
- if (last.healthy) return { healthy: true, output: '' };
497
- if (Date.now() >= deadline) break;
498
- sleep(HEALTH_POLL_MS);
499
- } while (Date.now() < deadline);
500
-
501
- const unhealthy = last.services
502
- .filter((s) => !isServiceHealthy(s))
503
- .map((s) => ` ${s.Service ?? s.Name ?? '?'}: state=${s.State ?? '?'} health=${s.Health || 'none'}`)
504
- .join('\n');
505
-
506
- const logs = exec('docker', [...composeArgs(composeFile, projectName), 'logs', '--tail', '30'], { cwd, env });
507
- return {
508
- healthy: false,
509
- output: [unhealthy && `Unhealthy services:\n${unhealthy}`, logs.code === 0 ? tailLines(logs.output, 30) : '']
510
- .filter(Boolean)
511
- .join('\n\n'),
512
- };
513
- }
514
-
515
- function sleep(ms) {
516
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
517
- }
518
-
519
- export function tearDownStack(cwd, { composeFile, projectName, env, volumes = false, images } = {}, exec = defaultExec) {
520
- const args = [...composeArgs(composeFile, projectName), 'down', '--remove-orphans'];
521
- if (images) args.push('--rmi', images);
522
- if (volumes) args.push('-v');
523
- const result = exec('docker', args, { cwd, env });
524
- return { status: result.code === 0 ? 'pass' : 'fail', output: result.output };
525
- }
526
-
527
- export function loadEnvFile(path) {
528
- try {
529
- const raw = readFileSync(path, 'utf8').replace(/^/, '');
530
- const out = {};
531
- for (const line of raw.split('\n')) {
532
- const trimmed = line.trim();
533
- if (!trimmed || trimmed.startsWith('#')) continue;
534
- const eq = trimmed.indexOf('=');
535
- if (eq <= 0) continue;
536
- const key = trimmed.slice(0, eq).trim();
537
- let value = trimmed.slice(eq + 1).trim();
538
- if (
539
- (value.startsWith('"') && value.endsWith('"')) ||
540
- (value.startsWith("'") && value.endsWith("'"))
541
- ) {
542
- value = value.slice(1, -1);
543
- }
544
- out[key] = value;
545
- }
546
- return out;
547
- } catch {
548
- return {};
549
- }
550
- }
551
-
552
- // Never hangs and never degrades broken auth to "skip": that is how every project with a login
553
- // screen would quietly end up with no e2e. A seed switched off by `mode` warns instead of going silent.
554
- export function prepareAuth(
555
- cwd,
556
- { config, env, timeout = 60_000, forceSeed = false } = {},
557
- exec = defaultExec,
558
- ) {
559
- const auth = config?.e2e?.auth;
560
- const mode = auth?.mode ?? 'none';
561
-
562
- if (mode === 'none') {
563
- if (auth?.seedCommand) {
564
- const declared = auth.mode == null ? 'absent' : `"${auth.mode}"`;
565
- return {
566
- status: 'skip',
567
- reason: null,
568
- warning:
569
- `e2e.auth.seedCommand is configured but e2e.auth.mode is ${declared} — ` +
570
- 'the seed never runs (set e2e.auth.mode to "seed" or "storageState")',
571
- };
572
- }
573
- return { status: 'skip', reason: null };
574
- }
575
-
576
- if (mode === 'bypass') {
577
- return { status: 'pass', reason: 'auth bypassed for the e2e environment' };
578
- }
579
-
580
- if (mode === 'storageState') {
581
- const statePath = auth.storageStatePath
582
- ? join(cwd, auth.storageStatePath)
583
- : null;
584
- const stateExists = Boolean(statePath && existsSync(statePath));
585
-
586
- // After `--fresh-e2e` dropped the volumes, a stored session authenticates a user that is gone:
587
- // every request is 403 and looks like a broken app.
588
- if (stateExists && !forceSeed) {
589
- return { status: 'pass', reason: 'reused stored auth session' };
590
- }
591
- if (!auth.seedCommand) {
592
- if (stateExists) {
593
- return {
594
- status: 'pass',
595
- reason: 'reused stored auth session (no e2e.auth.seedCommand to refresh it)',
596
- };
597
- }
598
- return {
599
- status: 'fail',
600
- reason:
601
- `e2e.auth.mode is "storageState" but ${auth.storageStatePath || '<storageStatePath>'} ` +
602
- 'does not exist and no e2e.auth.seedCommand is configured to create it',
603
- };
604
- }
605
- }
606
-
607
- if (!auth.seedCommand) {
608
- return {
609
- status: 'fail',
610
- reason: `e2e.auth.mode is "${mode}" but no e2e.auth.seedCommand is configured`,
611
- };
612
- }
613
-
614
- const [command, ...args] = String(auth.seedCommand).split(' ').filter(Boolean);
615
- const result = exec(command, args, { cwd, env, timeout });
616
-
617
- if (result.code !== 0) {
618
- return {
619
- status: 'fail',
620
- reason: `e2e auth setup failed (${auth.seedCommand}): ${firstLine(result.output)}`,
621
- };
622
- }
623
- return {
624
- status: 'pass',
625
- reason: forceSeed
626
- ? 'auth re-seeded against the fresh stack'
627
- : 'auth seeded for the e2e environment',
628
- };
629
- }
630
-
631
- export function stackEnvFor(cwd, { config, projectName, env } = {}) {
632
- // The credentials file sits under the caller's env: it must never override the feature's port block.
633
- const authEnv = config?.e2e?.auth?.envFile ? loadEnvFile(join(cwd, config.e2e.auth.envFile)) : {};
634
- return { COMPOSE_PROJECT_NAME: projectName, ...authEnv, ...(env || {}) };
635
- }
636
-
637
- // A data service mounts a named volume and is not built here: a built service is the app, and an
638
- // external volume belongs to someone else. A volume outside the project prefix (an explicit `name:`)
639
- // is shared with whatever else mounts that name, so it lands in `shared` and is never removed.
640
- export function dataServices(composeConfig, projectName = null) {
641
- const declared = composeConfig?.volumes ?? {};
642
- const services = [];
643
- const volumes = new Set();
644
- const shared = [];
645
- for (const [name, service] of Object.entries(composeConfig?.services ?? {})) {
646
- if (service?.build != null) continue;
647
- const named = (Array.isArray(service?.volumes) ? service.volumes : [])
648
- .filter((v) => v && typeof v === 'object' && v.type === 'volume' && v.source && !declared[v.source]?.external)
649
- .map((v) => declared[v.source]?.name ?? v.source);
650
- if (named.length === 0) continue;
651
- const foreign = projectName ? named.filter((v) => !v.startsWith(`${projectName}_`)) : [];
652
- if (foreign.length) { shared.push(...foreign.map((volume) => ({ service: name, volume }))); continue; }
653
- services.push(name);
654
- for (const v of named) volumes.add(v);
655
- }
656
- return { services, volumes: [...volumes], shared };
657
- }
658
-
659
- const DATA_NOT_READY =
660
- 'the e2e data was reset but is not migrated or seeded: run `morph-spec e2e up <feature> --fresh`, do not repeat the reset';
661
-
662
- /**
663
- * Puts the running stack's data back in a known state: `e2e.resetCommand`, else the services that
664
- * declare a named volume are recreated empty and everything that may migrate at startup (the other
665
- * compose services, the host services) is restarted without a rebuild; then the auth seed. A
666
- * re-seed alone would leave the previous flow's rows. A host-only stack has no volumes: it gets
667
- * the command or the seed. A failure after the data was touched marks the stack as broken.
668
- */
669
- export function resetE2eData(
670
- cwd,
671
- { config, composeFile, projectName, gitCommonDir = null, env, healthTimeout = DEFAULT_HEALTH_TIMEOUT } = {},
672
- exec = defaultExec,
673
- ) {
674
- const stackEnv = stackEnvFor(cwd, { config, projectName, env });
675
- const base = composeArgs(composeFile, projectName);
676
- const out = (fields) => ({ reset: { mode: 'none', services: [], volumes: [] }, auth: { status: 'skip', reason: null }, output: '', ...fields });
677
- const broken = (fields) => {
678
- setDataBroken(gitCommonDir, projectName, true);
679
- return out({ ...fields, status: 'fail', reason: `${fields.reason} — ${DATA_NOT_READY}` });
680
- };
681
-
682
- const up = composeFile
683
- ? getStackStatus(cwd, { composeFile, projectName, env: stackEnv }, exec).up
684
- : hostServicesUp(gitCommonDir, projectName);
685
- if (!up) {
686
- return out({ status: 'fail', reason: `stack ${projectName} is not up — run \`morph-spec e2e up\` first` });
687
- }
688
-
689
- let reset = { mode: 'none', services: [], volumes: [] };
690
- const resetCommand = config?.e2e?.resetCommand;
691
- if (resetCommand) {
692
- const [command, ...args] = String(resetCommand).split(' ').filter(Boolean);
693
- const run = exec(command, args, { cwd, env: stackEnv, timeout: healthTimeout });
694
- if (run.code !== 0) {
695
- return out({ status: 'fail', reason: `e2e.resetCommand failed (${resetCommand}): ${firstLine(run.output)}`, output: tailLines(run.output, OUTPUT_TAIL_LINES) });
696
- }
697
- reset = { mode: 'command', command: resetCommand, services: [], volumes: [] };
698
- } else if (composeFile) {
699
- const configJson = exec('docker', [...base, 'config', '--format', 'json'], { cwd, env: stackEnv });
700
- let parsed = null;
701
- try { parsed = configJson.code === 0 ? JSON.parse(configJson.output) : null; } catch { parsed = null; }
702
- if (!parsed) {
703
- return out({ status: 'fail', reason: 'could not read the compose config to find the data services', output: tailLines(configJson.output, OUTPUT_TAIL_LINES) });
704
- }
705
- const data = dataServices(parsed, projectName);
706
- if (data.shared.length > 0) {
707
- const names = data.shared.map((s) => `${s.volume} (${s.service})`).join(', ');
708
- return out({ status: 'fail', reason: `refusing to reset: ${names} is not scoped to ${projectName} and may hold data outside this feature's stack  set e2e.resetCommand` });
709
- }
710
- if (data.services.length > 0) {
711
- const steps = [
712
- [...base, 'rm', '-sfv', ...data.services],
713
- ['volume', 'rm', '-f', ...data.volumes],
714
- // An app that only migrates at startup would keep serving an empty database.
715
- [...base, 'up', '-d', '--wait', '--force-recreate'],
716
- ];
717
- for (const args of steps) {
718
- const step = exec('docker', args, { cwd, env: stackEnv, timeout: healthTimeout });
719
- if (step.code !== 0) {
720
- return broken({ reason: `reset step failed: docker ${args.join(' ')}`, output: tailLines(step.output, OUTPUT_TAIL_LINES) });
721
- }
722
- }
723
- const health = waitForHealthy(cwd, { composeFile, projectName, env: stackEnv, timeout: healthTimeout }, exec);
724
- if (!health.healthy) {
725
- return broken({ reason: 'the stack was recreated on empty data but never reported healthy', output: health.output });
726
- }
727
- reset = { mode: 'volumes', services: data.services, volumes: data.volumes };
728
- if (gitCommonDir) {
729
- const host = startHostServices(cwd, { services: config?.e2e?.hostServices, env: stackEnv, gitCommonDir, projectName, restart: true }, exec);
730
- if (host.status === 'fail') return broken({ reason: host.reason, output: host.output ?? '', reset });
731
- }
732
- }
733
- }
734
-
735
- const auth = prepareAuth(cwd, { config, env: stackEnv, forceSeed: true }, exec);
736
- if (auth.status === 'fail') {
737
- return reset.mode === 'none'
738
- ? out({ status: 'fail', reason: auth.reason, reset, auth })
739
- : broken({ reason: auth.reason, reset, auth });
740
- }
741
- setDataBroken(gitCommonDir, projectName, false);
742
- if (reset.mode === 'none' && auth.status === 'skip' && !composeFile) {
743
- return out({ status: 'skip', reason: 'nothing to reset: host-only stack with no e2e.resetCommand and no auth seed', reset, auth });
744
- }
745
- if (reset.mode === 'none' && auth.status === 'skip') {
746
- return out({ status: 'skip', reason: 'nothing to reset: no e2e.resetCommand, no service with a named volume and no auth seed', reset, auth });
747
- }
748
- return out({ status: 'pass', reason: null, reset, auth: { status: auth.status, reason: auth.reason } });
749
- }
750
-
751
- function hostServicesUp(gitCommonDir, projectName) {
752
- if (!gitCommonDir) return false;
753
- const services = hostServicesStatus(gitCommonDir, projectName);
754
- return services.length > 0 && services.every((s) => s.alive);
755
- }
756
-
757
- export const HOST_ONLY_STACK = Object.freeze({
758
- status: 'skip',
759
- reused: false,
760
- output: '',
761
- reason: 'no compose file: host services only',
762
- });
763
-
764
- /**
765
- * The one bring-up of `e2e up` and the verify node: compose up → host services in array order → seed.
766
- * Without a compose file the stack is the host services alone. `stage` names where a failure
767
- * stopped; nothing after it ran.
768
- */
769
- export function bringUpE2e(
770
- cwd,
771
- { config, composeFile, projectName, gitCommonDir = null, env, forceFresh = false, healthTimeout = DEFAULT_HEALTH_TIMEOUT } = {},
772
- exec = defaultExec,
773
- ) {
774
- const stackEnv = stackEnvFor(cwd, { config, projectName, env });
775
- const warnings = [];
776
- const stamp = computeSourceStamp(cwd, exec);
777
-
778
- if (isDataBroken(gitCommonDir, projectName)) {
779
- forceFresh = true;
780
- warnings.push('the last `e2e reset` left the data unusable: the stack was brought up fresh');
781
- }
782
- if (forceFresh && !composeFile) deleteStamp(gitCommonDir, projectName);
783
- const stack = composeFile
784
- ? bringUpStack(cwd, { composeFile, projectName, gitCommonDir, env: stackEnv, forceFresh, healthTimeout, stamp }, exec)
785
- : HOST_ONLY_STACK;
786
- const result = (fields) => ({
787
- stack,
788
- env: stackEnv,
789
- auth: { status: 'skip', reason: null },
790
- hostServices: { status: 'skip', reused: false, services: [], warnings: [] },
791
- warnings,
792
- command: null,
793
- output: '',
794
- ...fields,
795
- });
796
- if (stack.status === 'fail') {
797
- return result({
798
- status: 'fail',
799
- stage: 'compose',
800
- command: `docker compose -f ${composeFile} up -d --wait`,
801
- reason: stack.reason,
802
- output: stack.output,
803
- });
804
- }
805
-
806
- const services = config?.e2e?.hostServices;
807
- if (Array.isArray(services) && services.length > 0 && !gitCommonDir) {
808
- return result({
809
- status: 'fail',
810
- stage: 'host',
811
- reason: 'e2e.hostServices needs a git repository: their PID file lives in the git common dir',
812
- });
813
- }
814
- const host = startHostServices(cwd, { services, env: stackEnv, gitCommonDir, projectName, stamp, forceFresh }, exec);
815
- warnings.push(...(host.warnings ?? []));
816
- if (host.status === 'fail') {
817
- return result({ status: 'fail', stage: 'host', reason: host.reason, output: host.output ?? '', hostServices: host });
818
- }
819
-
820
- const auth = prepareAuth(cwd, { config, env: stackEnv, forceSeed: forceFresh }, exec);
821
- if (auth.warning) warnings.push(auth.warning);
822
- if (auth.status === 'fail') {
823
- return result({ status: 'fail', stage: 'auth', reason: auth.reason, hostServices: host, auth });
824
- }
825
- // `e2e status` reads freshness from this stamp; with compose `bringUpStack` already wrote it.
826
- if (!composeFile && gitCommonDir && stamp) {
827
- try {
828
- writeStamp(gitCommonDir, projectName, stamp);
829
- } catch {
830
- }
831
- }
832
- return result({ status: 'pass', stage: null, reason: stack.reason, hostServices: host, auth });
833
- }
834
-
835
- function specTimeoutFor(config) {
836
- const configured = config?.e2e?.specTimeoutMs;
837
- return Number.isFinite(configured) && configured > 0 ? configured : DEFAULT_SPEC_TIMEOUT;
838
- }
839
-
840
- /** @returns {{ status: 'pass'|'fail'|'skip', command: string|null, output: string, reason: string|null, warnings: string[] }} */
841
- export function runE2eCheck(cwd, options = {}) {
842
- const {
843
- config,
844
- featureName = 'default',
845
- gitCommonDir = null,
846
- env,
847
- skipRequested = false,
848
- keepUp = true,
849
- forceFresh = false,
850
- insideWorktree = isSecondaryWorktree(cwd),
851
- healthTimeout = DEFAULT_HEALTH_TIMEOUT,
852
- specTimeout = specTimeoutFor(config),
853
- beforeHeavy = null,
854
- countSpecs = null,
855
- _exec: exec = defaultExec,
856
- } = options;
857
-
858
- const warnings = [];
859
- const composeFile = resolveComposeFile(cwd, config);
860
- const integrations = Array.isArray(config?.project?.integrations) ? config.project.integrations : [];
861
-
862
- const hostOnly = isHostOnlyStack(config, composeFile);
863
- const applicability = decideApplicability({ composeFile, integrations, hostOnly, skipRequested });
864
- if (!applicability.run) {
865
- return { status: applicability.status, command: null, output: '', reason: applicability.reason, warnings };
866
- }
867
-
868
- if (composeFile) {
869
- // Isolation comes BEFORE the docker check: a non-isolable compose is a project defect
870
- // whether or not this machine has Docker.
871
- const lint = lintComposeIsolation(readComposeText(cwd, composeFile));
872
- const isolation = decideIsolation({ findings: lint.findings, insideWorktree });
873
- if (isolation.status === 'fail') {
874
- return {
875
- status: 'fail',
876
- command: null,
877
- output: lint.findings.map((f) => `${composeFile}:${f.line}: ${f.text}`).join('\n'),
878
- reason: isolation.reason,
879
- warnings,
880
- };
881
- }
882
- if (isolation.status === 'warn') warnings.push(isolation.reason);
883
-
884
- // A missing Docker is an environment gap: it skips, with a reason that never reads as a pass.
885
- if (!isDockerAvailable(cwd, exec)) {
886
- return {
887
- status: 'skip',
888
- command: null,
889
- output: '',
890
- reason: 'docker is not available in this environment — e2e could not run',
891
- warnings,
892
- };
893
- }
894
- }
895
-
896
- const projectName = composeProjectName(featureName);
897
-
898
- if (typeof beforeHeavy === 'function') beforeHeavy();
899
- const up = bringUpE2e(cwd, { config, composeFile, projectName, gitCommonDir, env, forceFresh, healthTimeout }, exec);
900
- warnings.push(...up.warnings);
901
- if (up.stage === 'compose') {
902
- return { status: 'fail', command: up.command, output: up.output, reason: up.reason, warnings };
903
- }
904
-
905
- try {
906
- if (up.status === 'fail') {
907
- return { status: 'fail', command: up.command, output: up.output, reason: up.reason, warnings };
908
- }
909
- const specs = runSpecs(
910
- cwd,
911
- { config, composeFile, up: up.stack, auth: up.auth, specTimeout, composeEnv: up.env, countSpecs },
912
- exec,
913
- );
914
- return { ...specs, warnings: [...warnings, ...(specs.warnings || [])] };
915
- } finally {
916
- if (!keepUp) {
917
- stopHostServices(gitCommonDir, projectName);
918
- if (composeFile) tearDownStack(cwd, { composeFile, projectName, env: up.env }, exec);
919
- }
920
- }
921
- }
922
-
923
- // Playwright's list reporter names a failure as ` 1) [chromium] › e2e/a.spec.ts:3:5 › title`.
924
- function failedSpecNames(output) {
925
- const names = [...String(output).matchAll(/^\s+\d+\)\s+(.+›.+)$/gm)].map((match) => match[1].trim());
926
- return [...new Set(names)];
927
- }
928
-
929
- // The suite gets the stack's env (with PLAYWRIGHT_BASE_URL): without it the config hits a hardcoded
930
- // localhost:3000 while the app sits on the feature's port, an ECONNREFUSED that looks like a broken app.
931
- function runSpecs(cwd, { config, composeFile, up, auth, specTimeout, composeEnv, countSpecs }, exec) {
932
- const frontendPath = config?.project?.frontendPath;
933
- const spec = resolveSpecCommand(cwd, config, frontendPath);
934
- const notes = [up.reused ? up.reason : null, auth?.reason].filter(Boolean);
935
-
936
- if (!spec) {
937
- return {
938
- status: 'pass',
939
- command: composeFile ? `docker compose -f ${composeFile} up -d --wait` : null,
940
- output: '',
941
- reason: joinNotes(
942
- composeFile
943
- ? 'smoke only — stack healthy, no Playwright specs found'
944
- : 'smoke only — host services healthy, no Playwright specs found',
945
- notes,
946
- ),
947
- warnings: findUnrunPlaywrightConfigs(cwd, frontendPath).map(unrunConfigWarning),
948
- };
949
- }
950
-
951
- const commandLine = `${spec.command} ${spec.args.join(' ')}`;
952
- const run = exec(spec.command, spec.args, { cwd: spec.cwd, timeout: specTimeout, env: composeEnv });
953
- // Counted from the FULL output, before the tail cut; unparseable is null, never 0.
954
- const count = typeof countSpecs === 'function' ? (countSpecs(run.output) ?? null) : null;
955
-
956
- // One rerun of the failed specs only: a flake must not cost a whole verify. `--last-failed`
957
- // needs Playwright 1.44+; an older one exits non-zero, and the node stays red.
958
- const retry = run.code !== 0 && spec.args.includes('playwright')
959
- ? exec(spec.command, [...spec.args, '--last-failed'], { cwd: spec.cwd, timeout: specTimeout, env: composeEnv })
960
- : null;
961
-
962
- // A spec the project declared in `e2e.quarantine` (out of the feature's scope, known red) is
963
- // named, never hidden: it stops failing the node only when every red spec is one of them.
964
- const stillRed = run.code !== 0 && retry?.code !== 0 ? failedSpecNames(retry?.output ?? run.output) : [];
965
- const quarantine = (config?.e2e?.quarantine ?? []).filter((q) => typeof q === 'string' && q.trim());
966
- if (stillRed.length > 0 && quarantine.length > 0 && stillRed.every((spec) => quarantine.some((q) => spec.includes(q)))) {
967
- return {
968
- status: 'pass',
969
- quarantinedSpecs: stillRed,
970
- flakySpecs: [],
971
- command: commandLine,
972
- output: '',
973
- reason: joinNotes(`quarentena (e2e.quarantine): ${stillRed.join('; ')}`, notes),
974
- count,
975
- };
976
- }
977
-
978
- if (run.code !== 0 && retry?.code !== 0) {
979
- return {
980
- status: 'fail',
981
- command: commandLine,
982
- output: tailLines(retry?.output ?? run.output, OUTPUT_TAIL_LINES),
983
- reason: 'e2e specs failed against the running stack',
984
- count,
985
- };
986
- }
987
-
988
- const flakySpecs = retry ? failedSpecNames(run.output) : [];
989
-
990
- return {
991
- status: 'pass',
992
- flakySpecs,
993
- command: commandLine,
994
- output: '',
995
- reason: notes.length ? notes.join('; ') : null,
996
- count,
997
- };
998
- }
999
-
1000
- function readComposeText(cwd, composeFile) {
1001
- try {
1002
- return readFileSync(join(cwd, composeFile), 'utf8');
1003
- } catch {
1004
- return '';
1005
- }
1006
- }
1007
-
1008
- function joinNotes(head, notes) {
1009
- return notes.length ? `${head} (${notes.join('; ')})` : head;
1010
- }
1011
-
1012
- function firstLine(text) {
1013
- const trimmed = (text || '').trim();
1014
- if (!trimmed) return 'no output';
1015
- return trimmed.split('\n')[0].slice(0, 200);
1016
- }
1017
-
1018
- function tailLines(text, n) {
1019
- const trimmed = (text || '').trim();
1020
- if (!trimmed) return '';
1021
- return trimmed.split('\n').slice(-n).join('\n');
1022
- }