@polymorphism-tech/morph-spec 10.12.1 → 11.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (323) hide show
  1. package/CLAUDE.md +27 -57
  2. package/README.md +51 -340
  3. package/bin/morph-spec.js +22 -373
  4. package/docs/CHEATSHEET.md +37 -166
  5. package/docs/QUICKSTART.md +14 -74
  6. package/framework/CLAUDE.md +15 -26
  7. package/framework/MORPH.md +34 -101
  8. package/framework/agents.json +8 -8
  9. package/framework/commands/morph-apply.md +5 -5
  10. package/framework/commands/morph-infra.md +1 -1
  11. package/framework/docs/CLI.md +74 -886
  12. package/framework/evals/review-checklist.md +14 -14
  13. package/framework/hooks/README.md +21 -189
  14. package/framework/hooks/claude-code/core/README.md +2 -5
  15. package/framework/hooks/claude-code/core/conventional-commit.js +2 -2
  16. package/framework/hooks/claude-code/core/denylist.json +3 -3
  17. package/framework/hooks/claude-code/core/graph-refresh-kick.js +2 -2
  18. package/framework/hooks/claude-code/core/masked-exit.js +6 -6
  19. package/framework/hooks/claude-code/core/pre-bash-denylist.js +2 -2
  20. package/framework/hooks/claude-code/core/protect-spec-files.js +17 -61
  21. package/framework/hooks/claude-code/core/stack-changed.js +35 -0
  22. package/framework/hooks/claude-code/core/validate-completion.js +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 +13 -11
  46. package/framework/rules/resend-standards.md +1 -1
  47. package/framework/rules/ui-design.md +4 -0
  48. package/framework/schemas/config.schema.json +95 -310
  49. package/framework/skills/README.md +12 -32
  50. package/framework/skills/core/create-umbraco-lp/SKILL.md +1 -1
  51. package/framework/skills/core/migrate-lp-to-umbraco/SKILL.md +1 -1
  52. package/framework/skills/core/morph-apply/SKILL.md +21 -46
  53. package/framework/skills/core/morph-plan/SKILL.md +28 -63
  54. package/framework/skills/core/morph-uiux/SKILL.md +23 -25
  55. package/framework/{templates/docs/ui-mockups.md → skills/core/morph-uiux/references/mockups.md} +4 -4
  56. package/framework/standards/STANDARDS.json +10 -11
  57. package/framework/standards/STANDARDS.meta.json +1 -1
  58. package/framework/standards/ai-agents/evals-with-cache.md +18 -32
  59. package/framework/standards/ai-agents/observability-patterns.md +2 -2
  60. package/framework/standards/architecture/code-comments.md +2 -5
  61. package/framework/standards/architecture/engineering-lens.md +1 -1
  62. package/framework/standards/backend/dotnet/testing.md +4 -4
  63. package/framework/standards/frontend/nextjs/lint.md +24 -10
  64. package/framework/standards/frontend/nextjs/testing.md +2 -2
  65. package/framework/standards/infrastructure/docker/local-compose-isolation.md +14 -30
  66. package/framework/templates/CLAUDE.md.core.guide.md +2 -2
  67. package/framework/templates/README.md +1 -1
  68. package/framework/templates/REGISTRY.json +3 -33
  69. package/framework/templates/docs/plan.md +3 -2
  70. package/framework/templates/dotnet/ai-kit/README.md +2 -4
  71. package/framework/templates/dotnet/ai-kit/src/Morph.AiKit/Evals/EvalCacheMissException.cs +1 -1
  72. package/framework/templates/dotnet/ai-kit/src/Morph.AiKit/Evals/EvalFixture.cs +1 -1
  73. package/package.json +1 -2
  74. package/src/commands/graph/explain.js +2 -1
  75. package/src/commands/graph/status.js +2 -1
  76. package/src/commands/mcp/mcp-setup.js +1 -2
  77. package/src/commands/project/doctor.js +5 -341
  78. package/src/commands/project/env.js +21 -52
  79. package/src/commands/project/init-contract.js +47 -0
  80. package/src/commands/project/init.js +36 -66
  81. package/src/commands/project/stack-scan.js +1 -1
  82. package/src/commands/project/update.js +15 -50
  83. package/src/commands/validation/check.js +128 -0
  84. package/src/commands/validation/plan-check.js +41 -64
  85. package/src/commands/validation/prove-red.js +1 -1
  86. package/src/core/paths/output-schema.js +0 -22
  87. package/src/core/templates/template-renderer.js +0 -14
  88. package/src/lib/ai/ai-project-scan.js +1 -6
  89. package/src/lib/check/attempts.js +38 -0
  90. package/src/lib/check/signals.js +145 -0
  91. package/src/lib/config/project-config.js +13 -0
  92. package/src/lib/contract/apply.js +62 -0
  93. package/src/lib/contract/defaults.js +96 -0
  94. package/src/lib/contract/merge.js +79 -0
  95. package/src/lib/contract/ports.js +43 -0
  96. package/src/lib/contract/scan.js +102 -0
  97. package/src/lib/detectors/claude-config-detector.js +7 -0
  98. package/src/lib/{procs → detectors}/mcp-config.js +1 -37
  99. package/src/lib/diff/diff-lines.js +64 -0
  100. package/src/lib/generators/architecture-scanner.js +1 -1
  101. package/src/lib/generators/scaffold-generator.js +0 -7
  102. package/src/lib/git/default-branch.js +0 -122
  103. package/src/lib/graph/diff-tree.js +2 -1
  104. package/src/lib/graph/god-nodes.js +2 -1
  105. package/src/lib/graph/graphify-runtime.js +0 -1
  106. package/src/lib/graph/graphifyignore.js +1 -1
  107. package/src/lib/graph/sanitize.js +2 -8
  108. package/src/lib/installers/memory-installer.js +15 -30
  109. package/src/lib/installers/stack-sync.js +16 -9
  110. package/src/lib/plan/checks.js +20 -64
  111. package/src/lib/plan/media.js +1 -1
  112. package/src/lib/plan/plan-parser.js +5 -5
  113. package/src/lib/review-reports.js +3 -77
  114. package/src/lib/scan/worktree-dirs.js +3 -0
  115. package/src/lib/specs/adr-index.js +2 -2
  116. package/src/lib/stack/dotnet-build-ignores.js +10 -2
  117. package/src/lib/stack/stack-scan.js +2 -2
  118. package/src/lib/stack-filter.js +3 -2
  119. package/src/lib/tests-audit/audit.js +1 -1
  120. package/src/scripts/setup-infra.js +6 -59
  121. package/src/utils/agents-installer.js +1 -34
  122. package/src/utils/atomic-json.js +27 -0
  123. package/src/utils/file-copier.js +4 -12
  124. package/src/utils/hooks-installer.js +9 -107
  125. package/claude-plugin.json +0 -14
  126. package/framework/commands/morph-archive.md +0 -46
  127. package/framework/commands/morph-hotfix.md +0 -17
  128. package/framework/commands/morph-preflight.md +0 -180
  129. package/framework/commands/morph-review.md +0 -15
  130. package/framework/commands/morph-status.md +0 -37
  131. package/framework/hooks/claude-code/core/block-destructive-worktree-removal.js +0 -80
  132. package/framework/hooks/claude-code/core/block-raw-worktree-add.js +0 -72
  133. package/framework/hooks/claude-code/core/enforce-phase-writes.js +0 -100
  134. package/framework/hooks/claude-code/core/gate-guard.js +0 -148
  135. package/framework/hooks/claude-code/core/heavy-gate.js +0 -78
  136. package/framework/hooks/claude-code/core/heavy-release.js +0 -23
  137. package/framework/hooks/claude-code/core/loop-detect.js +0 -79
  138. package/framework/hooks/claude-code/core/state-sync.js +0 -214
  139. package/framework/hooks/claude-code/core/telemetry-log.js +0 -259
  140. package/framework/hooks/claude-code/core/test-budget.js +0 -29
  141. package/framework/hooks/claude-code/core/worktree-context.js +0 -249
  142. package/framework/hooks/claude-code/core/worktree-create.js +0 -119
  143. package/framework/hooks/claude-code/core/worktree-env-inject.js +0 -68
  144. package/framework/hooks/claude-code/core/worktree-remove.js +0 -55
  145. package/framework/hooks/shared/build-check.js +0 -120
  146. package/framework/hooks/shared/claim-registry.js +0 -125
  147. package/framework/hooks/shared/e2e-check.js +0 -1022
  148. package/framework/hooks/shared/feature-locator.js +0 -82
  149. package/framework/hooks/shared/gate-event.js +0 -18
  150. package/framework/hooks/shared/gate-question.js +0 -20
  151. package/framework/hooks/shared/heavy-config.js +0 -113
  152. package/framework/hooks/shared/heavy-holders.js +0 -85
  153. package/framework/hooks/shared/heavy-slots.js +0 -280
  154. package/framework/hooks/shared/host-services.js +0 -440
  155. package/framework/hooks/shared/next-step.js +0 -181
  156. package/framework/hooks/shared/redact-secrets.js +0 -44
  157. package/framework/hooks/shared/reparse-scan.js +0 -40
  158. package/framework/hooks/shared/state-reader.js +0 -220
  159. package/framework/hooks/shared/state-writer.js +0 -112
  160. package/framework/hooks/shared/telemetry-logger.js +0 -101
  161. package/framework/hooks/shared/transcript-usage.js +0 -58
  162. package/framework/hooks/shared/worktree-root.js +0 -71
  163. package/framework/phases.json +0 -92
  164. package/framework/schemas/feature.schema.json +0 -242
  165. package/framework/skills/core/morph-apply/references/hotfix.md +0 -46
  166. package/framework/skills/core/morph-apply/references/machine.md +0 -30
  167. package/framework/skills/core/morph-apply/references/review.md +0 -77
  168. package/framework/skills/core/morph-plan/references/critique.md +0 -51
  169. package/framework/skills/core/morph-plan/references/interview.md +0 -37
  170. package/framework/templates/state.template.json +0 -17
  171. package/src/commands/dashboard/dashboard.js +0 -74
  172. package/src/commands/e2e/e2e.js +0 -400
  173. package/src/commands/observability/cost.js +0 -283
  174. package/src/commands/project/branch.js +0 -129
  175. package/src/commands/project/claim.js +0 -132
  176. package/src/commands/project/doctor-procs.js +0 -162
  177. package/src/commands/project/fleet.js +0 -66
  178. package/src/commands/project/heavy.js +0 -81
  179. package/src/commands/project/install-plugin-cmd.js +0 -27
  180. package/src/commands/project/status.js +0 -61
  181. package/src/commands/project/worktree.js +0 -1234
  182. package/src/commands/state/advance.js +0 -248
  183. package/src/commands/state/approve.js +0 -303
  184. package/src/commands/state/archive.js +0 -231
  185. package/src/commands/state/auto-approval.js +0 -67
  186. package/src/commands/state/create.js +0 -274
  187. package/src/commands/state/delete.js +0 -192
  188. package/src/commands/state/finish.js +0 -1247
  189. package/src/commands/state/gate-check.js +0 -244
  190. package/src/commands/state/gate-decision.js +0 -122
  191. package/src/commands/state/list.js +0 -244
  192. package/src/commands/state/next.js +0 -24
  193. package/src/commands/state/recap.js +0 -80
  194. package/src/commands/state/report-check.js +0 -244
  195. package/src/commands/state/retype.js +0 -110
  196. package/src/commands/validation/verify.js +0 -421
  197. package/src/core/state/feature-identity.js +0 -10
  198. package/src/core/state/gate-order.js +0 -23
  199. package/src/core/state/lifecycle-audit.js +0 -171
  200. package/src/core/state/state-manager.js +0 -523
  201. package/src/core/templates/template-seed.js +0 -21
  202. package/src/core/work-types.js +0 -44
  203. package/src/dashboard/app/App.jsx +0 -84
  204. package/src/dashboard/app/components/ActivityFeed.jsx +0 -166
  205. package/src/dashboard/app/components/CommandPalette.jsx +0 -144
  206. package/src/dashboard/app/components/DetailPanel.jsx +0 -43
  207. package/src/dashboard/app/components/EntityLink.jsx +0 -42
  208. package/src/dashboard/app/components/ErrorBoundary.jsx +0 -47
  209. package/src/dashboard/app/components/FlowGraph.jsx +0 -19
  210. package/src/dashboard/app/components/GatePauses.jsx +0 -116
  211. package/src/dashboard/app/components/KnowledgeMarkdown.jsx +0 -42
  212. package/src/dashboard/app/components/Markdown.jsx +0 -38
  213. package/src/dashboard/app/components/PhaseRail.jsx +0 -100
  214. package/src/dashboard/app/components/SearchFilter.jsx +0 -36
  215. package/src/dashboard/app/components/SessionMap.jsx +0 -77
  216. package/src/dashboard/app/components/Sidebar.jsx +0 -147
  217. package/src/dashboard/app/hooks/useMorphQuery.js +0 -44
  218. package/src/dashboard/app/hooks/usePref.js +0 -34
  219. package/src/dashboard/app/lib/format.js +0 -69
  220. package/src/dashboard/app/lib/phases.js +0 -75
  221. package/src/dashboard/app/lib/project.js +0 -38
  222. package/src/dashboard/app/main.jsx +0 -13
  223. package/src/dashboard/app/pages/Activity.jsx +0 -28
  224. package/src/dashboard/app/pages/AgentMap.jsx +0 -363
  225. package/src/dashboard/app/pages/FeatureDetail.jsx +0 -579
  226. package/src/dashboard/app/pages/Features.jsx +0 -393
  227. package/src/dashboard/app/pages/Guide.jsx +0 -145
  228. package/src/dashboard/app/pages/HookInspector.jsx +0 -444
  229. package/src/dashboard/app/pages/PhasePipeline.jsx +0 -273
  230. package/src/dashboard/app/pages/Portfolio.jsx +0 -190
  231. package/src/dashboard/app/pages/RulesMap.jsx +0 -285
  232. package/src/dashboard/app/pages/SkillsLibrary.jsx +0 -468
  233. package/src/dashboard/app/pages/Standards.jsx +0 -392
  234. package/src/dashboard/app/styles/index.css +0 -187
  235. package/src/dashboard/index.html +0 -14
  236. package/src/dashboard/package.json +0 -32
  237. package/src/dashboard/scanner/activity-scanner.js +0 -321
  238. package/src/dashboard/scanner/agents-scanner.js +0 -67
  239. package/src/dashboard/scanner/docs-scanner.js +0 -34
  240. package/src/dashboard/scanner/feature-status.js +0 -7
  241. package/src/dashboard/scanner/features-scanner.js +0 -397
  242. package/src/dashboard/scanner/hooks-scanner.js +0 -96
  243. package/src/dashboard/scanner/index.js +0 -21
  244. package/src/dashboard/scanner/phases-scanner.js +0 -14
  245. package/src/dashboard/scanner/portfolio.js +0 -129
  246. package/src/dashboard/scanner/project-api.js +0 -160
  247. package/src/dashboard/scanner/rules-scanner.js +0 -46
  248. package/src/dashboard/scanner/skills-scanner.js +0 -104
  249. package/src/dashboard/scanner/standards-scanner.js +0 -38
  250. package/src/dashboard/vite-plugin-morph-data.js +0 -120
  251. package/src/dashboard/vite.config.js +0 -26
  252. package/src/lib/ci/ci-verify.js +0 -30
  253. package/src/lib/ci/github-ci.js +0 -52
  254. package/src/lib/ci/pr-checks.js +0 -76
  255. package/src/lib/e2e/applicability.js +0 -39
  256. package/src/lib/e2e/compose-env.js +0 -80
  257. package/src/lib/e2e/stack-teardown.js +0 -96
  258. package/src/lib/git/branch-classifier.js +0 -104
  259. package/src/lib/git/evidence-staleness.js +0 -40
  260. package/src/lib/git/gh.js +0 -15
  261. package/src/lib/git/pending-prs.js +0 -58
  262. package/src/lib/git/pr-files.js +0 -31
  263. package/src/lib/git/pr-index.js +0 -39
  264. package/src/lib/git/tree-fingerprint.js +0 -58
  265. package/src/lib/git/tree-state.js +0 -125
  266. package/src/lib/heavy/cleanup.js +0 -72
  267. package/src/lib/heavy/gate.js +0 -168
  268. package/src/lib/heavy/live-stacks.js +0 -64
  269. package/src/lib/heavy/reclaim.js +0 -107
  270. package/src/lib/heavy/watchdog.js +0 -46
  271. package/src/lib/next-step.js +0 -12
  272. package/src/lib/plan/critique.js +0 -67
  273. package/src/lib/plan/plan-template.js +0 -18
  274. package/src/lib/procs/classify.js +0 -91
  275. package/src/lib/procs/list.js +0 -124
  276. package/src/lib/procs/prune.js +0 -47
  277. package/src/lib/procs/wslconfig.js +0 -70
  278. package/src/lib/projects/registry.js +0 -121
  279. package/src/lib/recap/piper.js +0 -36
  280. package/src/lib/recap/recap.js +0 -259
  281. package/src/lib/review-confirmation.js +0 -66
  282. package/src/lib/risk/diff-risk.js +0 -137
  283. package/src/lib/risk-detector.js +0 -638
  284. package/src/lib/specs/design-seed.js +0 -18
  285. package/src/lib/specs/screen-checklist.js +0 -315
  286. package/src/lib/stack/stack-profile.js +0 -69
  287. package/src/lib/tasks/eval-node.js +0 -293
  288. package/src/lib/tasks/linux-runner.js +0 -200
  289. package/src/lib/tasks/test-nodes.js +0 -414
  290. package/src/lib/tasks/test-runner.js +0 -569
  291. package/src/lib/telemetry/metrics.js +0 -384
  292. package/src/lib/telemetry/telemetry-reader.js +0 -276
  293. package/src/lib/telemetry/verify-event.js +0 -57
  294. package/src/lib/validators/code-budget/code-budget-validator.js +0 -170
  295. package/src/lib/validators/contracts/contract-compliance-validator.js +0 -219
  296. package/src/lib/validators/nextjs/next-component-validator.js +0 -142
  297. package/src/lib/validators/packages/package-validator.js +0 -310
  298. package/src/lib/validators/reuse/reuse-validator.js +0 -202
  299. package/src/lib/validators/reuse/symbol-scanner.js +0 -64
  300. package/src/lib/validators/validation-runner.js +0 -188
  301. package/src/lib/validators/verify-cache.js +0 -63
  302. package/src/lib/validators/verify-runner.js +0 -971
  303. package/src/lib/verify/affected.js +0 -143
  304. package/src/lib/verify/detached.js +0 -159
  305. package/src/lib/view/feature-html.js +0 -480
  306. package/src/lib/view/feature-page.client.js +0 -109
  307. package/src/lib/view/feature-page.css +0 -278
  308. package/src/lib/view/feature-view.js +0 -113
  309. package/src/lib/view/flow-layers.js +0 -79
  310. package/src/lib/view/flow-svg.js +0 -63
  311. package/src/lib/view/tokens.css +0 -18
  312. package/src/lib/work-type-detector.js +0 -81
  313. package/src/lib/worktree/dirs.js +0 -3
  314. package/src/lib/worktree/docker-audit.js +0 -175
  315. package/src/lib/worktree/env-allocator.js +0 -177
  316. package/src/lib/worktree/feature-truth.js +0 -145
  317. package/src/lib/worktree/finish-backup.js +0 -529
  318. package/src/lib/worktree/fleet-scanner.js +0 -223
  319. package/src/lib/worktree/ignored-triage.js +0 -136
  320. package/src/lib/worktree/vscode-settings.js +0 -112
  321. package/src/lib/worktree/worktree-audit.js +0 -323
  322. package/src/lib/worktree/worktree-include.js +0 -44
  323. package/src/scripts/install-plugin.js +0 -114
