@polymorphism-tech/morph-spec 10.12.0 → 11.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (323) hide show
  1. package/CLAUDE.md +27 -57
  2. package/README.md +51 -340
  3. package/bin/morph-spec.js +22 -373
  4. package/docs/CHEATSHEET.md +37 -166
  5. package/docs/QUICKSTART.md +14 -74
  6. package/framework/CLAUDE.md +15 -26
  7. package/framework/MORPH.md +34 -101
  8. package/framework/agents.json +8 -8
  9. package/framework/commands/morph-apply.md +5 -5
  10. package/framework/commands/morph-infra.md +1 -1
  11. package/framework/docs/CLI.md +74 -886
  12. package/framework/evals/review-checklist.md +14 -14
  13. package/framework/hooks/README.md +21 -189
  14. package/framework/hooks/claude-code/core/README.md +2 -5
  15. package/framework/hooks/claude-code/core/conventional-commit.js +2 -2
  16. package/framework/hooks/claude-code/core/denylist.json +3 -3
  17. package/framework/hooks/claude-code/core/graph-refresh-kick.js +2 -2
  18. package/framework/hooks/claude-code/core/masked-exit.js +6 -6
  19. package/framework/hooks/claude-code/core/pre-bash-denylist.js +2 -2
  20. package/framework/hooks/claude-code/core/protect-spec-files.js +17 -61
  21. package/framework/hooks/claude-code/core/stack-changed.js +35 -0
  22. package/framework/hooks/claude-code/core/validate-completion.js +31 -86
  23. package/framework/hooks/shared/{heavy-command.js → command-kind.js} +6 -79
  24. package/framework/hooks/shared/command-tokens.js +0 -139
  25. package/framework/hooks/shared/contract.js +14 -0
  26. package/framework/hooks/shared/feature-slug.js +21 -0
  27. package/framework/hooks/shared/frontend-locations.js +0 -1
  28. package/framework/hooks/shared/git-paths.js +0 -15
  29. package/framework/hooks/shared/graph-freshness.js +0 -19
  30. package/framework/hooks/shared/hook-response.js +0 -7
  31. package/framework/hooks/shared/morph-cli.js +2 -81
  32. package/framework/hooks/shared/owner-words.js +2 -120
  33. package/framework/hooks/shared/payload-utils.js +0 -39
  34. package/framework/hooks/shared/report-progress.js +7 -101
  35. package/framework/hooks/statusline.js +16 -60
  36. package/framework/mcp/registry.json +2 -2
  37. package/framework/rules/ai-agents-standards.md +1 -1
  38. package/framework/rules/asaas-standards.md +1 -1
  39. package/framework/rules/ef-standards.md +1 -1
  40. package/framework/rules/gsap-standards.md +1 -1
  41. package/framework/rules/hangfire-standards.md +1 -1
  42. package/framework/rules/implement-report.md +3 -3
  43. package/framework/rules/neon-auth-standards.md +1 -1
  44. package/framework/rules/nextjs-standards.md +1 -1
  45. package/framework/rules/plan-grammar.md +13 -11
  46. package/framework/rules/resend-standards.md +1 -1
  47. package/framework/rules/ui-design.md +4 -0
  48. package/framework/schemas/config.schema.json +95 -310
  49. package/framework/skills/README.md +12 -32
  50. package/framework/skills/core/create-umbraco-lp/SKILL.md +1 -1
  51. package/framework/skills/core/migrate-lp-to-umbraco/SKILL.md +1 -1
  52. package/framework/skills/core/morph-apply/SKILL.md +21 -46
  53. package/framework/skills/core/morph-plan/SKILL.md +28 -63
  54. package/framework/skills/core/morph-uiux/SKILL.md +23 -25
  55. package/framework/{templates/docs/ui-mockups.md → skills/core/morph-uiux/references/mockups.md} +4 -4
  56. package/framework/standards/STANDARDS.json +10 -11
  57. package/framework/standards/STANDARDS.meta.json +1 -1
  58. package/framework/standards/ai-agents/evals-with-cache.md +18 -32
  59. package/framework/standards/ai-agents/observability-patterns.md +2 -2
  60. package/framework/standards/architecture/code-comments.md +2 -5
  61. package/framework/standards/architecture/engineering-lens.md +1 -1
  62. package/framework/standards/backend/dotnet/testing.md +4 -4
  63. package/framework/standards/frontend/nextjs/lint.md +24 -10
  64. package/framework/standards/frontend/nextjs/testing.md +2 -2
  65. package/framework/standards/infrastructure/docker/local-compose-isolation.md +14 -30
  66. package/framework/templates/CLAUDE.md.core.guide.md +2 -2
  67. package/framework/templates/README.md +1 -1
  68. package/framework/templates/REGISTRY.json +3 -33
  69. package/framework/templates/docs/plan.md +3 -2
  70. package/framework/templates/dotnet/ai-kit/README.md +2 -4
  71. package/framework/templates/dotnet/ai-kit/src/Morph.AiKit/Evals/EvalCacheMissException.cs +1 -1
  72. package/framework/templates/dotnet/ai-kit/src/Morph.AiKit/Evals/EvalFixture.cs +1 -1
  73. package/package.json +1 -2
  74. package/src/commands/graph/explain.js +2 -1
  75. package/src/commands/graph/status.js +2 -1
  76. package/src/commands/mcp/mcp-setup.js +1 -2
  77. package/src/commands/project/doctor.js +5 -341
  78. package/src/commands/project/env.js +21 -52
  79. package/src/commands/project/init-contract.js +47 -0
  80. package/src/commands/project/init.js +36 -66
  81. package/src/commands/project/stack-scan.js +1 -1
  82. package/src/commands/project/update.js +15 -50
  83. package/src/commands/validation/check.js +128 -0
  84. package/src/commands/validation/plan-check.js +41 -64
  85. package/src/commands/validation/prove-red.js +1 -1
  86. package/src/core/paths/output-schema.js +0 -22
  87. package/src/core/templates/template-renderer.js +0 -14
  88. package/src/lib/ai/ai-project-scan.js +1 -6
  89. package/src/lib/check/attempts.js +38 -0
  90. package/src/lib/check/signals.js +145 -0
  91. package/src/lib/config/project-config.js +13 -0
  92. package/src/lib/contract/apply.js +62 -0
  93. package/src/lib/contract/defaults.js +96 -0
  94. package/src/lib/contract/merge.js +79 -0
  95. package/src/lib/contract/ports.js +43 -0
  96. package/src/lib/contract/scan.js +102 -0
  97. package/src/lib/detectors/claude-config-detector.js +7 -0
  98. package/src/lib/{procs → detectors}/mcp-config.js +1 -37
  99. package/src/lib/diff/diff-lines.js +64 -0
  100. package/src/lib/generators/architecture-scanner.js +1 -1
  101. package/src/lib/generators/scaffold-generator.js +0 -7
  102. package/src/lib/git/default-branch.js +0 -122
  103. package/src/lib/graph/diff-tree.js +2 -1
  104. package/src/lib/graph/god-nodes.js +2 -1
  105. package/src/lib/graph/graphify-runtime.js +0 -1
  106. package/src/lib/graph/graphifyignore.js +1 -1
  107. package/src/lib/graph/sanitize.js +2 -8
  108. package/src/lib/installers/memory-installer.js +15 -30
  109. package/src/lib/installers/stack-sync.js +16 -9
  110. package/src/lib/plan/checks.js +20 -64
  111. package/src/lib/plan/media.js +1 -1
  112. package/src/lib/plan/plan-parser.js +5 -5
  113. package/src/lib/review-reports.js +3 -77
  114. package/src/lib/scan/worktree-dirs.js +3 -0
  115. package/src/lib/specs/adr-index.js +2 -2
  116. package/src/lib/stack/dotnet-build-ignores.js +10 -2
  117. package/src/lib/stack/stack-scan.js +2 -2
  118. package/src/lib/stack-filter.js +3 -2
  119. package/src/lib/tests-audit/audit.js +1 -1
  120. package/src/scripts/setup-infra.js +6 -59
  121. package/src/utils/agents-installer.js +1 -34
  122. package/src/utils/atomic-json.js +27 -0
  123. package/src/utils/file-copier.js +4 -12
  124. package/src/utils/hooks-installer.js +9 -107
  125. package/claude-plugin.json +0 -14
  126. package/framework/commands/morph-archive.md +0 -46
  127. package/framework/commands/morph-hotfix.md +0 -17
  128. package/framework/commands/morph-preflight.md +0 -180
  129. package/framework/commands/morph-review.md +0 -15
  130. package/framework/commands/morph-status.md +0 -37
  131. package/framework/hooks/claude-code/core/block-destructive-worktree-removal.js +0 -80
  132. package/framework/hooks/claude-code/core/block-raw-worktree-add.js +0 -72
  133. package/framework/hooks/claude-code/core/enforce-phase-writes.js +0 -100
  134. package/framework/hooks/claude-code/core/gate-guard.js +0 -148
  135. package/framework/hooks/claude-code/core/heavy-gate.js +0 -78
  136. package/framework/hooks/claude-code/core/heavy-release.js +0 -23
  137. package/framework/hooks/claude-code/core/loop-detect.js +0 -79
  138. package/framework/hooks/claude-code/core/state-sync.js +0 -214
  139. package/framework/hooks/claude-code/core/telemetry-log.js +0 -259
  140. package/framework/hooks/claude-code/core/test-budget.js +0 -29
  141. package/framework/hooks/claude-code/core/worktree-context.js +0 -249
  142. package/framework/hooks/claude-code/core/worktree-create.js +0 -119
  143. package/framework/hooks/claude-code/core/worktree-env-inject.js +0 -68
  144. package/framework/hooks/claude-code/core/worktree-remove.js +0 -55
  145. package/framework/hooks/shared/build-check.js +0 -120
  146. package/framework/hooks/shared/claim-registry.js +0 -125
  147. package/framework/hooks/shared/e2e-check.js +0 -1022
  148. package/framework/hooks/shared/feature-locator.js +0 -82
  149. package/framework/hooks/shared/gate-event.js +0 -18
  150. package/framework/hooks/shared/gate-question.js +0 -20
  151. package/framework/hooks/shared/heavy-config.js +0 -113
  152. package/framework/hooks/shared/heavy-holders.js +0 -85
  153. package/framework/hooks/shared/heavy-slots.js +0 -280
  154. package/framework/hooks/shared/host-services.js +0 -440
  155. package/framework/hooks/shared/next-step.js +0 -181
  156. package/framework/hooks/shared/redact-secrets.js +0 -44
  157. package/framework/hooks/shared/reparse-scan.js +0 -40
  158. package/framework/hooks/shared/state-reader.js +0 -220
  159. package/framework/hooks/shared/state-writer.js +0 -112
  160. package/framework/hooks/shared/telemetry-logger.js +0 -101
  161. package/framework/hooks/shared/transcript-usage.js +0 -58
  162. package/framework/hooks/shared/worktree-root.js +0 -71
  163. package/framework/phases.json +0 -92
  164. package/framework/schemas/feature.schema.json +0 -242
  165. package/framework/skills/core/morph-apply/references/hotfix.md +0 -46
  166. package/framework/skills/core/morph-apply/references/machine.md +0 -30
  167. package/framework/skills/core/morph-apply/references/review.md +0 -77
  168. package/framework/skills/core/morph-plan/references/critique.md +0 -51
  169. package/framework/skills/core/morph-plan/references/interview.md +0 -37
  170. package/framework/templates/state.template.json +0 -17
  171. package/src/commands/dashboard/dashboard.js +0 -74
  172. package/src/commands/e2e/e2e.js +0 -400
  173. package/src/commands/observability/cost.js +0 -283
  174. package/src/commands/project/branch.js +0 -129
  175. package/src/commands/project/claim.js +0 -132
  176. package/src/commands/project/doctor-procs.js +0 -162
  177. package/src/commands/project/fleet.js +0 -66
  178. package/src/commands/project/heavy.js +0 -81
  179. package/src/commands/project/install-plugin-cmd.js +0 -27
  180. package/src/commands/project/status.js +0 -61
  181. package/src/commands/project/worktree.js +0 -1234
  182. package/src/commands/state/advance.js +0 -248
  183. package/src/commands/state/approve.js +0 -303
  184. package/src/commands/state/archive.js +0 -231
  185. package/src/commands/state/auto-approval.js +0 -67
  186. package/src/commands/state/create.js +0 -274
  187. package/src/commands/state/delete.js +0 -192
  188. package/src/commands/state/finish.js +0 -1247
  189. package/src/commands/state/gate-check.js +0 -244
  190. package/src/commands/state/gate-decision.js +0 -122
  191. package/src/commands/state/list.js +0 -244
  192. package/src/commands/state/next.js +0 -24
  193. package/src/commands/state/recap.js +0 -80
  194. package/src/commands/state/report-check.js +0 -244
  195. package/src/commands/state/retype.js +0 -110
  196. package/src/commands/validation/verify.js +0 -421
  197. package/src/core/state/feature-identity.js +0 -10
  198. package/src/core/state/gate-order.js +0 -23
  199. package/src/core/state/lifecycle-audit.js +0 -171
  200. package/src/core/state/state-manager.js +0 -523
  201. package/src/core/templates/template-seed.js +0 -21
  202. package/src/core/work-types.js +0 -44
  203. package/src/dashboard/app/App.jsx +0 -84
  204. package/src/dashboard/app/components/ActivityFeed.jsx +0 -166
  205. package/src/dashboard/app/components/CommandPalette.jsx +0 -144
  206. package/src/dashboard/app/components/DetailPanel.jsx +0 -43
  207. package/src/dashboard/app/components/EntityLink.jsx +0 -42
  208. package/src/dashboard/app/components/ErrorBoundary.jsx +0 -47
  209. package/src/dashboard/app/components/FlowGraph.jsx +0 -19
  210. package/src/dashboard/app/components/GatePauses.jsx +0 -116
  211. package/src/dashboard/app/components/KnowledgeMarkdown.jsx +0 -42
  212. package/src/dashboard/app/components/Markdown.jsx +0 -38
  213. package/src/dashboard/app/components/PhaseRail.jsx +0 -100
  214. package/src/dashboard/app/components/SearchFilter.jsx +0 -36
  215. package/src/dashboard/app/components/SessionMap.jsx +0 -77
  216. package/src/dashboard/app/components/Sidebar.jsx +0 -147
  217. package/src/dashboard/app/hooks/useMorphQuery.js +0 -44
  218. package/src/dashboard/app/hooks/usePref.js +0 -34
  219. package/src/dashboard/app/lib/format.js +0 -69
  220. package/src/dashboard/app/lib/phases.js +0 -75
  221. package/src/dashboard/app/lib/project.js +0 -38
  222. package/src/dashboard/app/main.jsx +0 -13
  223. package/src/dashboard/app/pages/Activity.jsx +0 -28
  224. package/src/dashboard/app/pages/AgentMap.jsx +0 -363
  225. package/src/dashboard/app/pages/FeatureDetail.jsx +0 -579
  226. package/src/dashboard/app/pages/Features.jsx +0 -393
  227. package/src/dashboard/app/pages/Guide.jsx +0 -145
  228. package/src/dashboard/app/pages/HookInspector.jsx +0 -444
  229. package/src/dashboard/app/pages/PhasePipeline.jsx +0 -273
  230. package/src/dashboard/app/pages/Portfolio.jsx +0 -190
  231. package/src/dashboard/app/pages/RulesMap.jsx +0 -285
  232. package/src/dashboard/app/pages/SkillsLibrary.jsx +0 -468
  233. package/src/dashboard/app/pages/Standards.jsx +0 -392
  234. package/src/dashboard/app/styles/index.css +0 -187
  235. package/src/dashboard/index.html +0 -14
  236. package/src/dashboard/package.json +0 -32
  237. package/src/dashboard/scanner/activity-scanner.js +0 -321
  238. package/src/dashboard/scanner/agents-scanner.js +0 -67
  239. package/src/dashboard/scanner/docs-scanner.js +0 -34
  240. package/src/dashboard/scanner/feature-status.js +0 -7
  241. package/src/dashboard/scanner/features-scanner.js +0 -397
  242. package/src/dashboard/scanner/hooks-scanner.js +0 -96
  243. package/src/dashboard/scanner/index.js +0 -21
  244. package/src/dashboard/scanner/phases-scanner.js +0 -14
  245. package/src/dashboard/scanner/portfolio.js +0 -129
  246. package/src/dashboard/scanner/project-api.js +0 -160
  247. package/src/dashboard/scanner/rules-scanner.js +0 -46
  248. package/src/dashboard/scanner/skills-scanner.js +0 -104
  249. package/src/dashboard/scanner/standards-scanner.js +0 -38
  250. package/src/dashboard/vite-plugin-morph-data.js +0 -120
  251. package/src/dashboard/vite.config.js +0 -26
  252. package/src/lib/ci/ci-verify.js +0 -30
  253. package/src/lib/ci/github-ci.js +0 -52
  254. package/src/lib/ci/pr-checks.js +0 -76
  255. package/src/lib/e2e/applicability.js +0 -39
  256. package/src/lib/e2e/compose-env.js +0 -80
  257. package/src/lib/e2e/stack-teardown.js +0 -96
  258. package/src/lib/git/branch-classifier.js +0 -104
  259. package/src/lib/git/evidence-staleness.js +0 -40
  260. package/src/lib/git/gh.js +0 -15
  261. package/src/lib/git/pending-prs.js +0 -58
  262. package/src/lib/git/pr-files.js +0 -31
  263. package/src/lib/git/pr-index.js +0 -39
  264. package/src/lib/git/tree-fingerprint.js +0 -58
  265. package/src/lib/git/tree-state.js +0 -125
  266. package/src/lib/heavy/cleanup.js +0 -72
  267. package/src/lib/heavy/gate.js +0 -168
  268. package/src/lib/heavy/live-stacks.js +0 -64
  269. package/src/lib/heavy/reclaim.js +0 -107
  270. package/src/lib/heavy/watchdog.js +0 -46
  271. package/src/lib/next-step.js +0 -12
  272. package/src/lib/plan/critique.js +0 -67
  273. package/src/lib/plan/plan-template.js +0 -18
  274. package/src/lib/procs/classify.js +0 -91
  275. package/src/lib/procs/list.js +0 -124
  276. package/src/lib/procs/prune.js +0 -47
  277. package/src/lib/procs/wslconfig.js +0 -70
  278. package/src/lib/projects/registry.js +0 -121
  279. package/src/lib/recap/piper.js +0 -36
  280. package/src/lib/recap/recap.js +0 -259
  281. package/src/lib/review-confirmation.js +0 -66
  282. package/src/lib/risk/diff-risk.js +0 -137
  283. package/src/lib/risk-detector.js +0 -638
  284. package/src/lib/specs/design-seed.js +0 -18
  285. package/src/lib/specs/screen-checklist.js +0 -315
  286. package/src/lib/stack/stack-profile.js +0 -69
  287. package/src/lib/tasks/eval-node.js +0 -293
  288. package/src/lib/tasks/linux-runner.js +0 -200
  289. package/src/lib/tasks/test-nodes.js +0 -414
  290. package/src/lib/tasks/test-runner.js +0 -569
  291. package/src/lib/telemetry/metrics.js +0 -384
  292. package/src/lib/telemetry/telemetry-reader.js +0 -276
  293. package/src/lib/telemetry/verify-event.js +0 -57
  294. package/src/lib/validators/code-budget/code-budget-validator.js +0 -170
  295. package/src/lib/validators/contracts/contract-compliance-validator.js +0 -219
  296. package/src/lib/validators/nextjs/next-component-validator.js +0 -142
  297. package/src/lib/validators/packages/package-validator.js +0 -310
  298. package/src/lib/validators/reuse/reuse-validator.js +0 -202
  299. package/src/lib/validators/reuse/symbol-scanner.js +0 -64
  300. package/src/lib/validators/validation-runner.js +0 -188
  301. package/src/lib/validators/verify-cache.js +0 -63
  302. package/src/lib/validators/verify-runner.js +0 -971
  303. package/src/lib/verify/affected.js +0 -143
  304. package/src/lib/verify/detached.js +0 -159
  305. package/src/lib/view/feature-html.js +0 -480
  306. package/src/lib/view/feature-page.client.js +0 -109
  307. package/src/lib/view/feature-page.css +0 -278
  308. package/src/lib/view/feature-view.js +0 -113
  309. package/src/lib/view/flow-layers.js +0 -79
  310. package/src/lib/view/flow-svg.js +0 -63
  311. package/src/lib/view/tokens.css +0 -18
  312. package/src/lib/work-type-detector.js +0 -81
  313. package/src/lib/worktree/dirs.js +0 -3
  314. package/src/lib/worktree/docker-audit.js +0 -175
  315. package/src/lib/worktree/env-allocator.js +0 -177
  316. package/src/lib/worktree/feature-truth.js +0 -145
  317. package/src/lib/worktree/finish-backup.js +0 -529
  318. package/src/lib/worktree/fleet-scanner.js +0 -223
  319. package/src/lib/worktree/ignored-triage.js +0 -136
  320. package/src/lib/worktree/vscode-settings.js +0 -112
  321. package/src/lib/worktree/worktree-audit.js +0 -323
  322. package/src/lib/worktree/worktree-include.js +0 -44
  323. package/src/scripts/install-plugin.js +0 -114
