@polymorphism-tech/morph-spec 10.12.1 → 11.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (323) hide show
  1. package/CLAUDE.md +27 -57
  2. package/README.md +53 -338
  3. package/bin/morph-spec.js +22 -373
  4. package/docs/CHEATSHEET.md +37 -166
  5. package/docs/QUICKSTART.md +14 -74
  6. package/framework/CLAUDE.md +15 -26
  7. package/framework/MORPH.md +34 -101
  8. package/framework/agents.json +12 -9
  9. package/framework/commands/morph-apply.md +5 -5
  10. package/framework/commands/morph-infra.md +1 -1
  11. package/framework/docs/CLI.md +74 -886
  12. package/framework/evals/review-checklist.md +14 -14
  13. package/framework/hooks/README.md +21 -189
  14. package/framework/hooks/claude-code/core/README.md +2 -5
  15. package/framework/hooks/claude-code/core/conventional-commit.js +2 -2
  16. package/framework/hooks/claude-code/core/denylist.json +3 -3
  17. package/framework/hooks/claude-code/core/graph-refresh-kick.js +2 -2
  18. package/framework/hooks/claude-code/core/masked-exit.js +6 -6
  19. package/framework/hooks/claude-code/core/pre-bash-denylist.js +2 -2
  20. package/framework/hooks/claude-code/core/protect-spec-files.js +17 -61
  21. package/framework/hooks/claude-code/core/stack-changed.js +35 -0
  22. package/framework/hooks/claude-code/core/validate-completion.js +32 -87
  23. package/framework/hooks/shared/{heavy-command.js → command-kind.js} +6 -79
  24. package/framework/hooks/shared/command-tokens.js +0 -139
  25. package/framework/hooks/shared/contract.js +14 -0
  26. package/framework/hooks/shared/feature-slug.js +21 -0
  27. package/framework/hooks/shared/frontend-locations.js +0 -1
  28. package/framework/hooks/shared/git-paths.js +0 -15
  29. package/framework/hooks/shared/graph-freshness.js +0 -19
  30. package/framework/hooks/shared/hook-response.js +0 -7
  31. package/framework/hooks/shared/morph-cli.js +2 -81
  32. package/framework/hooks/shared/owner-words.js +2 -120
  33. package/framework/hooks/shared/payload-utils.js +0 -39
  34. package/framework/hooks/shared/report-progress.js +7 -101
  35. package/framework/hooks/statusline.js +16 -60
  36. package/framework/mcp/registry.json +2 -2
  37. package/framework/rules/ai-agents-standards.md +1 -1
  38. package/framework/rules/asaas-standards.md +1 -1
  39. package/framework/rules/ef-standards.md +1 -1
  40. package/framework/rules/gsap-standards.md +1 -1
  41. package/framework/rules/hangfire-standards.md +1 -1
  42. package/framework/rules/implement-report.md +3 -3
  43. package/framework/rules/neon-auth-standards.md +1 -1
  44. package/framework/rules/nextjs-standards.md +1 -1
  45. package/framework/rules/plan-grammar.md +15 -13
  46. package/framework/rules/resend-standards.md +1 -1
  47. package/framework/rules/ui-design.md +5 -1
  48. package/framework/schemas/config.schema.json +95 -310
  49. package/framework/skills/README.md +12 -32
  50. package/framework/skills/core/create-umbraco-lp/SKILL.md +1 -1
  51. package/framework/skills/core/migrate-lp-to-umbraco/SKILL.md +1 -1
  52. package/framework/skills/core/morph-apply/SKILL.md +21 -46
  53. package/framework/skills/core/morph-plan/SKILL.md +28 -63
  54. package/framework/skills/core/morph-uiux/SKILL.md +23 -25
  55. package/framework/{templates/docs/ui-mockups.md → skills/core/morph-uiux/references/mockups.md} +4 -4
  56. package/framework/standards/STANDARDS.json +10 -11
  57. package/framework/standards/STANDARDS.meta.json +1 -1
  58. package/framework/standards/ai-agents/evals-with-cache.md +18 -32
  59. package/framework/standards/ai-agents/observability-patterns.md +2 -2
  60. package/framework/standards/architecture/code-comments.md +2 -5
  61. package/framework/standards/architecture/engineering-lens.md +1 -1
  62. package/framework/standards/backend/dotnet/testing.md +4 -4
  63. package/framework/standards/frontend/nextjs/lint.md +24 -10
  64. package/framework/standards/frontend/nextjs/testing.md +2 -2
  65. package/framework/standards/infrastructure/docker/local-compose-isolation.md +14 -30
  66. package/framework/templates/CLAUDE.md.core.guide.md +2 -2
  67. package/framework/templates/README.md +1 -1
  68. package/framework/templates/REGISTRY.json +3 -33
  69. package/framework/templates/docs/plan.md +3 -2
  70. package/framework/templates/dotnet/ai-kit/README.md +2 -4
  71. package/framework/templates/dotnet/ai-kit/src/Morph.AiKit/Evals/EvalCacheMissException.cs +1 -1
  72. package/framework/templates/dotnet/ai-kit/src/Morph.AiKit/Evals/EvalFixture.cs +1 -1
  73. package/package.json +1 -2
  74. package/src/commands/graph/explain.js +2 -1
  75. package/src/commands/graph/status.js +2 -1
  76. package/src/commands/mcp/mcp-setup.js +1 -2
  77. package/src/commands/project/doctor.js +13 -342
  78. package/src/commands/project/env.js +21 -52
  79. package/src/commands/project/init-contract.js +47 -0
  80. package/src/commands/project/init.js +36 -66
  81. package/src/commands/project/stack-scan.js +1 -1
  82. package/src/commands/project/update.js +16 -53
  83. package/src/commands/validation/check.js +128 -0
  84. package/src/commands/validation/plan-check.js +41 -64
  85. package/src/commands/validation/prove-red.js +1 -1
  86. package/src/core/paths/output-schema.js +0 -22
  87. package/src/core/templates/template-renderer.js +0 -14
  88. package/src/lib/ai/ai-project-scan.js +1 -6
  89. package/src/lib/check/attempts.js +38 -0
  90. package/src/lib/check/signals.js +145 -0
  91. package/src/lib/config/project-config.js +13 -0
  92. package/src/lib/contract/apply.js +62 -0
  93. package/src/lib/contract/defaults.js +96 -0
  94. package/src/lib/contract/merge.js +79 -0
  95. package/src/lib/contract/ports.js +43 -0
  96. package/src/lib/contract/scan.js +102 -0
  97. package/src/lib/detectors/claude-config-detector.js +7 -0
  98. package/src/lib/{procs → detectors}/mcp-config.js +1 -37
  99. package/src/lib/diff/diff-lines.js +64 -0
  100. package/src/lib/generators/architecture-scanner.js +1 -1
  101. package/src/lib/generators/scaffold-generator.js +0 -7
  102. package/src/lib/git/default-branch.js +0 -122
  103. package/src/lib/graph/diff-tree.js +2 -1
  104. package/src/lib/graph/god-nodes.js +2 -1
  105. package/src/lib/graph/graphify-runtime.js +0 -1
  106. package/src/lib/graph/graphifyignore.js +1 -1
  107. package/src/lib/graph/sanitize.js +2 -8
  108. package/src/lib/installers/memory-installer.js +15 -30
  109. package/src/lib/installers/stack-sync.js +16 -9
  110. package/src/lib/plan/checks.js +20 -64
  111. package/src/lib/plan/media.js +1 -1
  112. package/src/lib/plan/plan-parser.js +5 -5
  113. package/src/lib/review-reports.js +3 -77
  114. package/src/lib/scan/worktree-dirs.js +3 -0
  115. package/src/lib/specs/adr-index.js +2 -2
  116. package/src/lib/stack/dotnet-build-ignores.js +10 -2
  117. package/src/lib/stack/stack-scan.js +2 -2
  118. package/src/lib/stack-filter.js +3 -2
  119. package/src/lib/tests-audit/audit.js +1 -1
  120. package/src/scripts/setup-infra.js +6 -59
  121. package/src/utils/agents-installer.js +13 -37
  122. package/src/utils/atomic-json.js +27 -0
  123. package/src/utils/file-copier.js +24 -24
  124. package/src/utils/hooks-installer.js +9 -107
  125. package/claude-plugin.json +0 -14
  126. package/framework/commands/morph-archive.md +0 -46
  127. package/framework/commands/morph-hotfix.md +0 -17
  128. package/framework/commands/morph-preflight.md +0 -180
  129. package/framework/commands/morph-review.md +0 -15
  130. package/framework/commands/morph-status.md +0 -37
  131. package/framework/hooks/claude-code/core/block-destructive-worktree-removal.js +0 -80
  132. package/framework/hooks/claude-code/core/block-raw-worktree-add.js +0 -72
  133. package/framework/hooks/claude-code/core/enforce-phase-writes.js +0 -100
  134. package/framework/hooks/claude-code/core/gate-guard.js +0 -148
  135. package/framework/hooks/claude-code/core/heavy-gate.js +0 -78
  136. package/framework/hooks/claude-code/core/heavy-release.js +0 -23
  137. package/framework/hooks/claude-code/core/loop-detect.js +0 -79
  138. package/framework/hooks/claude-code/core/state-sync.js +0 -214
  139. package/framework/hooks/claude-code/core/telemetry-log.js +0 -259
  140. package/framework/hooks/claude-code/core/test-budget.js +0 -29
  141. package/framework/hooks/claude-code/core/worktree-context.js +0 -249
  142. package/framework/hooks/claude-code/core/worktree-create.js +0 -119
  143. package/framework/hooks/claude-code/core/worktree-env-inject.js +0 -68
  144. package/framework/hooks/claude-code/core/worktree-remove.js +0 -55
  145. package/framework/hooks/shared/build-check.js +0 -120
  146. package/framework/hooks/shared/claim-registry.js +0 -125
  147. package/framework/hooks/shared/e2e-check.js +0 -1022
  148. package/framework/hooks/shared/feature-locator.js +0 -82
  149. package/framework/hooks/shared/gate-event.js +0 -18
  150. package/framework/hooks/shared/gate-question.js +0 -20
  151. package/framework/hooks/shared/heavy-config.js +0 -113
  152. package/framework/hooks/shared/heavy-holders.js +0 -85
  153. package/framework/hooks/shared/heavy-slots.js +0 -280
  154. package/framework/hooks/shared/host-services.js +0 -440
  155. package/framework/hooks/shared/next-step.js +0 -181
  156. package/framework/hooks/shared/redact-secrets.js +0 -44
  157. package/framework/hooks/shared/reparse-scan.js +0 -40
  158. package/framework/hooks/shared/state-reader.js +0 -220
  159. package/framework/hooks/shared/state-writer.js +0 -112
  160. package/framework/hooks/shared/telemetry-logger.js +0 -101
  161. package/framework/hooks/shared/transcript-usage.js +0 -58
  162. package/framework/hooks/shared/worktree-root.js +0 -71
  163. package/framework/phases.json +0 -92
  164. package/framework/schemas/feature.schema.json +0 -242
  165. package/framework/skills/core/morph-apply/references/hotfix.md +0 -46
  166. package/framework/skills/core/morph-apply/references/machine.md +0 -30
  167. package/framework/skills/core/morph-apply/references/review.md +0 -77
  168. package/framework/skills/core/morph-plan/references/critique.md +0 -51
  169. package/framework/skills/core/morph-plan/references/interview.md +0 -37
  170. package/framework/templates/state.template.json +0 -17
  171. package/src/commands/dashboard/dashboard.js +0 -74
  172. package/src/commands/e2e/e2e.js +0 -400
  173. package/src/commands/observability/cost.js +0 -283
  174. package/src/commands/project/branch.js +0 -129
  175. package/src/commands/project/claim.js +0 -132
  176. package/src/commands/project/doctor-procs.js +0 -162
  177. package/src/commands/project/fleet.js +0 -66
  178. package/src/commands/project/heavy.js +0 -81
  179. package/src/commands/project/install-plugin-cmd.js +0 -27
  180. package/src/commands/project/status.js +0 -61
  181. package/src/commands/project/worktree.js +0 -1234
  182. package/src/commands/state/advance.js +0 -248
  183. package/src/commands/state/approve.js +0 -303
  184. package/src/commands/state/archive.js +0 -231
  185. package/src/commands/state/auto-approval.js +0 -67
  186. package/src/commands/state/create.js +0 -274
  187. package/src/commands/state/delete.js +0 -192
  188. package/src/commands/state/finish.js +0 -1247
  189. package/src/commands/state/gate-check.js +0 -244
  190. package/src/commands/state/gate-decision.js +0 -122
  191. package/src/commands/state/list.js +0 -244
  192. package/src/commands/state/next.js +0 -24
  193. package/src/commands/state/recap.js +0 -80
  194. package/src/commands/state/report-check.js +0 -244
  195. package/src/commands/state/retype.js +0 -110
  196. package/src/commands/validation/verify.js +0 -421
  197. package/src/core/state/feature-identity.js +0 -10
  198. package/src/core/state/gate-order.js +0 -23
  199. package/src/core/state/lifecycle-audit.js +0 -171
  200. package/src/core/state/state-manager.js +0 -523
  201. package/src/core/templates/template-seed.js +0 -21
  202. package/src/core/work-types.js +0 -44
  203. package/src/dashboard/app/App.jsx +0 -84
  204. package/src/dashboard/app/components/ActivityFeed.jsx +0 -166
  205. package/src/dashboard/app/components/CommandPalette.jsx +0 -144
  206. package/src/dashboard/app/components/DetailPanel.jsx +0 -43
  207. package/src/dashboard/app/components/EntityLink.jsx +0 -42
  208. package/src/dashboard/app/components/ErrorBoundary.jsx +0 -47
  209. package/src/dashboard/app/components/FlowGraph.jsx +0 -19
  210. package/src/dashboard/app/components/GatePauses.jsx +0 -116
  211. package/src/dashboard/app/components/KnowledgeMarkdown.jsx +0 -42
  212. package/src/dashboard/app/components/Markdown.jsx +0 -38
  213. package/src/dashboard/app/components/PhaseRail.jsx +0 -100
  214. package/src/dashboard/app/components/SearchFilter.jsx +0 -36
  215. package/src/dashboard/app/components/SessionMap.jsx +0 -77
  216. package/src/dashboard/app/components/Sidebar.jsx +0 -147
  217. package/src/dashboard/app/hooks/useMorphQuery.js +0 -44
  218. package/src/dashboard/app/hooks/usePref.js +0 -34
  219. package/src/dashboard/app/lib/format.js +0 -69
  220. package/src/dashboard/app/lib/phases.js +0 -75
  221. package/src/dashboard/app/lib/project.js +0 -38
  222. package/src/dashboard/app/main.jsx +0 -13
  223. package/src/dashboard/app/pages/Activity.jsx +0 -28
  224. package/src/dashboard/app/pages/AgentMap.jsx +0 -363
  225. package/src/dashboard/app/pages/FeatureDetail.jsx +0 -579
  226. package/src/dashboard/app/pages/Features.jsx +0 -393
  227. package/src/dashboard/app/pages/Guide.jsx +0 -145
  228. package/src/dashboard/app/pages/HookInspector.jsx +0 -444
  229. package/src/dashboard/app/pages/PhasePipeline.jsx +0 -273
  230. package/src/dashboard/app/pages/Portfolio.jsx +0 -190
  231. package/src/dashboard/app/pages/RulesMap.jsx +0 -285
  232. package/src/dashboard/app/pages/SkillsLibrary.jsx +0 -468
  233. package/src/dashboard/app/pages/Standards.jsx +0 -392
  234. package/src/dashboard/app/styles/index.css +0 -187
  235. package/src/dashboard/index.html +0 -14
  236. package/src/dashboard/package.json +0 -32
  237. package/src/dashboard/scanner/activity-scanner.js +0 -321
  238. package/src/dashboard/scanner/agents-scanner.js +0 -67
  239. package/src/dashboard/scanner/docs-scanner.js +0 -34
  240. package/src/dashboard/scanner/feature-status.js +0 -7
  241. package/src/dashboard/scanner/features-scanner.js +0 -397
  242. package/src/dashboard/scanner/hooks-scanner.js +0 -96
  243. package/src/dashboard/scanner/index.js +0 -21
  244. package/src/dashboard/scanner/phases-scanner.js +0 -14
  245. package/src/dashboard/scanner/portfolio.js +0 -129
  246. package/src/dashboard/scanner/project-api.js +0 -160
  247. package/src/dashboard/scanner/rules-scanner.js +0 -46
  248. package/src/dashboard/scanner/skills-scanner.js +0 -104
  249. package/src/dashboard/scanner/standards-scanner.js +0 -38
  250. package/src/dashboard/vite-plugin-morph-data.js +0 -120
  251. package/src/dashboard/vite.config.js +0 -26
  252. package/src/lib/ci/ci-verify.js +0 -30
  253. package/src/lib/ci/github-ci.js +0 -52
  254. package/src/lib/ci/pr-checks.js +0 -76
  255. package/src/lib/e2e/applicability.js +0 -39
  256. package/src/lib/e2e/compose-env.js +0 -80
  257. package/src/lib/e2e/stack-teardown.js +0 -96
  258. package/src/lib/git/branch-classifier.js +0 -104
  259. package/src/lib/git/evidence-staleness.js +0 -40
  260. package/src/lib/git/gh.js +0 -15
  261. package/src/lib/git/pending-prs.js +0 -58
  262. package/src/lib/git/pr-files.js +0 -31
  263. package/src/lib/git/pr-index.js +0 -39
  264. package/src/lib/git/tree-fingerprint.js +0 -58
  265. package/src/lib/git/tree-state.js +0 -125
  266. package/src/lib/heavy/cleanup.js +0 -72
  267. package/src/lib/heavy/gate.js +0 -168
  268. package/src/lib/heavy/live-stacks.js +0 -64
  269. package/src/lib/heavy/reclaim.js +0 -107
  270. package/src/lib/heavy/watchdog.js +0 -46
  271. package/src/lib/next-step.js +0 -12
  272. package/src/lib/plan/critique.js +0 -67
  273. package/src/lib/plan/plan-template.js +0 -18
  274. package/src/lib/procs/classify.js +0 -91
  275. package/src/lib/procs/list.js +0 -124
  276. package/src/lib/procs/prune.js +0 -47
  277. package/src/lib/procs/wslconfig.js +0 -70
  278. package/src/lib/projects/registry.js +0 -121
  279. package/src/lib/recap/piper.js +0 -36
  280. package/src/lib/recap/recap.js +0 -259
  281. package/src/lib/review-confirmation.js +0 -66
  282. package/src/lib/risk/diff-risk.js +0 -137
  283. package/src/lib/risk-detector.js +0 -638
  284. package/src/lib/specs/design-seed.js +0 -18
  285. package/src/lib/specs/screen-checklist.js +0 -315
  286. package/src/lib/stack/stack-profile.js +0 -69
  287. package/src/lib/tasks/eval-node.js +0 -293
  288. package/src/lib/tasks/linux-runner.js +0 -200
  289. package/src/lib/tasks/test-nodes.js +0 -414
  290. package/src/lib/tasks/test-runner.js +0 -569
  291. package/src/lib/telemetry/metrics.js +0 -384
  292. package/src/lib/telemetry/telemetry-reader.js +0 -276
  293. package/src/lib/telemetry/verify-event.js +0 -57
  294. package/src/lib/validators/code-budget/code-budget-validator.js +0 -170
  295. package/src/lib/validators/contracts/contract-compliance-validator.js +0 -219
  296. package/src/lib/validators/nextjs/next-component-validator.js +0 -142
  297. package/src/lib/validators/packages/package-validator.js +0 -310
  298. package/src/lib/validators/reuse/reuse-validator.js +0 -202
  299. package/src/lib/validators/reuse/symbol-scanner.js +0 -64
  300. package/src/lib/validators/validation-runner.js +0 -188
  301. package/src/lib/validators/verify-cache.js +0 -63
  302. package/src/lib/validators/verify-runner.js +0 -971
  303. package/src/lib/verify/affected.js +0 -143
  304. package/src/lib/verify/detached.js +0 -159
  305. package/src/lib/view/feature-html.js +0 -480
  306. package/src/lib/view/feature-page.client.js +0 -109
  307. package/src/lib/view/feature-page.css +0 -278
  308. package/src/lib/view/feature-view.js +0 -113
  309. package/src/lib/view/flow-layers.js +0 -79
  310. package/src/lib/view/flow-svg.js +0 -63
  311. package/src/lib/view/tokens.css +0 -18
  312. package/src/lib/work-type-detector.js +0 -81
  313. package/src/lib/worktree/dirs.js +0 -3
  314. package/src/lib/worktree/docker-audit.js +0 -175
  315. package/src/lib/worktree/env-allocator.js +0 -177
  316. package/src/lib/worktree/feature-truth.js +0 -145
  317. package/src/lib/worktree/finish-backup.js +0 -529
  318. package/src/lib/worktree/fleet-scanner.js +0 -223
  319. package/src/lib/worktree/ignored-triage.js +0 -136
  320. package/src/lib/worktree/vscode-settings.js +0 -112
  321. package/src/lib/worktree/worktree-audit.js +0 -323
  322. package/src/lib/worktree/worktree-include.js +0 -44
  323. package/src/scripts/install-plugin.js +0 -114
