@polymorphism-tech/morph-spec 10.12.0 → 11.0.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 +51 -340
  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 +8 -8
  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 +31 -86
  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 +13 -11
  46. package/framework/rules/resend-standards.md +1 -1
  47. package/framework/rules/ui-design.md +4 -0
  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 +5 -341
  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 +15 -50
  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 +1 -34
  122. package/src/utils/atomic-json.js +27 -0
  123. package/src/utils/file-copier.js +4 -12
  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,315 +0,0 @@
1
- // Cada tela é `## Tela: <nome>` com um `### Checklist de tela`, uma linha por item (tabela ou lista).
2
- // "Não se aplica" é resposta válida; vazio, "?" ou "a definir" não são. Telas `## S001: …` sem
3
- // nenhuma `## Tela:` são o formato legado, isento.
4
-
5
- import { createHash } from 'crypto';
6
- import { existsSync, readFileSync } from 'fs';
7
- import { dirname, join } from 'path';
8
- import { getAbsoluteOutputPath } from '../../core/paths/output-schema.js';
9
- import { verifierScreenChecklist } from '../review-reports.js';
10
- import { LEGACY_MOCKUP_EXEMPTION, uiuxChecklistPause } from '../risk-detector.js';
11
-
12
- /** `match` roda sobre o rótulo normalizado; um rótulo que casa com vários itens responde a todos. */
13
- export const SCREEN_CHECKLIST_ITEMS = [
14
- { id: 'servidor', label: 'Lista no servidor', match: /\bpaginacao\b|\bordenacao\b|\bservidor\b/ },
15
- { id: 'estados', label: 'Estados vazio e carregando', match: /\bvazio\b|\bcarregando\b|\bcarregamento\b/ },
16
- { id: 'erro', label: 'Erro com próxima ação', match: /\berro\b/ },
17
- { id: 'acao', label: 'Uma ação primária', match: /\bprimaria\b/ },
18
- { id: 'mobile', label: 'Celular', match: /\bmobile\b|\bcelular\b/ },
19
- ];
20
-
21
- // As exatas, e as que começam adiando a decisão ("a definir depois", "TBD.").
22
- const PLACEHOLDERS = new Set(['', '-', '--', '—', '–', '...', 'x', 'todo', 'definir', 'pendente']);
23
- const PLACEHOLDER_PREFIX_RE = /^(a definir|tbd|\?|…)/;
24
-
25
- const LEGACY_SCREEN_HEADING_RE = /^##\s+S\d+\s*:/i;
26
-
27
- const NOT_APPLICABLE_RE = /^(nao se aplica|n\/a)\b/;
28
-
29
- const SCREEN_HEADING_RE = /^##\s+tela\s*[:—–-]\s*(.+?)\s*#*\s*$/i;
30
- const CHECKLIST_HEADING_RE = /^(#{3,6})\s+checklist\b/i;
31
- const COMPONENTS_HEADING_RE = /^(#{3,6})\s+componentes\b/i;
32
- const REGISTRY_ITEM_RE = /@[\w-]+\/[\w-]+/;
33
- const PROTOTYPE_LINE_RE = /prot[oó]tipo/i;
34
- const PROTOTYPE_PATH_RE = /(?:1-design\/)?(prototipos\/[^\s`|)\]]+\.html)/i;
35
-
36
- /** De onde vem cada componente da tela: já existe no projeto, vem de um registry do shadcn, ou é escrito agora. */
37
- export const COMPONENT_ORIGINS = ['projeto', 'registry', 'novo'];
38
-
39
- /** As larguras dos prints que o laço de autocrítica deixa ao lado do protótipo. */
40
- export const PROTOTYPE_WIDTHS = [1280, 390];
41
-
42
- /** Minúsculas, sem acento, sem marcação inline, espaços colapsados. */
43
- export function normalizeLabel(text) {
44
- return String(text ?? '')
45
- .normalize('NFD')
46
- .replace(/[\u0300-\u036f]/g, '')
47
- .replace(/[*_`"“”]/g, '')
48
- .toLowerCase()
49
- .replace(/\s+/g, ' ')
50
- .trim();
51
- }
52
-
53
- function screenKey(name) {
54
- return normalizeLabel(name).replace(/^tela\s*[:—–-]\s*/, '').replace(/[.:;,]+$/, '');
55
- }
56
-
57
- function itemsOf(label) {
58
- const norm = normalizeLabel(label);
59
- return SCREEN_CHECKLIST_ITEMS.filter((item) => item.match.test(norm)).map((item) => item.id);
60
- }
61
-
62
- function checklistRow(line) {
63
- const trimmed = line.trim();
64
- if (trimmed.startsWith('|')) {
65
- const cells = tableCells(trimmed);
66
- if (cells.length < 2 || cells.every((c) => /^:?-{2,}:?$/.test(c) || c === '')) return null;
67
- return [cells[0], cells.slice(1).join(' ').trim()];
68
- }
69
- const bullet = /^[-*+]\s+(.+)$/.exec(trimmed.replace(/\*\*/g, ''));
70
- if (!bullet) return null;
71
- const colon = bullet[1].indexOf(':');
72
- if (colon === -1) return null;
73
- return [bullet[1].slice(0, colon), bullet[1].slice(colon + 1).trim()];
74
- }
75
-
76
- function componentRow(line) {
77
- const trimmed = line.trim();
78
- if (!trimmed.startsWith('|')) return null;
79
- const cells = tableCells(trimmed);
80
- if (cells.every((c) => /^:?-{2,}:?$/.test(c) || c === '')) return null;
81
- if (normalizeLabel(cells[0]) === 'componente') return null;
82
- return { name: cells[0], origin: normalizeLabel(cells[1]), source: cells.slice(2).join(' ').trim() };
83
- }
84
-
85
- export function tableCells(line) {
86
- const inner = line.trim().replace(/^\|/, '').replace(/\|$/, '');
87
- return inner.split(/(?<!\\)\|/).map((cell) => cell.trim());
88
- }
89
-
90
- // Um exemplo dentro de ``` não é uma tela.
91
- function proseLines(markdown) {
92
- const out = [];
93
- let fenced = false;
94
- for (const line of String(markdown ?? '').replace(/\r\n/g, '\n').split('\n')) {
95
- if (/^\s*(```|~~~)/.test(line)) { fenced = !fenced; continue; }
96
- if (!fenced) out.push(line);
97
- }
98
- return out;
99
- }
100
-
101
- export function parseScreens(markdown) {
102
- const screens = [];
103
- let screen = null;
104
- let section = null;
105
-
106
- for (const line of proseLines(markdown)) {
107
- const heading = /^(#{1,6})\s/.exec(line);
108
- if (heading) {
109
- const level = heading[1].length;
110
- const named = SCREEN_HEADING_RE.exec(line);
111
- if (level <= 2) {
112
- screen = named && named[1].trim() ? { name: named[1].trim(), hasChecklist: false, answers: new Map(), components: [], prototype: null } : null;
113
- if (screen) screens.push(screen);
114
- section = null;
115
- continue;
116
- }
117
- const checklist = CHECKLIST_HEADING_RE.exec(line);
118
- const components = COMPONENTS_HEADING_RE.exec(line);
119
- if (screen && checklist) {
120
- screen.hasChecklist = true;
121
- section = { kind: 'checklist', level: checklist[1].length };
122
- } else if (screen && components) {
123
- section = { kind: 'components', level: components[1].length };
124
- } else if (section && level <= section.level) {
125
- section = null;
126
- }
127
- continue;
128
- }
129
- if (screen && !screen.prototype && PROTOTYPE_LINE_RE.test(line)) {
130
- screen.prototype = PROTOTYPE_PATH_RE.exec(line)?.[1] ?? null;
131
- }
132
- if (!screen || !section) continue;
133
- if (section.kind === 'components') {
134
- const component = componentRow(line);
135
- if (component) screen.components.push(component);
136
- continue;
137
- }
138
- const row = checklistRow(line);
139
- if (!row) continue;
140
- for (const id of itemsOf(row[0])) {
141
- if (!screen.answers.has(id) || !screen.answers.get(id)) screen.answers.set(id, row[1]);
142
- }
143
- }
144
- return screens;
145
- }
146
-
147
- function isPlaceholder(answer) {
148
- const norm = normalizeLabel(answer).replace(/[.!;:,]+$/, '').trim();
149
- return PLACEHOLDERS.has(norm) || PLACEHOLDER_PREFIX_RE.test(norm);
150
- }
151
- const isNotApplicable = (answer) => NOT_APPLICABLE_RE.test(normalizeLabel(answer));
152
-
153
- const labelOf = (id) => SCREEN_CHECKLIST_ITEMS.find((item) => item.id === id)?.label ?? id;
154
-
155
- // Sem nenhuma `## Tela:`, só o formato antigo é legado; qualquer outro heading é "nenhuma tela
156
- // declarada", senão trocar o heading pularia o checklist.
157
- export function auditScreenChecklist(markdown) {
158
- const parsed = parseScreens(markdown);
159
- const problems = [];
160
- if (parsed.length === 0) {
161
- if (proseLines(markdown).some((line) => LEGACY_SCREEN_HEADING_RE.test(line))) {
162
- return { legacy: true, screens: [], problems };
163
- }
164
- problems.push('nenhuma tela declarada no formato `## Tela: <nome>`');
165
- }
166
- const screens = parsed.map((screen) => {
167
- const missing = [];
168
- const unanswered = [];
169
- for (const { id } of SCREEN_CHECKLIST_ITEMS) {
170
- if (!screen.answers.has(id)) missing.push(id);
171
- else if (isPlaceholder(screen.answers.get(id))) unanswered.push(id);
172
- }
173
- if (!screen.hasChecklist) {
174
- problems.push(`tela "${screen.name}" sem \`### Checklist de tela\``);
175
- } else {
176
- if (missing.length) problems.push(`tela "${screen.name}": falta ${missing.map(labelOf).join(', ')}`);
177
- if (unanswered.length) problems.push(`tela "${screen.name}": sem resposta em ${unanswered.map(labelOf).join(', ')}`);
178
- }
179
- return { name: screen.name, hasChecklist: screen.hasChecklist, missing, unanswered, prototype: screen.prototype, states: statesOf(screen), components: screen.components };
180
- });
181
- return { legacy: false, screens, problems };
182
- }
183
-
184
- const MISSING_SOURCE = {
185
- projeto: 'sem o caminho do componente que já existe',
186
- registry: 'sem o item do registry (`@registry/item`)',
187
- novo: 'sem o que foi buscado e por que não serve',
188
- };
189
-
190
- // Componente novo só depois da busca: a linha diz de onde ele vem, e `novo` carrega o motivo.
191
- export function auditComponents(screens) {
192
- const problems = [];
193
- for (const screen of screens) {
194
- const rows = screen.components ?? [];
195
- if (rows.length === 0) {
196
- problems.push(`tela "${screen.name}" sem a tabela \`### Componentes\` (Componente | Origem | Fonte ou motivo)`);
197
- continue;
198
- }
199
- for (const { name, origin, source } of rows) {
200
- if (!COMPONENT_ORIGINS.includes(origin)) {
201
- problems.push(`tela "${screen.name}": componente "${name}" sem origem válida (${COMPONENT_ORIGINS.join(', ')})`);
202
- } else if (isPlaceholder(source) || (origin === 'registry' && !REGISTRY_ITEM_RE.test(source))) {
203
- problems.push(`tela "${screen.name}": componente "${name}" ${MISSING_SOURCE[origin]}`);
204
- }
205
- }
206
- }
207
- return problems;
208
- }
209
-
210
- /** The states the prototype must switch to, by the checklist items that apply to the screen. */
211
- export const PROTOTYPE_STATES = { estados: ['vazio', 'carregando'], erro: ['erro'] };
212
- export const STATE_PRINT_WIDTH = 390;
213
-
214
- function statesOf(screen) {
215
- return Object.entries(PROTOTYPE_STATES).flatMap(([id, states]) => {
216
- const answer = screen.answers.get(id);
217
- return answer && !isPlaceholder(answer) && !isNotApplicable(answer) ? states : [];
218
- });
219
- }
220
-
221
- // Linha **Protótipo:** da tela + o HTML + os prints do laço de autocrítica ao lado dele; cada estado
222
- // que o checklist diz que se aplica tem `data-estado` no HTML e o print de celular.
223
- export function auditPrototypes(screens, designDir) {
224
- const problems = [];
225
- for (const screen of screens) {
226
- if (!screen.prototype) {
227
- problems.push(`tela "${screen.name}" sem a linha \`**Protótipo:** 1-design/prototipos/<tela>.html\``);
228
- continue;
229
- }
230
- const base = screen.prototype.replace(/\.html$/i, '');
231
- const states = screen.states ?? [];
232
- const expected = [
233
- screen.prototype,
234
- ...PROTOTYPE_WIDTHS.map((width) => `${base}-${width}.png`),
235
- ...states.map((state) => `${base}-${state}-${STATE_PRINT_WIDTH}.png`),
236
- ];
237
- const missing = expected.filter((rel) => !existsSync(join(designDir, rel)));
238
- if (missing.length) problems.push(`tela "${screen.name}": falta ${missing.map((rel) => `1-design/${rel}`).join(', ')}`);
239
- const html = existsSync(join(designDir, screen.prototype)) ? readFileSync(join(designDir, screen.prototype), 'utf8') : '';
240
- const unswitchable = html ? states.filter((state) => !new RegExp(`data-estado\\s*=\\s*["']${state}["']`).test(html)) : [];
241
- if (unswitchable.length) {
242
- problems.push(`tela "${screen.name}": o protótipo não alterna para ${unswitchable.join(', ')} (falta \`data-estado="…"\` no seletor de estado)`);
243
- }
244
- }
245
- return problems;
246
- }
247
-
248
- // Coleta, nunca decide: quem pausa é o risk-detector. No review cobra-se a conferência (`uncovered`), não o design.
249
- export function collectScreenChecklist(cwd, featureName, gateName) {
250
- const mockups = readMockups(cwd, featureName);
251
- if (mockups === null) return { mockups: false, legacy: false, screens: [], problems: [] };
252
- const audit = auditScreenChecklist(mockups);
253
- const signal = { mockups: true, legacy: audit.legacy, screens: audit.screens.map((s) => s.name), problems: audit.problems };
254
- if (audit.legacy) signal.exempt = LEGACY_MOCKUP_EXEMPTION;
255
- if (gateName === 'uiux' && !audit.legacy) {
256
- const designDir = dirname(getAbsoluteOutputPath(cwd, featureName, 'uiMockups'));
257
- signal.components = auditComponents(audit.screens);
258
- signal.prototypes = auditPrototypes(audit.screens, designDir);
259
- }
260
- if (gateName === 'review') {
261
- const report = verifierScreenChecklist(cwd, featureName);
262
- signal.section = report.section;
263
- signal.uncovered = checklistCoverage(mockups, report.section ? report.body : '');
264
- }
265
- return signal;
266
- }
267
-
268
- // Lido por approve e advance para que o `auto` nunca passe onde o gate-check pausaria. Uma decisão com
269
- // `pause: false` destrava só o design que ela viu: guarda `mockupsHash`, e mudar o arquivo volta a conferir.
270
- export function uiuxAutoApprovalBlock(cwd, featureName, feature) {
271
- const decision = feature?.gateDecisions?.uiux;
272
- if (decision?.pause === false && decision.mockupsHash === mockupsHash(cwd, featureName)) return null;
273
- return uiuxChecklistPause(collectScreenChecklist(cwd, featureName, 'uiux'));
274
- }
275
-
276
- // Linha marcada como não verificável conta como conferida: o que pausa é a ausência da linha.
277
- export function checklistCoverage(designMarkdown, reportSection) {
278
- const covered = new Map();
279
- for (const line of proseLines(reportSection)) {
280
- if (!line.trim().startsWith('|')) continue;
281
- const cells = tableCells(line);
282
- if (cells.length < 2) continue;
283
- const key = screenKey(cells[0]);
284
- if (!covered.has(key)) covered.set(key, new Set());
285
- for (const id of itemsOf(cells[1])) covered.get(key).add(id);
286
- }
287
-
288
- const gaps = [];
289
- for (const screen of parseScreens(designMarkdown)) {
290
- const done = covered.get(screenKey(screen.name)) ?? new Set();
291
- const owed = [...screen.answers]
292
- .filter(([, answer]) => !isPlaceholder(answer) && !isNotApplicable(answer))
293
- .map(([id]) => id)
294
- .filter((id) => !done.has(id));
295
- if (owed.length) gaps.push(`${screen.name}: ${owed.map(labelOf).join(', ')}`);
296
- }
297
- return gaps;
298
- }
299
-
300
- // BOM e CRLF não contam: o checkout de outra máquina é o mesmo arquivo.
301
- export function mockupsHash(cwd, featureName) {
302
- const text = readMockups(cwd, featureName);
303
- if (text === null) return null;
304
- return createHash('sha256').update(text.replace(/^\uFEFF/, '').replace(/\r\n/g, '\n')).digest('hex').slice(0, 16);
305
- }
306
-
307
- /** O `1-design/mockups.md` da feature, ou null quando ausente/ilegível. Nunca lança. */
308
- export function readMockups(cwd, featureName) {
309
- try {
310
- const path = getAbsoluteOutputPath(cwd, featureName, 'uiMockups');
311
- return existsSync(path) ? readFileSync(path, 'utf8') : null;
312
- } catch {
313
- return null;
314
- }
315
- }
@@ -1,69 +0,0 @@
1
- import { readFileSync, existsSync } from 'fs';
2
- import { join } from 'path';
3
-
4
- const DOTNET_STACKS = new Set(['dotnet', 'aspnet']);
5
- const NEXTJS_STACKS = new Set(['nextjs', 'next', 'next.js']);
6
- const NO_VALIDATOR_STACKS = new Set(['nodejs-cli', 'node-cli', 'cli']);
7
-
8
- const PROFILES = {
9
- dotnet: {
10
- isDotnet: true, isNextjs: false,
11
- defaultValidators: ['packages'],
12
- },
13
- nextjs: {
14
- isDotnet: false, isNextjs: true,
15
- defaultValidators: ['nextjs-component'],
16
- },
17
- empty: {
18
- isDotnet: false, isNextjs: false,
19
- defaultValidators: [],
20
- },
21
- };
22
-
23
- function readStack(cwd) {
24
- const configPath = join(cwd, '.morph', 'config', 'config.json');
25
- if (!existsSync(configPath)) return null;
26
- try {
27
- return JSON.parse(readFileSync(configPath, 'utf8')).project?.stack ?? null;
28
- } catch {
29
- return null;
30
- }
31
- }
32
-
33
- function mergeProfiles(profiles) {
34
- return {
35
- isDotnet: profiles.some((p) => p.isDotnet),
36
- isNextjs: profiles.some((p) => p.isNextjs),
37
- defaultValidators: [...new Set(profiles.flatMap((p) => p.defaultValidators))],
38
- };
39
- }
40
-
41
- /** A compound stack ("dotnet-nextjs", "dotnet+nextjs") merges the profile of each segment. */
42
- export function getStackProfile(cwd, stackOverride) {
43
- const root = cwd ?? process.cwd();
44
- const raw = stackOverride ?? readStack(root);
45
- const stack = raw?.toLowerCase() ?? 'unknown';
46
-
47
- const segments = stack.split(/[-+]/).filter(Boolean);
48
-
49
- if (segments.length <= 1) {
50
- let profile;
51
- if (NEXTJS_STACKS.has(stack)) {
52
- profile = PROFILES.nextjs;
53
- } else if (NO_VALIDATOR_STACKS.has(stack)) {
54
- profile = PROFILES.empty;
55
- } else if (DOTNET_STACKS.has(stack) || stack === 'unknown') {
56
- profile = PROFILES.dotnet;
57
- } else {
58
- profile = PROFILES.empty;
59
- }
60
- return { stack, ...profile };
61
- }
62
-
63
- const matched = [];
64
- if (segments.some((s) => DOTNET_STACKS.has(s))) matched.push(PROFILES.dotnet);
65
- if (segments.some((s) => NEXTJS_STACKS.has(s))) matched.push(PROFILES.nextjs);
66
-
67
- const profile = matched.length > 0 ? mergeProfiles(matched) : PROFILES.empty;
68
- return { stack, ...profile };
69
- }
@@ -1,293 +0,0 @@
1
- import { existsSync, readFileSync, readdirSync, statSync } from 'fs';
2
- import { join, resolve } from 'path';
3
- import { tmpdir } from 'os';
4
-
5
- import { isInside } from './test-runner.js';
6
- import { resolveAiPin } from '../ai/pin-drift.js';
7
-
8
- export const EVAL_RUNNER = 'evals';
9
-
10
- /** The SAME name the .NET fixture writes. */
11
- export const EVAL_STAMP_FILE = '.morph-eval-cache.json';
12
-
13
- /** Relative to the cache root's parent. */
14
- export const DEFAULT_DATASET_DIR = 'eval-datasets';
15
-
16
- export const DEFAULT_ENV_FILE = '.env.evals';
17
-
18
- /**
19
- * Only the `Microsoft.Extensions.AI` family decides the cache format: that library
20
- * computes the cache key. Reacting to unrelated provider bumps would fail for nothing.
21
- * @returns {Record<string, string>} name → exact version
22
- */
23
- export function cacheRelevantPackages(packages) {
24
- const out = {};
25
- for (const [name, entry] of Object.entries(packages ?? {})) {
26
- if (name === 'Microsoft.Extensions.AI' || name.startsWith('Microsoft.Extensions.AI.Evaluation')) {
27
- out[name] = entry?.version;
28
- }
29
- }
30
- return out;
31
- }
32
-
33
- export function resolveEvalPaths(node, projectPath) {
34
- const root = resolve(projectPath);
35
- const evals = node?.evals ?? {};
36
- const cacheRoot = resolve(root, evals.cachePath ?? '');
37
- const beside = resolve(cacheRoot, '..');
38
-
39
- return {
40
- cacheRoot,
41
- datasetRoot: evals.datasetPath ? resolve(root, evals.datasetPath) : join(beside, DEFAULT_DATASET_DIR),
42
- // Outside the committed cache tree: results carry latency and token usage,
43
- // so committing them is a diff on every run with no signal in it.
44
- resultsRoot: join(beside, 'eval-results'),
45
- envFile: resolve(root, evals.envFile ?? DEFAULT_ENV_FILE),
46
- };
47
- }
48
-
49
- /** Fail-CLOSED: a typo must never make the eval silently disappear. */
50
- export function evalBlockProblem(raw, projectPath) {
51
- const evals = raw?.evals;
52
-
53
- if (evals === undefined) {
54
- return 'runner "evals" requires an evals.cachePath — a default would create a cache tree somewhere nobody declared';
55
- }
56
- if (typeof evals !== 'object' || evals === null || Array.isArray(evals)) {
57
- return 'evals must be an object';
58
- }
59
- if (typeof evals.cachePath !== 'string' || !evals.cachePath.trim()) {
60
- return 'evals.cachePath must be a non-empty string';
61
- }
62
- for (const key of ['datasetPath', 'envFile']) {
63
- if (evals[key] !== undefined && (typeof evals[key] !== 'string' || !evals[key].trim())) {
64
- return `evals.${key} must be a non-empty string`;
65
- }
66
- }
67
-
68
- const root = resolve(projectPath ?? '.');
69
- for (const key of ['cachePath', 'datasetPath']) {
70
- const value = evals[key];
71
- if (typeof value !== 'string' || !value.trim()) continue;
72
- if (!isInside(resolve(root, value.trim()), root)) {
73
- return `evals.${key} "${value}" resolves outside the project root`;
74
- }
75
- }
76
-
77
- return null;
78
- }
79
-
80
- function cacheHasEntries(cacheRoot) {
81
- const walk = (dir) => {
82
- let entries;
83
- try {
84
- entries = readdirSync(dir, { withFileTypes: true });
85
- } catch {
86
- return false;
87
- }
88
- for (const entry of entries) {
89
- const full = join(dir, entry.name);
90
- if (entry.isDirectory()) {
91
- if (walk(full)) return true;
92
- } else if (entry.name !== EVAL_STAMP_FILE) {
93
- return true;
94
- }
95
- }
96
- return false;
97
- };
98
- return walk(cacheRoot);
99
- }
100
-
101
- /** null for absent OR unreadable. */
102
- export function readEvalStamp(cacheRoot) {
103
- const path = join(cacheRoot, EVAL_STAMP_FILE);
104
- if (!existsSync(path)) return null;
105
- try {
106
- const parsed = JSON.parse(readFileSync(path, 'utf8'));
107
- return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
108
- } catch {
109
- return null;
110
- }
111
- }
112
-
113
- /**
114
- * Judged BEFORE `dotnet test`: finding a bad cache at the end costs the whole clock.
115
- * A bad cache is `fail`, never `skip` — a skip is a green gate over nothing.
116
- * @returns {{status: 'fail'|null, reason: string|null}} status null means RUN
117
- */
118
- export function evalPreflight(projectPath, node, options = {}) {
119
- const { refresh = false } = options;
120
-
121
- if (node?.runner !== EVAL_RUNNER) return { status: null, reason: null };
122
-
123
- const { cacheRoot, envFile } = resolveEvalPaths(node, projectPath);
124
-
125
- // Demanding a populated, stamped cache in refresh would make the FIRST cache impossible.
126
- if (refresh) {
127
- if (!existsSync(envFile)) {
128
- return {
129
- status: 'fail',
130
- reason: `eval-refresh-no-credential: --refresh-cache exige o arquivo de credencial "${envFile}", que não existe`,
131
- };
132
- }
133
- return { status: null, reason: null };
134
- }
135
-
136
- if (!existsSync(cacheRoot)) {
137
- return { status: 'fail', reason: `eval-cache-missing: ${cacheRoot}` };
138
- }
139
-
140
- if (!cacheHasEntries(cacheRoot)) {
141
- // Distinct from `missing`: an empty committed directory is usually a `.gitignore` mistake.
142
- return { status: 'fail', reason: `eval-cache-empty: ${cacheRoot} não contém nenhuma entrada de cache` };
143
- }
144
-
145
- const pin = resolveAiPin(projectPath);
146
- if (!pin) {
147
- return { status: null, reason: null };
148
- }
149
-
150
- const stamp = readEvalStamp(cacheRoot);
151
- if (!stamp) {
152
- return {
153
- status: 'fail',
154
- reason: `eval-cache-unstamped: ${join(cacheRoot, EVAL_STAMP_FILE)} ausente ou ilegível`
155
- + ' — a árvore não diz sob quais versões foi gravada; rode verify --refresh-cache',
156
- };
157
- }
158
-
159
- const expected = cacheRelevantPackages(pin.packages);
160
- const recorded = stamp.packages ?? {};
161
- const divergent = Object.entries(expected)
162
- .filter(([name, version]) => recorded[name] !== version)
163
- .map(([name, version]) => `${name}: gravada ${recorded[name] ?? '(ausente)'} vs pin ${version}`);
164
-
165
- if (divergent.length > 0) {
166
- return {
167
- status: 'fail',
168
- reason: `eval-cache-stale-pin: ${divergent.join('; ')} — rode verify --refresh-cache`,
169
- };
170
- }
171
-
172
- return { status: null, reason: null };
173
- }
174
-
175
- /**
176
- * The CLI picks the summary path, not the fixture: two eval nodes in one verify must not collide.
177
- * @returns {{env: Record<string,string>, summaryPath: string}}
178
- */
179
- export function evalNodeEnv(node, projectPath, options = {}) {
180
- const { refresh = false } = options;
181
- const { cacheRoot, datasetRoot, resultsRoot, envFile } = resolveEvalPaths(node, projectPath);
182
- const summaryPath = join(tmpdir(), `morph-eval-${node.id}-${process.pid}.json`);
183
-
184
- const env = {
185
- MORPH_EVAL_CACHE: cacheRoot,
186
- MORPH_EVAL_DATASET: datasetRoot,
187
- MORPH_EVAL_RESULTS: resultsRoot,
188
- MORPH_EVAL_MODE: refresh ? 'refresh' : 'offline',
189
- MORPH_EVAL_SUMMARY: summaryPath,
190
- MORPH_EVAL_ENVFILE: envFile,
191
- };
192
-
193
- const pin = resolveAiPin(projectPath);
194
- if (pin) {
195
- env.MORPH_EVAL_PIN = JSON.stringify({
196
- pinnedAt: pin.pinnedAt,
197
- packages: cacheRelevantPackages(pin.packages),
198
- });
199
- }
200
-
201
- // Absent credential file is NOT an error offline: that is the point of a warm cache.
202
- Object.assign(env, readEnvFile(envFile));
203
-
204
- return { env, summaryPath };
205
- }
206
-
207
- /** Fail-open to `{}`: an unreadable credential file must not take down a run that needed none. */
208
- export function readEnvFile(path) {
209
- if (!path || !existsSync(path)) return {};
210
- let text;
211
- try {
212
- text = readFileSync(path, 'utf8');
213
- } catch {
214
- return {};
215
- }
216
-
217
- const out = {};
218
- for (const line of text.split(/\r?\n/)) {
219
- const trimmed = line.trim();
220
- if (!trimmed || trimmed.startsWith('#')) continue;
221
- const eq = trimmed.indexOf('=');
222
- if (eq <= 0) continue;
223
- const key = trimmed.slice(0, eq).trim();
224
- let value = trimmed.slice(eq + 1).trim();
225
- if (value.length >= 2 && ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'")))) {
226
- value = value.slice(1, -1);
227
- }
228
- if (key) out[key] = value;
229
- }
230
- return out;
231
- }
232
-
233
- /** @returns {object|null} null is UNKNOWN, never zero: a missing file must not fabricate a count drop. */
234
- export function readEvalSummary(path) {
235
- if (!path || !existsSync(path)) return null;
236
- try {
237
- const parsed = JSON.parse(readFileSync(path, 'utf8'));
238
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
239
- return parsed;
240
- } catch {
241
- return null;
242
- }
243
- }
244
-
245
- /**
246
- * The ONLY source of an eval node's count. The `dotnet` extractor counts xunit cases,
247
- * another unit, so an unreadable summary is null — never 0, never the extractor's number.
248
- */
249
- export function evalScenarioCount(summary) {
250
- const n = summary?.scenarios;
251
- return Number.isInteger(n) ? n : null;
252
- }
253
-
254
- /** Never throws on a malformed summary: a crash would report "verify crashed" instead of "eval failed". */
255
- export function evalFailureLines(summary) {
256
- const failures = summary?.failures;
257
- if (!Array.isArray(failures)) return [];
258
-
259
- return failures
260
- .filter((f) => f && typeof f === 'object')
261
- .map((f) => {
262
- const scenario = typeof f.scenario === 'string' && f.scenario ? f.scenario : '(cenário sem nome)';
263
- const assertion = typeof f.assertion === 'string' && f.assertion ? f.assertion : '(asserção sem nome)';
264
- const kind = typeof f.kind === 'string' && f.kind ? f.kind : '(régua desconhecida)';
265
- const reason = typeof f.reason === 'string' && f.reason ? f.reason : '(sem motivo registrado)';
266
- return `eval-fail: ${scenario} — ${assertion} (${kind}): ${reason}`;
267
- });
268
- }
269
-
270
- /** Zero scenarios with exit 0 is red: the exit code cannot see a suite where nothing ran. */
271
- export function evalEmptyRunProblem(summary) {
272
- if (summary && summary.scenarios === 0) {
273
- return 'eval-empty-run: a suíte de eval avaliou 0 cenários e saiu verde';
274
- }
275
- return null;
276
- }
277
-
278
- /** A warning, not a failure: without it the fresh cache stays on one disk and CI misses tomorrow. */
279
- export function evalColdCacheWarning(summary) {
280
- if (summary?.cache === 'cold') {
281
- const misses = Number.isInteger(summary.misses) ? summary.misses : '?';
282
- return `a árvore de cache mudou (${misses} miss(es)) — commite ${EVAL_STAMP_FILE} e as entradas novas`;
283
- }
284
- return null;
285
- }
286
-
287
- export function isDirectory(path) {
288
- try {
289
- return statSync(path).isDirectory();
290
- } catch {
291
- return false;
292
- }
293
- }