@@ -1,9 +1,5 @@
1
1
  import { createHash } from 'crypto';
2
- import { existsSync, readFileSync } from 'fs';
3
- import { getAbsoluteOutputPath } from '../../core/paths/output-schema.js';
4
2
  import { frozenBody } from '../../../framework/hooks/shared/errata.js';
5
- import { getFeature } from '../../../framework/hooks/shared/state-reader.js';
6
- import { planNames } from '../../../framework/hooks/shared/report-progress.js';
7
3
  import { findArtifactTerms } from './artifact-vocabulary.js';
8
4
  import { mediaCitationError } from './media.js';
9
5
  import { scenarioLabel, WORK_NAME } from '../../../framework/hooks/shared/owner-words.js';
@@ -16,14 +12,6 @@ export function planHash(text) {
16
12
  return createHash('sha256').update(frozenBody(text), 'utf8').digest('hex');
17
13
  }
18
14
 
19
- // A frozen body already extracted under older rules cannot gain a `risco:` line, so it is not demanded.
20
- export function planRuleOptions(cwd, featureName) {
21
- return {
22
- workType: getFeature(featureName, cwd)?.workType ?? null,
23
- riskRules: readPlanChecks(cwd, featureName).status !== 'fresh',
24
- };
25
- }
26
-
27
15
  const foldRisk = (s) => s.normalize('NFD').replace(/\p{M}/gu, '').replace(/`/g, '').toLowerCase().trim();
28
16
  const RISK_BY_FOLD = new Map(RISK_KINDS.map((r) => [foldRisk(r), r]));
29
17
  const RUNG_BY_FOLD = new Map(REWORK_RUNGS.map((r) => [foldRisk(r), r]));
@@ -50,10 +38,10 @@ function transitionErrors(plan, key, at) {
50
38
  return errors;
51
39
  }
52
40
 
53
- function defaultsErrors(plan, { workType, riskRules }, at) {
41
+ function defaultsErrors(plan, workType, at) {
54
42
  const { items, none } = plan.defaults;
55
43
  if (!plan.present.defaults) {
56
- return riskRules && !POLICY_PLAN_WORK_TYPES.includes(workType)
44
+ return !POLICY_PLAN_WORK_TYPES.includes(workType)
57
45
  ? [`seção obrigatória ausente: ## ${SECTIONS.defaults} — numere o que você decidiu sem perguntar, ou escreva "nenhum"`]
58
46
  : [];
59
47
  }