@@ -1,4 +1,4 @@
1
- # Checklist do Gate 3 — verificador, revisor, segurança
1
+ # Checklist da revisão — verificador, revisor, segurança
2
2
 
3
3
  Três agentes em contexto fresco, cada um com o seu relatório em `4-review/`. Ninguém dá nota. Cada
4
4
  relatório começa igual e é append-only (vale o último `**Verdict:**`):
@@ -18,7 +18,7 @@ relatório começa igual e é append-only (vale o último `**Verdict:**`):
18
18
  - (o que melhoraria, sem bloquear)
19
19
  ```
20
20
 
21
- O `**Reviewed-SHA:**` é obrigatório: o `approve` recusa relatório sem ele ou de outro sha. Sem bloqueador, escreva `Nenhum.` na seção. `SHIP` com bloqueador aberto é contradição e pausa o gate.
21
+ O `**Reviewed-SHA:**` é obrigatório: é o commit que você julgou, e relatório sem ele ou de outro sha não vale. Sem bloqueador, escreva `Nenhum.` na seção. `SHIP` com bloqueador aberto é contradição: o `check --report` lê como pedido de correção.
22
22
  Confirmação depois de uma correção: seção nova ao fim com `**Verdict:**` e o `**Reviewed-SHA:**` novo —
23
23
  julgando só os seus bloqueadores, ou, sem eles, só o delta `{sha anterior}..{sha novo}`. Bloqueador
24
24
  que a correção fechou sai de `## Bloqueadores` (escreva `Nenhum.`) e o fechamento vai em `## Notas`;
