@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,82 +0,0 @@
1
- // A pathless gate question is matched against the slugs on disk, never parsed.
2
- // When it names no known feature the caller must REFUSE TO GUESS: a gate on the
3
- // wrong feature is close to unrecoverable, writing nothing costs one `approve`.
4
-
5
- import { execSync } from 'child_process';
6
- import { loadState } from './state-reader.js';
7
- import { morphBranchFeature } from './git-paths.js';
8
-
9
- // `loadState`, not a directory listing: it also sees features only the index carries.
10
- export function featureNamesIn(root) {
11
- try {
12
- const state = loadState(root);
13
- return state?.features ? Object.keys(state.features) : [];
14
- } catch {
15
- return [];
16
- }
17
- }
18
-
19
- export function allWorkTrees(sessionRoot) {
20
- const roots = [sessionRoot];
21
- try {
22
- const out = execSync('git worktree list --porcelain', {
23
- cwd: sessionRoot,
24
- stdio: ['pipe', 'pipe', 'pipe'],
25
- timeout: 2000,
26
- }).toString();
27
- for (const line of out.split('\n')) {
28
- if (!line.startsWith('worktree ')) continue;
29
- const path = line.slice('worktree '.length).trim();
30
- if (path && !roots.includes(path)) roots.push(path);
31
- }
32
- } catch {
33
- }
34
- return roots;
35
- }
36
-
37
- const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
38
-
39
- // `export` must not match inside "export-hub". Zero and ambiguous matches are
40
- // both null: they must lead to the same refusal.
41
- export function featureNamedIn(text, names) {
42
- if (typeof text !== 'string' || !Array.isArray(names) || names.length === 0) return null;
43
- const haystack = text.toLowerCase();
44
- const hits = names.filter((name) =>
45
- new RegExp(`(^|[^a-z0-9-])${escapeRe(String(name).toLowerCase())}([^a-z0-9-]|$)`).test(haystack)
46
- );
47
- return hits.length === 1 ? hits[0] : null;
48
- }
49
-
50
- // A slug-shaped token naming no known feature: the question is about a feature
51
- // not yet registered. Requires a hyphen, so template prose never matches.
52
- export function unrecognizedSlugLike(text, names) {
53
- if (typeof text !== 'string') return null;
54
- const known = new Set((names || []).map((n) => String(n).toLowerCase()));
55
- const tokens = text.toLowerCase().match(/[a-z0-9]+(?:-[a-z0-9]+)+/g) || [];
56
- return tokens.find((t) => !known.has(t)) ?? null;
57
- }
58
-
59
- // The tree on `morph/<f>` owns the feature and wins: the primary root only carries its index
60
- // entry, and `morph-spec approve` refuses any other tree. Without an owner, the session root wins.
61
- export function locateFeatureForQuestion(text, sessionRoot) {
62
- const trees = allWorkTrees(sessionRoot);
63
- const localNames = featureNamesIn(sessionRoot);
64
- const ownerOr = (name, root) => trees.find((t) => morphBranchFeature(t) === name) ?? root;
65
-
66
- const local = featureNamedIn(text, localNames);
67
- if (local) return { name: local, root: ownerOr(local, sessionRoot) };
68
-
69
- for (const root of trees) {
70
- if (root === sessionRoot) continue;
71
- const found = featureNamedIn(text, featureNamesIn(root));
72
- if (found) return { name: found, root: ownerOr(found, root) };
73
- }
74
-
75
- const allNames = trees.flatMap(featureNamesIn);
76
- if (unrecognizedSlugLike(text, allNames)) return null;
77
-
78
- // With exactly ONE feature in the tree there is nothing else the answer could be about.
79
- if (localNames.length === 1) return { name: localNames[0], root: ownerOr(localNames[0], sessionRoot) };
80
-
81
- return null;
82
- }
@@ -1,18 +0,0 @@
1
- import { existsSync } from 'fs';
2
- import { join } from 'path';
3
- import { appendTelemetryEvent } from './telemetry-logger.js';
4
-
5
- export const GATE_EVENT = 'Gate';
6
- export const GATE_STEPS = ['decision', 'approve', 'unapprove'];
7
-
8
- /**
9
- * The trail `cost --metrics` turns into "what did the human do with each pause":
10
- * `gateDecisions` keeps only the latest decision, so the history lives here.
11
- */
12
- export function recordGateEvent(projectPath, { feature, gate, step, pause, signal, source, resolver, approvedBy }) {
13
- if (!existsSync(join(projectPath || process.cwd(), '.morph'))) return;
14
- const event = { event: GATE_EVENT, feature, gate, step };
15
- if (step === 'decision') Object.assign(event, { pause: pause === true, signal: signal ?? null, source: source ?? null, ...(pause === true ? { resolver: resolver ?? 'human' } : {}) });
16
- else event.approvedBy = approvedBy ?? null;
17
- appendTelemetryEvent(event, projectPath);
18
- }
@@ -1,20 +0,0 @@
1
- const OWNER_FORM = [
2
- [/\baprovar\s+o\s+plano\s+d[eoa]\b/i, 'plan'],
3
- [/\baprovar\s+as\s+telas\s+d[eoa]\b/i, 'uiux'],
4
- [/\baprovar\s+a\s+entrega\s+d[eoa]\b/i, 'review'],
5
- ];
6
-
7
- /** Explicit gate names win over words a feature slug may also carry ("plan", "design", "review"). */
8
- export function gateFromQuestion(question) {
9
- if (typeof question !== 'string') return null;
10
- const head = question.split(/\r?\n/).find((l) => l.trim()) ?? '';
11
- for (const [re, gate] of OWNER_FORM) if (re.test(head)) return gate;
12
- if (/gate\s+uiux/i.test(question)) return 'uiux';
13
- if (/gate\s+3\b/i.test(question)) return 'review';
14
- if (/gate\s+(?:[12]\b|d[oe]\s+plano|plan\b)/i.test(question)) return 'plan';
15
- const lower = question.toLowerCase();
16
- if (lower.includes('plano') || lower.includes('plan')) return 'plan';
17
- if (lower.includes('design')) return 'uiux';
18
- if (lower.includes('review') || lower.includes('ship')) return 'review';
19
- return null;
20
- }
@@ -1,113 +0,0 @@
1
- import { existsSync, readFileSync } from 'node:fs';
2
- import { availableParallelism } from 'node:os';
3
- import { join } from 'node:path';
4
-
5
- const CONFIG_FILE = join('.morph', 'config', 'config.json');
6
-
7
- export const HEAVY_DEFAULTS = Object.freeze({
8
- enabled: true,
9
- slots: 2,
10
- minFreeMemGb: 4,
11
- minFreeMemGbByKind: Object.freeze({ unit: 1.5, build: 4, e2e: 4 }),
12
- waitTimeoutSec: 600,
13
- maxHoldMinutes: 90,
14
- reclaimIdleMinutes: 20,
15
- reclaimContainers: Object.freeze(['morph-pgtest']),
16
- detachedWaitMinutes: 60,
17
- criticalFreeMemGb: 1,
18
- yieldToUser: true,
19
- shutdownBuildServer: true,
20
- disableNodeReuse: false,
21
- gateBash: true,
22
- });
23
-
24
- export const HEAVY_KINDS = Object.freeze(['unit', 'build', 'e2e']);
25
-
26
- export const CPU_SHARE_ENVS = Object.freeze(['DOTNET_PROCESSOR_COUNT', 'VITEST_MAX_FORKS', 'VITEST_MAX_THREADS']);
27
-
28
- /** A quarter of the machine stays with the person; what is left goes to one run, or is split by the slots. */
29
- export function cpuShareOf(slots, { cores = availableParallelism(), alone = false } = {}) {
30
- const usable = cores - Math.max(2, Math.floor(cores / 4));
31
- return Math.max(2, alone ? usable : Math.floor(usable / slots));
32
- }
33
-
34
- const isBool = (v) => typeof v === 'boolean';
35
- const isGb = (v) => typeof v === 'number' && Number.isFinite(v) && v >= 0;
36
- const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
37
- const VALID = {
38
- enabled: isBool,
39
- slots: (v) => Number.isInteger(v) && v >= 1,
40
- minFreeMemGb: isGb,
41
- minFreeMemGbByKind: isPlainObject,
42
- waitTimeoutSec: (v) => typeof v === 'number' && Number.isFinite(v) && v >= 0,
43
- maxHoldMinutes: (v) => typeof v === 'number' && Number.isFinite(v) && v > 0,
44
- reclaimIdleMinutes: (v) => typeof v === 'number' && Number.isFinite(v) && v >= 0,
45
- yieldToUser: isBool,
46
- reclaimContainers: (v) => Array.isArray(v) && v.every((p) => typeof p === 'string' && /^[\w.-]+$/.test(p)),
47
- detachedWaitMinutes: (v) => typeof v === 'number' && Number.isFinite(v) && v >= 0,
48
- criticalFreeMemGb: isGb,
49
- shutdownBuildServer: isBool,
50
- disableNodeReuse: isBool,
51
- gateBash: isBool,
52
- };
53
-
54
- export function readProjectConfig(projectPath) {
55
- const file = join(projectPath, CONFIG_FILE);
56
- if (!existsSync(file)) return null;
57
- try {
58
- return JSON.parse(readFileSync(file, 'utf8').replace(/^/, ''));
59
- } catch {
60
- return null;
61
- }
62
- }
63
-
64
- export function resolveHeavyConfig(config, env = process.env) {
65
- const out = { ...HEAVY_DEFAULTS };
66
- const warnings = [];
67
- const raw = config?.heavy;
68
- let byKind = {};
69
-
70
- if (raw !== undefined) {
71
- if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
72
- warnings.push('`heavy` no config.json não é um objeto; usando os padrões');
73
- } else {
74
- for (const [key, value] of Object.entries(raw)) {
75
- if (!(key in VALID)) warnings.push(`heavy.${key} não existe; ignorada`);
76
- else if (key === 'minFreeMemGbByKind' && VALID[key](value)) byKind = value;
77
- else if (VALID[key](value)) out[key] = value;
78
- else warnings.push(`heavy.${key} inválida (${JSON.stringify(value)}); usando ${JSON.stringify(HEAVY_DEFAULTS[key])}`);
79
- }
80
- }
81
- }
82
-
83
- out.minFreeMemGbByKind = resolveByKind(byKind, isGb(raw?.minFreeMemGb) ? raw.minFreeMemGb : null, warnings);
84
-
85
- if (/^(off|0|false)$/i.test(env.MORPH_HEAVY ?? '')) out.enabled = false;
86
- const envSlots = Number(env.MORPH_HEAVY_SLOTS);
87
- if (env.MORPH_HEAVY_SLOTS !== undefined && VALID.slots(envSlots)) out.slots = envSlots;
88
- const envWait = Number(env.MORPH_HEAVY_WAIT_SEC);
89
- if (env.MORPH_HEAVY_WAIT_SEC && VALID.waitTimeoutSec(envWait)) out.waitTimeoutSec = envWait;
90
-
91
- return { ...out, warnings };
92
- }
93
-
94
- // An explicit `minFreeMemGb` without a per-kind entry still governs that kind:
95
- // a project that set 0 (RAM check off) or a stricter floor keeps it after the split.
96
- function resolveByKind(byKind, explicitFloor, warnings) {
97
- const out = {};
98
- for (const kind of HEAVY_KINDS) out[kind] = explicitFloor ?? HEAVY_DEFAULTS.minFreeMemGbByKind[kind];
99
- for (const [kind, value] of Object.entries(byKind)) {
100
- if (!HEAVY_KINDS.includes(kind)) warnings.push(`heavy.minFreeMemGbByKind.${kind} não existe; use ${HEAVY_KINDS.join(', ')}`);
101
- else if (isGb(value)) out[kind] = value;
102
- else warnings.push(`heavy.minFreeMemGbByKind.${kind} inválida (${JSON.stringify(value)}); usando ${out[kind]}`);
103
- }
104
- return out;
105
- }
106
-
107
- export function minFreeMemFor(config, kind) {
108
- return config.minFreeMemGbByKind?.[kind] ?? config.minFreeMemGb;
109
- }
110
-
111
- export function readHeavyConfig(projectPath, env = process.env) {
112
- return resolveHeavyConfig(readProjectConfig(projectPath), env);
113
- }
@@ -1,85 +0,0 @@
1
- import { readdirSync, readFileSync, statSync } from 'node:fs';
2
- import { freemem, homedir } from 'node:os';
3
- import { join } from 'node:path';
4
- import { pidAlive } from './process-alive.js';
5
-
6
- export const GB = 1024 ** 3;
7
- export const WRITE_GRACE_MS = 5000;
8
- export const EXCLUSIVE_MAX_AGE_MS = 2 * 60 * 1000;
9
- export const SLOT_FILE = /^slot-\d+\.lock$/;
10
-
11
- export function heavyDir(env = process.env, { platform = process.platform, home = homedir() } = {}) {
12
- if (env.MORPH_HEAVY_DIR) return env.MORPH_HEAVY_DIR;
13
- if (platform === 'win32') return join(env.LOCALAPPDATA || join(home, 'AppData', 'Local'), 'morph-spec', 'heavy');
14
- return join(env.XDG_STATE_HOME || join(home, '.local', 'state'), 'morph-spec', 'heavy');
15
- }
16
-
17
- export const mtimeOf = (path) => {
18
- try { return statSync(path).mtimeMs; } catch { return null; }
19
- };
20
-
21
- const leaseTtlMs = (meta) => (Number.isFinite(meta.ttlMs) && meta.ttlMs > 0 ? meta.ttlMs : Infinity);
22
-
23
- export function readLockFile(path, { now, isAlive, maxHoldMs }) {
24
- const t = now();
25
- let meta;
26
- try {
27
- meta = JSON.parse(readFileSync(path, 'utf8'));
28
- } catch {
29
- const mtime = mtimeOf(path);
30
- if (mtime === null) return null;
31
- const writing = t - mtime < WRITE_GRACE_MS;
32
- return { path, pid: null, since: null, label: '(gravando)', live: writing, unreadable: true };
33
- }
34
- const age = t - Date.parse(meta.since);
35
- const inWindow = age >= 0 && age < maxHoldMs;
36
- // A per-call lease belongs to a hook process that is long gone: only its TTL says when it lapses.
37
- const live = meta.leaseId ? inWindow && age < leaseTtlMs(meta) : inWindow && Boolean(isAlive(meta.pid));
38
- return { ...meta, path, live };
39
- }
40
-
41
- export function scanHolders(dir, ctx) {
42
- let names = [];
43
- try { names = readdirSync(dir).filter((n) => SLOT_FILE.test(n)); } catch { return { live: [], stale: [] }; }
44
- const live = [];
45
- const stale = [];
46
- for (const name of names) {
47
- const holder = readLockFile(join(dir, name), ctx);
48
- if (!holder) continue;
49
- (holder.live ? live : stale).push(holder);
50
- }
51
- return { live, stale };
52
- }
53
-
54
- export function readHolders(dir, ctx) {
55
- return scanHolders(dir, ctx).live;
56
- }
57
-
58
- export function readExclusive(dir, ctx) {
59
- const holder = readLockFile(join(dir, 'exclusive.lock'), { ...ctx, maxHoldMs: EXCLUSIVE_MAX_AGE_MS });
60
- return holder?.live ? holder : null;
61
- }
62
-
63
- const ageText = (ms) => {
64
- const min = Math.floor(ms / 60000);
65
- return min < 1 ? `${Math.max(0, Math.floor(ms / 1000))}s` : `${min}m`;
66
- };
67
-
68
- export function describeHolder(h, now = Date.now()) {
69
- const what = [h.label, [h.feature, h.node].filter(Boolean).join('/')].filter(Boolean).join(' ');
70
- const age = h.since ? `, há ${ageText(now - Date.parse(h.since))}` : '';
71
- const who = h.leaseId ? 'chamada Bash' : `pid ${h.pid ?? '?'}`;
72
- return `${what || 'processo'}, ${who}${age}`;
73
- }
74
-
75
- export function heavyStatus({
76
- dir, maxHoldMs, now = Date.now, isAlive = pidAlive, freeMem = freemem,
77
- }) {
78
- const ctx = { now, isAlive, maxHoldMs };
79
- return {
80
- dir,
81
- holders: readHolders(dir, ctx),
82
- exclusive: readExclusive(dir, ctx),
83
- freeGb: freeMem() / GB,
84
- };
85
- }
@@ -1,280 +0,0 @@
1
- import {
2
- closeSync, mkdirSync, openSync, readdirSync, readFileSync, rmdirSync, unlinkSync, writeFileSync, writeSync,
3
- } from 'node:fs';
4
- import { freemem } from 'node:os';
5
- import { join } from 'node:path';
6
- import { pidAlive } from './process-alive.js';
7
- import {
8
- GB, SLOT_FILE, describeHolder, mtimeOf, readExclusive, scanHolders,
9
- } from './heavy-holders.js';
10
-
11
- export { heavyDir, heavyStatus, describeHolder } from './heavy-holders.js';
12
-
13
- const MUTEX_STALE_MS = 10_000;
14
- const POLL_MS = 500;
15
- const REPORT_EVERY_MS = 30_000;
16
-
17
- export function sleepSync(ms) {
18
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, Math.max(1, ms));
19
- }
20
-
21
- function withClaimMutex(dir, fn, { now }) {
22
- const path = join(dir, 'claim.lock');
23
- for (let attempt = 0; attempt < 50; attempt++) {
24
- try {
25
- mkdirSync(path);
26
- try {
27
- return { value: fn() };
28
- } finally {
29
- try { rmdirSync(path); } catch { /* já removido */ }
30
- }
31
- } catch (err) {
32
- if (err?.code !== 'EEXIST') return null;
33
- const mtime = mtimeOf(path);
34
- if (mtime !== null && now() - mtime > MUTEX_STALE_MS) {
35
- try { rmdirSync(path); } catch { /* outro já recolheu */ }
36
- } else {
37
- sleepSync(20);
38
- }
39
- }
40
- }
41
- return null;
42
- }
43
-
44
- function liveHoldersPruningStale(dir, ctx) {
45
- const { live, stale } = scanHolders(dir, ctx);
46
- for (const holder of stale) {
47
- try { unlinkSync(holder.path); } catch { /* já solto */ }
48
- }
49
- return live;
50
- }
51
-
52
- const kindSuffix = (kind) => (kind ? ` (${kind})` : '');
53
-
54
- // Two full verify suites never run together; a sub-agent filter or a build only takes a slot.
55
- export const isVerifySuite = ({ label, node }) => label === 'verify' && node === 'tests';
56
-
57
- const runningSuite = (holders, ownPath = null) => holders.find((h) => h.path !== ownPath && isVerifySuite(h));
58
-
59
- function blockedText(blocked, slots, now) {
60
- const holders = blocked.holders.map((h) => describeHolder(h, now)).join('; ');
61
- if (blocked.reason === 'suite') return `aguardando o verify de outra feature terminar a suíte de testes (${describeHolder(blocked.holders[0], now)})`;
62
- if (blocked.reason === 'exclusive') return `aguardando limpeza do servidor de build (${describeHolder(blocked.exclusive, now)})`;
63
- if (blocked.reason === 'memory') {
64
- const cause = blocked.holders.length
65
- ? `slots em uso: ${holders}`
66
- : 'nenhum slot em uso: a pressão vem de fora do semáforo (vmmem do WSL, IDE, outros processos)';
67
- return `aguardando RAM livre${kindSuffix(blocked.kind)}: ${blocked.freeGb.toFixed(1)} GB < ${blocked.minFreeMemGb} GB mínimos — ${cause}`;
68
- }
69
- return `aguardando slot pesado (${blocked.holders.length}/${slots}): ${holders}`;
70
- }
71
-
72
- function tryClaim(dir, opts, ctx) {
73
- const {
74
- slots, label, feature, node, cwd, minFreeMemGb, freeMem, kind, suite, lease: leaseSpec,
75
- } = opts;
76
- const guarded = withClaimMutex(dir, () => {
77
- const holders = liveHoldersPruningStale(dir, ctx);
78
- const exclusive = readExclusive(dir, ctx);
79
- if (exclusive) return { blocked: { reason: 'exclusive', holders, exclusive } };
80
- // A full queue is the deeper reason: with no free slot, waiting out the other suite is not enough.
81
- if (holders.length >= slots) return { blocked: { reason: 'slots', holders } };
82
- const running = suite ? runningSuite(holders) : null;
83
- if (running) return { blocked: { reason: 'suite', holders: [running] } };
84
- const freeGb = freeMem() / GB;
85
- if (minFreeMemGb > 0 && freeGb < minFreeMemGb) return { blocked: { reason: 'memory', holders, freeGb, minFreeMemGb, kind } };
86
-
87
- for (let i = 0; i < slots + holders.length + 1; i++) {
88
- const path = join(dir, `slot-${i}.lock`);
89
- try {
90
- const fd = openSync(path, 'wx');
91
- const meta = {
92
- pid: leaseSpec ? null : process.pid,
93
- since: new Date(ctx.now()).toISOString(),
94
- label,
95
- feature,
96
- node,
97
- cwd,
98
- ...(leaseSpec ? { leaseId: leaseSpec.id, ttlMs: leaseSpec.ttlMs } : {}),
99
- };
100
- writeSync(fd, JSON.stringify(meta));
101
- closeSync(fd);
102
- return { lease: { path, pid: meta.pid, slot: i, meta } };
103
- } catch (err) {
104
- if (err?.code !== 'EEXIST') return { blocked: { reason: 'slots', holders } };
105
- }
106
- }
107
- return { blocked: { reason: 'slots', holders } };
108
- }, ctx);
109
- return guarded ? guarded.value : { blocked: { reason: 'contended', holders: [] } };
110
- }
111
-
112
- export function acquireHeavy(opts) {
113
- const {
114
- dir, slots, waitTimeoutMs, maxHoldMs,
115
- now = Date.now, sleep = sleepSync, isAlive = pidAlive, freeMem = freemem,
116
- log = (m) => process.stderr.write(`${m}\n`), env = process.env,
117
- } = opts;
118
- const ctx = { now, isAlive, maxHoldMs };
119
- const claimOpts = { ...opts, freeMem, minFreeMemGb: opts.minFreeMemGb ?? 0 };
120
-
121
- try { mkdirSync(dir, { recursive: true }); } catch { return { status: 'acquired', lease: null, waitedMs: 0, unavailable: true }; }
122
-
123
- const leaseOwner = Number(env.MORPH_HEAVY_LEASE);
124
- if (Number.isInteger(leaseOwner) && leaseOwner > 0 && scanHolders(dir, ctx).live.some((h) => h.pid === leaseOwner)) {
125
- return { status: 'acquired', lease: null, waitedMs: 0, reentrant: true };
126
- }
127
-
128
- return pollClaim(() => tryClaim(dir, claimOpts, ctx), {
129
- ...opts, now, sleep, log, minFreeMemGb: claimOpts.minFreeMemGb,
130
- });
131
- }
132
-
133
- function pollClaim(claim, {
134
- slots, waitTimeoutMs, minFreeMemGb = 0, kind = null, now, sleep, log,
135
- }) {
136
- const start = now();
137
- let lastReport = -Infinity;
138
- for (;;) {
139
- const attempt = claim();
140
- if (attempt.lease) return { status: 'acquired', lease: attempt.lease, waitedMs: now() - start };
141
-
142
- const waited = now() - start;
143
- const { blocked } = attempt;
144
- if (waited >= waitTimeoutMs) {
145
- return {
146
- status: 'busy',
147
- reason: blocked.reason,
148
- holders: blocked.holders,
149
- freeGb: blocked.freeGb ?? null,
150
- minFreeMemGb,
151
- kind,
152
- waitedMs: waited,
153
- };
154
- }
155
- if (blocked.reason !== 'contended' && now() - lastReport >= REPORT_EVERY_MS) {
156
- log(blockedText(blocked, slots, now()));
157
- lastReport = now();
158
- }
159
- sleep(Math.min(POLL_MS, Math.max(1, waitTimeoutMs - waited)));
160
- }
161
- }
162
-
163
- // Keeps the slot held while it waits: releasing it would let a build or filter take the place.
164
- export function enterVerifySuite(opts) {
165
- const {
166
- dir, lease, maxHoldMs,
167
- now = Date.now, sleep = sleepSync, isAlive = pidAlive, log = (m) => process.stderr.write(`${m}\n`),
168
- } = opts;
169
- const ctx = { now, isAlive, maxHoldMs };
170
- const claim = () => {
171
- const guarded = withClaimMutex(dir, () => {
172
- const running = runningSuite(scanHolders(dir, ctx).live, lease.path);
173
- if (running) return { blocked: { reason: 'suite', holders: [running] } };
174
- updateLease(lease, { node: 'tests' });
175
- return { lease };
176
- }, ctx);
177
- return guarded ? guarded.value : { blocked: { reason: 'contended', holders: [] } };
178
- };
179
- return pollClaim(claim, { ...opts, now, sleep, log });
180
- }
181
-
182
- // For a holder whose next node needs more RAM than it was admitted with: it keeps its slot and
183
- // waits only on memory, since re-claiming would hit the re-entrant path and skip the check.
184
- export function awaitFreeMemory(opts) {
185
- const {
186
- minFreeMemGb, waitTimeoutMs, kind = null,
187
- now = Date.now, sleep = sleepSync, freeMem = freemem, log = (m) => process.stderr.write(`${m}\n`),
188
- } = opts;
189
- const start = now();
190
- let lastReport = -Infinity;
191
- for (;;) {
192
- const freeGb = freeMem() / GB;
193
- const waited = now() - start;
194
- if (!(minFreeMemGb > 0) || freeGb >= minFreeMemGb) return { status: 'acquired', waitedMs: waited };
195
- if (waited >= waitTimeoutMs) {
196
- return {
197
- status: 'busy', reason: 'memory', holders: [], freeGb, minFreeMemGb, kind, waitedMs: waited,
198
- };
199
- }
200
- if (now() - lastReport >= REPORT_EVERY_MS) {
201
- log(`aguardando RAM livre${kindSuffix(kind)}: ${freeGb.toFixed(1)} GB < ${minFreeMemGb} GB mínimos, segurando o slot já tomado`);
202
- lastReport = now();
203
- }
204
- sleep(Math.min(POLL_MS, Math.max(1, waitTimeoutMs - waited)));
205
- }
206
- }
207
-
208
- export function updateLease(lease, patch) {
209
- if (!lease) return;
210
- try {
211
- const current = JSON.parse(readFileSync(lease.path, 'utf8'));
212
- if (current.pid !== lease.pid) return;
213
- writeFileSync(lease.path, JSON.stringify({ ...current, ...patch }));
214
- } catch { /* o lease foi recolhido; nada a atualizar */ }
215
- }
216
-
217
- export function releaseHeavy(lease) {
218
- if (!lease) return;
219
- try {
220
- if (JSON.parse(readFileSync(lease.path, 'utf8')).pid === lease.pid) unlinkSync(lease.path);
221
- } catch { /* já solto */ }
222
- }
223
-
224
- export function releaseLeaseById(dir, id) {
225
- let names = [];
226
- try { names = readdirSync(dir).filter((n) => SLOT_FILE.test(n)); } catch { return false; }
227
- for (const name of names) {
228
- const path = join(dir, name);
229
- try {
230
- if (JSON.parse(readFileSync(path, 'utf8')).leaseId !== id) continue;
231
- unlinkSync(path);
232
- return true;
233
- } catch { /* já solto, ou ainda sendo gravado */ }
234
- }
235
- return false;
236
- }
237
-
238
- export function describeBusy(result, config) {
239
- const waited = Math.round(result.waitedMs / 1000);
240
- if (result.reason === 'memory') {
241
- const floor = result.minFreeMemGb ?? config.minFreeMemGb;
242
- const key = result.kind ? `heavy.minFreeMemGbByKind.${result.kind}` : 'heavy.minFreeMemGb';
243
- return `sem RAM livre há ${waited}s (${result.freeGb?.toFixed(1)} GB < ${floor} GB mínimos${kindSuffix(result.kind)}, ${key})`;
244
- }
245
- if (result.reason === 'suite') return `o verify de outra feature segue na suíte de testes após ${waited}s (heavy.waitTimeoutSec)`;
246
- if (result.reason === 'exclusive') return `limpeza do servidor de build ainda em curso após ${waited}s`;
247
- return `${result.holders.length}/${config.slots} slots pesados ocupados por ${waited}s (heavy.waitTimeoutSec)`;
248
- }
249
-
250
- export function runExclusive(opts, fn) {
251
- const {
252
- dir, label, maxHoldMs, now = Date.now, isAlive = pidAlive,
253
- } = opts;
254
- const ctx = { now, isAlive, maxHoldMs };
255
- try { mkdirSync(dir, { recursive: true }); } catch { return { ran: false, reason: 'unavailable', holders: [] }; }
256
-
257
- const own = Number((opts.env ?? process.env).MORPH_HEAVY_LEASE);
258
- const claimed = withClaimMutex(dir, () => {
259
- const holders = liveHoldersPruningStale(dir, ctx).filter((h) => h.pid !== own);
260
- if (holders.length) return { ran: false, reason: 'holders', holders };
261
- if (readExclusive(dir, ctx)) return { ran: false, reason: 'exclusive', holders: [] };
262
- try {
263
- const fd = openSync(join(dir, 'exclusive.lock'), 'wx');
264
- writeSync(fd, JSON.stringify({ pid: process.pid, since: new Date(now()).toISOString(), label }));
265
- closeSync(fd);
266
- } catch {
267
- return { ran: false, reason: 'exclusive', holders: [] };
268
- }
269
- return { ran: true };
270
- }, ctx);
271
-
272
- if (!claimed) return { ran: false, reason: 'contended', holders: [] };
273
- if (!claimed.value.ran) return claimed.value;
274
-
275
- try {
276
- return { ran: true, result: fn() };
277
- } finally {
278
- try { unlinkSync(join(dir, 'exclusive.lock')); } catch { /* já solto */ }
279
- }
280
- }