@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,175 +0,0 @@
1
- // Stays out of `doctor --full`: a docker check in a repo with no compose file
2
- // could only be permanently yellow. Read-only; the `fix` strings are for a human.
3
- import { execFileSync } from 'child_process';
4
- import { resolve } from 'path';
5
-
6
- import {
7
- composeProjectName,
8
- defaultExec,
9
- isDockerAvailable,
10
- parseComposePs,
11
- } from '../../../framework/hooks/shared/e2e-check.js';
12
- import { allocateEnvBlock, allocatedFeatures, portLayout, resolveFleetConfig } from './env-allocator.js';
13
-
14
- const PROJECT_PROBE = 'probe';
15
- export const MORPH_PROJECT_PREFIX = composeProjectName(PROJECT_PROBE).slice(0, -PROJECT_PROBE.length);
16
-
17
- export function resolveGitCommonDir(cwd) {
18
- try {
19
- const common = execFileSync('git', ['rev-parse', '--git-common-dir'], {
20
- cwd, stdio: 'pipe', encoding: 'utf-8', windowsHide: true,
21
- }).trim();
22
- return common ? resolve(cwd, common) : null;
23
- } catch {
24
- return null;
25
- }
26
- }
27
-
28
- // On Windows git and docker report the drive letter in different case.
29
- export const samePathCase = process.platform === 'win32' ? (s) => s.toLowerCase() : (s) => s;
30
- const norm = (p) => samePathCase(resolve(String(p)).replace(/\\/g, '/'));
31
-
32
- // The `morph-` prefix is host-global: two repos with the same feature name share
33
- // a project name, so ownership comes from the compose file path. No path = not ours.
34
- function belongsToRoot(entry, rootNorm) {
35
- const configFiles = String(entry?.ConfigFiles ?? '').split(',').map((s) => s.trim()).filter(Boolean);
36
- if (configFiles.length === 0) return false;
37
- return configFiles.some((f) => {
38
- try {
39
- return norm(f).startsWith(`${rootNorm}/`);
40
- } catch {
41
- return false;
42
- }
43
- });
44
- }
45
-
46
- function publishedPorts(entry) {
47
- const ports = new Set();
48
- for (const pub of Array.isArray(entry?.Publishers) ? entry.Publishers : []) {
49
- const p = Number(pub?.PublishedPort);
50
- if (Number.isInteger(p) && p > 0) ports.add(p);
51
- }
52
- const raw = String(entry?.Ports ?? '');
53
- for (const m of raw.matchAll(/:(\d{1,5})->/g)) {
54
- const p = Number(m[1]);
55
- if (Number.isInteger(p) && p > 0) ports.add(p);
56
- }
57
- return ports;
58
- }
59
-
60
- export function stackBelongsTo(entry, root) {
61
- return belongsToRoot(entry, norm(root));
62
- }
63
-
64
- function composeProjectOf(entry) {
65
- const labels = String(entry?.Labels ?? '');
66
- for (const part of labels.split(',')) {
67
- const idx = part.indexOf('=');
68
- if (idx < 0) continue;
69
- if (part.slice(0, idx).trim() === 'com.docker.compose.project') return part.slice(idx + 1).trim() || null;
70
- }
71
- return null;
72
- }
73
-
74
- function containerNameOf(entry) {
75
- const names = String(entry?.Names ?? entry?.Name ?? '').split(',').map((s) => s.trim()).filter(Boolean);
76
- return names[0] || String(entry?.ID ?? 'container desconhecido');
77
- }
78
-
79
- // `null` = unreadable, distinct from `[]` = docker answered with nothing running.
80
- export function parseDockerJson(raw) {
81
- const text = String(raw ?? '').trim();
82
- if (!text) return [];
83
- const parsed = parseComposePs(text);
84
- if (parsed.length > 0) return parsed;
85
- // parseComposePs returns `[]` for non-JSON too; only a literal `[]` is "nothing".
86
- return /^\[\s*\]$/.test(text) ? [] : null;
87
- }
88
-
89
- /**
90
- * `[]` means "nothing to report", not unknown: with no port block allocated or
91
- * no docker, nothing can collide. Docker errors are fail-open.
92
- * `features` is passed in so the audit and `auditWorktrees` share one scan.
93
- */
94
- export function auditDockerStacks(root, { exec = defaultExec, features = [], gitCommonDir } = {}) {
95
- const commonDir = gitCommonDir === undefined ? resolveGitCommonDir(root) : gitCommonDir;
96
- if (!commonDir) return [];
97
-
98
- const allocated = allocatedFeatures(commonDir);
99
- if (allocated.length === 0) return [];
100
-
101
- if (!isDockerAvailable(root, exec)) return [];
102
-
103
- const known = new Set(features);
104
- const rootNorm = norm(root);
105
- const issues = [];
106
-
107
- const lsResult = exec('docker', ['compose', 'ls', '--format', 'json'], { cwd: root });
108
- if (lsResult.code !== 0) return [];
109
- const projects = parseDockerJson(lsResult.output);
110
- if (projects === null) return [];
111
-
112
- const knownProjects = new Set([...known].map((f) => composeProjectName(f)));
113
- for (const entry of projects) {
114
- const name = String(entry?.Name ?? '').trim();
115
- if (!name.startsWith(MORPH_PROJECT_PREFIX)) continue;
116
- if (knownProjects.has(name)) continue;
117
- if (!belongsToRoot(entry, rootNorm)) continue;
118
-
119
- const slug = name.slice(MORPH_PROJECT_PREFIX.length);
120
- issues.push({
121
- type: 'docker-stack-orphan',
122
- severity: 'warn',
123
- feature: slug || null,
124
- detail: `stack docker "${name}" está de pé (${String(entry?.Status ?? 'estado desconhecido')}) e não corresponde a nenhuma feature desta árvore — sobra de outra sessão, segurando o bloco de portas e os volumes de "${slug}"`,
125
- // Not `e2e down {slug}`: the feature's compose file no longer resolves.
126
- fix: `docker compose -p ${name} down -v`,
127
- });
128
- }
129
-
130
- const psResult = exec('docker', ['ps', '--format', 'json'], { cwd: root });
131
- if (psResult.code !== 0) return [];
132
- const containers = parseDockerJson(psResult.output);
133
- if (containers === null) return [];
134
-
135
- const { basePort, blockSize } = resolveFleetConfig(root);
136
- for (const feature of allocated) {
137
- if (!known.has(feature)) continue;
138
-
139
- let layout;
140
- try {
141
- // Feature is already in the registry, so allocateEnvBlock writes nothing.
142
- const block = allocateEnvBlock(feature, { gitCommonDir: commonDir, basePort, blockSize });
143
- layout = portLayout(block, { feature });
144
- } catch {
145
- continue;
146
- }
147
-
148
- const ownProject = layout.COMPOSE_PROJECT_NAME;
149
- const expected = new Map();
150
- for (const key of ['PORT', 'API_PORT', 'POSTGRES_PORT', 'REDIS_PORT']) {
151
- const port = Number(layout[key]);
152
- if (Number.isInteger(port)) expected.set(port, key);
153
- }
154
-
155
- for (const container of containers) {
156
- const project = composeProjectOf(container);
157
- if (project === ownProject) continue;
158
- for (const port of publishedPorts(container)) {
159
- const key = expected.get(port);
160
- if (!key) continue;
161
- issues.push({
162
- type: 'docker-port-held',
163
- severity: 'warn',
164
- feature,
165
- detail: `a porta ${port} (${key} do bloco de "${feature}") está publicada pelo container ${containerNameOf(container)}${project ? ` do projeto compose "${project}"` : ' (sem projeto compose)'}, não por "${ownProject}" — a stack de "${feature}" não sobe enquanto ela estiver presa`,
166
- fix: project
167
- ? `docker compose -p ${project} down (ou pare o container ${containerNameOf(container)}) antes de subir a stack de "${feature}"`
168
- : `docker stop ${containerNameOf(container)} antes de subir a stack de "${feature}"`,
169
- });
170
- }
171
- }
172
- }
173
-
174
- return issues;
175
- }
@@ -1,177 +0,0 @@
1
- // The registry lives under the COMMON git dir: shared by every linked worktree,
2
- // invisible to the `git status` the finish gates read, and survives `git clean -fdx`.
3
-
4
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'fs';
5
- import { join } from 'path';
6
- import { composeProjectName } from '../../../framework/hooks/shared/e2e-check.js';
7
-
8
- const DEFAULT_BASE_PORT = 4000;
9
- const DEFAULT_BLOCK_SIZE = 10;
10
- const MAX_PORT = 65535;
11
-
12
- // Chromium's kRestrictedPorts (net/base/port_util.cc): the browser refuses them with
13
- // ERR_UNSAFE_PORT, so a block holding one is a stack Playwright and the verifier cannot open.
14
- const BROWSER_UNSAFE_PORTS = new Set([
15
- 1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42, 43, 53, 69, 77, 79, 87, 95, 101, 102, 103,
16
- 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 137, 139, 143, 161, 179, 389, 427, 465, 512, 513,
17
- 514, 515, 526, 530, 531, 532, 540, 548, 554, 556, 563, 587, 601, 636, 989, 990, 993, 995, 1719, 1720,
18
- 1723, 2049, 3659, 4045, 4190, 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668, 6669, 6679, 6697, 10080,
19
- ]);
20
-
21
- export function blockHasUnsafePort(base, blockSize) {
22
- for (let port = base; port < base + blockSize; port += 1) {
23
- if (BROWSER_UNSAFE_PORTS.has(port)) return true;
24
- }
25
- return false;
26
- }
27
-
28
- export function registryPath(gitCommonDir) {
29
- return join(gitCommonDir, 'morph-spec', 'env-registry.json');
30
- }
31
-
32
- function readRegistry(gitCommonDir) {
33
- try {
34
- const raw = readFileSync(registryPath(gitCommonDir), 'utf8').replace(/^/, '');
35
- const parsed = JSON.parse(raw);
36
- if (parsed && typeof parsed.allocations === 'object' && parsed.allocations !== null) {
37
- return parsed;
38
- }
39
- } catch { /* fail-open: a re-allocation, never a crash */ }
40
- return { version: 1, allocations: {} };
41
- }
42
-
43
- function writeRegistry(gitCommonDir, registry) {
44
- const path = registryPath(gitCommonDir);
45
- mkdirSync(join(gitCommonDir, 'morph-spec'), { recursive: true });
46
- const tmp = `${path}.tmp.${process.pid}`;
47
- writeFileSync(tmp, `${JSON.stringify(registry, null, 2)}\n`, 'utf8');
48
- renameSync(tmp, path);
49
- }
50
-
51
- export function resolveFleetConfig(rootPath) {
52
- const defaults = { basePort: DEFAULT_BASE_PORT, blockSize: DEFAULT_BLOCK_SIZE };
53
- try {
54
- const raw = readFileSync(join(rootPath, '.morph', 'config', 'config.json'), 'utf8').replace(/^/, '');
55
- const cfg = JSON.parse(raw);
56
- const fleet = cfg?.fleet || {};
57
- return {
58
- basePort: Number.isInteger(fleet.basePort) && fleet.basePort > 0 ? fleet.basePort : defaults.basePort,
59
- blockSize: Number.isInteger(fleet.blockSize) && fleet.blockSize > 0 ? fleet.blockSize : defaults.blockSize,
60
- };
61
- } catch {
62
- return defaults;
63
- }
64
- }
65
-
66
- /**
67
- * First free index wins, so released slots are reused instead of creeping toward the port ceiling.
68
- * A block with a browser-unsafe port is never handed out, and one recorded before this rule is moved.
69
- */
70
- export function allocateEnvBlock(feature, { gitCommonDir, basePort = DEFAULT_BASE_PORT, blockSize = DEFAULT_BLOCK_SIZE }) {
71
- const registry = readRegistry(gitCommonDir);
72
-
73
- const existing = registry.allocations[feature];
74
- if (existing && Number.isInteger(existing.index)) {
75
- const base = basePort + existing.index * blockSize;
76
- if (!blockHasUnsafePort(base, blockSize)) {
77
- return { index: existing.index, base, range: [base, base + blockSize - 1], created: false };
78
- }
79
- }
80
-
81
- const used = new Set(
82
- Object.entries(registry.allocations)
83
- .filter(([name]) => name !== feature)
84
- .map(([, a]) => a?.index)
85
- .filter((i) => Number.isInteger(i)),
86
- );
87
- let index = 0;
88
- while (used.has(index) || blockHasUnsafePort(basePort + index * blockSize, blockSize)) index += 1;
89
-
90
- const base = basePort + index * blockSize;
91
- if (base + blockSize - 1 > MAX_PORT) {
92
- throw new Error(`env-allocator: port block ${base}-${base + blockSize - 1} exceeds ${MAX_PORT}`);
93
- }
94
-
95
- registry.allocations[feature] = { index, base, createdAt: new Date().toISOString() };
96
- writeRegistry(gitCommonDir, registry);
97
- return { index, base, range: [base, base + blockSize - 1], created: true };
98
- }
99
-
100
- /** Read-only on purpose: `allocateEnvBlock` writes, and an audit that allocates invents the state it reports. */
101
- export function allocatedFeatures(gitCommonDir) {
102
- const registry = readRegistry(gitCommonDir);
103
- return Object.entries(registry.allocations)
104
- .filter(([, a]) => Number.isInteger(a?.index))
105
- .map(([feature]) => feature);
106
- }
107
-
108
- export function releaseEnvBlock(feature, { gitCommonDir }) {
109
- const registry = readRegistry(gitCommonDir);
110
- if (!registry.allocations[feature]) return false;
111
- delete registry.allocations[feature];
112
- writeRegistry(gitCommonDir, registry);
113
- return true;
114
- }
115
-
116
- // A new offset here must also be published by the compose template, or it is a port nobody listens on.
117
- export const PORT_OFFSETS = Object.freeze({ web: 0, api: 1, postgres: 2, redis: 3 });
118
-
119
- /**
120
- * The single layout both `worktree.env` and the compose env derive from. `COMPOSE_PROJECT_NAME`
121
- * is in it so a hand-run `docker compose up` in the worktree lands in the isolated project.
122
- */
123
- export function portLayout(block, { stack = '', feature = '', aliases = {} } = {}) {
124
- const env = {};
125
- if (feature) env.COMPOSE_PROJECT_NAME = composeProjectName(feature);
126
- env.MORPH_PORT_BASE = String(block.base);
127
- env.MORPH_PORT_RANGE = `${block.range[0]}-${block.range[1]}`;
128
- env.PORT = String(block.base + PORT_OFFSETS.web);
129
- env.API_PORT = String(block.base + PORT_OFFSETS.api);
130
- env.POSTGRES_PORT = String(block.base + PORT_OFFSETS.postgres);
131
- env.REDIS_PORT = String(block.base + PORT_OFFSETS.redis);
132
- if (/\bdotnet\b/i.test(String(stack))) {
133
- env.ASPNETCORE_URLS = `http://localhost:${block.base + PORT_OFFSETS.api}`;
134
- }
135
- for (const [alias, port] of Object.entries(aliases)) env[alias] = String(block.base + PORT_OFFSETS[port]);
136
- return env;
137
- }
138
-
139
- const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
140
- const RESERVED_ENV_NAMES = new Set([
141
- ...Object.keys(portLayout({ base: 0, range: [0, 0] }, { stack: 'dotnet', feature: 'x' })),
142
- 'PLAYWRIGHT_BASE_URL',
143
- 'MORPH_FEATURE',
144
- ]);
145
-
146
- export function resolvePortAliases(config) {
147
- const declared = config?.e2e?.portEnvNames;
148
- const aliases = {};
149
- const problems = [];
150
- if (declared === undefined || declared === null) return { aliases, problems };
151
- if (typeof declared !== 'object' || Array.isArray(declared)) {
152
- return { aliases, problems: [`e2e.portEnvNames deve ser um objeto { ${Object.keys(PORT_OFFSETS).join('|')}: "NOME" }`] };
153
- }
154
- for (const [port, name] of Object.entries(declared)) {
155
- const at = `e2e.portEnvNames.${port}`;
156
- if (!Object.hasOwn(PORT_OFFSETS, port)) problems.push(`${at}: porta desconhecida (use ${Object.keys(PORT_OFFSETS).join('|')})`);
157
- else if (typeof name !== 'string' || !ENV_NAME.test(name)) problems.push(`${at}: ${JSON.stringify(name)} não é um nome de variável de ambiente válido`);
158
- else if (RESERVED_ENV_NAMES.has(name)) problems.push(`${at}: "${name}" já é uma variável do layout`);
159
- else if (Object.hasOwn(aliases, name)) problems.push(`${at}: "${name}" já é o alias de ${aliases[name]}`);
160
- else aliases[name] = port;
161
- }
162
- return { aliases, problems };
163
- }
164
-
165
- /**
166
- * `morphFeature` names the feature a `task/<n>` tree works for; the block and compose
167
- * project stay keyed by `feature`, or the sub-agent would get the feature's own ports.
168
- */
169
- export function buildEnvFileContent(feature, block, stack = '', { morphFeature = null, aliases = {} } = {}) {
170
- const lines = [
171
- `# Managed by morph-spec — ambiente dedicado desta worktree (feature: ${feature}).`,
172
- '# Derivado, git-invisível, regenerado por `worktree setup|link`; nunca editar nem commitar.',
173
- `MORPH_FEATURE=${morphFeature || feature}`,
174
- ...Object.entries(portLayout(block, { stack, feature, aliases })).map(([k, v]) => `${k}=${v}`),
175
- ];
176
- return `${lines.join('\n')}\n`;
177
- }
@@ -1,145 +0,0 @@
1
- // After `create --worktree`, the root keeps the feature.json frozen at birth; the
2
- // committed copy on `morph/{f}` is the truth. Fail-open: null means "read the disk".
3
-
4
- import { execFileSync } from 'child_process';
5
- import { existsSync, readFileSync } from 'fs';
6
- import { join } from 'path';
7
- import { isGitRepo, resolvePrimaryRoot, findWorktreeForFeature, buildBranchName } from '../../commands/project/worktree.js';
8
-
9
- /** Branch holding the feature's truth, or `null` when this tree IS its checkout (read the disk). */
10
- export function branchToReadFrom(root, feature, location, branch) {
11
- if (location === 'worktree' || !root || !feature) return null;
12
- const featureBranch = branch || `morph/${feature}`;
13
- try {
14
- const current = execFileSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: root, stdio: 'pipe' })
15
- .toString().trim();
16
- return current === featureBranch ? null : featureBranch;
17
- } catch {
18
- return null;
19
- }
20
- }
21
-
22
- // `ls-tree -z` is load-bearing: without it git quotes non-ASCII paths, the prefix
23
- // strip fails and the file set comes back silently empty.
24
- export function branchView(root, feature, featureBranch) {
25
- const prefix = `.morph/features/${feature}/`;
26
- let fj;
27
- try {
28
- fj = JSON.parse(execFileSync('git', ['show', `${featureBranch}:${prefix}feature.json`], {
29
- cwd: root, stdio: 'pipe',
30
- }).toString());
31
- } catch {
32
- return null;
33
- }
34
-
35
- const files = new Set();
36
- try {
37
- const out = execFileSync('git', ['ls-tree', '-r', '--name-only', '-z', featureBranch, '--', prefix], {
38
- cwd: root, stdio: 'pipe',
39
- }).toString();
40
- for (const raw of out.split('\0')) {
41
- const p = raw.trim();
42
- if (p.startsWith(prefix)) files.add(p.slice(prefix.length));
43
- }
44
- } catch { /* the gates alone still beat a stale working tree */ }
45
-
46
- return { fj, files };
47
- }
48
-
49
- export function morphBranches(root) {
50
- try {
51
- const out = execFileSync('git', ['for-each-ref', '--format=%(refname:short)', 'refs/heads/morph/'], {
52
- cwd: root, stdio: 'pipe',
53
- }).toString();
54
- const names = new Set();
55
- for (const line of out.split('\n')) {
56
- const b = line.trim();
57
- if (b) names.add(b.slice('morph/'.length));
58
- }
59
- return names;
60
- } catch {
61
- return new Set();
62
- }
63
- }
64
-
65
- /** null on detached HEAD, no repo or no commits yet. */
66
- export function currentBranch(cwd) {
67
- try {
68
- const out = execFileSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd, stdio: 'pipe' }).toString().trim();
69
- return out === 'HEAD' ? null : out || null;
70
- } catch {
71
- return null;
72
- }
73
- }
74
-
75
- function readLocalFeatureJson(dir, feature) {
76
- const p = join(dir, '.morph', 'features', feature, 'feature.json');
77
- if (!existsSync(p)) return null;
78
- try {
79
- return JSON.parse(readFileSync(p, 'utf8'));
80
- } catch {
81
- return null;
82
- }
83
- }
84
-
85
- /**
86
- * Order: git's worktree registry, then the feature.json pointer, then cwd, then the branch.
87
- * The registry comes first so a stale `feature.worktree` pointer never wins.
88
- * @returns {{ source: 'cwd'|'registry'|'pointer'|'branch-only'|'none', tree: string|null, branch: string|null, worktree: {path:string, branch:string}|null, pointerDangling: boolean }}
89
- */
90
- export function resolveFeatureTree(feature, cwd = process.cwd()) {
91
- const localFj = readLocalFeatureJson(cwd, feature);
92
- const pointerPath = localFj?.worktree?.path || null;
93
- const pointerDangling = Boolean(pointerPath) && !existsSync(pointerPath);
94
-
95
- const inGit = isGitRepo(cwd);
96
- const root = inGit ? resolvePrimaryRoot(cwd) : null;
97
-
98
- if (inGit && root) {
99
- const registered = findWorktreeForFeature(feature, root);
100
- if (registered && existsSync(registered.path)) {
101
- const branch = registered.branch || buildBranchName(feature);
102
- if (registered.path.replace(/\\/g, '/') === cwd.replace(/\\/g, '/')) {
103
- return { source: 'cwd', tree: cwd, branch, worktree: { path: registered.path, branch }, pointerDangling };
104
- }
105
- return { source: 'registry', tree: registered.path, branch, worktree: { path: registered.path, branch }, pointerDangling };
106
- }
107
- }
108
-
109
- if (pointerPath && !pointerDangling) {
110
- const branch = localFj?.worktree?.branch || buildBranchName(feature);
111
- return { source: 'pointer', tree: pointerPath, branch, worktree: { path: pointerPath, branch }, pointerDangling };
112
- }
113
-
114
- if (localFj) {
115
- return { source: 'cwd', tree: cwd, branch: null, worktree: null, pointerDangling };
116
- }
117
-
118
- if (inGit && root) {
119
- const branch = buildBranchName(feature);
120
- const view = branchView(root, feature, branch);
121
- if (view) {
122
- return { source: 'branch-only', tree: null, branch, worktree: null, pointerDangling: false };
123
- }
124
- }
125
-
126
- return { source: 'none', tree: null, branch: null, worktree: null, pointerDangling: false };
127
- }
128
-
129
- /** Blocked only when a live worktree other than cwd owns the feature, so the root skeleton is never stamped. */
130
- export function assertOwnerTree(feature, cwd = process.cwd()) {
131
- const owner = resolveFeatureTree(feature, cwd);
132
- const blocked = owner.source === 'registry' || owner.source === 'pointer';
133
- return { blocked, tree: owner.tree, branch: owner.branch };
134
- }
135
-
136
- export function ownerTreeRefusalLines(feature, tree, branch, commandLine) {
137
- return [
138
- { tone: 'red', text: `\n❌ A feature "${feature}" não pode ser mutada A PARTIR DESTA ÁRVORE.` },
139
- { tone: 'gray', text: ` O worktree dono está vivo em: ${tree}${branch ? ` (branch ${branch})` : ''}` },
140
- { tone: 'gray', text: ' Rode o comando LÁ — a mutação é gravada no feature.json daquela árvore:' },
141
- { tone: 'cyan', text: ` cd "${tree}" && ${commandLine}` },
142
- { tone: 'yellow', text: '\n NÃO use --force aqui: ele carimbaria a mutação na cópia da raiz, duplicando' },
143
- { tone: 'yellow', text: ' uma escrita que a outra árvore já tem e desalinhando os dois feature.json.\n' },
144
- ];
145
- }