@@ -42,7 +42,7 @@ diferente") é nota; nota não bloqueia e não pede rodada nova. Na dúvida, sem
42
42
  ## Verificador (`4-review/verifier.md`)
43
43
 
44
44
  Missão: **fazer cada cenário acontecer** e dizer se o resultado é o que o `2-plan/checks.json`
45
- promete. Você recebe os cenários, a URL da app e o comando de reset — não o plano, o diff nem o relato
45
+ promete. Você recebe os cenários e a URL da app — não o plano, o diff nem o relato
46
46
  de quem implementou, de propósito: você prova o comportamento, não a versão dele que o implementador
47
47
  conta. O default de todo `Cn` é NÃO PROVADO; o que você não executou (ou, em `leitura`, não leu)
48
48
  nunca vira PROVADO por inferência.
@@ -56,17 +56,17 @@ nunca vira PROVADO por inferência.
56
56
  | C2 | FALHA | /tenants?status=ativo lista 3 inativos (print `4-review/c2.png`) |
57
57
  ```
58
58
 
59
- Uma linha por cenário, status exato `PROVADO`, `NÃO PROVADO` ou `FALHA`. O gate pausa com cenário
60
- sem linha ou não PROVADO. Numa confirmação, uma `## Checks` nova só com os Cn pedidos: vale a última
59
+ Uma linha por cenário, status exato `PROVADO`, `NÃO PROVADO` ou `FALHA`. Cenário sem linha ou não
60
+ PROVADO sai no `## Resultado` como `nao-provado`. Numa confirmação, uma `## Checks` nova só com os Cn pedidos: vale a última
61
61
  linha de cada Cn.
