@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
@@ -3,101 +3,46 @@
3
3
  import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'fs';
4
4
  import { join } from 'path';
5
5
  import { createHash } from 'crypto';
6
- import {
7
- stateExists, getActiveFeature, getMostRecentFeature, derivePhaseForFeature,
8
- } from '../../shared/state-reader.js';
6
+ import { contractExists } from '../../shared/contract.js';
7
+ import { featureFromBranch } from '../../shared/feature-slug.js';
9
8
  import { contextResult, runStandalone } from '../../shared/hook-response.js';
10
- import { appendTelemetryEvent } from '../../shared/telemetry-logger.js';
11
- import { readTranscriptUsage, usageDelta } from '../../shared/transcript-usage.js';
12
- import { implementProgress, ownerRef } from '../../shared/report-progress.js';
13
- import { scenarioLabel } from '../../shared/owner-words.js';
14
- import { SESSION_MARK } from '../../shared/next-step.js';
9
+ import { implementProgress } from '../../shared/report-progress.js';
10
+ import { scenarioLabel, SESSION_MARK } from '../../shared/owner-words.js';
15
11
 
16
- function auditReport(featurePath) {
12
+ export function unprovenScenarios(featurePath) {
17
13
  const progress = implementProgress(featurePath);
18
- if (!progress || progress.legacy) return [];
14
+ if (!progress) return [];
19
15
  return progress.checks.filter((c) => c.status === 'feito' && !c.evidence.trim())
20
16
  .map((c) => `${scenarioLabel(c)} está marcado feito sem prova (o teste, a linha de código ou o passo que mostra que funciona).`);
21
17
  }
22
18
 
23
- export async function run(payload) {
24
- try {
25
- if (process.env.MORPH_STOP_HOOK_ACTIVE === '1') return null;
26
-
27
- if (!stateExists()) return null;
28
-
29
- let active = getActiveFeature() || getMostRecentFeature();
30
- if (!active) return null;
31
-
32
- const { name, feature } = active;
33
- const cwd = process.cwd();
34
- const warnings = [];
35
-
36
- const memDir = join(cwd, '.morph', 'memory');
37
- try { mkdirSync(memDir, { recursive: true }); } catch {}
38
-
39
- const currentPhase = feature.phase || derivePhaseForFeature(name, cwd);
40
-
41
- // Hash-gated: the audit re-runs every Stop, so only a changed warning set is injected; resolving clears the hash.
42
- try {
43
- const featurePath = join(cwd, '.morph', 'features', name);
44
- const reportWarnings = auditReport(featurePath);
45
-
46
- const warnedHashesPath = join(memDir, 'warned-hashes.json');
47
- let warnedHashes = {};
48
- try {
49
- if (existsSync(warnedHashesPath)) warnedHashes = JSON.parse(readFileSync(warnedHashesPath, 'utf-8'));
50
- } catch { /* corrupt file — start fresh */ }
51
-
52
- if (reportWarnings.length > 0) {
53
- const hash = createHash('sha1').update(reportWarnings.join('\n')).digest('hex');
54
- if (warnedHashes[name]?.reports !== hash) {
55
- warnings.push('📋 Relatório da construção:');
56
- for (const w of reportWarnings) warnings.push(` • ${w}`);
57
- warnings.push(`${SESSION_MARK} preencha a prova de cada cenário acima no progresso da construção e confira com \`morph-spec report-check ${name}\` de ${ownerRef(cwd, name, feature)}.`);
58
- warnedHashes[name] = { ...warnedHashes[name], reports: hash };
59
- try { writeFileSync(warnedHashesPath, JSON.stringify(warnedHashes, null, 2), 'utf-8'); } catch {}
60
- }
61
- } else if (warnedHashes[name]?.reports) {
62
- delete warnedHashes[name].reports;
63
- try { writeFileSync(warnedHashesPath, JSON.stringify(warnedHashes, null, 2), 'utf-8'); } catch {}
64
- }
65
- } catch {}
66
-
67
- // The transcript total is cumulative: summing the per-session `delta` is the only sum that does not double-count.
68
- try {
69
- const usage = readTranscriptUsage(payload?.transcript_path);
70
- if (usage) {
71
- const usagePath = join(memDir, 'session-usage.json');
72
- let stored = {};
73
- try {
74
- if (existsSync(usagePath)) stored = JSON.parse(readFileSync(usagePath, 'utf-8'));
75
- } catch { /* corrupt file — start fresh */ }
76
-
77
- const sessionKey = payload?.session_id || 'default';
78
- const { delta, changed } = usageDelta(stored[sessionKey], usage);
79
- if (changed) {
80
- appendTelemetryEvent({
81
- event: 'SessionUsage',
82
- sessionId: payload?.session_id ?? null,
83
- feature: name,
84
- phase: currentPhase,
85
- ...usage,
86
- delta,
87
- }, cwd);
88
- stored[sessionKey] = usage;
89
- try { writeFileSync(usagePath, JSON.stringify(stored, null, 2), 'utf-8'); } catch {}
90
- }
91
- }
92
- } catch {}
93
-
94
- if (warnings.length === 0) return null;
19
+ // Every Stop runs the audit; only a changed warning set is said again.
20
+ function changed(memDir, slug, warnings) {
21
+ const path = join(memDir, 'warned-hashes.json');
22
+ let seen = {};
23
+ try { if (existsSync(path)) seen = JSON.parse(readFileSync(path, 'utf-8')); } catch { /* start fresh */ }
24
+ const hash = warnings.length ? createHash('sha1').update(warnings.join('\n')).digest('hex') : null;
25
+ if (seen[slug] === hash) return false;
26
+ if (hash) seen[slug] = hash; else delete seen[slug];
27
+ try { mkdirSync(memDir, { recursive: true }); writeFileSync(path, JSON.stringify(seen, null, 2)); } catch { /* fail-open */ }
28
+ return Boolean(hash);
29
+ }
95
30
 
96
- const message = [
97
- 'MORPH-SPEC:',
98
- ...warnings.map(w => ` ${w}`),
99
- ].join('\n');
100
- return contextResult(message, 'Stop');
31
+ export async function run() {
32
+ try {
33
+ const cwd = process.env.CLAUDE_PROJECT_DIR || process.cwd();
34
+ if (!contractExists(cwd)) return null;
35
+ const slug = featureFromBranch(cwd);
36
+ if (!slug) return null;
37
+ const featurePath = join(cwd, '.morph', 'features', slug);
38
+ if (!existsSync(featurePath)) return null;
39
+ const warnings = unprovenScenarios(featurePath);
40
+ if (!changed(join(cwd, '.morph', 'memory'), slug, warnings)) return null;
41
+ return contextResult([
42
+ 'MORPH-SPEC — relatório da construção:',
43
+ ...warnings.map((w) => ` • ${w}`),
44
+ `${SESSION_MARK} preencha a evidência de cada cenário acima no 3-implement/report.md.`,
45
+ ].join('\n'), 'Stop');
101
46
  } catch {
102
47
  return null;
103
48
  }
@@ -109,9 +109,8 @@ function kindOfTokens(tokens) {
109
109
 
110
110
  const segmentTokens = (segment) => skipWrappers(tokenize(segment.replace(/^[\s({]+/, '').replace(/[\s)}]+$/, '')));
111
111
 
112
- // Judges only each segment's executable: `morph-spec heavy run -- dotnet test` already holds its
113
- // own slot, and `echo "dotnet build"` runs nothing.
114
- export function heavyKind(command) {
112
+ // Judges only each segment's executable: `echo "dotnet build"` runs nothing.
113
+ export function buildOrTestKind(command) {
115
114
  for (const segment of splitSegments(command)) {
116
115
  const tokens = segmentTokens(segment);
117
116
  const kind = kindOfTokens(tokens);
@@ -120,9 +119,6 @@ export function heavyKind(command) {
120
119
  return null;
121
120
  }
122
121
 
123
- export const REVIEW_AGENT_TYPES = new Set(['morph-verifier', 'morph-reviewer', 'morph-security']);
124
- export const QUEUE_FULL_EXIT = 3;
125
-
126
122
  const LIST_FLAGS = new Set(['--list', '--listTests', '--list-tests']);
127
123
  const TEST_LABEL = /^(dotnet (test|vstest)|(npx )?(vitest|jest|playwright test)|(npm|pnpm|yarn|bun) (test|run test(:\S+)?)|(powershell|pwsh) test-script)$/;
128
124
  const NODE_RUNNERS = new Set(['vitest', 'jest']);
@@ -133,20 +129,8 @@ function morphArgs(tokens) {
133
129
  return null;
134
130
  }
135
131
 
136
- // `morph-spec heavy run -- <cmd>` is peeled here, unlike in heavyKind: the slot is already held,
137
- // but the run still spends a test round.
138
132
  function* commandTokens(command) {
139
- for (const segment of splitSegments(command)) {
140
- const tokens = segmentTokens(segment);
141
- const args = morphArgs(tokens);
142
- if (args?.[0] === 'heavy' && args[1] === 'run') {
143
- const rest = args.slice(2);
144
- const dashes = rest.indexOf('--');
145
- yield skipWrappers(dashes >= 0 ? rest.slice(dashes + 1) : rest);
146
- } else {
147
- yield tokens;
148
- }
149
- }
133
+ for (const segment of splitSegments(command)) yield segmentTokens(segment);
150
134
  }
151
135
 
152
136
  function testKindOfTokens(tokens) {
@@ -160,37 +144,6 @@ function testKindOfTokens(tokens) {
160
144
  return kind && TEST_LABEL.test(kind) ? kind : null;
161
145
  }
162
146
 
163
- const DOTNET_FILTERS = /^(--filter|--tests|--treenode-filter|\/testcasefilter:)/i;
164
- const SCRIPT_FILTERS = /^(-Filter|--filter|-TestFilter)$/i;
165
- const NAME_FILTERS = /^(-t|-g|--grep|--testNamePattern|--test-name-pattern|--testPathPattern|--filter)(=|$)/;
166
- // A bare word may be a flag's value (`--reporter dot`); only a path-shaped argument selects files.
167
- const TEST_PATH = /[\\/]|\.(spec|test)\b|\.[cm]?[jt]sx?$/;
168
- const PATH_VALUE_FLAGS = new Set(['-c', '--config', '--project', '--root', '--workspace', '--outputFile', '--reporter', ...PM_DIR_FLAGS]);
169
-
170
- function isFilteredRun(kind, tokens) {
171
- // A test script's own filter parameter is the bench a plan declares (`test-pg.ps1 -Filter X`).
172
- if (kind.endsWith(TEST_SCRIPT_SUFFIX)) return tokens.some((t, i) => SCRIPT_FILTERS.test(t) && i + 1 < tokens.length);
173
- const runnerAt = executable(tokens[0]) === 'node'
174
- ? tokens.findIndex((t, i) => i > 0 && executable(t).replace(/\.[cm]?js$/, '') === kind)
175
- : 0;
176
- const args = tokens.slice(runnerAt + 1);
177
- if (kind.startsWith('dotnet')) return args.some((a) => DOTNET_FILTERS.test(a));
178
- for (let i = 0; i < args.length; i++) {
179
- if (PATH_VALUE_FLAGS.has(args[i])) { i++; continue; }
180
- if (NAME_FILTERS.test(args[i]) || (!args[i].startsWith('-') && TEST_PATH.test(args[i]))) return true;
181
- }
182
- return false;
183
- }
184
-
185
- /** `{ kind, filtered }` for the first test run in `command`, `null` when there is none. */
186
- export function testRunCall(command) {
187
- for (const tokens of commandTokens(command)) {
188
- const kind = testKindOfTokens(tokens);
189
- if (kind) return { kind, filtered: isFilteredRun(kind, tokens) };
190
- }
191
- return null;
192
- }
193
-
194
147
  export function testRunKind(command) {
195
148
  for (const tokens of commandTokens(command)) {
196
149
  const kind = testKindOfTokens(tokens);
@@ -199,36 +152,10 @@ export function testRunKind(command) {
199
152
  return null;
200
153
  }
201
154
 
202
- export function morphVerifyCall(command) {
155
+ export function morphCheckCall(command) {
203
156
  for (const tokens of commandTokens(command)) {
204
157
  const args = morphArgs(tokens);
205
- if (!args || firstArg(args) !== 'verify' || args.some((a) => INFO_FLAGS.has(a))) continue;
206
- return { filtered: args.some((a) => a === '--filter' || a.startsWith('--filter=')) };
158
+ if (args && firstArg(args) === 'check' && !args.some((a) => INFO_FLAGS.has(a))) return true;
207
159
  }
208
- return null;
209
- }
210
-
211
- const E2E_CLASS = /\be2e\b|playwright|compose up/;
212
- const UNIT_CLASS = /^(tests|(npx )?(vitest|jest)|(npm|pnpm|yarn|bun) (test|run test(:\S+)?))$/;
213
-
214
- // Maps a `heavyKind` label or a verify node to the RAM class it pays. `dotnet test` and anything
215
- // unknown stay `build`: they compile before running, and the fallback must never lower a floor.
216
- export function heavyClass(label) {
217
- const s = String(label ?? '').toLowerCase().trim();
218
- if (E2E_CLASS.test(s)) return 'e2e';
219
- if (UNIT_CLASS.test(s)) return 'unit';
220
- return 'build';
221
- }
222
-
223
- // The lease has no live process to watch: this TTL is the only thing that frees it after a
224
- // denied or interrupted call.
225
- const BASH_DEFAULT_TIMEOUT_MS = 2 * 60_000;
226
- const BASH_MAX_TIMEOUT_MS = 10 * 60_000;
227
- const LEASE_SLACK_MS = 30_000;
228
-
229
- export function leaseTtlMs(toolInput, env = process.env) {
230
- const fallback = Number(env.BASH_DEFAULT_TIMEOUT_MS) || BASH_DEFAULT_TIMEOUT_MS;
231
- const max = Math.max(Number(env.BASH_MAX_TIMEOUT_MS) || BASH_MAX_TIMEOUT_MS, fallback);
232
- const asked = Number(toolInput?.timeout);
233
- return Math.min(Number.isFinite(asked) && asked > 0 ? asked : fallback, max) + LEASE_SLACK_MS;
160
+ return false;
234
161
  }
@@ -79,8 +79,6 @@ export function exitCodeMasked(command) {
79
79
  return (segments.length > 1 && REPORTER.test(last)) || /\|\|/.test(last.replace(/"[^"]*"|'[^']*'/g, ''));
80
80
  }
81
81
 
82
- const WRITE_REDIRECT = /^(?:[1&])?>>?\|?/;
83
-
84
82
  function quotedTokens(text) {
85
83
  const tokens = [];
86
84
  const re = /"([^"]*)"|'([^']*)'|(\S+)/g;
@@ -92,9 +90,6 @@ function quotedTokens(text) {
92
90
  }
93
91
 
94
92
  const CHAIN = /^(?:&&|\|\||\||\|&)$/;
95
- const ASSIGNMENT = /^([A-Za-z_]\w*)=(.*)$/;
96
- const REDIRECT = /^(?:\d|&)?[<>]/;
97
- const SCRIPT_RUNNER = /^(?:python[\d.]*|py|node|bun|deno)$/;
98
93
 
99
94
  export function simpleCommands(head) {
100
95
  const commands = [];
@@ -124,137 +119,3 @@ export function gitInvocations(command) {
124
119
  }
125
120
  return invocations;
126
121
  }
127
-
128
- function positionals(args, takesValue) {
129
- const out = [];
130
- const values = [];
131
- for (let i = 0; i < args.length; i++) {
132
- const { text, quoted } = args[i];
133
- if (!quoted && REDIRECT.test(text)) { if (/[<>]$/.test(text)) i++; continue; }
134
- if (!quoted && text.startsWith('-') && text !== '-') {
135
- if (takesValue(text) && i + 1 < args.length) values.push(args[++i].text);
136
- continue;
137
- }
138
- out.push(text);
139
- }
140
- return { files: out, values };
141
- }
142
-
143
- function sedTargets(args) {
144
- const inPlace = args.some(({ text, quoted }) => !quoted && (/^-[A-Za-z]*i/.test(text) || text.startsWith('--in-place')));
145
- if (!inPlace) return [];
146
- const { files, values } = positionals(args, (o) => /^-[A-Za-z]*[ef]$/.test(o) || o === '--expression' || o === '--file');
147
- return values.length > 0 ? files : files.slice(1);
148
- }
149
-
150
- function perlTargets(args) {
151
- if (!args.some(({ text, quoted }) => !quoted && /^-[A-Za-z]*i/.test(text))) return [];
152
- const { files, values } = positionals(args, (o) => /^-[A-Za-z.]*[eE]$/.test(o));
153
- return values.length > 0 ? files : files.slice(1);
154
- }
155
-
156
- function copyTargets(args) {
157
- if (args.some(({ text }) => text === '-t' || text.startsWith('--target-directory'))) return [];
158
- const { files } = positionals(args, () => false);
159
- if (files.length < 2) return [];
160
- const dest = files[files.length - 1];
161
- if (!dest.endsWith('/')) return [dest];
162
- return files.slice(0, -1).map((src) => dest + src.replace(/^.*\//, ''));
163
- }
164
-
165
- const PY_OPEN_WRITE = /\bopen\(\s*([^,()]+?)\s*,\s*(?:mode\s*=\s*)?(['"])([^'"]*)\2/g;
166
- const JS_WRITE = /\b(?:writeFileSync|writeFile|appendFileSync|appendFile)\(\s*([^,()]+?)\s*,/g;
167
- const PY_PATH_WRITE = /\.write_(?:text|bytes)\(/;
168
- const STRING_LITERAL = /(['"`])((?:(?!\1)[^\\\n]|\\.)*)\1/g;
169
- const PATH_LITERAL = /^[\w@./-]*[\w-]\.[A-Za-z]{1,5}$/;
170
-
171
- function literalOf(expr) {
172
- const m = /^(['"`])([^'"`]*)\1$/.exec(expr.trim());
173
- return m ? m[2] : null;
174
- }
175
-
176
- // A write call with a computed path (`open(p, "w")`) counts every path-shaped literal in the script.
177
- function scriptWrites(script) {
178
- const literals = [];
179
- let computed = PY_PATH_WRITE.test(script);
180
- for (const m of script.matchAll(PY_OPEN_WRITE)) {
181
- if (!/[wax+]/.test(m[3])) continue;
182
- const lit = literalOf(m[1]);
183
- if (lit === null) computed = true; else literals.push(lit);
184
- }
185
- for (const m of script.matchAll(JS_WRITE)) {
186
- const lit = literalOf(m[1]);
187
- if (lit === null) computed = true; else literals.push(lit);
188
- }
189
- if (!computed) return literals;
190
- const mentioned = [...script.matchAll(STRING_LITERAL)].map((m) => m[2]).filter((s) => PATH_LITERAL.test(s));
191
- return [...new Set([...literals, ...mentioned])];
192
- }
193
-
194
- function runnerScript(args, body) {
195
- for (let i = 0; i < args.length; i++) {
196
- if (['-c', '-e', '-p', '--eval', '--print'].includes(args[i].text) && !args[i].quoted) return args[i + 1]?.text ?? null;
197
- }
198
- const { files } = positionals(args, () => false);
199
- return (files.length === 0 || files[0] === '-') ? body : null;
200
- }
201
-
202
- function heredocBody(lines, at) {
203
- if (at < 0) return null;
204
- const delim = /<<-?\s*(['"]?)([\w.-]+)\1/.exec(lines[at])?.[2];
205
- if (!delim) return null;
206
- const end = lines.findIndex((line, i) => i > at && line.trim() === delim);
207
- return lines.slice(at + 1, end < 0 ? undefined : end).join('\n');
208
- }
209
-
210
- function commandWriteTargets(head, body) {
211
- const vars = new Map();
212
- const expand = ({ text, single }) => (single ? text : text.replace(/\$\{?([A-Za-z_]\w*)\}?/g, (all, name) => vars.get(name) ?? all));
213
- const targets = [];
214
- for (const tokens of simpleCommands(head)) {
215
- let i = 0;
216
- for (; i < tokens.length && !tokens[i].quoted && ASSIGNMENT.test(tokens[i].text); i++) {
217
- const [, name, value] = ASSIGNMENT.exec(tokens[i].text);
218
- vars.set(name, value);
219
- }
220
- if (i >= tokens.length) continue;
221
- const word = tokens[i].text.replace(/^.*[\\/]/, '').replace(/\.exe$/i, '');
222
- const args = tokens.slice(i + 1).map((t) => ({ ...t, text: expand(t) }));
223
- if (word === 'sed') targets.push(...sedTargets(args));
224
- else if (word === 'perl') targets.push(...perlTargets(args));
225
- else if (word === 'cp' || word === 'mv') targets.push(...copyTargets(args));
226
- else if (SCRIPT_RUNNER.test(word)) {
227
- const script = runnerScript(args, body);
228
- if (script) targets.push(...scriptWrites(script));
229
- }
230
- }
231
- return targets;
232
- }
233
-
234
- // The redirect scan stops at the heredoc line: the body is data, and an
235
- // apostrophe in it would derail the quote-aware split.
236
- export function writeTargets(command) {
237
- const lines = String(command || '').split('\n');
238
- const heredocAt = lines.findIndex((line) => line.includes('<<'));
239
- const head = (heredocAt >= 0 ? lines.slice(0, heredocAt + 1) : lines).join('\n');
240
- const tokens = quotedTokens(head);
241
-
242
- const targets = [];
243
- for (let i = 0; i < tokens.length; i++) {
244
- const { text, quoted } = tokens[i];
245
- if (quoted) continue;
246
- const op = text.match(WRITE_REDIRECT);
247
- if (op) {
248
- const rest = text.slice(op[0].length);
249
- const target = rest || tokens[i + 1]?.text;
250
- if (target && !target.startsWith('&')) targets.push(target);
251
- continue;
252
- }
253
- if (text.replace(/^.*[\/]/, '') === 'tee') {
254
- for (let j = i + 1; j < tokens.length && !/^[;&|]/.test(tokens[j].text); j++) {
255
- if (!tokens[j].text.startsWith('-')) targets.push(tokens[j].text);
256
- }
257
- }
258
- }
259
- return [...new Set([...targets, ...commandWriteTargets(head, heredocBody(lines, heredocAt))])];
260
- }
@@ -0,0 +1,14 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+
4
+ export const CONTRACT_FILE = join('.morph', 'config', 'config.json');
5
+
6
+ export const NO_CONTRACT_MESSAGE = 'Este repo não tem contrato (.morph/config/config.json): rode morph-spec init.';
7
+
8
+ export function contractExists(projectPath) {
9
+ try {
10
+ return existsSync(join(projectPath || process.cwd(), CONTRACT_FILE));
11
+ } catch {
12
+ return false;
13
+ }
14
+ }
@@ -0,0 +1,21 @@
1
+ import { execFileSync } from 'child_process';
2
+
3
+ /** The feature folder of a branch: whoever created the worktree named it, morph-spec only reads it. */
4
+ export function slugOfBranch(branch) {
5
+ const slug = String(branch || '')
6
+ .replace(/^refs\/heads\//, '')
7
+ .replace(/^morph(-task)?\//, '')
8
+ .toLowerCase()
9
+ .replace(/[^a-z0-9]+/g, '-')
10
+ .replace(/^-+|-+$/g, '');
11
+ return slug || null;
12
+ }
13
+
14
+ export function featureFromBranch(cwd) {
15
+ try {
16
+ const branch = execFileSync('git', ['symbolic-ref', '--short', 'HEAD'], { cwd, stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim();
17
+ return slugOfBranch(branch);
18
+ } catch {
19
+ return null;
20
+ }
21
+ }
@@ -1,4 +1,3 @@
1
1
  // `src/lib/detectors` re-exports this list, because a hook cannot import `src/`.
2
2
  export const PACKAGE_LOCATIONS = ['.', 'src/frontend', 'src/web', 'frontend', 'apps/web', 'packages/app'];
3
3
 
4
- export const E2E_SPEC_LOCATIONS = [...PACKAGE_LOCATIONS, 'web'];
@@ -26,21 +26,6 @@ function privateGitDirOf(dotGitFile) {
26
26
  return isAbsolute(match[1]) ? match[1] : resolve(dirname(dotGitFile), match[1]);
27
27
  }
28
28
 
29
- const MORPH_BRANCH = /^ref:\s*refs\/heads\/morph\/([A-Za-z0-9._-]+)\s*$/;
30
-
31
- /** Reads `<root>/.git` exactly, without climbing; `null` for any branch other than `morph/<feature>`. */
32
- export function morphBranchFeature(root) {
33
- try {
34
- const dotGit = join(root, '.git');
35
- const gitDir = statSync(dotGit).isDirectory() ? dotGit : privateGitDirOf(dotGit);
36
- if (!gitDir) return null;
37
- const name = MORPH_BRANCH.exec(readFileSync(join(gitDir, 'HEAD'), 'utf8').trim())?.[1];
38
- return name && name !== '.' && name !== '..' ? name : null;
39
- } catch {
40
- return null;
41
- }
42
- }
43
-
44
29
  /** Outside any repo or on an unreadable path, answers `false`: the lenient direction for e2e isolation. */
45
30
  export function isSecondaryWorktree(startDir) {
46
31
  try {
@@ -107,25 +107,6 @@ export function ignoreRulesHash(tree) {
107
107
  return rulesHash(ignoreTextOf(tree));
108
108
  }
109
109
 
110
- // Só lê: quem confere a árvore chama isto antes das recusas, e
111
- // `dropLeftoverIgnore` só depois delas.
112
- export function withoutLeftoverIgnore(tree, lines) {
113
- const leftover = `?? ${GRAPHIFY_IGNORE}`;
114
- if (!lines.includes(leftover) || !isTemporaryIgnore(readText(join(tree, GRAPHIFY_IGNORE)))) return lines;
115
- return lines.filter((line) => line !== leftover);
116
- }
117
-
118
- export function dropLeftoverIgnore(tree) {
119
- const path = join(tree, GRAPHIFY_IGNORE);
120
- if (!isTemporaryIgnore(readText(path))) return false;
121
- try {
122
- unlinkSync(path);
123
- return true;
124
- } catch {
125
- return false;
126
- }
127
- }
128
-
129
110
  // No win32 o caminho não distingue caixa.
130
111
  export function treeKey(tree) {
131
112
  const path = resolve(tree);
@@ -53,10 +53,3 @@ export async function runStandalone(run) {
53
53
  process.exit(0);
54
54
  }
55
55
 
56
- // A rewrite without a decision is ignored, so it carries `allow`: use it ONLY when
57
- // the input changed, or every call it touches skips the permission prompt.
58
- export function updatedInputResult(updatedInput, eventName, context) {
59
- const out = { hookEventName: eventName, permissionDecision: 'allow', updatedInput };
60
- if (context) out.additionalContext = context;
61
- return { hookSpecificOutput: out };
62
- }
@@ -1,18 +1,8 @@
1
- // A hook cannot import `src/`, so it reuses a CLI command by spawning the CLI; this is the one
2
- // place that finds it. On win32 `morph-spec.cmd` is located on PATH by hand and run through the
3
- // shell, since Node refuses to spawn a `.cmd` without one.
4
- import { spawnSync } from 'child_process';
1
+ // On win32 Node refuses to spawn a `.cmd` without a shell, so the hooks locate it on PATH by hand
2
+ // and quote it for cmd.exe themselves.
5
3
  import { existsSync } from 'fs';
6
4
  import { delimiter, join } from 'path';
7
5
 
8
- function splitCommand(command) {
9
- const tokens = [];
10
- const re = /"([^"]*)"|'([^']*)'|(\S+)/g;
11
- let m;
12
- while ((m = re.exec(command)) !== null) tokens.push(m[1] ?? m[2] ?? m[3]);
13
- return tokens;
14
- }
15
-
16
6
  export function quoteForCmd(arg) {
17
7
  if (arg === '') return '""';
18
8
  if (!/[\s"&|<>^()]/.test(arg)) return arg;
@@ -31,72 +21,3 @@ export function findFirstOnPath(files, env) {
31
21
  }
32
22
  return null;
33
23
  }
34
-
35
- const findOnPath = (file, env) => findFirstOnPath([file], env);
36
-
37
- export function lastJsonLine(stdout) {
38
- const lines = String(stdout || '').split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
39
- for (let i = lines.length - 1; i >= 0; i--) {
40
- if (!lines[i].startsWith('{')) continue;
41
- try {
42
- const parsed = JSON.parse(lines[i]);
43
- if (parsed && typeof parsed === 'object') return parsed;
44
- } catch { /* not this line */ }
45
- }
46
- return null;
47
- }
48
-
49
- function candidates(env) {
50
- const list = [];
51
- const explicit = env.MORPH_SPEC_BIN && splitCommand(env.MORPH_SPEC_BIN);
52
- if (explicit && explicit.length) {
53
- list.push({ file: explicit[0], args: explicit.slice(1), shell: false, kind: 'env' });
54
- }
55
- if (process.platform === 'win32') {
56
- const cmd = findOnPath('morph-spec.cmd', env);
57
- if (cmd) list.push({ file: cmd, args: [], shell: true, kind: 'path' });
58
- const npx = findOnPath('npx.cmd', env);
59
- if (npx) list.push({ file: npx, args: ['--no-install', 'morph-spec'], shell: true, kind: 'npx' });
60
- } else {
61
- list.push({ file: 'morph-spec', args: [], shell: false, kind: 'path' });
62
- list.push({ file: 'npx', args: ['--no-install', 'morph-spec'], shell: false, kind: 'npx' });
63
- }
64
- return list;
65
- }
66
-
67
- const NOT_FOUND_RE = /not recognized as an internal or external command|could not determine executable to run|command not found|ENOENT/i;
68
-
69
- /**
70
- * A missing CLI is `{ unavailable: true }`, never a throw. `json` is the last stdout line that
71
- * parses as an object.
72
- * @returns {{ ok: boolean, code: number|null, stdout: string, stderr: string, json: object|null, unavailable: boolean }}
73
- */
74
- export function runMorphSpec(args, { cwd, timeoutMs = 120000, env } = {}) {
75
- const runEnv = env || process.env;
76
- const argv = Array.isArray(args) ? args.map(String) : [];
77
-
78
- for (const cand of candidates(runEnv)) {
79
- let r;
80
- try {
81
- const full = [...cand.args, ...argv];
82
- r = cand.shell
83
- ? spawnSync(quoteForCmd(cand.file), full.map(quoteForCmd), { cwd, env: runEnv, encoding: 'utf8', timeout: timeoutMs, shell: true, stdio: ['ignore', 'pipe', 'pipe'] })
84
- : spawnSync(cand.file, full, { cwd, env: runEnv, encoding: 'utf8', timeout: timeoutMs, shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
85
- } catch (err) {
86
- if (err?.code === 'ENOENT') continue;
87
- return { ok: false, code: null, stdout: '', stderr: String(err?.message || err), json: null, unavailable: false };
88
- }
89
- if (r.error) {
90
- if (r.error.code === 'ENOENT') continue;
91
- return { ok: false, code: null, stdout: r.stdout || '', stderr: String(r.error.message || r.error), json: null, unavailable: false };
92
- }
93
- const stdout = r.stdout || '';
94
- const stderr = r.stderr || '';
95
- // Shell and npx report "not found" as a non-zero exit, never ENOENT; the explicit
96
- // MORPH_SPEC_BIN is excluded so a real morph-spec failure is never read as absence.
97
- if (cand.kind !== 'env' && r.status !== 0 && !stdout.trim() && NOT_FOUND_RE.test(stderr)) continue;
98
- return { ok: r.status === 0, code: r.status, stdout, stderr, json: lastJsonLine(stdout), unavailable: false };
99
- }
100
-
101
- return { ok: false, code: null, stdout: '', stderr: 'morph-spec CLI not found (MORPH_SPEC_BIN, PATH, npx)', json: null, unavailable: true };
102
- }