@@ -1,6 +1,5 @@
1
- import { join, resolve } from 'path';
2
- import { homedir } from 'os';
3
- import fs from 'fs-extra';
1
+ import { existsSync } from 'fs';
2
+ import { join } from 'path';
4
3
  import ora from 'ora';
5
4
  import { execSync } from 'child_process';
6
5
  import { logger } from '../../utils/logger.js';
@@ -29,16 +28,21 @@ import {
29
28
  import { setupInfra } from '../../scripts/setup-infra.js';
30
29
  import { getProjectTags } from '../../lib/stack-filter.js';
31
30
  import { updateCommand } from './update.js';
32
- import { resolvePrimaryRoot } from './worktree.js';
33
- import { registerProject } from '../../lib/projects/registry.js';
34
31
  import { setProjectStack } from '../../lib/installers/stack-sync.js';
35
32
  import { installStackAssets } from '../../lib/installers/stack-assets.js';
33
+ import { scanRepo } from '../../lib/contract/scan.js';
34
+ import { initDryRun, refreshContract } from './init-contract.js';
35
+ import { isSecondaryWorktree } from '../../../framework/hooks/shared/git-paths.js';
36
+ import { seedFromPrimary } from '../../../framework/hooks/shared/graph-refresh.js';
36
37
 
37
38
  const GREENFIELD_CHOICES = [
38
- { name: 'dotnet+nextjs — stack do Morph: .NET 10 + EF Core/Neon + Next.js/Shadcn (recomendada)', value: { stack: 'dotnet+nextjs', integrations: ['neon'] } },
39
- { name: 'dotnet — só a API .NET (EF Core/Neon)', value: { stack: 'dotnet', integrations: ['neon'] } },
39
+ { name: 'dotnet+nextjs — stack do Morph: .NET 10 + EF Core/Neon + Next.js/Shadcn (recomendada)', value: { stack: 'dotnet+nextjs', integrations: ['neon', 'ef'] } },
40
+ { name: 'dotnet — só a API .NET (EF Core/Neon)', value: { stack: 'dotnet', integrations: ['neon', 'ef'] } },
40
41
  { name: 'nextjs — só o app web Next.js', value: { stack: 'nextjs', integrations: [] } },
41
- { name: 'Decidir depois (o /morph-plan pergunta)', value: null },
42
+ { name: 'node — Node/TypeScript sem framework web', value: { stack: 'node', integrations: [] } },
43
+ { name: 'LP Umbraco — backend Umbraco + front Next.js', value: { stack: 'dotnet+nextjs', integrations: ['umbraco'] } },
44
+ { name: 'python', value: { stack: 'python', integrations: [] } },
45
+ { name: 'Outra — decidir depois (o /morph-plan pergunta)', value: null },
42
46
  ];
43
47
 
44
48
  /** Empty project: `--stack` wins; a terminal is asked, the Morph stack first; no terminal leaves it to the plan. */
@@ -64,45 +68,31 @@ async function reinstallForStack(targetPath, stackTags, spinner) {
64
68
  spinner.succeed(`Stack-filtered assets reinstalled for [${stackTags.join(', ')}]`);
65
69
  }
66
70
 
67
- /**
68
- * A linked worktree junctions `.claude/` and `.morph/framework/` but not `.morph/config`/state:
69
- * a full install there orphans a second, disconnected one. `--force` overrides.
70
- */
71
- export function checkSecondaryWorktreeGuard(targetPath, options = {}) {
72
- if (options.force) return { blocked: false };
73
- const target = resolve(targetPath).replace(/\\/g, '/');
74
- const root = resolvePrimaryRoot(targetPath);
75
- if (root === target) return { blocked: false };
76
- return { blocked: true, root, target };
71
+ // A fresh worktree carries the committed contract but not the gitignored harness: that is an install, not a refresh.
72
+ function harnessInstalled(targetPath) {
73
+ return ['.morph/framework/hooks', '.claude/skills/morph-plan'].every((p) => existsSync(join(targetPath, p)));
77
74
  }
78
75
 
79
76
  export async function initCommand(options) {
80
77
  const targetPath = options.path || process.cwd();
78
+ if (options.dryRun) return initDryRun(targetPath, { json: options.json });
81
79
 
82
80
  logger.header('MORPH-SPEC Framework Installation');
83
81
  logger.dim(`Target: ${targetPath}`);
84
82
  logger.blank();
85
83
 
86
- const worktreeGuard = checkSecondaryWorktreeGuard(targetPath, options);
87
- if (worktreeGuard.blocked) {
88
- logger.warn(`Você está num worktree secundário (${worktreeGuard.target}).`);
89
- logger.warn(`O morph-spec já está instalado na raiz primária (${worktreeGuard.root}).`);
90
- logger.warn('Para reparar infra do worktree use `morph-spec worktree link --all`, não `init`.');
91
- process.exit(0);
92
- }
93
-
94
84
  const morphPath = join(targetPath, '.morph');
95
- if (await pathExists(morphPath)) {
85
+ if (await pathExists(morphPath) && harnessInstalled(targetPath)) {
96
86
  if (!options.force) {
97
87
  const projectCheck = await checkProjectOutdated(targetPath);
98
88
  if (projectCheck.isOutdated) {
99
89
  logger.info(`MORPH already initialized (v${projectCheck.current}). Framework update available (v${projectCheck.cliVersion}).`);
100
90
  logger.blank();
101
- return updateCommand(options);
91
+ await updateCommand(options);
92
+ return refreshContract(targetPath);
102
93
  }
103
- logger.warn('MORPH already initialized in this directory (up to date).');
104
- logger.dim('Use --force to overwrite existing installation.');
105
- process.exit(1);
94
+ logger.info('MORPH já instalado e em dia: atualizando o contrato pelo repo.');
95
+ return refreshContract(targetPath);
106
96
  }
107
97
  logger.warn('Overwriting existing MORPH installation...');
108
98
  }
@@ -112,11 +102,10 @@ export async function initCommand(options) {
112
102
  try {
113
103
 
114
104
  spinner.stop();
115
- // The secondary-worktree guard already ran above; setupInfra must not re-apply it.
116
- const infraResult = await setupInfra(targetPath, { force: true });
117
- if (infraResult?.refused) {
118
- process.exitCode = 1;
119
- return infraResult;
105
+ const infraResult = await setupInfra(targetPath);
106
+ // A new worktree starts from a root commit: the root's graph is in date for it or one refresh away.
107
+ if (isSecondaryWorktree(targetPath)) {
108
+ try { if (seedFromPrimary(targetPath).seeded) logger.dim(' ✓ grafo de código copiado da raiz (morph-spec graph refresh o atualiza)'); } catch { /* the graph is optional */ }
120
109
  }
121
110
  spinner.start('Continuing...');
122
111
 
@@ -190,9 +179,7 @@ export async function initCommand(options) {
190
179
 
191
180
  spinner.text = 'Detecting project stack...';
192
181
  let detectedStack = 'unknown';
193
- const hasProjectFiles = await pathExists(join(targetPath, 'package.json'))
194
- || await pathExists(join(targetPath, 'src'))
195
- || (await fs.readdir(targetPath)).some(f => f.endsWith('.csproj'));
182
+ const hasProjectFiles = scanRepo(targetPath).stack !== null;
196
183
 
197
184
  if (hasProjectFiles) {
198
185
  try {
@@ -268,6 +255,11 @@ export async function initCommand(options) {
268
255
  }
269
256
  }
270
257
 
258
+ spinner.stop();
259
+ await refreshContract(targetPath);
260
+ config = await readJson(configPath);
261
+ spinner.start('Continuing...');
262
+
271
263
  let mcpSetupResult = null;
272
264
  if (!options.skipMcp) {
273
265
  try {
@@ -424,20 +416,15 @@ export async function initCommand(options) {
424
416
  }
425
417
 
426
418
  spinner.succeed('MORPH-SPEC installed successfully!');
427
- registerProject(targetPath, 'init');
428
419
 
429
420
  logger.blank();
430
421
  logger.success(`MORPH-SPEC v${cliVersion} installed successfully!`);
431
422
  logger.blank();
432
423
  logger.header('Next Steps');
433
424
 
434
- logger.step(1, 'Review .morph/config/config.json');
435
- logger.step(2, 'Open project in VS Code with Claude Code');
436
- logger.step(3, 'Start your first feature:');
437
- logger.blank();
438
- logger.box([
439
- 'Ask Claude Code to implement a feature'
440
- ]);
425
+ logger.step(1, 'Review .morph/config/config.json (tests, risk, limits)');
426
+ logger.step(2, 'Start a new Claude Code session on a feature branch');
427
+ logger.step(3, 'Run /morph-plan with the issue or the goal');
441
428
  logger.blank();
442
429
 
443
430
  logger.info('Files installed:');
@@ -450,7 +437,7 @@ export async function initCommand(options) {
450
437
  logger.dim(` ✓ .claude/commands/ (slash commands)`);
451
438
  }
452
439
  if (rulesCopied) {
453
- logger.dim(` ✓ .claude/rules/ (5 path-scoped rules)`);
440
+ logger.dim(` ✓ .claude/rules/ (path-scoped rules for the stack)`);
454
441
  }
455
442
  logger.dim(` ✓ .claude/settings.local.json (${hooksResult.installed} hooks installed)`);
456
443
  if (integrationsCreated) {
@@ -468,7 +455,7 @@ export async function initCommand(options) {
468
455
 
469
456
  const agents = infraResult?.agents;
470
457
  if (agents) {
471
- logger.dim(` ✓ .claude/agents/ (${agents.installed ?? 0} Gate 3 agents installed)`);
458
+ logger.dim(` ✓ .claude/agents/ (${agents.installed ?? 0} review personas installed)`);
472
459
  } else {
473
460
  logger.dim(' ✓ .claude/agents/ (native subagents installed)');
474
461
  }
@@ -476,23 +463,6 @@ export async function initCommand(options) {
476
463
  logger.dim(' ✓ ~/.claude/statusline.js (global statusline installed)');
477
464
 
478
465
  logger.blank();
479
- const globalSettingsPath = join(homedir(), '.claude', 'settings.local.json');
480
- let agentTeamsEnabled = false;
481
- try {
482
- const globalSettings = await readJson(globalSettingsPath);
483
- agentTeamsEnabled = globalSettings?.env?.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS === '1';
484
- } catch {
485
- }
486
-
487
- if (agentTeamsEnabled) {
488
- logger.success('Agent Teams: CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS enabled ✓');
489
- } else {
490
- logger.warn('Agent Teams not enabled. To activate multi-agent workflows, add to ~/.claude/settings.local.json:');
491
- logger.dim(' {"env": {"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"}}');
492
- }
493
-
494
- logger.blank();
495
-
496
466
  try {
497
467
  const { installProjectMemory } = await import('../../lib/installers/memory-installer.js');
498
468
  const memResult = await installProjectMemory(targetPath, {
@@ -1,4 +1,4 @@
1
- import { readMorphConfig } from '../../lib/tasks/test-runner.js';
1
+ import { readMorphConfig } from '../../lib/config/project-config.js';
2
2
  import { scanStack, renderStackScan } from '../../lib/stack/stack-scan.js';
3
3
 
4
4
  /** Scan the tree at `cwd`; prints, never writes — the plan reads stdout. */
@@ -1,4 +1,4 @@
1
- import { join, dirname, relative, isAbsolute } from 'path';
1
+ import { basename, join, dirname, relative, isAbsolute, resolve } from 'path';
2
2
  import { fileURLToPath } from 'url';
3
3
  import { spawnSync } from 'child_process';
4
4
  import { existsSync, readdirSync, readFileSync } from 'fs';
@@ -36,8 +36,6 @@ import { reconcileLegacyTemplatesCopy } from '../../lib/installers/templates-rec
36
36
  import { createEffects } from '../../lib/installers/effects.js';
37
37
  import { syncStackTooling } from '../../lib/installers/stack-tooling.js';
38
38
  import { detectClaudeConfig } from '../../lib/detectors/claude-config-detector.js';
39
- import { applyEditorSettings } from '../../lib/worktree/vscode-settings.js';
40
- import { registerProject } from '../../lib/projects/registry.js';
41
39
  import {
42
40
  writeGraphifyignore, describeOutdatedIgnore, graphifyignoreTracked,
43
41
  } from '../../lib/graph/graphifyignore.js';
@@ -118,14 +116,9 @@ function restoreUserConfig(morphPath, targetPath, configBackup, currentVersion,
118
116
  configBackup.frameworkVersion = currentVersion;
119
117
  fx.writeJson(configPath, configBackup);
120
118
  } else {
121
- const dirName = targetPath.split(/[\\/]/).pop();
122
119
  const defaultConfig = {
123
- framework: 'global',
124
120
  frameworkVersion: currentVersion,
125
- project: {
126
- name: dirName,
127
- architecture: 'unknown'
128
- }
121
+ project: { name: basename(resolve(targetPath)) },
129
122
  };
130
123
  fx.writeJson(configPath, defaultConfig);
131
124
  }
@@ -148,29 +141,13 @@ export function stateJsonIsTracked(targetPath) {
148
141
  }
149
142
  }
150
143
 
151
- const SLICES_HEADING = /^## Fatias\s*$/m;
152
-
153
- /** Active features still planned in 9.x slices: a plan with `## Fatias` and no `3-implement/report.md` yet. */
154
- export function legacySliceFeatures(targetPath) {
155
- const featuresDir = join(targetPath, '.morph', 'features');
156
- let names;
157
- try { names = readdirSync(featuresDir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name); } catch { return []; }
158
- return names.filter((name) => {
159
- const dir = join(featuresDir, name);
160
- if (existsSync(join(dir, '3-implement', 'report.md'))) return false;
161
- try { return SLICES_HEADING.test(readFileSync(join(dir, '2-plan', 'plan.md'), 'utf8')); } catch { return false; }
162
- }).sort();
163
- }
164
-
165
- export function legacySliceNotice(names) {
166
- if (names.length === 0) return null;
167
- return `Feature(s) planejada(s) em fatias (9.x): ${names.join(', ')}. Plano não aprovado: tire \`## Fatias\` e rode \`morph-spec plan-check <f>\`. `
168
- + 'Já em implement: segue pelos `reports/F*.md`; para o formato novo, crie `3-implement/report.md` com uma linha por `Cn` (CHANGELOG 10.0.0).';
169
- }
170
-
171
- export function untrackCommittedStateJson(targetPath, fx = createEffects({ dryRun: false })) {
172
- if (!stateJsonIsTracked(targetPath)) return false;
173
- return fx.gitIndex('rm --cached --quiet', '.morph/state.json', { cwd: targetPath });
144
+ /** Up to 10.x the feature state lived in `.morph/state.json`; from 11 the branch is the feature and the file is dead. */
145
+ export function removeLegacyState(targetPath, fx = createEffects({ dryRun: false })) {
146
+ const path = join(targetPath, '.morph', 'state.json');
147
+ if (!existsSync(path)) return false;
148
+ if (stateJsonIsTracked(targetPath)) fx.gitIndex('rm --cached --quiet', '.morph/state.json', { cwd: targetPath });
149
+ fx.remove(path);
150
+ return true;
174
151
  }
175
152
 
176
153
  /**
@@ -467,12 +444,9 @@ export async function updateCommand(options = {}) {
467
444
 
468
445
  updateSpinner.text = 'Updating charter, schemas and evals...';
469
446
  const canonicalFrameworkDir = join(__dirname, '..', '..', '..', 'framework');
470
- for (const file of ['MORPH.md', 'phases.json']) {
471
- const src = join(canonicalFrameworkDir, file);
472
- if (await pathExists(src)) {
473
- fx.copyFile(src, join(morphPath, 'framework', file));
474
- }
475
- }
447
+ fx.copyFile(join(canonicalFrameworkDir, 'MORPH.md'), join(morphPath, 'framework', 'MORPH.md'));
448
+ const deadPhases = join(morphPath, 'framework', 'phases.json');
449
+ if (existsSync(deadPhases)) fx.remove(deadPhases);
476
450
  for (const dir of ['schemas', 'evals']) {
477
451
  const src = join(canonicalFrameworkDir, dir);
478
452
  if (await pathExists(src)) {
@@ -600,9 +574,6 @@ export async function updateCommand(options = {}) {
600
574
  await updateGitignore(targetPath, fx);
601
575
  await ensureGitattributes(targetPath, fx);
602
576
 
603
- updateSpinner.text = 'Editor excludes for worktrees (.vscode/settings.json)...';
604
- try { applyEditorSettings(targetPath, { fx }); } catch {}
605
-
606
577
  // Swap an unedited generated .graphifyignore when its RULES change (header-only diffs are left);
607
578
  // an edited one is left alone with the change printed. Only an existing file: the graph is opt-in.
608
579
  let graphIgnore = null;
@@ -616,10 +587,7 @@ export async function updateCommand(options = {}) {
616
587
  }
617
588
  }
618
589
 
619
- const sliceNotice = legacySliceNotice(legacySliceFeatures(targetPath));
620
- if (sliceNotice) notices.push(sliceNotice);
621
-
622
- const untracked = untrackCommittedStateJson(targetPath, fx);
590
+ const legacyStateRemoved = removeLegacyState(targetPath, fx);
623
591
 
624
592
  updateSpinner.text = 'Saving version info...';
625
593
  await saveProjectMorphVersion(targetPath, cliCheck.current, fx);
@@ -628,9 +596,6 @@ export async function updateCommand(options = {}) {
628
596
  logger.blank();
629
597
 
630
598
  if (!dryRun) {
631
- // Outside the project, so not an effect of the update itself.
632
- registerProject(targetPath, 'update');
633
-
634
599
  if (projectCheck.current && projectCheck.current !== cliCheck.current) {
635
600
  logger.success(`Updated: ${projectCheck.current} → ${cliCheck.current}`);
636
601
  } else if (!projectCheck.current) {
@@ -667,8 +632,8 @@ export async function updateCommand(options = {}) {
667
632
  logger.dim(' ✓ .graphifyignore (dublês, fixtures e helpers de teste voltam ao grafo da raiz no próximo refresh');
668
633
  logger.dim(' em background — início de sessão ou comando git do agente; numa worktree: morph-spec graph refresh)');
669
634
  }
670
- if (untracked) {
671
- logger.dim(' ✓ .morph/state.json untracked (git rm --cached) — commit to finalize');
635
+ if (legacyStateRemoved) {
636
+ logger.dim(' ✓ .morph/state.json removido: a feature agora é a pasta do branch');
672
637
  logger.warn('Migration: .morph/state.json was removed from git tracking. The');
673
638
  logger.dim(' working file stays (rebuilt from feature.json); commit the deletion');
674
639
  logger.dim(' so it stops being swept into per-feature commits.');
@@ -0,0 +1,128 @@
1
+ import chalk from 'chalk';
2
+ import { spawnSync } from 'child_process';
3
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
4
+ import { dirname, join, resolve } from 'path';
5
+ import { contractExists, NO_CONTRACT_MESSAGE } from '../../../framework/hooks/shared/contract.js';
6
+ import { readMorphConfig } from '../../lib/config/project-config.js';
7
+ import { getAbsoluteOutputPath } from '../../core/paths/output-schema.js';
8
+ import { featureFromBranch } from '../../../framework/hooks/shared/feature-slug.js';
9
+ import { git } from '../../lib/diff/diff-lines.js';
10
+ import { changedFiles, finalSignals, planSignals, reportSignals, reviewSignals, riskSignals, signalText, sizeSignals, uncommittedSignals } from '../../lib/check/signals.js';
11
+ import { reviewReports } from '../../lib/review-reports.js';
12
+ import { worktreeEnv } from '../project/env.js';
13
+ import { recordAttempt, stuckSignal } from '../../lib/check/attempts.js';
14
+
15
+ const TIERS = ['fast', 'full', 'e2e'];
16
+ const TAIL_LINES = 15;
17
+ const DEFAULT_TIMEOUT_MS = 30 * 60 * 1000;
18
+
19
+ function testsFor(config, tier) {
20
+ if (tier === 'e2e') {
21
+ const command = config?.e2e?.command;
22
+ return command ? [{ id: 'e2e', command }] : [];
23
+ }
24
+ const tests = Array.isArray(config?.project?.tests) ? config.project.tests : [];
25
+ return tier === 'fast' ? tests.filter((t) => t.tier === 'fast') : tests;
26
+ }
27
+
28
+ function run(root, t, env) {
29
+ const started = Date.now();
30
+ const r = spawnSync(t.command, {
31
+ cwd: resolve(root, t.cwd ?? '.'), env: { ...env, ...t.env }, shell: true, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024,
32
+ timeout: t.timeoutMs ?? DEFAULT_TIMEOUT_MS, windowsHide: true,
33
+ });
34
+ const out = `${r.stdout ?? ''}${r.stderr ?? ''}`.trimEnd();
35
+ const exit = r.status ?? (r.error ? 124 : 1);
36
+ return { id: t.id, command: t.command, cwd: t.cwd ?? '.', exit, ms: Date.now() - started, tail: exit === 0 ? '' : out.split('\n').slice(-TAIL_LINES).join('\n') };
37
+ }
38
+
39
+ function readChecks(root, feature) {
40
+ if (!feature) return null;
41
+ try { return JSON.parse(readFileSync(getAbsoluteOutputPath(root, feature, 'checks'), 'utf8')); } catch { return null; }
42
+ }
43
+
44
+ function readReport(root, feature) {
45
+ if (!feature) return '';
46
+ try { return readFileSync(getAbsoluteOutputPath(root, feature, 'implementReport'), 'utf8'); } catch { return ''; }
47
+ }
48
+
49
+ function currentBranch(root) {
50
+ try { return git(root, ['rev-parse', '--abbrev-ref', 'HEAD']).trim(); } catch { return null; }
51
+ }
52
+
53
+ /** `## Resultado` is the line the orchestrator reads: it opens the PR as ready or as a draft labelled precisa-humano. */
54
+ export function writeResult(root, feature, result) {
55
+ const path = getAbsoluteOutputPath(root, feature, 'implementReport');
56
+ const lines = [`## Resultado`, '', `status: ${result.status}`];
57
+ for (const s of result.signals) lines.push(`- ${signalText(s)}`);
58
+ const section = `${lines.join('\n')}\n`;
59
+ const text = existsSync(path) ? readFileSync(path, 'utf8') : '';
60
+ const rest = text.replace(/\n?## Resultado\n[\s\S]*?(?=\n## |$)/, '').trimEnd();
61
+ mkdirSync(dirname(path), { recursive: true });
62
+ writeFileSync(path, `${rest ? `${rest}\n\n` : ''}${section}`);
63
+ return path;
64
+ }
65
+
66
+ export function runCheck(root, { tier = 'fast', feature = null, final = false } = {}) {
67
+ const config = readMorphConfig(root) ?? {};
68
+ const limits = config.project?.limits ?? {};
69
+ const env = { ...process.env, ...worktreeEnv(root) };
70
+ const runs = testsFor(config, tier).map((t) => run(root, t, env));
71
+ const checks = readChecks(root, feature);
72
+ const reportText = readReport(root, feature);
73
+ const failures = runs.filter((r) => r.exit !== 0);
74
+
75
+ const files = changedFiles(root, { committed: final });
76
+ // A proposed plan waits for approval: nothing is implemented or reviewed yet, by design.
77
+ const closing = final && checks?.summary?.source !== 'proposta';
78
+ const signals = [
79
+ ...planSignals(checks, limits),
80
+ ...reportSignals(reportText),
81
+ ...(closing ? finalSignals(checks, reportText, runs) : []),
82
+ ...(closing && feature ? reviewSignals(reviewReports(root, feature), (checks?.checks ?? []).map((c) => c.id)) : []),
83
+ ...(final ? uncommittedSignals(root) : []),
84
+ ...(files ? [...riskSignals(files, config.project?.risk), ...sizeSignals(files, limits)] : []),
85
+ ];
86
+ const attempt = recordAttempt(root, currentBranch(root), failures);
87
+ const stuck = stuckSignal(attempt, limits);
88
+ if (stuck) signals.push(stuck);
89
+ if (failures.length) signals.push({ kind: 'vermelho', onde: failures.map((f) => f.id).join(', ') });
90
+
91
+ const status = signals.length ? 'precisa-humano' : 'pronto';
92
+ return { ok: failures.length === 0, tier, feature, runs, signals, stuck: Boolean(stuck), attempt, status, diffKnown: files !== null };
93
+ }
94
+
95
+ export function checkCommand(options = {}) {
96
+ const root = process.cwd();
97
+ if (!contractExists(root)) {
98
+ console.error(chalk.red(NO_CONTRACT_MESSAGE));
99
+ process.exit(2);
100
+ }
101
+ const tier = options.tier ?? 'fast';
102
+ if (!TIERS.includes(tier)) {
103
+ console.error(chalk.red(`--tier ${tier} não existe: ${TIERS.join(', ')}`));
104
+ process.exit(2);
105
+ }
106
+ const feature = options.feature || featureFromBranch(root);
107
+ const result = runCheck(root, { tier, feature, final: Boolean(options.report) });
108
+ if (options.report && feature) result.reportPath = writeResult(root, feature, result);
109
+
110
+ if (options.json) {
111
+ console.log(JSON.stringify(result, null, 2));
112
+ process.exit(result.ok ? 0 : 1);
113
+ }
114
+
115
+ if (!result.runs.length) console.log(chalk.yellow(`Nenhum comando no tier ${tier} do contrato (.morph/config/config.json → project.tests).`));
116
+ for (const r of result.runs) {
117
+ const secs = `${(r.ms / 1000).toFixed(1)}s`;
118
+ console.log(r.exit === 0 ? chalk.green(`✓ ${r.id} (${secs})`) : chalk.red(`✗ ${r.id} (exit ${r.exit}, ${secs})`));
119
+ if (r.exit !== 0) console.log(chalk.gray(r.tail.split('\n').map((l) => ` ${l}`).join('\n')));
120
+ }
121
+ if (!result.diffKnown) console.log(chalk.yellow('Sem base para o diff (branch default não achada): sinais de risco não calculados.'));
122
+ for (const s of result.signals) console.log(chalk.yellow(`⚠ ${signalText(s)}`));
123
+ if (result.stuck) console.log(chalk.red('PARE: sinalize precisa-humano em vez de tentar de novo.'));
124
+ if (!result.ok && !result.stuck) console.log(chalk.red('Vermelho: corrija e rode de novo.'));
125
+ else console.log(result.status === 'pronto' ? chalk.green('Resultado: pronto') : chalk.yellow('Resultado: precisa-humano'));
126
+ if (result.reportPath) console.log(chalk.gray(` ## Resultado gravado em ${result.reportPath}`));
127
+ process.exit(result.ok ? 0 : 1);
128
+ }
@@ -1,27 +1,17 @@
1
1
  import chalk from 'chalk';
2
2
  import { existsSync, readFileSync } from 'fs';
3
3
  import { join } from 'path';
4
- import { atomicWriteJson } from '../../core/state/state-manager.js';
5
- import { getFeature, isGateApproved } from '../../../framework/hooks/shared/state-reader.js';
6
- import { SESSION_MARK } from '../../../framework/hooks/shared/next-step.js';
7
- import { FEATURE_VIEW_FILE, getAbsoluteOutputPath } from '../../core/paths/output-schema.js';
4
+ import { atomicWriteJson } from '../../utils/atomic-json.js';
5
+ import { SESSION_MARK } from '../../../framework/hooks/shared/owner-words.js';
6
+ import { contractExists, NO_CONTRACT_MESSAGE } from '../../../framework/hooks/shared/contract.js';
7
+ import { featureFromBranch } from '../../../framework/hooks/shared/feature-slug.js';
8
+ import { getAbsoluteOutputPath } from '../../core/paths/output-schema.js';
8
9
  import { parsePlan } from '../../lib/plan/plan-parser.js';
9
- import { buildChecks, planHash, planRuleOptions, validatePlan } from '../../lib/plan/checks.js';
10
- import { critiqueByAgent } from '../../lib/plan/critique.js';
11
- import { revocationWarnings } from '../../lib/specs/adr-index.js';
12
- import { assertOwnerTree, ownerTreeRefusalLines } from '../../lib/worktree/feature-truth.js';
13
- import { seedDotnetBuildIgnores } from '../../lib/stack/dotnet-build-ignores.js';
14
- import { reportDotnetIgnores } from '../state/advance.js';
10
+ import { buildChecks, planHash, validatePlan } from '../../lib/plan/checks.js';
11
+ import { revocationWarnings, updateAdrIndex } from '../../lib/specs/adr-index.js';
12
+ import { reportDotnetIgnores, seedDotnetBuildIgnores } from '../../lib/stack/dotnet-build-ignores.js';
15
13
  import { syncStackRules } from '../../lib/installers/stack-sync.js';
16
- import { ownerRef } from '../../../framework/hooks/shared/report-progress.js';
17
-
18
- function nameOf(featureName) {
19
- try { return ownerRef(process.cwd(), featureName, getFeature(featureName, process.cwd())); } catch { return featureName; }
20
- }
21
-
22
- function readJson(path) {
23
- try { return JSON.parse(readFileSync(path, 'utf8')); } catch { return null; }
24
- }
14
+ import { readMorphConfig } from '../../lib/config/project-config.js';
25
15
 
26
16
  /** Parse and judge `2-plan/plan.md` of the project at `cwd`; with no error, write `2-plan/checks.json`. */
27
17
  export function runPlanCheck(featureName, cwd = process.cwd()) {
@@ -32,42 +22,37 @@ export function runPlanCheck(featureName, cwd = process.cwd()) {
32
22
 
33
23
  const text = readFileSync(planPath, 'utf8');
34
24
  const plan = parsePlan(text);
35
- const { errors, warnings } = validatePlan(plan, { ...planRuleOptions(cwd, featureName), text });
25
+ const { errors, warnings } = validatePlan(plan, { text });
36
26
  warnings.push(...revocationWarnings(cwd, plan));
37
- const hash = planHash(text);
38
- const result = { ...base, planHash: hash, errors, warnings, written: false };
39
- if (errors.length > 0) return { ...result, ok: false, exit: 1 };
40
-
41
- const approved = isGateApproved(featureName, 'plan', cwd);
42
- const previous = existsSync(checksPath) ? readJson(checksPath) : null;
43
- if (approved && previous && previous.planHash !== hash) {
44
- return { ...result, ok: false, exit: 1, error: 'frozen', previousHash: previous.planHash ?? null };
27
+ const maxScenarios = readMorphConfig(cwd)?.project?.limits?.maxScenarios;
28
+ if (maxScenarios && plan.scenarios.length > maxScenarios) {
29
+ warnings.push(`${plan.scenarios.length} cenários passam do limite do contrato (${maxScenarios}): divida em PRs menores ou justifique em ## Notas`);
45
30
  }
31
+ const result = { ...base, name: plan.summary?.name ?? null, planHash: planHash(text), errors, warnings, written: false };
32
+ if (errors.length > 0) return { ...result, ok: false, exit: 1 };
46
33
 
47
34
  const checks = buildChecks(featureName, text, plan);
48
35
  atomicWriteJson(checksPath, checks);
49
- const critique = critiqueByAgent(checks, text);
50
- return {
51
- ...result, ok: true, exit: 0, written: true, scenarios: checks.checks.length, viewPath: join(cwd, '.morph', 'features', featureName, FEATURE_VIEW_FILE),
52
- critique: { by: critique.agent ? 'agent' : 'session', reasons: critique.reasons },
53
- };
36
+ const adrs = updateAdrIndex(cwd, join(cwd, '.morph', 'features', featureName));
37
+ return { ...result, ok: true, exit: 0, written: true, scenarios: checks.checks.length, adrs };
54
38
  }
55
39
 
56
- export function planCheckCommand(featureName, options = {}) {
57
- const owner = assertOwnerTree(featureName, process.cwd());
58
- if (owner.blocked) {
59
- for (const { tone, text } of ownerTreeRefusalLines(featureName, owner.tree, owner.branch, `morph-spec plan-check ${featureName}`)) {
60
- console.error(chalk[tone](text));
61
- }
62
- process.exit(1);
40
+ export function planCheckCommand(featureArg, options = {}) {
41
+ const cwd = process.cwd();
42
+ if (!contractExists(cwd)) {
43
+ console.error(chalk.red(NO_CONTRACT_MESSAGE));
44
+ process.exit(2);
45
+ }
46
+ const featureName = featureArg || featureFromBranch(cwd);
47
+ if (!featureName) {
48
+ console.error(chalk.red('Sem feature: passe o nome ou rode dentro de um branch (a pasta da feature vem do branch).'));
49
+ process.exit(2);
63
50
  }
64
51
 
65
- const result = runPlanCheck(featureName);
66
- // After the plan validates: in a greenfield project the plan is where the stack is born.
67
- const stackSync = result.written
68
- ? syncStackRules(process.cwd(), { log: (line) => console.error(chalk.gray(line)) })
69
- : null;
70
- const gitignoreAdded = result.written ? seedDotnetBuildIgnores(process.cwd(), { featureName }) : [];
52
+ const result = runPlanCheck(featureName, cwd);
53
+ // In a greenfield project the plan is where the stack is born.
54
+ const stackSync = result.written ? syncStackRules(cwd, { log: (line) => console.error(chalk.gray(line)) }) : null;
55
+ const gitignoreAdded = result.written ? seedDotnetBuildIgnores(cwd, { featureName }) : [];
71
56
  if (options.json) {
72
57
  if (stackSync?.added.length) result.rulesAdded = stackSync.added;
73
58
  if (gitignoreAdded.length) result.gitignoreAdded = gitignoreAdded;
@@ -76,36 +61,28 @@ export function planCheckCommand(featureName, options = {}) {
76
61
  process.exit(result.exit);
77
62
  }
78
63
 
79
- const ref = nameOf(featureName);
64
+ const ref = result.name ? `${result.name} (${featureName})` : featureName;
80
65
  if (result.error === 'plan-not-found') {
81
66
  console.error(chalk.red(`O plano de ${ref} ainda não existe (${result.plan}).`));
82
- console.error(chalk.gray(` ${SESSION_MARK} o create escreve o esqueleto em 2-plan/plan.md (chore/hotfix: você o cria); gramática completa: morph-spec plan-check --help`));
67
+ console.error(chalk.gray(` ${SESSION_MARK} escreva 2-plan/plan.md; gramática completa: morph-spec plan-check --help`));
83
68
  process.exit(2);
84
69
  }
85
70
 
86
- if (result.error === 'frozen') {
87
- console.log(chalk.red(`✗ O plano de ${ref} já foi aprovado e o texto mudou depois.`));
88
- console.log(chalk.red(' A versão aprovada continua valendo: ela fica congelada.'));
89
- console.log(chalk.gray(' Se era um fato errado sobre o código, a correção vai em ## Errata, no fim do plano.'));
90
- console.log(chalk.gray(' Se o que vai ser feito mudou, o plano volta para a sua aprovação.'));
91
- console.log(chalk.gray(` ${SESSION_MARK} errata não muda o planHash; escopo novo → morph-spec unapprove ${featureName} plan, rode plan-check e reapresente o gate.`));
92
- } else if (!result.ok) {
93
- console.log(chalk.red(`✗ O plano de ${ref} tem ${result.errors.length} problema(s) para corrigir antes de seguir:`));
94
- }
71
+ if (!result.ok) console.log(chalk.red(`✗ O plano de ${ref} tem ${result.errors.length} problema(s) para corrigir antes de seguir:`));
95
72
  for (const e of result.errors) console.log(chalk.red(` ✗ ${e}`));
96
73
  if (result.warnings.length) console.log(chalk.yellow(result.ok ? 'Pontos de atenção:' : 'Também vale olhar:'));
97
74
  for (const w of result.warnings) console.log(chalk.yellow(` ⚠ ${w}`));
98
75
 
99
76
  if (result.ok) {
100
- console.log(chalk.green(`✓ Plano de ${ref} conferido: ${result.scenarios} cenário(s), pronto para aprovação.`));
101
- console.log(chalk.gray(` Página da feature: ${result.viewPath}`));
102
- console.log(chalk.gray(result.critique.by === 'agent'
103
- ? ` Quem revisa o plano: um revisor separado, que não viu a conversa (${result.critique.reasons.join('; ')}).`
104
- : ' Quem revisa o plano: a própria sessão, com a lista de conferência (o plano não tem sinal de risco).'));
77
+ console.log(chalk.green(`✓ Plano de ${ref} conferido: ${result.scenarios} cenário(s). O plan.md congela a partir daqui.`));
105
78
  console.log(chalk.gray(` ${SESSION_MARK} ${join('2-plan', 'checks.json')} gravado (${result.planHash.slice(0, 12)})`));
79
+ const { added = [], revoked = [], narrowed = [] } = result.adrs ?? {};
80
+ if (added.length + revoked.length + narrowed.length) {
81
+ console.log(chalk.gray(` acervo de decisões (.morph/specs/adrs/): ${[...added.map((r) => `+${r}`), ...revoked.map((r) => `-${r}`), ...narrowed.map((r) => `~${r}`)].join(' ')}`));
82
+ }
106
83
  reportDotnetIgnores(gitignoreAdded);
107
- } else if (!result.error) {
108
- console.log(chalk.gray(` ${SESSION_MARK} corrija ${result.plan} e rode morph-spec plan-check ${featureName} de novo; checks.json não foi gravado.`));
84
+ } else {
85
+ console.log(chalk.gray(` ${SESSION_MARK} corrija ${result.plan} e rode morph-spec plan-check de novo; checks.json não foi gravado.`));
109
86
  }
110
87
  process.exit(result.exit);
111
88
  }
@@ -3,7 +3,7 @@ import { execFileSync, spawnSync } from 'child_process';
3
3
  import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs';
4
4
  import { dirname, join } from 'path';
5
5
  import { detectDefaultBranch } from '../../lib/git/default-branch.js';
6
- import { diffLines, fileClass } from '../../lib/risk/diff-risk.js';
6
+ import { diffLines, fileClass } from '../../lib/diff/diff-lines.js';
7
7
 
8
8
  const git = (cwd, args) => execFileSync('git', args, { cwd, stdio: 'pipe' }).toString();
9
9