62
62
 
63
63
  **Como provar, pelo `prova:` do Cn:**
64
64
 
65
65
  | `prova:` | Execução |
66
66
  |---|---|
67
- | `e2e` | Navegue o fluxo com o Playwright MCP na URL do dispatch, como o usuário faria, disparando a ação até o efeito (controle presente não prova nada); confira o resultado na tela, no console e no network. Rode `morph-spec e2e reset {feature}` **antes de cada fluxo**: estado de um fluxo nunca prova o seguinte. |
68
- | `teste` | Ache o teste que cobre o Cn e rode **só ele**, pelo filtro do próprio runner (`dotnet test --filter <nome>`, `node --test <arquivo>`, `npx vitest run <arquivo> -t <nome>`, `npx playwright test <arquivo>`). `verify --filter` escolhe um nó inteiro da suíte: só serve quando o nó é esse teste. Verde não basta: leia o teste — ele morde? Nasceu afirmando o que já era verdade, só testa a recusa e nunca a escrita, ou o assert passa pelo motivo errado → bloqueador `teste`. Sem teste para um Cn com `risco:` → `teste`. |
69
- | `eval` | Rode o nó de evals filtrado (`--filter <nó-evals> --skip-e2e --no-persist`) e compare a saída com o cenário. |
67
+ | `e2e` | Navegue o fluxo com o Playwright MCP na URL do dispatch, como o usuário faria, disparando a ação até o efeito (controle presente não prova nada); confira o resultado na tela, no console e no network. Volte o dado ao estado de partida **antes de cada fluxo**: estado de um fluxo nunca prova o seguinte. |
68
+ | `teste` | Ache o teste que cobre o Cn e rode **só ele**, pelo filtro do próprio runner (`dotnet test --filter <nome>`, `node --test <arquivo>`, `npx vitest run <arquivo> -t <nome>`, `npx playwright test <arquivo>`). Verde não basta: leia o teste — ele morde? Nasceu afirmando o que já era verdade, só testa a recusa e nunca a escrita, ou o assert passa pelo motivo errado → bloqueador `teste`. Sem teste para um Cn com `risco:` → `teste`. |
69
+ | `eval` | Rode só a eval do cenário e compare a saída com ele. |
70
70
  | `leitura` | `arquivo:linha` do código que entrega o cenário e a **fiação**: caminho da entrada real ao efeito (a camada pura não prova que o handler a chama). Sem teste, e pedir teste não é bloqueador. |
71
71
  | `manual` | Reproduza o passo de `3-implement/evidencias/{Cn}.md` e diga se o resultado bate. |
72
72
 