@@ -65,10 +53,14 @@ function defaultsErrors(plan, { workType, riskRules }, at) {
65
53
  : [];
66
54
  }
67
55
 
68
- export function validatePlan(plan, { workType = null, riskRules = true, text = null } = {}) {
56
+ export function validatePlan(plan, { text = null } = {}) {
69
57
  const errors = [];
70
58
  const warnings = [];
71
- const media = riskRules ? mediaCitationError(text) : null;
59
+ const workType = plan.summary?.kind ?? null;
60
+ if (workType !== null && !WORK_NAME[workType]) {
61
+ errors.push(`## Resumo: "- Tipo: ${workType}" não existe — use ${Object.keys(WORK_NAME).join(', ')}`);
62
+ }
63
+ const media = mediaCitationError(text);
72
64
  if (media) errors.push(media);
73
65
  const at = (line) => (line ? ` (linha ${line})` : '');
74
66
 
@@ -102,10 +94,10 @@ export function validatePlan(plan, { workType = null, riskRules = true, text = n
102
94
  const risk = c.risk === null ? null : RISK_BY_FOLD.get(foldRisk(c.risk)) ?? false;
103
95
  if (risk === false) {
104
96
  errors.push(`${name}: "risco: ${c.risk}" não é uma das opções (${RISK_KINDS.join(' | ')})${at(c.line)}`);
105
- } else if (riskRules && proof === 'teste' && risk === null) {
97
+ } else if (proof === 'teste' && risk === null) {
106
98
  errors.push(`${name}: tem "prova: teste" mas não diz o "risco:" (${RISK_KINDS.join(' | ')}). Sem risco, a prova é "leitura" ou "e2e"${at(c.line)}`);
107
99
  } else if (risk && proof === 'leitura') {
108
- (riskRules ? errors : warnings).push(`${name}: tem "risco: ${risk}" e é provado só lendo o código. Cenário com risco se prova rodando ("teste" ou "e2e")${at(c.line)}`);
100
+ errors.push(`${name}: tem "risco: ${risk}" e é provado só lendo o código. Cenário com risco se prova rodando ("teste" ou "e2e")${at(c.line)}`);
109
101
  }
110
102
  if (canonicalRung(c.rung) === false) {
111
103
  errors.push(`${name}: "degrau: ${c.rung}" não é uma das opções (${REWORK_RUNGS.join(' | ')})${at(c.line)}`);
@@ -117,27 +109,23 @@ export function validatePlan(plan, { workType = null, riskRules = true, text = n
117
109
  }
118
110
 
119
111
  const isRegression = (c) => ['teste', 'e2e'].includes(c.proof?.toLowerCase()) && c.risk !== null && RISK_BY_FOLD.get(foldRisk(c.risk)) === 'regressão';
120
- if (riskRules && REGRESSION_WORK_TYPES.includes(workType) && plan.scenarios.length > 0 && !plan.scenarios.some(isRegression)) {
112
+ if (REGRESSION_WORK_TYPES.includes(workType) && plan.scenarios.length > 0 && !plan.scenarios.some(isRegression)) {
121
113
  errors.push(`${WORK_NAME[workType]} sem cenário que prove que o bug não volta (${workType}): escreva um cenário com o sintoma real, "prova: teste" e "risco: regressão"`);
122
114
  }
123
115
 
124
- errors.push(...defaultsErrors(plan, { workType, riskRules }, at));
116
+ errors.push(...defaultsErrors(plan, workType, at));
125
117
  errors.push(...transitionErrors(plan, 'states', at), ...transitionErrors(plan, 'flow', at));
126
118
  warnings.push(...defaultsWarnings(plan, at));
127
- if (riskRules && !(plan.summary.today && plan.summary.after)) {
128
- warnings.push(`## ${SECTIONS.summary} sem "- Hoje:" e "- Depois:" — a página da feature abre com o texto técnico do plano; escreva as duas linhas para quem não lê código`);
119
+ if (!(plan.summary.today && plan.summary.after)) {
120
+ warnings.push(`## ${SECTIONS.summary} sem "- Hoje:" e "- Depois:" — o PR e a revisão abrem com o texto técnico do plano; escreva as duas linhas para quem não lê código`);
129
121
  }
130
- const bare = riskRules ? plan.adrs.filter((a) => !(a.plain.decided && a.plain.why && a.plain.cost)).map((a) => a.id) : [];
122
+ const bare = plan.adrs.filter((a) => !(a.plain.decided && a.plain.why && a.plain.cost)).map((a) => a.id);
131
123
  if (bare.length) {
132
- warnings.push(`${bare.join(', ')} sem "**Decidimos:**", "**Por quê:**" e "**O que custa:**" — a página mostra a decisão por essas três linhas, uma frase cada, sem código`);
124
+ warnings.push(`${bare.join(', ')} sem "**Decidimos:**", "**Por quê:**" e "**O que custa:**" — uma frase cada, sem código: é o que o revisor e o PR mostram da decisão`);
133
125
  }
134
126
 
135
- const isSlices = (s) => /^fatias$/i.test(s.name.trim());
136
- if (plan.sections.some((s) => !s.key && isSlices(s))) {
137
- warnings.push('## Fatias não é lida desde a 10.0: o plano inteiro se implementa numa sessão, e os cenários definem o pronto');
138
- }
139
127
  const known = new Set(Object.values(SECTIONS).map(foldRisk));
140
- for (const s of plan.sections.filter((section) => !section.key && !isSlices(section))) {
128
+ for (const s of plan.sections.filter((section) => !section.key)) {
141
129
  warnings.push(known.has(foldRisk(s.name))
142
130
  ? `## ${s.name} repetida${at(s.line)} — só a primeira é lida, o conteúdo desta se perde`
143
131
  : `## ${s.name} não é seção do plano${at(s.line)}: a conferência do plano não a lê`);
@@ -172,38 +160,6 @@ export function buildChecks(feature, text, plan) {
172
160
  };
173
161
  }
174
162
 
175
- const summaryOf = (plan) => ({ name: plan.summary?.name ?? null, after: plan.summary?.after ?? null });
176
-
177
- /** plan-check writes the checks only with zero errors, so `fresh` also means the plan passed every rule. */
178
- export function readPlanChecks(cwd, featureName) {
179
- const planPath = getAbsoluteOutputPath(cwd, featureName, 'plan');
180
- const checksPath = getAbsoluteOutputPath(cwd, featureName, 'checks');
181
- if (!existsSync(planPath)) return { status: 'no-plan', checks: null };
182
- if (!existsSync(checksPath)) return { status: 'no-checks', checks: null };
183
- let checks;
184
- try {
185
- checks = JSON.parse(readFileSync(checksPath, 'utf8'));
186
- } catch {
187
- return { status: 'unreadable', checks: null };
188
- }
189
- if (checks?.version !== CHECKS_VERSION || !Array.isArray(checks.checks)) {
190
- return { status: 'unreadable', checks: null };
191
- }
192
- let plan;
193
- try {
194
- plan = readFileSync(planPath, 'utf8');
195
- } catch {
196
- return { status: 'no-plan', checks };
197
- }
198
- return { status: checks.planHash === planHash(plan) ? 'fresh' : 'stale', checks: withPlanNames(checks, plan) };
199
- }
200
-
201
- function withPlanNames(checks, planText) {
202
- if (checks.summary && checks.checks.every((c) => c?.title)) return checks;
203
- const { titles, summary } = planNames(planText);
204
- return {
205
- ...checks,
206
- summary: checks.summary ?? summary,
207
- checks: checks.checks.map((c) => (c?.title || !titles.has(c?.id) ? c : { ...c, title: titles.get(c.id) })),
208
- };
209
- }
163
+ // The scenarios came from the issue, or the agent proposed them because the issue had none: then someone approves first.
164
+ const sourceOf = (text) => (/^propost/i.test(String(text ?? '').trim()) ? 'proposta' : text ? 'issue' : null);
165
+ const summaryOf = (plan) => ({ name: plan.summary?.name ?? null, after: plan.summary?.after ?? null, source: sourceOf(plan.summary?.source) });
@@ -38,5 +38,5 @@ export function mediaCitationError(planText) {
38
38
  const hit = GENERATED_MEDIA_RE.exec(text);
39
39
  if (!hit) return null;
40
40
  return `o plano fala em mídia gerada ("${hit[0].trim()}") sem citar o standard: cite ${MEDIA_STANDARD_IDS.map((id) => `\`${id}\``).join(', ')} `
41
- + 'conforme o caso (é o que arma as provas de mídia do Gate 3), ou escreva a linha "Mídia gerada: não" se nada é gerado por IA';
41
+ + 'conforme o caso (é o que arma as provas de mídia na revisão), ou escreva a linha "Mídia gerada: não" se nada é gerado por IA';
42
42
  }
@@ -33,9 +33,9 @@ const PROOF_RE = /^\s*prova\s*:\s*(.*?)\s*$/i;
33
33
  const RISK_RE = /^\s*risco\s*:\s*(.*?)\s*$/i;
34
34
  const RUNG_RE = /^\s*degrau\s*:\s*(.*?)\s*$/i;
35
35
  const TITLE_RE = /^\s*t[ií]tulo\s*:\s*(.*?)\s*$/i;
36
- const SUMMARY_RE = /^\s*[-*]\s+\**\s*(nome|hoje|depois|aten[çc][ãa]o)\s*\**\s*:\s*\**\s*(.+?)\s*$/i;
37
- const SUMMARY_KEYS = { nome: 'name', hoje: 'today', depois: 'after' };
38
- export const ADR_PLAIN_LABELS = { decided: 'Decidimos', why: 'Por quê', cost: 'O que custa' };
36
+ const SUMMARY_RE = /^\s*[-*]\s+\**\s*(nome|tipo|hoje|depois|origem|aten[çc][ãa]o)\s*\**\s*:\s*\**\s*(.+?)\s*$/i;
37
+ const SUMMARY_KEYS = { nome: 'name', tipo: 'kind', hoje: 'today', depois: 'after', origem: 'source' };
38
+
39
39
  export const ADR_PLAIN = {
40
40
  decided: /^\s*\*\*Decidimos:\*\*\s*(.+?)\s*$/im,
41
41
  why: /^\s*\*\*Por qu[eê]:\*\*\s*(.+?)\s*$/im,
@@ -154,7 +154,7 @@ function parseReuse(lines) {
154
154
  }
155
155
 
156
156
  function parseSummary(lines) {
157
- const found = { name: null, today: null, after: null, watch: [] };
157
+ const found = { name: null, kind: null, today: null, after: null, source: null, watch: [] };
158
158
  const rest = [];
159
159
  let open = null;
160
160
  for (const line of lines) {
@@ -170,7 +170,7 @@ function parseSummary(lines) {
170
170
  open = null;
171
171
  rest.push(line.raw);
172
172
  }
173
- return { name: found.name?.text ?? null, today: found.today?.text ?? null, after: found.after?.text ?? null, watch: found.watch.map((w) => w.text), rest: rest.join('\n').trim() };
173
+ return { name: found.name?.text ?? null, kind: found.kind?.text.trim().toLowerCase() ?? null, today: found.today?.text ?? null, after: found.after?.text ?? null, source: found.source?.text ?? null, watch: found.watch.map((w) => w.text), rest: rest.join('\n').trim() };
174
174
  }
175
175
 
176
176
  function parseDefaults(lines) {
@@ -1,14 +1,12 @@
1
1
  import { existsSync, readFileSync } from 'fs';
2
2
  import { join } from 'path';
3
- import { OUTPUT_SCHEMA, getAbsoluteOutputPath } from '../core/paths/output-schema.js';
3
+ import { OUTPUT_SCHEMA } from '../core/paths/output-schema.js';
4
4
  import { PARTIAL_MARKER } from '../../framework/hooks/shared/report-progress.js';
5
5
 
6
6
  export const VERDICT_TOKEN = '**Verdict:**';
7
7
  export const REVIEWED_SHA_TOKEN = '**Reviewed-SHA:**';
8
8
  export const VERDICTS = ['SHIP', 'FIX'];
9
9
  export const BLOCKER_TYPES = ['check', 'teste', 'regressao', 'seguranca', 'escopo', 'arquitetura', 'performance', 'irreversivel'];
10
- // The plan is frozen by then: the session cannot declare the rung itself, only the human can accept it.
11
- export const HUMAN_BLOCKER_TYPES = ['irreversivel'];
12
10
  export const CHECK_STATUSES = ['PROVADO', 'NÃO PROVADO', 'FALHA'];
13
11
 
14
12
  export const REVIEW_ROLES = {
@@ -27,21 +25,6 @@ const REVIEWED_SHA_RE = /\*\*Reviewed-SHA:\*\*\s*`?([0-9a-f]{7,40})/gi;
27
25
  const sectionRe = (title) => new RegExp(`^(#{2,3})\\s+${title}\\s*$`, 'gim');
28
26
  const BLOCKERS_SECTION_RE = sectionRe('Bloqueadores');
29
27
  const CHECKS_SECTION_RE = sectionRe('Checks');
30
- const MEDIA_SECTION_RE = /^##\s+M[íi]dia\s+gerada\s*$/m;
31
- const SCREEN_CHECKLIST_SECTION_RE = sectionRe('Checklist\\s+de\\s+tela');
32
-
33
- /**
34
- * Hotfix: só o verificador, escrito pelo orquestrador sem dispatch. Fora dele manda o `risk` do diff
35
- * (`src/lib/risk/diff-risk.js`): `low`/`none` = só o revisor, escrito pela sessão com o checklist.
36
- * Sem risco medido, o tipo decide (chore leve).
37
- */
38
- export function requiredReviewRoles({ workType, securityRequired = false, risk = null } = {}) {
39
- // Sem `security` mesmo em caminho sensível: o humano assina todo hotfix.
40
- if (workType === 'hotfix') return ['verifier'];
41
- const light = risk ? ['low', 'none'].includes(risk) : workType === 'chore';
42
- const base = light ? ['reviewer'] : ['verifier', 'reviewer'];
43
- return securityRequired ? [...base, 'security'] : base;
44
- }
45
28
 
46
29
  function sectionBodies(text, re) {
47
30
  return [...text.matchAll(re)].map((m) => {
@@ -153,7 +136,7 @@ function parseRound(text) {
153
136
  };
154
137
  }
155
138
 
156
- // `partial`: `PARCIAL` na 1ª linha, com ou sem veredito. `ok` só diz legível: quem decide é o risk-detector.
139
+ // `partial`: `PARCIAL` na 1ª linha, com ou sem veredito. `ok` só diz legível.
157
140
  function stateOf(path, text) {
158
141
  if (text === null) return { status: 'missing', path };
159
142
  const parsed = parseReviewReport(text);
@@ -170,8 +153,7 @@ function readText(path) {
170
153
  }
171
154
  }
172
155
 
173
- /** Os três relatórios a partir do diretório da feature — sem git; o dashboard lê árvores arquivadas. */
174
- export function reviewReportsFromDir(featureDir) {
156
+ function reviewReportsFromDir(featureDir) {
175
157
  const out = {};
176
158
  for (const role of ROLE_ORDER) {
177
159
  const path = join(featureDir, '4-review', reviewFileName(role));
@@ -180,10 +162,6 @@ export function reviewReportsFromDir(featureDir) {
180
162
  return out;
181
163
  }
182
164
 
183
- export function reviewReportPath(cwd, featureName, role) {
184
- return getAbsoluteOutputPath(cwd, featureName, REVIEW_ROLES[role].output);
185
- }
186
-
187
165
  export function reviewReports(cwd, featureName) {
188
166
  return reviewReportsFromDir(join(cwd, '.morph', 'features', featureName));
189
167
  }
@@ -200,55 +178,3 @@ export function checksCoverage(checkIds, rows) {
200
178
  }
201
179
  return { missing, notProven };
202
180
  }
203
-
204
- /** O sinal que `reviewPause` lê; `checkIds: null` = cobertura não conferível. */
205
- export function reviewSignal(reports, { required, checkIds }) {
206
- const out = { required, reports: {} };
207
- for (const role of ROLE_ORDER) {
208
- const r = reports[role];
209
- if (!required.includes(role) && r.status === 'missing') continue;
210
- out.reports[role] = r.status === 'missing'
211
- ? { status: 'missing' }
212
- : {
213
- status: r.status,
214
- verdict: r.verdict ?? null,
215
- blockers: r.blockers.length,
216
- blockerIds: r.blockers.map((b) => b.id),
217
- humanBlockerIds: r.blockers.filter((b) => HUMAN_BLOCKER_TYPES.includes(b.type)).map((b) => b.id),
218
- untyped: r.untyped.length,
219
- superseded: r.superseded,
220
- rounds: r.rounds.length,
221
- };
222
- }
223
- out.checks = !required.includes('verifier')
224
- ? { status: 'not-required', missing: [], notProven: [] }
225
- : checkIds === null
226
- ? { status: 'no-checks', missing: [], notProven: [] }
227
- : { status: 'ok', total: checkIds.length, ...checksCoverage(checkIds, reports.verifier.checks) };
228
- return out;
229
- }
230
-
231
- /**
232
- * Veredito combinado para leitura (dashboard, list): FIX se qualquer relatório
233
- * presente diz FIX ou tem bloqueador; SHIP só com todo exigido em SHIP.
234
- */
235
- export function combinedVerdict(reports, required) {
236
- const present = ROLE_ORDER.filter((r) => reports[r].status !== 'missing');
237
- if (present.some((r) => reports[r].verdict === 'FIX' || reports[r].blockers.length > 0)) return 'FIX';
238
- return required.every((r) => reports[r].status === 'ok' && reports[r].verdict === 'SHIP') ? 'SHIP' : null;
239
- }
240
-
241
- export function allBlockers(reports) {
242
- return ROLE_ORDER.flatMap((role) => (reports[role].blockers ?? []).map((b) => ({ ...b, role })));
243
- }
244
-
245
- export function verifierMediaSection(cwd, featureName) {
246
- const text = readText(reviewReportPath(cwd, featureName, 'verifier'));
247
- return text !== null && MEDIA_SECTION_RE.test(text);
248
- }
249
-
250
- export function verifierScreenChecklist(cwd, featureName) {
251
- const text = readText(reviewReportPath(cwd, featureName, 'verifier'));
252
- const body = text === null ? null : lastSectionBody(text, SCREEN_CHECKLIST_SECTION_RE);
253
- return body === null ? { section: false, body: '' } : { section: true, body };
254
- }
@@ -0,0 +1,3 @@
1
+ export const WORKTREES_DIR = 'worktrees';
2
+ export const LEGACY_WORKTREES_DIR = '.worktrees';
3
+ export const WORKTREE_DIR_NAMES = [WORKTREES_DIR, LEGACY_WORKTREES_DIR];
@@ -90,7 +90,7 @@ export function updateAdrIndex(cwd, featureDir) {
90
90
  result.problems.push({
91
91
  id: rev.id,
92
92
  reason: 'adr-not-indexed',
93
- message: `${rev.id} não está no índice de ADRs ativos (${INDEX_LABEL}) — nada a retirar; o plan.md arquivado segue como história`,
93
+ message: `${rev.id} não está no índice de ADRs ativos (${INDEX_LABEL}) — nada a retirar; o plan.md segue como história`,
94
94
  });
95
95
  continue;
96
96
  }
@@ -107,7 +107,7 @@ export function updateAdrIndex(cwd, featureDir) {
107
107
  return result;
108
108
  }
109
109
 
110
- /** What the finish would fail to apply from the revocation table, reported while the plan can still change. */
110
+ /** What updateAdrIndex would fail to apply from the revocation table, reported before the plan freezes. */
111
111
  export function revocationWarnings(cwd, plan) {
112
112
  const { entries, problems } = parseRevocations(plan.conflicts?.text);
113
113
  const warnings = problems.map((p) => `### Conflitos com o acervo: ${p.message}`);
@@ -1,10 +1,11 @@
1
+ import chalk from 'chalk';
1
2
  import { existsSync, readdirSync, readFileSync } from 'fs';
2
3
  import { join } from 'path';
3
4
  import { ensureDotnetBuildIgnores } from '../../utils/file-copier.js';
4
5
  import { getProjectTags } from '../stack-filter.js';
5
- import { readMorphConfig } from '../tasks/test-runner.js';
6
+ import { readMorphConfig } from '../config/project-config.js';
6
7
  import { getAbsoluteOutputPath } from '../../core/paths/output-schema.js';
7
- import { WORKTREE_DIR_NAMES } from '../worktree/dirs.js';
8
+ import { WORKTREE_DIR_NAMES } from '../scan/worktree-dirs.js';
8
9
 
9
10
  const SKIPPED_DIRS = new Set([...WORKTREE_DIR_NAMES, 'node_modules', 'bin', 'obj']);
10
11
  const DOTNET_PROJECT_FILE = /\.(?:csproj|slnx?)$/i;
@@ -40,3 +41,10 @@ export function seedDotnetBuildIgnores(tree, options = {}) {
40
41
  return [];
41
42
  }
42
43
  }
44
+
45
+ export function reportDotnetIgnores(added) {
46
+ if (added.length) console.log(chalk.gray(` .gitignore: ${added.join(' ')} adicionados (projeto .NET) — commite antes do primeiro build.`));
47
+ for (const { entry, file } of added.skipped || []) {
48
+ console.log(chalk.yellow(` .gitignore: ${entry} não adicionado — esconderia fonte versionada (${file}); ignore a saída de build pelo caminho do projeto.`));
49
+ }
50
+ }
@@ -2,8 +2,8 @@ import { existsSync, readFileSync, readdirSync, statSync } from 'fs';
2
2
  import { join, relative } from 'path';
3
3
  import { getProjectTags } from '../stack-filter.js';
4
4
  import { PACKAGE_LOCATIONS } from '../detectors/index.js';
5
- import { isTestPath } from '../graph/sanitize.js';
6
- import { WORKTREE_DIR_NAMES } from '../worktree/dirs.js';
5
+ import { isTestPath } from '../diff/diff-lines.js';
6
+ import { WORKTREE_DIR_NAMES } from '../scan/worktree-dirs.js';
7
7
 
8
8
  export const SEVERITIES = ['Bloqueante', 'Alto', 'Médio', 'Baixo'];
9
9
  export const MAX_FILES = 20000;
@@ -28,7 +28,7 @@ export function parseStacks(content) {
28
28
  return ['*'];
29
29
  }
30
30
 
31
- /** Stack tags (`project.stack` split by '-' or '+') plus `project.integrations`, deduplicated. */
31
+ /** Stack tags (`project.stack` split by '-' or '+') plus `project.integrations` and the scanned `project.tags`, deduplicated. */
32
32
  export function getProjectTags(config) {
33
33
  const stack = config?.project?.stack;
34
34
  const stackTags = (stack && typeof stack === 'string')
@@ -37,7 +37,8 @@ export function getProjectTags(config) {
37
37
  const integrations = Array.isArray(config?.project?.integrations)
38
38
  ? config.project.integrations
39
39
  : [];
40
- return [...new Set([...stackTags, ...integrations])];
40
+ const tags = Array.isArray(config?.project?.tags) ? config.project.tags : [];
41
+ return [...new Set([...stackTags, ...integrations, ...tags])];
41
42
  }
42
43
 
43
44
  /** Empty or '*' stacks always install; otherwise any intersection with the project tags. */
@@ -1,7 +1,7 @@
1
1
  import { execFileSync } from 'child_process';
2
2
  import { readFileSync } from 'fs';
3
3
  import { basename, join } from 'path';
4
- import { isTestPath } from '../graph/sanitize.js';
4
+ import { isTestPath } from '../diff/diff-lines.js';
5
5
 
6
6
  export const PROSE_MIN_HITS = 3;
7
7
  export const FAMILY_MIN_SIZE = 4;
@@ -1,4 +1,4 @@
1
- import { join, dirname, resolve } from 'path';
1
+ import { basename, join, dirname, resolve } from 'path';
2
2
  import { fileURLToPath } from 'url';
3
3
  import { execSync } from 'child_process';
4
4
  import { readFileSync, readdirSync, existsSync } from 'fs';
@@ -13,13 +13,11 @@ import {
13
13
  ensureGitattributes
14
14
  } from '../utils/file-copier.js';
15
15
  import { parseStacks, getProjectTags, shouldInstall } from '../lib/stack-filter.js';
16
- import { applyEditorSettings } from '../lib/worktree/vscode-settings.js';
17
16
  import { injectMorphImport } from '../utils/claude-md-injector.js';
18
17
  import { saveProjectMorphVersion, getInstalledCLIVersion, getProjectMorphVersion } from '../utils/version-checker.js';
19
18
  import { installClaudeHooks, installGlobalStatusline } from '../utils/claude-settings-manager.js';
20
19
  import { installSkills } from '../utils/skills-installer.js';
21
20
  import { installAgents } from '../utils/agents-installer.js';
22
- import { resolvePrimaryRoot } from '../commands/project/worktree.js';
23
21
  import { reconcileLegacyTemplatesCopy } from '../lib/installers/templates-reconcile.js';
24
22
  import { realEffects } from '../lib/installers/effects.js';
25
23
  import { installRulesForStack } from '../lib/installers/rules-installer.js';
@@ -114,7 +112,7 @@ export async function updateClaudeMdAgentsBlock(claudeMdPath, agents = [], optio
114
112
  ? agents.map(a => `- \`${a.name}\` — ${a.title}${a.domains?.length ? ` (${a.domains.join(', ')})` : ''}`).join('\n')
115
113
  : '_Nenhum agente instalado — rode `morph-spec setup-infra --reinstall`._';
116
114
 
117
- const block = `${START}\n**Agentes do Gate 3** (derivado de agents.json na última instalação):\n\n${list}\n${END}`;
115
+ const block = `${START}\n**Personas de revisão** (derivado de agents.json na última instalação):\n\n${list}\n${END}`;
118
116
  const updated = content.replace(
119
117
  new RegExp(`${START}[\\s\\S]*?${END}`),
120
118
  block
@@ -123,11 +121,10 @@ export async function updateClaudeMdAgentsBlock(claudeMdPath, agents = [], optio
123
121
  }
124
122
 
125
123
  /**
126
- * Headless install: no prompts, no stack detection. `force` skips the secondary-worktree guard
127
- * for callers that already ran an equivalent check.
124
+ * Headless install: no prompts, no stack detection.
128
125
  */
129
126
  export async function setupInfra(targetPath, {
130
- _exec = execSync, _detectGraphifyVersion = null, _log = null, reinstall = false, force = false,
127
+ _exec = execSync, _detectGraphifyVersion = null, _log = null, reinstall = false,
131
128
  } = {}) {
132
129
  const quiet = process.env.MORPH_QUIET === '1';
133
130
 
@@ -136,20 +133,6 @@ export async function setupInfra(targetPath, {
136
133
  else if (!quiet) process.stdout.write(msg + '\n');
137
134
  }
138
135
 
139
- // In a linked worktree only .claude/ and .morph/framework/ are junctions to the root: a full
140
- // install would scaffold a second, disconnected config/state tree. `reinstall` touches only
141
- // the junctioned subset.
142
- if (!reinstall && !force) {
143
- const target = resolve(targetPath).replace(/\\/g, '/');
144
- const root = resolvePrimaryRoot(targetPath);
145
- if (root !== target) {
146
- log(`Você está num worktree secundário (${target}).`);
147
- log(`O morph-spec já está instalado na raiz primária (${root}).`);
148
- log('Para reparar infra do worktree use `morph-spec worktree link --all`, não `init`/`setup-infra`.');
149
- return { blocked: true, root, target };
150
- }
151
- }
152
-
153
136
  if (reinstall) {
154
137
  log('setup-infra (reinstall): re-installing stack-aware assets...');
155
138
  const { agentCounts } = await installStackAwareAssets(targetPath, log);
@@ -172,29 +155,18 @@ export async function setupInfra(targetPath, {
172
155
  const frameworkDestDir = join(morphPath, 'framework');
173
156
  const contextDir = join(morphPath, 'context');
174
157
  const featuresDir = join(morphPath, 'features');
175
- const checkpointsDir = join(morphPath, 'checkpoints');
176
- const memoryDir = join(morphPath, 'memory');
177
- const archiveDir = join(morphPath, 'archive');
178
158
 
179
159
  await ensureDir(configDir);
180
160
  await ensureDir(frameworkDestDir);
181
161
  await ensureDir(contextDir);
182
162
  await ensureDir(featuresDir);
183
- await ensureDir(checkpointsDir);
184
- await ensureDir(memoryDir);
185
- await ensureDir(archiveDir);
186
163
 
187
164
  log('Step 3: Writing config.json...');
188
165
  const configPath = join(configDir, 'config.json');
189
166
  if (!(await pathExists(configPath))) {
190
- const dirName = targetPath.split(/[\/]/).pop();
191
167
  const config = {
192
- framework: 'global',
193
168
  frameworkVersion: getInstalledCLIVersion(),
194
- trust: 'auto',
195
- project: {
196
- name: dirName
197
- }
169
+ project: { name: basename(resolve(targetPath)) },
198
170
  };
199
171
  await writeJson(configPath, config);
200
172
  }
@@ -202,8 +174,7 @@ export async function setupInfra(targetPath, {
202
174
  log('Step 4: Writing context/README.md...');
203
175
  const contextReadmePath = join(contextDir, 'README.md');
204
176
  if (!(await pathExists(contextReadmePath))) {
205
- const dirName = targetPath.split(/[\/]/).pop();
206
- const readmeContent = `# ${dirName} — Project Context\n\nRun \`morph-spec context refresh\` to generate architecture context.\n`;
177
+ const readmeContent = `# ${basename(resolve(targetPath))} — Project Context\n\nRun \`morph-spec context refresh\` to generate architecture context.\n`;
207
178
  await writeFile(contextReadmePath, readmeContent);
208
179
  }
209
180
 
@@ -267,13 +238,6 @@ export async function setupInfra(targetPath, {
267
238
  await copyFile(cliMdSrc, cliMdDest);
268
239
  }
269
240
 
270
- log('Step 8c: Copying phases.json...');
271
- const phasesSrc = join(FRAMEWORK_DIR, 'phases.json');
272
- const phasesDest = join(frameworkDestDir, 'phases.json');
273
- if (await pathExists(phasesSrc)) {
274
- await copyFile(phasesSrc, phasesDest);
275
- }
276
-
277
241
  log('Step 8d: Copying schemas...');
278
242
  const schemasSrc = join(FRAMEWORK_DIR, 'schemas');
279
243
  const schemasDest = join(frameworkDestDir, 'schemas');
@@ -312,9 +276,6 @@ export async function setupInfra(targetPath, {
312
276
  await updateGitignore(targetPath);
313
277
  await ensureGitattributes(targetPath);
314
278
 
315
- log('Step 18a: Editor excludes for worktrees...');
316
- try { applyEditorSettings(targetPath); } catch { /* fail-open */ }
317
-
318
279
  // Fail-open por inteiro: o wrapper de CLI mata o processo em qualquer throw.
319
280
  log('Step 18b: Codebase graph (graphify)...');
320
281
  try {
@@ -369,20 +330,6 @@ export async function setupInfra(targetPath, {
369
330
  log(` ⚠ Step do grafo pulado: ${err.message}`);
370
331
  }
371
332
 
372
- log('Step 19: Initializing state.json...');
373
- const statePath = join(morphPath, 'state.json');
374
- if (!(await pathExists(statePath))) {
375
- const dirName = targetPath.split(/[\/\\]/).pop();
376
- const now = new Date().toISOString();
377
- await writeJson(statePath, {
378
- version: '5.0.0',
379
- project: { name: dirName, type: 'unknown', createdAt: now, updatedAt: now },
380
- features: {},
381
- threads: {},
382
- metadata: { totalFeatures: 0, completedFeatures: 0, totalTimeSpent: 0, lastUpdated: now }
383
- });
384
- }
385
-
386
333
  log('setup-infra: complete.');
387
334
 
388
335
  return { agents: { installed: agentCounts?.installed ?? 0 } };
@@ -198,7 +198,7 @@ const STANDARDS_HINT = 'Digest de cada um: `morph-spec standards --find <id>`; s
198
198
  '`morph-spec standards --show <id>#<âncora>` (`--show <id>` lista as âncoras).';
199
199
 
200
200
  export const REVIEW_REPORT_CONTRACT = [
201
- '## Relatório do Gate 3',
201
+ '## Relatório da revisão',
202
202
  '',
203
203
  'Grave o relatório que o dispatch nomeia ANTES de encerrar — o arquivo é o retorno, não a mensagem final. ' +
204
204
  'Se ele já existir quando você começar, é resíduo de outra rodada: não o leia antes de escrever o seu (ancoragem no veredito alheio), ' +
@@ -374,39 +374,6 @@ function diffAgentMd(onDisk, rendered) {
374
374
  return fields.length > 0 ? fields : ['frontmatter'];
375
375
  }
376
376
 
377
- export function formatStandardRef(standard) {
378
- if (typeof standard === 'string') return `- ${standard}`;
379
- const id = standard.id || String(standard);
380
- const parts = [standard.scope, standard.priority].filter(Boolean);
381
- return parts.length > 0 ? `- ${id} (${parts.join(', ')})` : `- ${id}`;
382
- }
383
-
384
- export function parseSkillFile(rawContent) {
385
- const content = rawContent.replace(/\r\n/g, '\n');
386
- const match = content.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
387
- if (!match) {
388
- return {
389
- name: null, description: null, allowedTools: 'Read, Write, Edit, Bash, Glob, Grep',
390
- color: null, effort: null, permissionMode: null, background: false, stacks: [],
391
- body: rawContent,
392
- };
393
- }
394
- const fm = match[1];
395
- const body = match[2];
396
- const name = (fm.match(/^name:\s*(.+)$/m) ?? [])[1]?.trim() ?? null;
397
- const allowedTools = (fm.match(/^allowed-tools:\s*(.+)$/m) ?? [])[1]?.trim() ?? 'Read, Write, Edit, Bash, Glob, Grep';
398
- const color = (fm.match(/^color:\s*(.+)$/m) ?? [])[1]?.trim() ?? null;
399
- let description = null;
400
- const blockMatch = fm.match(/^description:\s*>\s*\n((?:[ \t]+.*\n?)*)/m);
401
- if (blockMatch) {
402
- description = blockMatch[1].trim().replace(/\s+/g, ' ');
403
- } else {
404
- const inlineMatch = fm.match(/^description:\s*(.+)$/m);
405
- if (inlineMatch) description = inlineMatch[1].trim();
406
- }
407
- return { name, description, allowedTools, color, effort: null, permissionMode: null, background: false, stacks: [], body };
408
- }
409
-
410
377
  export function collectSkillFiles(dir) {
411
378
  const results = [];
412
379
  if (!existsSync(dir)) return results;
@@ -0,0 +1,27 @@
1
+ import { existsSync, mkdirSync, renameSync, unlinkSync, writeFileSync } from 'fs';
2
+ import { dirname } from 'path';
3
+
4
+ // Temp file + rename, so a reader never sees half a file; EPERM retries cover a Windows scanner holding the target.
5
+ export function atomicWriteJson(targetPath, data) {
6
+ const dir = dirname(targetPath);
7
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
8
+
9
+ const tmpPath = `${targetPath}.tmp.${process.pid}`;
10
+ writeFileSync(tmpPath, JSON.stringify(data, null, 2), 'utf8');
11
+
12
+ const MAX_RETRIES = 5;
13
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
14
+ try {
15
+ renameSync(tmpPath, targetPath);
16
+ return;
17
+ } catch (err) {
18
+ if (err.code === 'EPERM' && attempt < MAX_RETRIES) {
19
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50 * (attempt + 1));
20
+ } else {
21
+ try { unlinkSync(tmpPath); } catch { }
22
+ throw err;
23
+ }
24
+ }
25
+ }
26
+ }
27
+