@@ -74,17 +74,17 @@ Verificações mecânicas valem para todo Cn de backend (.NET minimal API / Next
74
74
  lambda de endpoint registrado em `Program.cs`; prefixo de rota server-direct e de proxy como
75
75
  constantes distintas.
76
76
 
77
- Você não roda a suíte inteira nem `verify` sem filtro (o hook `test-budget` nega): antes do dispatch
78
- rodaram os testes que o diff alcança, e a suíte completa roda depois dos relatórios. Stack fora do ar ou URL ausente: os `e2e` ficam NÃO PROVADO com o motivo — achado de
77
+ Você não roda a suíte inteira (é do `morph-spec check --tier full`): antes do dispatch rodaram
78
+ os testes do contrato, e a suíte completa roda de novo no `check --report`. Stack fora do ar ou URL ausente: os `e2e` ficam NÃO PROVADO com o motivo — achado de
79
79
  infra, não defeito seu a provar; não suba nem derrube o stack.
80
80
 
81
81
  **Feature que gera mídia** (o `plan.md` cita um standard de mídia): grave `## Mídia gerada`, uma
82
82
  linha por afirmação — custo controlado, revisão humana, mídia marcada, hot path não bloqueado —, cada
83
83
  uma com o código que a prende e o teste que a prova. A régua de cada afirmação está em
84
84
  `.morph/framework/standards/ai-agents/modalities-image-gen.md`, `ai-agents/media-video.md` e
85
- `ai-agents/media-pipeline.md`. Afirmação falsa é bloqueador. Sem a seção, o gate pausa.
85
+ `ai-agents/media-pipeline.md`. Afirmação falsa é bloqueador. A seção é obrigatória.
86
86
 
87
- **Prompt ou modelo alterado**: o nó `evals` do verify é a prova; sem ele, o gate pausa sozinho.
87
+ **Prompt ou modelo alterado**: a eval é a prova; sem eval rodada, o Cn fica NÃO PROVADO.
88
88
 
89
89
  **Contrato de tela** (`1-design/mockups.md` com `## Tela:`): grave `## Checklist de tela`, uma linha por
90
90
  item decidido de cada tela:
@@ -93,8 +93,8 @@ item decidido de cada tela:
93
93
 
94
94
  Veredito `cumpre` / `diverge` / `não verificável` (com o motivo). Paginação, ordenação ou filtro que o
95
95
  checklist põe no servidor e a tela faz em memória, ou estado vazio/carregando/erro decidido e
96
- ausente, é bloqueador `check`. Divergência registrada em `plan.md ## Decisões` é nota. Sem a seção,
97
- havendo item decidido, o gate pausa.
96
+ ausente, é bloqueador `check`. Divergência registrada em `plan.md ## Decisões` é nota. Havendo item
97
+ decidido, a seção é obrigatória.
98
98
 
99
99
  ## Revisor (`4-review/reviewer.md`)
100
100
 
@@ -1,198 +1,30 @@
1
- # MORPH-SPEC Hooks Architecture (v2)
1
+ # MORPH-SPEC Hooks
2
2
 
3
- Comprehensive hooks system for enforcing spec-driven development at the Claude Code level.
4
-
5
- ## Architecture
3
+ Guardrails silenciosos: nenhum hook orquestra, decide fase ou roda teste. Todo hook é fail-open —
4
+ sem contrato (`.morph/config/config.json`) ou com qualquer erro, não faz nada.
6
5
 
7
6
  ```
8
7
  framework/hooks/
9
- ├── claude-code/
10
- │ └── core/ # every hook, plus chain.js (one process per multi-hook group)
11
- ├── shared/ # code hooks share (and src/ imports): state reader, guards, e2e, heavy, telemetry
12
- ├── statusline.js # global statusline, not a hook: phase and scenarios through the project's .morph/framework/hooks/shared
13
- └── README.md
14
- ```
15
-
16
- The registered set is `MORPH_HOOKS` in `src/utils/hooks-installer.js` — the table below lists it. No hook builds,
17
- typechecks or runs tests: that is `morph-spec verify`.
18
-
19
- ## Hook Events
20
-
21
- | Event | Hook | Type | Purpose |
22
- |-------|------|------|---------|
23
- | **SessionStart** | worktree-context.js | Context inject | Secondary worktree → feature identity (name/branch/phase) + missing-junction warning; primary root → active-feature summary (phase, slices done/total, pending gates), silent if none. Also seeds a worktree that has no codebase graph from the root's, and launches the background refresh of the ROOT's graph (`shared/graph-refresh.js`) |
24
- | **PreToolUse** (Write\|Edit) | _(native permissions.deny)_ | Block | Blocks edits to state.json and .morph/framework/ |
25
- | **PreToolUse** (Write\|Edit) | protect-spec-files.js | Block | Blocks edits to `plan.md` (and the uiux artifacts) after their gate is approved; an append-only `## Errata` block at the end of `plan.md` passes. A plan gate stamped by policy (chore, hotfix) freezes only once plan-check wrote `checks.json` |
26
- | **PreToolUse** (Write\|Edit) | enforce-phase-writes.js | Block | Ensures writes go to current phase directory |
27
- | **PreToolUse** (Bash) | pre-bash-denylist.js | Block | Blocks `rm -rf .morph/` and direct state edits |
28
- | **PreToolUse** (Bash) | conventional-commit.js | Block | Blocks a `git commit -m` whose subject is not Conventional Commits (`<type>(<scope>): <subject>`); a `$(…)`/heredoc message, `-F` and git-generated `Merge`/`Revert` pass |
29
- | **PreToolUse** (Bash) | block-destructive-worktree-removal.js | Block | Blocks `git worktree remove` / `rm -rf` / `Remove-Item -Recurse` on a directory holding reparse points (the infra junctions a raw removal would FOLLOW out, emptying the root's `.claude/`); names `morph-spec worktree remove` |
30
- | **PreToolUse** (Bash) | block-raw-worktree-add.js | Block | Blocks raw `git worktree add` (a tree with no junctions → no hooks, no port block, no identity, outside `worktrees/`); names `morph-spec worktree setup <feature>` / `worktree provision <name> --base <ref>`. `list`/`prune`/`remove`/`lock`/`move`/`repair` pass. Also blocks any `git` whose dir (cwd, `cd`, `-C`) is a `worktrees/<x>` folder without its `.git` file: git would walk up and act on the root's default branch; names `worktree remove --target` |
31
- | **WorktreeCreate** | worktree-create.js | Replaces native | Fires for `claude -w`, EnterWorktree and `Agent isolation:"worktree"`; replaces Claude Code's bare `git worktree add`. Runs `morph-spec worktree setup <n>` (known feature) or `worktree provision <n>` (task tree, branch `morph-task/<n>`), bases a task tree on the default branch, prints the path as its last stdout line. CLI unreachable → plain git, still under `<root>/worktrees/` |
32
- | **WorktreeRemove** | worktree-remove.js | Fail-open | Routes Claude Code's own cleanup through `morph-spec worktree remove --target --if-clean` (junctions dropped first; a dirty tree is left alone). Always exit 0. Secondary net — the event was observed NOT to fire headless; the Bash guard above stays the primary defense |
33
- | **PostToolUse** (Write\|Edit) | comment-guard.js | Blocking | Blocks when the edit ADDED a comment the `architecture-code-comments` standard never allows: process history (ADR, scenario/slice id, gate, plan.md), banner/`#region`, a block over 3 lines, or a doc-comment outside a published package. Old comments are never reported; last link of the chain |
34
- | **PostToolUse** (Write\|Edit\|AskUserQuestion) | state-sync.js | State sync | Autonomous state updates (feature register, output tracking, gate approval) |
35
- | **PostToolUse** (Write\|Edit\|AskUserQuestion) | gate-guard.js | Advisory | Warns (never blocks) when a gate action disagrees with the persisted gateDecisions |
36
- | **PostToolUse** (all tools) | telemetry-log.js | Telemetry | Appends every tool call (skill, sub-agent dispatch + prompt, knowledge-base read, bash/edit) to `.morph/logs/events.jsonl`; silent, fail-open — the NLH execution-path capture read back by `morph-spec cost` |
37
- | **PostToolUse** (all tools) | loop-detect.js | Advisory | Warns when the last 8 actions collapse to ≤2 unique signatures |
38
- | **PostToolUse** (all tools) | graph-refresh-kick.js | Background | After a Bash or PowerShell command that runs git/gh/morph-spec, launches the DETACHED refresh of the ROOT's codebase graph (`shared/graph-refresh.js`: cwd in the git common dir, never a worktree; one lock per repository; staleness by `shared/graph-freshness.js` — stamp plus the per-tree run record in `<git-common-dir>/morph-spec/graph-refresh-state.json`); never waits, never injects |
39
- | **PostToolUse** (all tools) | masked-exit.js | Advisory | After a Bash test/build/verify run (`testRunKind`/`morphVerifyCall`/`heavyKind` of the producer) whose exit `exitCodeMasked` hides (`\| tail`, `; echo`, `\|\| true`, `&`), names the form and says to write the output to `.morph/logs/test-last.log` and read it; silent when the command prints `$?`/`PIPESTATUS` |
40
- | **PostToolUseFailure** (all tools) | telemetry-log.js | Telemetry | The failed call (a Bash that exits non-zero fires only this event): exit code parsed from the `Exit code N` line, outcome and duration — never the error body |
41
- | **PostToolBatch** | telemetry-log.js | Telemetry | One `ToolBatch` event per model turn that used tools (the turn counter of `cost --metrics`) |
42
- | **SubagentStop** | telemetry-log.js | Telemetry | `AgentUsage`: the sub-agent's token usage read from its own transcript, as a delta per agent; never blocks the stop |
43
- | **UserPromptSubmit** | telemetry-log.js | Telemetry | Appends the user's prompt to the same `events.jsonl` stream; silent, fail-open |
44
- | **Stop** | validate-completion.js | Advisory | Warns about scenarios marked `feito` without evidence in `3-implement/report.md` (hash-deduped, only re-injects when the warning set changes) |
45
-
46
- ## Design Principles
47
-
48
- 1. **Fail-open**: All hooks catch exceptions and `exit 0` — never accidentally block legitimate work
49
- 2. **Non-morph projects**: Every hook checks for `.morph/state.json` first and exits silently if missing
50
- 3. **Performance**: PreToolUse hooks use synchronous state reads for <100ms execution
51
- 4. **Cross-platform**: All hooks use `path.join()`/`path.resolve()`, no hardcoded path separators
52
- 5. **Node.js only**: All hooks use `node` as executor (no PowerShell/bash dependency)
53
-
54
- ## Installation
55
-
56
- Hooks are automatically installed by `morph-spec init` and updated by `morph-spec update`.
57
-
58
- During init/update, the entire `framework/hooks/` directory is copied to `.morph/framework/hooks/`.
59
- Hook commands in `.claude/settings.local.json` reference `$CLAUDE_PROJECT_DIR/.morph/framework/hooks/`
60
- so they work correctly in any project regardless of how morph-spec was installed.
61
-
62
- The installer writes to `.claude/settings.local.json`:
63
-
64
- ```json
65
- {
66
- "hooks": {
67
- "SessionStart": [{ "matcher": "startup|resume|compact", "hooks": [...] }],
68
- "UserPromptSubmit": [{ "hooks": [...] }],
69
- "PreToolUse": [
70
- { "matcher": "Write|Edit", "hooks": [...] },
71
- { "matcher": "Bash", "hooks": [...] }
72
- ],
73
- "PostToolUse": [
74
- { "matcher": "Bash", "hooks": [...] }
75
- ],
76
- "Stop": [{ "hooks": [...] }],
77
- "PreCompact": [{ "hooks": [...] }],
78
- "Notification": [{ "matcher": "idle_prompt", "hooks": [...] }]
79
- }
80
- }
81
- ```
82
-
83
- ## Shared Utilities
84
-
85
- All Claude Code hooks import from `framework/hooks/shared/`:
86
-
87
- | Module | Purpose |
88
- |--------|---------|
89
- | `state-reader.js` | `loadState()`, `getActiveFeature()`, `getFeaturePhase()`, `isGateApproved()`, `getPendingGates()` |
90
- | `phase-utils.js` | Phase constants, path extraction, file classification |
91
- | `hook-response.js` | `block(reason)`, `approve(context)`, `injectContext(text)`, `pass()` |
92
- | `stdin-reader.js` | `readStdin()` — Promise-based stdin JSON reader |
93
- | `telemetry-logger.js` | `appendTelemetryEvent()`, `readTelemetryEvents()` — append-only JSONL event stream (`.morph/logs/events.jsonl`); stamps `schemaVersion`/`eventId` and redacts secrets |
94
- | `redact-secrets.js` | `redactSecrets()` — pattern redaction of obvious secrets in persisted free text |
95
- | `transcript-usage.js` | `readTranscriptUsage()`, `usageDelta()` — token usage of a transcript, deduplicated by message id, and the reset-safe delta between samples |
96
- | `morph-cli.js` | `runMorphSpec(args, { cwd, timeoutMs, env })` — spawns the morph-spec CLI from a hook (`MORPH_SPEC_BIN` → `morph-spec` on PATH → `npx --no-install`); `unavailable: true` when none resolves, never a throw. Hooks may never import from `src/` |
97
- | `command-tokens.js` | `tokenize(command)` — quote-aware shell tokenizer shared by the Bash guards (a hook must never import a sibling hook: its standalone tail would fire); `exitCodeMasked()`/`producerOf()` — whether a pipe hides the exit code, and the command without its output filter |
98
-
99
- `injectContext(text)` is how `worktree-context.js` (and any other SessionStart hook) delivers context: it emits `{ "hookSpecificOutput": { "hookEventName": "SessionStart", "additionalContext": text } }` on stdout. Claude Code only honors additional context nested under `hookSpecificOutput` — a bare top-level field is ignored.
100
-
101
- ## How Hooks Work
102
-
103
- ### PreToolUse (Write|Edit) Flow
104
-
8
+ ├── claude-code/core/ # os hooks, mais chain.js (um processo por grupo de vários hooks)
9
+ ├── shared/ # o código que os hooks dividem (e que src/ importa)
10
+ └── statusline.js # statusline global, não é hook: modelo, contexto, limites, branch e os cenários da feature do branch
105
11
  ```
106
- Claude calls Write/Edit tool
107
- ↓
108
- Claude Code sends JSON to stdin: { tool_input: { file_path: "..." } }
109
- ↓
110
- [native permissions.deny]
111
- ├── Is .morph/state.json? → BLOCK (use CLI)
112
- ├── Is .morph/framework/**? → BLOCK (read-only)
113
- └── Other → continue
114
- ↓
115
- protect-spec-files.js
116
- ├── Is in .morph/features/{feature}/?
117
- │ ├── Is plan.md and plan gate approved? → BLOCK (unless append-only ## Errata)
118
- │ ├── Is a 1-design/ artifact and uiux gate approved? → BLOCK
119
- │ └── Gate not approved → pass
120
- └── Not a feature file → pass
121
- ↓
122
- enforce-phase-writes.js
123
- ├── Is in .morph/features/{feature}/?
124
- │ ├── Phase is implement → pass (unrestricted)
125
- │ ├── Target dir matches phase dir → pass
126
- │ └── Target dir doesn't match → BLOCK
127
- └── Not a feature file → pass
128
- ```
129
-
130
- ### SessionStart Flow
131
-
132
- ```
133
- Session starts/resumes/compacts
134
- ↓
135
- worktree-context.js
136
- ├── No morph project (no state.json AND no .morph/features/) → silent exit
137
- ├── Secondary worktree (git-dir != git-common-dir)?
138
- │ ├── Feature identified (branch morph/{f}, or the lone .morph/features/ dir)
139
- │ │ → inject: "🌳 Worktree desta feature: {f} (branch morph/{f}, fase {phase}).
140
- │ │ Trabalhe apenas nesta feature nesta sessão; o estado vive no .morph/
141
- │ │ deste worktree." + a warning appended if node_modules/.claude
142
- │ │ junctions are missing ("Rode: morph-spec worktree link --all")
143
- │ └── No feature identified → silent exit
144
- └── Primary root (not a worktree)
145
- ├── Has active (in_progress/draft) feature → inject summary:
146
- │ "MORPH-SPEC: feature ativa {name} (fase {phase}) · tasks {c}/{t}
147
- │ · gates pendentes: {gate, gate}"
148
- └── No active feature → silent exit (don't clutter idle sessions)
149
- ```
150
-
151
- v8 note: this hook also fulfills the SessionStart injection role this README
152
- used to describe as `inject-morph-context.js` — that file was documented but
153
- never registered in `MORPH_HOOKS`; `worktree-context.js` is the hook that
154
- actually ships (v3.2.0), and its primary-root branch covers the same
155
- active-feature-summary ground.
156
-
157
- ## Testing
158
-
159
- ```bash
160
- # Run hook tests
161
- npm test -- test/hooks/
162
-
163
- # Run shared utilities tests
164
- npm test -- test/hooks/shared-utils.test.js
165
-
166
- # Run installer tests
167
- npm test -- test/hooks/hooks-installer.test.js
168
- ```
169
-
170
- ## Troubleshooting
171
-
172
- ### Hooks Not Running
173
-
174
- ```bash
175
- # Check if hooks are installed
176
- cat .claude/settings.local.json | jq '.hooks'
177
-
178
- # Reinstall hooks
179
- morph-spec update
180
- ```
181
-
182
- ### Hook Blocking Legitimate Work
183
-
184
- All hooks are fail-open. If a hook is incorrectly blocking:
185
12
 
186
- 1. The hook catches its own errors and exits 0
187
- 2. If truly stuck, remove the specific hook from `.claude/settings.local.json`
188
- 3. Report the issue so the hook logic can be fixed
13
+ O conjunto registrado é `MORPH_HOOKS` em `src/utils/hooks-installer.js`, instalado em `.claude/settings.local.json`:
189
14
 
190
- ### Resetting All Morph Hooks
191
-
192
- ```bash
193
- morph-spec doctor --reset
194
- ```
15
+ | Evento | Hook | Efeito | Para quê |
16
+ |---|---|---|---|
17
+ | PreToolUse `Write\|Edit` | `protect-spec-files.js` | bloqueia | `checks.json` só o `plan-check` escreve; `plan.md` congela depois do `plan-check` — só a `## Errata` no fim passa |
18
+ | PreToolUse `Bash` | `pre-bash-denylist.js` | bloqueia | comandos destrutivos da `denylist.json` (`DROP TABLE`, `rm -rf /`, matar processo por nome…) |
19
+ | PreToolUse `Bash` | `conventional-commit.js` | bloqueia | `git commit -m` fora de Conventional Commits; `$(…)`/heredoc, `-F` e `Merge`/`Revert` passam |
20
+ | PostToolUse `Write\|Edit` | `comment-guard.js` | bloqueia | comentário de forma proibida no trecho adicionado (processo, banner, código comentado, bloco > 3 linhas) |
21
+ | PostToolUse `Bash` | `graph-refresh-kick.js` | silencioso | comando que move o HEAD → refresh do grafo da raiz em segundo plano |
22
+ | PostToolUse `Bash` | `stack-changed.js` | avisa | manifesto da stack mudou → `morph-spec init` atualiza o contrato |
23
+ | PostToolUse `Bash` | `masked-exit.js` | avisa | exit de teste/build/`morph-spec check` escondido por pipe, `\|\| true` ou `; echo` |
24
+ | Stop | `validate-completion.js` | avisa | cenário `feito` sem evidência no `3-implement/report.md` (uma vez por conjunto de avisos) |
195
25
 
196
- ---
26
+ Os grupos com mais de um hook rodam num processo só por `chain.js`: o primeiro bloqueio encerra a
27
+ cadeia, e uma exceção num elo não impede o seguinte.
197
28
 
198
- *MORPH-SPEC by Polymorphism Tech — Hooks Architecture v2.7*
29
+ Além dos hooks, `permissions.deny` impede escrita em `.morph/framework/**` e nos arquivos gerados de
30
+ `.claude/` (rules, skills, agents `morph-*`, `CLAUDE.md`).
@@ -1,7 +1,4 @@
1
1
  # hooks/claude-code/core
2
- Part of morph-spec NLH.
3
- See `framework/MORPH.md` for full documentation.
4
2
 
5
- ## test-budget
6
-
7
- `PreToolUse` Bash (antes do `heavy-gate`). Só age nos agentes do Gate 3 (`agent_id` com `agent_type` em `REVIEW_AGENT_TYPES`: `morph-verifier`/`morph-reviewer`/`morph-security`) com `.morph/` presente. Nega `morph-spec verify` sem `--filter` e a suíte de teste inteira; libera o teste filtrado (`testRunCall` de `framework/hooks/shared/heavy-command.js` decide o que é filtro). A sessão principal e os demais sub-agents não são tocados. Sem contador. Fail-open.
3
+ Os hooks registrados por `MORPH_HOOKS` (`src/utils/hooks-installer.js`); a tabela de cada um está em
4
+ `framework/hooks/README.md`.
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { blockResult, runStandalone } from '../../shared/hook-response.js';
3
- import { stateExists } from '../../shared/state-reader.js';
3
+ import { contractExists } from '../../shared/contract.js';
4
4
  import { gitInvocations } from '../../shared/command-tokens.js';
5
5
 
6
6
  export const CONVENTIONAL = /^(feat|fix|refactor|test|chore|docs|perf|ci|build|style|revert)(\([^)]+\))?!?: \S/;
@@ -35,7 +35,7 @@ export function nonConventionalSubject(command) {
35
35
 
36
36
  export async function run(payload) {
37
37
  try {
38
- if (!stateExists()) return null;
38
+ if (!contractExists()) return null;
39
39
 
40
40
  const command = payload?.tool_input?.command || '';
41
41
  if (!command.includes('commit')) return null;
@@ -76,7 +76,7 @@
76
76
  ],
77
77
  "subagentOnly": true,
78
78
  "display": "git add -A",
79
- "reason": "altera a árvore que o Gate 3 está lendo"
79
+ "reason": "altera a árvore que a revisão está lendo"
80
80
  },
81
81
  {
82
82
  "executable": "git",
@@ -85,7 +85,7 @@
85
85
  ],
86
86
  "subagentOnly": true,
87
87
  "display": "git stash",
88
- "reason": "altera a árvore que o Gate 3 está lendo"
88
+ "reason": "altera a árvore que a revisão está lendo"
89
89
  },
90
90
  {
91
91
  "executable": "git",
@@ -100,7 +100,7 @@
100
100
  ],
101
101
  "subagentOnly": true,
102
102
  "display": "git checkout --",
103
- "reason": "altera a árvore que o Gate 3 está lendo"
103
+ "reason": "altera a árvore que a revisão está lendo"
104
104
  }
105
105
  ]
106
106
  }
@@ -3,7 +3,7 @@
3
3
  // Wide filter on purpose: the refresh only runs when the root's graph is behind HEAD, and a HEAD-moving command
4
4
  // left unrecognized is how the graph falls behind.
5
5
 
6
- import { stateExists } from '../../shared/state-reader.js';
6
+ import { contractExists } from '../../shared/contract.js';
7
7
  import { runStandalone } from '../../shared/hook-response.js';
8
8
  import { tokenize } from '../../shared/command-tokens.js';
9
9
  import { kickGraphRefresh } from '../../shared/graph-refresh.js';
@@ -22,7 +22,7 @@ export async function run(payload) {
22
22
  if (!SHELL_TOOLS.has(payload?.tool_name)) return null;
23
23
  if (!touchesGit(payload?.tool_input?.command)) return null;
24
24
  const dir = payload?.cwd || process.env.CLAUDE_PROJECT_DIR || process.cwd();
25
- if (!stateExists(dir)) return null;
25
+ if (!contractExists(dir)) return null;
26
26
  kickGraphRefresh(dir);
27
27
  } catch {}
28
28
  return null;
@@ -1,17 +1,17 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { stateExists } from '../../shared/state-reader.js';
3
+ import { contractExists } from '../../shared/contract.js';
4
4
  import { contextResult, runStandalone } from '../../shared/hook-response.js';
5
5
  import { exitCodeMasked, hasUnquotedPipe, producerOf } from '../../shared/command-tokens.js';
6
- import { heavyKind, morphVerifyCall, testRunKind } from '../../shared/heavy-command.js';
7
- import { SESSION_MARK } from '../../shared/next-step.js';
6
+ import { buildOrTestKind, morphCheckCall, testRunKind } from '../../shared/command-kind.js';
7
+ import { SESSION_MARK } from '../../shared/owner-words.js';
8
8
 
9
9
  // Printing `$?` or PIPESTATUS puts the real code in the output, so the session already sees it.
10
10
  const EXIT_SHOWN = /\$\?|PIPESTATUS/;
11
11
 
12
12
  function runKind(producer) {
13
- if (morphVerifyCall(producer)) return 'morph-spec verify';
14
- return testRunKind(producer) ?? heavyKind(producer);
13
+ if (morphCheckCall(producer)) return 'morph-spec check';
14
+ return testRunKind(producer) ?? buildOrTestKind(producer);
15
15
  }
16
16
 
17
17
  function maskForm(command) {
@@ -33,7 +33,7 @@ export async function run(payload) {
33
33
  if (payload?.tool_name !== 'Bash') return null;
34
34
  const command = payload.tool_input?.command;
35
35
  if (typeof command !== 'string' || !command.trim()) return null;
36
- if (!stateExists(payload.cwd || undefined)) return null;
36
+ if (!contractExists(payload.cwd || undefined)) return null;
37
37
  if (!exitCodeMasked(command) || EXIT_SHOWN.test(command)) return null;
38
38
  const kind = runKind(producerOf(command));
39
39
  if (!kind) return null;
@@ -3,7 +3,7 @@ import { readFileSync } from 'fs';
3
3
  import { join, dirname } from 'path';
4
4
  import { fileURLToPath } from 'url';
5
5
  import { blockResult, runStandalone } from '../../shared/hook-response.js';
6
- import { stateExists } from '../../shared/state-reader.js';
6
+ import { contractExists } from '../../shared/contract.js';
7
7
  import { tokenize } from '../../shared/command-tokens.js';
8
8
 
9
9
  const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -40,7 +40,7 @@ export function matchesExecutableRule(command, rule) {
40
40
 
41
41
  export async function run(payload) {
42
42
  try {
43
- if (!stateExists()) return null;
43
+ if (!contractExists()) return null;
44
44
 
45
45
  const command = payload?.tool_input?.command || '';
46
46
  if (!command) return null;
@@ -1,18 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  import { existsSync, readFileSync } from 'fs';
4
- import { stateExists, isGateApproved, getFeature } from '../../shared/state-reader.js';
5
- import {
6
- isFeaturePath,
7
- extractFeatureName,
8
- getBasename,
9
- PROTECTED_SPEC_FILES
10
- } from '../../shared/phase-utils.js';
4
+ import { contractExists } from '../../shared/contract.js';
5
+ import { isFeaturePath, extractFeatureName, getBasename } from '../../shared/phase-utils.js';
11
6
  import { blockResult, runStandalone } from '../../shared/hook-response.js';
12
7
  import { getFilePath, getToolName, resolveMorphRoot, resolveTargetPath } from '../../shared/payload-utils.js';
13
8
  import { ERRATA_HEADING, errataViolation } from '../../shared/errata.js';
14
- import { GATE_NAME } from '../../shared/owner-words.js';
15
- import { SESSION_MARK } from '../../shared/next-step.js';
9
+ import { SESSION_MARK } from '../../shared/owner-words.js';
16
10
 
17
11
  const CHECKS_FILE = 'checks.json';
18
12
 
@@ -31,81 +25,43 @@ function proposedText(payload, toolName, original) {
31
25
 
32
26
  export async function run(payload) {
33
27
  try {
34
- if (process.env.MORPH_AMEND_PHASE) {
35
- console.error(`[morph-spec] modo emenda (MORPH_AMEND_PHASE=${process.env.MORPH_AMEND_PHASE}): proteção dos arquivos aprovados desligada`);
36
- return null;
37
- }
38
-
39
- if (!payload) return null;
40
-
41
28
  const filePath = getFilePath(payload);
42
- if (!filePath) return null;
43
-
44
- if (!isFeaturePath(filePath)) return null;
29
+ if (!filePath || !isFeaturePath(filePath)) return null;
45
30
 
46
- // The gate lives in the feature.json of the tree that OWNS the file: asking the session's tree left this guard dark in a worktree.
31
+ // The feature folder of the tree that OWNS the file, not of the session's tree.
47
32
  const root = resolveMorphRoot(filePath, process.cwd());
48
- if (!stateExists(root)) return null;
33
+ if (!contractExists(root)) return null;
49
34
 
50
35
  const featureName = extractFeatureName(filePath);
51
- if (!featureName) return null;
52
-
53
36
  const filename = getBasename(filePath);
54
- const requiredGate = PROTECTED_SPEC_FILES[filename];
55
-
56
- if (!requiredGate) return null;
37
+ if (!featureName || (filename !== 'plan.md' && filename !== CHECKS_FILE)) return null;
57
38
 
58
- // Generated only by the CLI: a hand-written one would carry checks the parser never judged.
59
- // Decided before the creation carve-out, since chore/hotfix are born with the plan gate stamped.
39
+ // Generated only by plan-check: a hand-written one would carry checks the parser never judged.
60
40
  if (filename === CHECKS_FILE) {
61
41
  return blockResult(
62
42
  `MORPH-SPEC: '${CHECKS_FILE}' é a lista de cenários tirada do plano pela ferramenta; ninguém escreve nele à mão.\n` +
63
- `${SESSION_MARK} edite 2-plan/plan.md e rode \`morph-spec plan-check ${featureName}\`: ele lê o plano e grava ${CHECKS_FILE}. ` +
64
- `Depois da ${GATE_NAME.plan} o plano congela: fato errado vai em \`${ERRATA_HEADING}\` (só acrescenta, ${CHECKS_FILE} não muda); ` +
65
- `mudança de escopo pede \`morph-spec unapprove ${featureName} plan\`, depois plan-check e o gate de novo.`
43
+ `${SESSION_MARK} edite 2-plan/plan.md e rode \`morph-spec plan-check\`: ele lê o plano e grava ${CHECKS_FILE}.`
66
44
  );
67
45
  }
68
46
 
69
- if (!isGateApproved(featureName, requiredGate, root)) {
70
- return null;
71
- }
72
-
47
+ // The plan freezes once plan-check validated it; before that it is a draft.
73
48
  const absPath = resolveTargetPath(filePath, root);
74
-
75
- // A file not yet on disk is its CREATION (chore/hotfix are born with `plan` stamped), not an edit of a frozen spec.
76
- // The criterion is existence, never `approvedBy`: by signature, deleting a spec first would license rewriting it.
77
- if (!existsSync(absPath)) {
78
- return null;
79
- }
80
-
81
- // A policy stamp is not a decision: that spec freezes once its checks file exists (written only with zero errors).
82
- const gate = getFeature(featureName, root)?.approvalGates?.[requiredGate];
83
- if (filename === 'plan.md' && String(gate?.approvedBy ?? '').startsWith('policy:')
84
- && !existsSync(absPath.replace(/plan\.md$/, CHECKS_FILE))) {
85
- return null;
86
- }
49
+ if (!existsSync(absPath) || !existsSync(absPath.replace(/plan\.md$/, CHECKS_FILE))) return null;
87
50
 
88
51
  // The only way through is the append-only errata; any read or rebuild failure falls into the block.
89
- const toolName = getToolName(payload);
90
52
  let errataCheck = null;
91
53
  try {
92
54
  const original = readFileSync(absPath, 'utf-8');
93
- const proposed = proposedText(payload, toolName, original);
55
+ const proposed = proposedText(payload, getToolName(payload), original);
94
56
  if (proposed !== null) errataCheck = errataViolation(original, proposed);
95
- } catch {}
57
+ } catch { /* blocked below */ }
58
+ if (errataCheck?.ok) return null;
96
59
 
97
- if (errataCheck?.ok) {
98
- return null;
99
- }
100
60
  return blockResult(
101
- `MORPH-SPEC: '${filename}' está travado: a ${GATE_NAME[requiredGate] ?? requiredGate} já saiu (gate ${requiredGate}), ` +
102
- `e mudar o que foi aprovado quebra o combinado.\n\n` +
61
+ `MORPH-SPEC: 'plan.md' está congelado: o plan-check já o validou e a implementação segue esse texto.\n\n` +
103
62
  (errataCheck ? `Esta mudança não é uma errata válida: ${errataCheck.why}.\n\n` : '') +
104
- `Corrigir um FATO ERRADO sobre o código (o texto aprovado afirma algo que o\n` +
105
- `código desmente) não exige desfazer a aprovação: acrescente sob \`${ERRATA_HEADING}\` no\n` +
106
- `FIM do arquivo, deixando o corpo intacto; só acrescenta e fica na trilha.\n\n` +
107
- `${SESSION_MARK} mudar o ESCOPO combinado é outra coisa: \`morph-spec unapprove ${featureName} ${requiredGate}\`, ` +
108
- `edite, rode plan-check quando for o plan.md, e apresente o gate de novo para aprovação.`
63
+ `Fato errado sobre o código: acrescente sob \`${ERRATA_HEADING}\` no FIM do arquivo, deixando o corpo intacto.\n` +
64
+ `${SESSION_MARK} escopo que mudou é outro plano: termine como precisa-humano e diga o porquê em ## Notas.`
109
65
  );
110
66
  } catch {
111
67
  return null;
@@ -0,0 +1,35 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { execFileSync } from 'child_process';
4
+ import { contractExists } from '../../shared/contract.js';
5
+ import { contextResult, runStandalone } from '../../shared/hook-response.js';
6
+ import { gitInvocations } from '../../shared/command-tokens.js';
7
+ import { SESSION_MARK } from '../../shared/owner-words.js';
8
+
9
+ export const STACK_MANIFEST = /(^|\/)(package\.json|pyproject\.toml|requirements(-[\w-]+)?\.txt|[^/]+\.csproj|[^/]+\.slnx?|Directory\.Packages\.props|(docker-)?compose(\.[\w-]+)?\.ya?ml)$/i;
10
+
11
+ function committedFiles(cwd) {
12
+ const out = execFileSync('git', ['diff-tree', '--no-commit-id', '--name-only', '-r', 'HEAD'], { cwd, stdio: ['ignore', 'pipe', 'ignore'] });
13
+ return out.toString().split('\n').filter(Boolean);
14
+ }
15
+
16
+ export async function run(payload, deps = {}) {
17
+ try {
18
+ if (payload?.tool_name !== 'Bash') return null;
19
+ const command = payload.tool_input?.command;
20
+ if (typeof command !== 'string' || !gitInvocations(command).some(({ sub }) => sub === 'commit')) return null;
21
+ const cwd = payload.cwd || process.env.CLAUDE_PROJECT_DIR || process.cwd();
22
+ if (!contractExists(cwd)) return null;
23
+ const touched = (deps.committedFiles ?? committedFiles)(cwd).filter((f) => STACK_MANIFEST.test(f));
24
+ if (!touched.length) return null;
25
+ return contextResult(
26
+ `A stack do projeto pode ter mudado: o commit mexeu em ${touched.slice(0, 3).join(', ')}${touched.length > 3 ? ` (+${touched.length - 3})` : ''}.\n`
27
+ + `${SESSION_MARK} rode \`morph-spec init\` para atualizar o contrato (.morph/config/config.json) e as rules da stack; edição manual do contrato é mantida.`,
28
+ 'PostToolUse',
29
+ );
30
+ } catch {
31
+ return null;
32
+ }
33
+ }
34
+
35
+ await runStandalone(run);