@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,1234 +0,0 @@
1
- import { execSync, execFileSync, spawnSync } from 'child_process';
2
- import { existsSync, mkdirSync, symlinkSync, readFileSync, writeFileSync, lstatSync, unlinkSync, rmdirSync, cpSync, copyFileSync, readdirSync, renameSync } from 'fs';
3
- import { join, resolve, dirname, basename } from 'path';
4
- import chalk from 'chalk';
5
- import { detectDefaultBranch, freshDefaultRef } from '../../lib/git/default-branch.js';
6
- import { isTestArtifact, triageIgnoredPaths } from '../../lib/worktree/ignored-triage.js';
7
- import {
8
- finishBackupDir,
9
- writeFeatureScopeBackup,
10
- writeWorktreeIgnoredBackup,
11
- enforceBackupRetention,
12
- newBackupStamp,
13
- } from '../../lib/worktree/finish-backup.js';
14
- // Lives in hooks/shared: the PreToolUse guardrail needs the same answer and hooks cannot import `src/`.
15
- import { findReparsePoints } from '../../../framework/hooks/shared/reparse-scan.js';
16
- import { ensureCommonExclude } from '../../../framework/hooks/shared/git-exclude.js';
17
- import { seedGraphFromRoot } from '../../../framework/hooks/shared/graph-refresh.js';
18
- import { dropLeftoverIgnore, withoutLeftoverIgnore } from '../../../framework/hooks/shared/graph-freshness.js';
19
-
20
- import { WORKTREES_DIR, LEGACY_WORKTREES_DIR, WORKTREE_DIR_NAMES } from '../../lib/worktree/dirs.js';
21
- import { applyEditorSettings } from '../../lib/worktree/vscode-settings.js';
22
- import { copyWorktreeIncludes } from '../../lib/worktree/worktree-include.js';
23
- import { containerDirs, externalContainer, isInContainer, newWorktreesDir } from '../../../framework/hooks/shared/worktree-root.js';
24
-
25
- /** Fail-open: the editor file is a convenience, never a reason a worktree is not created. */
26
- function rootAndEditorReport(root) {
27
- const { warning } = externalContainer(root);
28
- const worktreeRoot = warning ? { worktreeRootWarning: warning } : {};
29
- try {
30
- const report = applyEditorSettings(root);
31
- return report.status === 'off' ? worktreeRoot : { ...worktreeRoot, editorSettings: report };
32
- } catch {
33
- return worktreeRoot;
34
- }
35
- }
36
- export { WORKTREES_DIR, LEGACY_WORKTREES_DIR, WORKTREE_DIR_NAMES };
37
-
38
- /** Also guards git calls: `& | ; > ^` are legal in a refname but cmd.exe metacharacters on Windows. */
39
- export function isValidFeatureName(name) {
40
- return typeof name === 'string' && /^[a-z0-9][a-z0-9-]*$/.test(name);
41
- }
42
-
43
- export function isGitRepo(cwd = process.cwd()) {
44
- try {
45
- execSync('git rev-parse --git-dir', { cwd, stdio: 'pipe' });
46
- return true;
47
- } catch {
48
- return false;
49
- }
50
- }
51
-
52
- export function branchExists(branch, cwd = process.cwd()) {
53
- try {
54
- execSync(`git show-ref --verify --quiet refs/heads/${branch}`, { cwd, stdio: 'pipe' });
55
- return true;
56
- } catch {
57
- return false;
58
- }
59
- }
60
-
61
- export function worktreeExists(worktreePath, cwd = process.cwd()) {
62
- try {
63
- const output = execSync('git worktree list --porcelain', { cwd, stdio: 'pipe' }).toString();
64
- const absPath = resolve(cwd, worktreePath).replace(/\\/g, '/');
65
- return output.replace(/\\/g, '/').includes(absPath);
66
- } catch {
67
- return false;
68
- }
69
- }
70
-
71
- /** Always forward slashes. */
72
- export function buildWorktreePath(feature, cwd = process.cwd(), options = {}) {
73
- const suffix = options.fresh ? `-${getDateSuffix()}` : '';
74
- const normalizedCwd = cwd.replace(/\\/g, '/');
75
- const container = externalContainer(normalizedCwd).dir ?? `${normalizedCwd}/${WORKTREES_DIR}`;
76
- return `${container}/${feature}${suffix}`;
77
- }
78
-
79
- export function buildBranchName(feature, options = {}) {
80
- const suffix = options.fresh ? `-${getDateSuffix()}` : '';
81
- return `morph/${feature}${suffix}`;
82
- }
83
-
84
- function getDateSuffix() {
85
- return new Date().toISOString().slice(0, 10).replace(/-/g, '');
86
- }
87
-
88
- function trackedPackageNodeModules(mainCwd) {
89
- let out;
90
- try {
91
- out = execFileSync('git', ['ls-files', '-z', '--', '*package.json'], { cwd: mainCwd, stdio: 'pipe' }).toString();
92
- } catch {
93
- return [];
94
- }
95
- const dirs = [];
96
- for (const file of out.split('\0')) {
97
- const parts = file.split('/');
98
- if (parts.length < 2 || parts.at(-1) !== 'package.json') continue;
99
- const dirParts = parts.slice(0, -1);
100
- if (dirParts.includes('node_modules') || WORKTREE_DIR_NAMES.includes(dirParts[0])) continue;
101
- const rel = join(...dirParts, 'node_modules');
102
- if (existsSync(join(mainCwd, rel))) dirs.push(rel);
103
- }
104
- return dirs;
105
- }
106
-
107
- // The ONLY links `finish` may auto-remove (never widened to any reparse point found), plus the
108
- // `node_modules` of each tracked nested package: a monorepo package has its own install.
109
- function resolveInfraLinkDirs(mainCwd) {
110
- const dirs = ['node_modules', '.claude'];
111
- if (existsSync(join(mainCwd, '.morph', 'framework'))) {
112
- dirs.push(join('.morph', 'framework'));
113
- }
114
- try {
115
- const configPath = join(mainCwd, '.morph', 'config', 'config.json');
116
- if (existsSync(configPath)) {
117
- const config = JSON.parse(readFileSync(configPath, 'utf8'));
118
- const frontendPath = config?.project?.frontendPath;
119
- if (frontendPath) dirs.push(join(frontendPath, 'node_modules'));
120
- }
121
- } catch {}
122
- for (const rel of trackedPackageNodeModules(mainCwd)) {
123
- if (!dirs.includes(rel)) dirs.push(rel);
124
- }
125
- return dirs;
126
- }
127
-
128
- /**
129
- * `.morph/state.json` is never linked: an atomic write (tmp + rename) makes a new inode and silently
130
- * severs a hard link, so the worktree materializes its own (`materializeState`).
131
- */
132
- export function setupInfraLinks(worktreePath, mainCwd, opts = {}) {
133
- const mainAbs = resolve(mainCwd);
134
- const wtAbs = resolve(worktreePath);
135
-
136
- const dirLinks = (Array.isArray(opts.dirs) && opts.dirs.length)
137
- ? opts.dirs
138
- : resolveInfraLinkDirs(mainAbs);
139
-
140
- for (const rel of dirLinks) {
141
- const target = join(mainAbs, rel);
142
- const linkPath = join(wtAbs, rel);
143
- if (!existsSync(target) || existsSync(linkPath)) continue;
144
- try {
145
- const parent = dirname(linkPath);
146
- if (!existsSync(parent)) mkdirSync(parent, { recursive: true });
147
- symlinkSync(target, linkPath, 'junction');
148
- } catch {}
149
- }
150
-
151
- // Only reparse points: `lstat` reports a POSIX symlink and a Windows junction alike, so the
152
- // exclude lands identically on both platforms.
153
- excludeWorktreePaths(mainAbs, dirLinks.filter((rel) => {
154
- try {
155
- return lstatSync(join(wtAbs, rel)).isSymbolicLink();
156
- } catch {
157
- return false; // never created (target absent, or the symlink call failed)
158
- }
159
- }));
160
- }
161
-
162
- /** Marks the block `excludeWorktreePaths` owns in `.git/info/exclude`. */
163
- const EXCLUDE_MARKER = '# morph-spec: infra links inside worktrees (managed — see setupInfraLinks)';
164
-
165
- /**
166
- * Git sees a POSIX symlink as a FILE, so a dirs-only rule misses it and `git add -A` commits the links
167
- * (the merge then eats the root's installation). The COMMON dir's `info/exclude` is honored by every
168
- * worktree; the accepted cost is that it also hides an untracked `.claude/` in the root.
169
- */
170
- function excludeWorktreePaths(mainCwd, rels) {
171
- // Anchored (`/x`): these live at the top of a worktree, and an unanchored
172
- // `node_modules` would also swallow nested ones the user may track.
173
- ensureCommonExclude(mainCwd, rels.map((rel) => `/${rel.replace(/\\/g, '/')}`), EXCLUDE_MARKER);
174
- }
175
-
176
- /** Fail-open: outside a git repo (or on a git error) returns `cwd` itself, normalized. */
177
- export function resolvePrimaryRoot(cwd = process.cwd()) {
178
- try {
179
- const output = execSync('git worktree list --porcelain', { cwd, stdio: 'pipe' }).toString();
180
- const line = output.split('\n').find((l) => l.startsWith('worktree '));
181
- if (line) {
182
- return line.slice('worktree '.length).trim().replace(/\\/g, '/');
183
- }
184
- } catch {}
185
- return resolve(cwd).replace(/\\/g, '/');
186
- }
187
-
188
- /**
189
- * Writes an EMPTY index when there is nothing to hydrate: every hook fail-opens on `stateExists()`,
190
- * and a tree with neither state.json nor features left them all silently dark.
191
- */
192
- export async function ensureLocalState(worktreePath) {
193
- const result = await materializeState(worktreePath);
194
- if (result.materialized) return result;
195
- const statePath = join(worktreePath, '.morph', 'state.json');
196
- if (existsSync(statePath)) return { ...result, materialized: true };
197
- try {
198
- const { atomicWriteJson } = await import('../../core/state/state-manager.js');
199
- const now = new Date().toISOString();
200
- mkdirSync(join(worktreePath, '.morph'), { recursive: true });
201
- atomicWriteJson(statePath, {
202
- version: '5.0.0',
203
- project: { name: basename(worktreePath), type: 'unknown', createdAt: now, updatedAt: now },
204
- features: {},
205
- threads: {},
206
- metadata: { totalFeatures: 0, completedFeatures: 0, totalTimeSpent: 0, lastUpdated: now },
207
- });
208
- return { materialized: true, seeded: true, reason: result.reason };
209
- } catch (err) {
210
- return { materialized: false, reason: (err && err.message) || result.reason };
211
- }
212
- }
213
-
214
- export async function materializeState(worktreePath) {
215
- const featuresDir = join(worktreePath, '.morph', 'features');
216
- if (!existsSync(featuresDir)) {
217
- return { materialized: false, reason: 'no-features' };
218
- }
219
-
220
- const prevCwd = process.cwd();
221
- try {
222
- process.chdir(resolve(worktreePath));
223
- const { loadState } = await import('../../core/state/state-manager.js');
224
- loadState(false);
225
- // loadState(false) writes nothing for a present-but-empty features dir: don't report success then.
226
- if (existsSync(join(worktreePath, '.morph', 'state.json'))) {
227
- return { materialized: true };
228
- }
229
- return { materialized: false, reason: 'no-features-to-hydrate' };
230
- } catch (err) {
231
- return { materialized: false, reason: (err && err.message) || 'unknown' };
232
- } finally {
233
- process.chdir(prevCwd);
234
- }
235
- }
236
-
237
- // Nothing launched in the background: a detached process holding a worktree directory made
238
- // `finish` fail on win32. Fail-open: no root graph, no copy.
239
- function seedWorktreeGraph(worktreePath, root) {
240
- try {
241
- return seedGraphFromRoot(worktreePath, root);
242
- } catch {
243
- return { seeded: false, reason: 'seed-failed' };
244
- }
245
- }
246
-
247
- // A fresh tree has no obj/: the first build otherwise fails with NETSDK1004 (project.assets.json missing).
248
- // node_modules is not installed here: setupInfraLinks junctions the root's. Off with MORPH_WORKTREE_RESTORE=0.
249
- function restoreWorktree(worktreePath) {
250
- if (process.env.MORPH_WORKTREE_RESTORE === '0') return { status: 'skipped', reason: 'MORPH_WORKTREE_RESTORE=0' };
251
- let solution;
252
- try {
253
- solution = readdirSync(worktreePath).find((f) => /\.slnx?$/i.test(f));
254
- } catch {
255
- solution = null;
256
- }
257
- if (!solution) return null;
258
- const r = spawnSync(`dotnet restore "${join(worktreePath, solution)}"`, { cwd: worktreePath, shell: true, stdio: 'pipe', timeout: 10 * 60_000 });
259
- if (r.error || r.status !== 0) {
260
- const tail = `${r.stdout ?? ''}${r.stderr ?? ''}`.trim().split(/\r?\n/).slice(-3).join(' ');
261
- return { status: 'failed', target: solution, detail: (r.error?.message || tail).slice(0, 300) };
262
- }
263
- return { status: 'ok', target: solution };
264
- }
265
-
266
- /**
267
- * Non-exiting core of `worktree setup`. exitCode 1 = refused (`invalid-feature-name`),
268
- * 2 = already exists here, 3 = a live worktree for the feature exists elsewhere.
269
- */
270
- export async function runWorktreeSetup(feature, options = {}) {
271
- const cwd = options.cwd || process.cwd();
272
-
273
- // A plain kebab slug before it reaches a path, a refname or any git call (see isValidFeatureName).
274
- if (!isValidFeatureName(feature)) {
275
- return { ok: false, exitCode: 1, created: false, error: 'invalid-feature-name', feature };
276
- }
277
-
278
- if (!isGitRepo(cwd)) {
279
- return { ok: true, exitCode: 0, created: false, error: 'not-a-git-repo', feature };
280
- }
281
-
282
- const branch = buildBranchName(feature, options);
283
- const worktreePath = buildWorktreePath(feature, cwd, options);
284
-
285
- if (!options.fresh && worktreeExists(worktreePath, cwd)) {
286
- return { ok: false, exitCode: 2, created: false, alreadyExists: true, path: worktreePath, branch, feature };
287
- }
288
-
289
- // Anti-dupe: refuse a second LIVE worktree for this feature; a recorded path gone from disk does not block.
290
- try {
291
- const featureJsonPath = join(cwd, '.morph', 'features', feature, 'feature.json');
292
- if (existsSync(featureJsonPath)) {
293
- const fj = JSON.parse(readFileSync(featureJsonPath, 'utf8'));
294
- const existingPath = fj?.worktree?.path;
295
- if (existingPath) {
296
- const normalizedExisting = existingPath.replace(/\\/g, '/');
297
- const normalizedNew = worktreePath.replace(/\\/g, '/');
298
- if (normalizedExisting !== normalizedNew && existsSync(existingPath)) {
299
- return {
300
- ok: false, exitCode: 3, created: false, error: 'worktree-exists-elsewhere', existingPath, feature,
301
- hint: `A different live worktree is already registered for "${feature}". `
302
- + `If it's stale (removed by hand, or by \`git worktree prune\` directly, outside \`morph-spec finish\`/\`worktree remove\`), `
303
- + `run \`morph-spec doctor --worktrees --prune\` to clear the registration, or `
304
- + `\`morph-spec worktree remove --target "${existingPath}"\` if the directory is still there but unwanted.`,
305
- };
306
- }
307
- }
308
- }
309
- } catch { /* fail-open — malformed feature.json must never block setup */ }
310
-
311
- let branchedFrom = null;
312
- try {
313
- // Off the DEFAULT branch, never HEAD: a root parked on another `morph/*` would hand over its commits.
314
- // No resolvable default → off HEAD, reported as `branchedFrom: null`.
315
- if (!branchExists(branch, cwd)) {
316
- const defaultBranch = freshDefaultRef(cwd);
317
- if (defaultBranch) {
318
- execFileSync('git', ['branch', branch, defaultBranch], { cwd, stdio: 'pipe' });
319
- branchedFrom = defaultBranch;
320
- } else {
321
- execFileSync('git', ['branch', branch], { cwd, stdio: 'pipe' });
322
- }
323
- }
324
-
325
- const parentDir = newWorktreesDir(cwd);
326
- if (!existsSync(parentDir)) {
327
- mkdirSync(parentDir, { recursive: true });
328
- }
329
-
330
- execSync(`git worktree add "${worktreePath}" ${branch}`, { cwd, stdio: 'pipe' });
331
-
332
- setupInfraLinks(worktreePath, cwd);
333
- const included = copyWorktreeIncludes(worktreePath, cwd);
334
-
335
- // Fail-open: a worktree without ports is degraded, never broken.
336
- const envBlock = await allocateWorktreeEnv(worktreePath, cwd, feature);
337
-
338
- const materialized = await ensureLocalState(worktreePath);
339
-
340
- const graph = seedWorktreeGraph(worktreePath, cwd);
341
- const restore = restoreWorktree(worktreePath);
342
-
343
- try {
344
- const { loadState, saveState } = await import('../../core/state/state-manager.js');
345
- const state = loadState(false);
346
- if (state?.features?.[feature]) {
347
- state.features[feature].worktree = { path: worktreePath, branch, createdAt: new Date().toISOString() };
348
- saveState(state);
349
- }
350
- } catch {
351
- }
352
-
353
- return {
354
- ok: true,
355
- exitCode: 0,
356
- created: true,
357
- path: worktreePath,
358
- branch,
359
- branchedFrom,
360
- feature,
361
- ...(included.length ? { worktreeInclude: included } : {}),
362
- materialized: materialized.materialized,
363
- ...(envBlock ? { env: { base: envBlock.base, range: envBlock.range } } : {}),
364
- ...(graph.seeded ? { graph: 'seeded' } : {}),
365
- ...(restore ? { restore } : {}),
366
- ...rootAndEditorReport(resolvePrimaryRoot(cwd)),
367
- nextStep: `Abra o Claude Code em ${worktreePath} para trabalhar nesta feature`,
368
- };
369
- } catch (err) {
370
- return { ok: true, exitCode: 0, created: false, error: (err.message || 'unknown').slice(0, 200), feature };
371
- }
372
- }
373
-
374
- export async function worktreeSetupCommand(feature, options = {}) {
375
- const { ok, exitCode, ...result } = await runWorktreeSetup(feature, options);
376
- console.log(JSON.stringify(result));
377
- process.exit(exitCode);
378
- }
379
-
380
- /** A separate namespace on purpose: a scratch tree must never impersonate `morph/<feature>`. */
381
- export function buildTaskBranchName(name) {
382
- return `morph-task/${name}`;
383
- }
384
-
385
- const ROOT_ENV_FILE_RE = /^\.env(\..+)?$/;
386
-
387
- /**
388
- * Only a REAL file, never overwriting, and only when git IGNORES it in the tree: a visible copy
389
- * would dirty it and `finish` refuses a dirty tree. At teardown the copy is a replica of the root's.
390
- */
391
- export function copyRootEnvFiles(worktreePath, root) {
392
- let names;
393
- try {
394
- names = readdirSync(root).filter((n) => ROOT_ENV_FILE_RE.test(n));
395
- } catch {
396
- return [];
397
- }
398
- const copied = [];
399
- for (const name of names) {
400
- const dst = join(worktreePath, name);
401
- try {
402
- if (!lstatSync(join(root, name)).isFile()) continue;
403
- try { lstatSync(dst); continue; } catch {}
404
- execFileSync('git', ['check-ignore', '-q', '--', name], { cwd: worktreePath, stdio: 'pipe' });
405
- copyFileSync(join(root, name), dst);
406
- copied.push(name);
407
- } catch {}
408
- }
409
- return copied;
410
- }
411
-
412
- /** Non-exiting core of `worktree provision`: `setup` without the feature identity. Exit codes mirror `setup`. */
413
- export async function runWorktreeProvision(name, options = {}) {
414
- const cwd = options.cwd || process.cwd();
415
-
416
- if (!isValidFeatureName(name)) {
417
- return { ok: false, exitCode: 1, created: false, error: 'invalid-name', name };
418
- }
419
- if (!isGitRepo(cwd)) {
420
- return { ok: true, exitCode: 0, created: false, error: 'not-a-git-repo', name };
421
- }
422
-
423
- // Always the PRIMARY root: a tree nested under a feature worktree is invisible to fleet and doctor.
424
- const root = resolvePrimaryRoot(cwd);
425
- const branch = buildTaskBranchName(name);
426
- const worktreePath = buildWorktreePath(name, root);
427
-
428
- if (worktreeExists(worktreePath, root)) {
429
- return { ok: true, exitCode: 2, created: false, alreadyExists: true, path: worktreePath, branch, kind: 'task-isolation', name };
430
- }
431
-
432
- let branchedFrom = null;
433
- try {
434
- if (!branchExists(branch, root)) {
435
- const base = options.base || detectDefaultBranch(root);
436
- if (base) {
437
- execFileSync('git', ['branch', branch, base], { cwd: root, stdio: 'pipe' });
438
- branchedFrom = base;
439
- } else {
440
- execFileSync('git', ['branch', branch], { cwd: root, stdio: 'pipe' });
441
- }
442
- }
443
-
444
- const parentDir = newWorktreesDir(root);
445
- if (!existsSync(parentDir)) mkdirSync(parentDir, { recursive: true });
446
-
447
- execFileSync('git', ['worktree', 'add', worktreePath, branch], { cwd: root, stdio: 'pipe' });
448
-
449
- setupInfraLinks(worktreePath, root);
450
- const envFiles = copyRootEnvFiles(worktreePath, root);
451
- const included = copyWorktreeIncludes(worktreePath, root);
452
- // A tree born from `morph/<f>` works FOR that feature: MORPH_FEATURE says
453
- // so, while the port block stays the task's own (`task/<name>`).
454
- const forFeature = String(options.base || '').match(/^morph\/(.+)$/)?.[1] ?? null;
455
- const envBlock = await allocateWorktreeEnv(worktreePath, root, `task/${name}`, { morphFeature: forFeature });
456
- const materialized = await ensureLocalState(worktreePath);
457
- const graph = seedWorktreeGraph(worktreePath, root);
458
-
459
- return {
460
- ok: true,
461
- exitCode: 0,
462
- created: true,
463
- path: worktreePath,
464
- branch,
465
- branchedFrom,
466
- kind: 'task-isolation',
467
- name,
468
- ...(forFeature ? { feature: forFeature } : {}),
469
- ...(envFiles.length ? { envFiles } : {}),
470
- ...(included.length ? { worktreeInclude: included } : {}),
471
- materialized: materialized.materialized,
472
- ...(envBlock ? { env: { base: envBlock.base, range: envBlock.range } } : {}),
473
- ...(graph.seeded ? { graph: 'seeded' } : {}),
474
- ...rootAndEditorReport(root),
475
- };
476
- } catch (err) {
477
- return { ok: true, exitCode: 0, created: false, error: (err.message || 'unknown').slice(0, 200), name };
478
- }
479
- }
480
-
481
- export async function worktreeProvisionCommand(name, options = {}) {
482
- const { ok, exitCode, ...result } = await runWorktreeProvision(name, options);
483
- console.log(JSON.stringify(result));
484
- process.exit(exitCode);
485
- }
486
-
487
- export async function worktreeLinkCommand(options = {}) {
488
- const cwdArg = options.cwd || process.cwd();
489
- const root = resolvePrimaryRoot(cwdArg);
490
- const target = resolve(options.target || options.cwd || process.cwd()).replace(/\\/g, '/');
491
-
492
- if (target === root) {
493
- console.log(JSON.stringify({ linked: [], skipped: ['is-primary-root'], root, target }));
494
- process.exit(0);
495
- }
496
-
497
- if (!isGitRepo(cwdArg)) {
498
- console.log(JSON.stringify({ error: 'not-a-git-repo' }));
499
- process.exit(0);
500
- }
501
-
502
- const dirs = options.all
503
- ? resolveInfraLinkDirs(root)
504
- : ['node_modules'];
505
-
506
- const alreadyPresent = {};
507
- for (const rel of dirs) {
508
- alreadyPresent[rel] = existsSync(join(target, rel));
509
- }
510
-
511
- setupInfraLinks(target, root, { dirs });
512
-
513
- const linked = [];
514
- const skipped = [];
515
- for (const rel of dirs) {
516
- if (alreadyPresent[rel]) {
517
- skipped.push(rel);
518
- } else if (existsSync(join(target, rel))) {
519
- linked.push(rel);
520
- } else {
521
- skipped.push(rel);
522
- }
523
- }
524
-
525
- // Allocation is idempotent (same key → same block): regenerating never moves a worktree's ports.
526
- let env = null;
527
- if (options.all) {
528
- const key = envKeyForWorktree(target, root);
529
- const block = key ? await allocateWorktreeEnv(target, root, key) : null;
530
- if (block) env = { key, base: block.base, range: block.range };
531
- }
532
-
533
- console.log(JSON.stringify({ linked, skipped, root, target, ...(env ? { env } : {}) }));
534
- process.exit(0);
535
- }
536
-
537
- /** `morph/<f>` → `<f>`, `morph-task/<n>` → `task/<n>`, `null` for a branch morph does not own. */
538
- export function envKeyForWorktree(worktreePath, root) {
539
- const norm = resolve(worktreePath).replace(/\\/g, '/');
540
- const entry = parseWorktreeList(root).find((e) => e.path === norm);
541
- const branch = entry?.branch?.replace(/^refs\/heads\//, '') ?? null;
542
- if (!branch) return null;
543
- const feature = branch.match(/^morph\/(.+)$/)?.[1];
544
- if (feature) return feature;
545
- const task = branch.match(/^morph-task\/(.+)$/)?.[1];
546
- return task ? `task/${task}` : null;
547
- }
548
-
549
- /**
550
- * The manifest's single writer. Without `morphFeature` (the `link --all` repair) the MORPH_FEATURE
551
- * already in the file is kept. `null` when no block could be written.
552
- */
553
- export async function allocateWorktreeEnv(worktreePath, root, envKey, { morphFeature } = {}) {
554
- const envPath = join(worktreePath, '.morph', 'worktree.env');
555
- if (morphFeature === undefined && envKey.startsWith('task/')) {
556
- try {
557
- const kept = readFileSync(envPath, 'utf8').match(/^MORPH_FEATURE=(.+)$/m)?.[1]?.trim();
558
- morphFeature = kept && kept !== envKey ? kept : null;
559
- } catch { morphFeature = null; }
560
- }
561
- try {
562
- const { allocateEnvBlock, resolveFleetConfig, buildEnvFileContent, resolvePortAliases } =
563
- await import('../../lib/worktree/env-allocator.js');
564
- const common = execSync('git rev-parse --git-common-dir', { cwd: root, stdio: 'pipe' }).toString().trim();
565
- if (!common) return null;
566
- const gitCommonDir = resolve(root, common);
567
- const block = allocateEnvBlock(envKey, { gitCommonDir, ...resolveFleetConfig(root) });
568
- let stack = '';
569
- let aliases = {};
570
- try {
571
- const cfg = JSON.parse(readFileSync(join(root, '.morph', 'config', 'config.json'), 'utf8').replace(/^/, ''));
572
- stack = cfg?.project?.stack || '';
573
- aliases = resolvePortAliases(cfg).aliases;
574
- } catch {}
575
- mkdirSync(join(worktreePath, '.morph'), { recursive: true });
576
- writeFileSync(envPath, buildEnvFileContent(envKey, block, stack, { morphFeature, aliases }), 'utf8');
577
- excludeWorktreePaths(root, [join('.morph', 'worktree.env')]);
578
- return block;
579
- } catch {
580
- return null;
581
- }
582
- }
583
-
584
- /** Fail-open: `[]` on any git error. */
585
- export function parseWorktreeList(cwd) {
586
- let output;
587
- try {
588
- output = execSync('git worktree list --porcelain', { cwd, stdio: 'pipe' }).toString();
589
- } catch {
590
- return [];
591
- }
592
-
593
- const entries = [];
594
- let current = null;
595
- for (const line of output.split('\n')) {
596
- if (line.startsWith('worktree ')) {
597
- if (current) entries.push(current);
598
- current = { path: line.slice('worktree '.length).trim().replace(/\\/g, '/'), branch: null, head: null, locked: false };
599
- } else if (/^locked(\s|$)/.test(line) && current) {
600
- current.locked = true;
601
- } else if (line.startsWith('branch ') && current) {
602
- current.branch = line.slice('branch '.length).trim();
603
- } else if (line.startsWith('HEAD ') && current) {
604
- current.head = line.slice('HEAD '.length).trim();
605
- }
606
- }
607
- if (current) entries.push(current);
608
- return entries;
609
- }
610
-
611
- /**
612
- * Returns the branch the worktree is ACTUALLY on, never the computed one: via the path fallback they
613
- * can diverge, and the caller refuses on mismatch rather than merge a branch it never validated.
614
- */
615
- export function findWorktreeForFeature(feature, root) {
616
- const expectedBranch = buildBranchName(feature);
617
- const refName = `refs/heads/${expectedBranch}`;
618
- const entries = parseWorktreeList(root);
619
-
620
- let match = entries.find((e) => e.branch === refName);
621
- if (!match) {
622
- const guesses = containerDirs(root).map((dir) => `${dir}/${feature}`);
623
- match = entries.find((e) => guesses.includes(e.path));
624
- }
625
- if (!match) return null;
626
-
627
- const actual = match.branch ? match.branch.replace(/^refs\/heads\//, '') : null;
628
- return { path: match.path, branch: actual, expectedBranch };
629
- }
630
-
631
- /**
632
- * Must run before `git worktree remove`: its `--force` fallback FOLLOWS junctions and deletes the root's
633
- * real `.claude/` and `.morph/framework/`. Only the known inventory, never any reparse point found.
634
- */
635
- export function unlinkWorktreeInfraLinks(worktreePath, mainCwd) {
636
- const removed = [];
637
- for (const rel of resolveInfraLinkDirs(mainCwd)) {
638
- const p = join(worktreePath, rel);
639
- let st;
640
- try {
641
- st = lstatSync(p);
642
- } catch {
643
- continue;
644
- }
645
- if (!st.isSymbolicLink() && !st.isDirectory()) continue;
646
- try {
647
- // symlink → unlink; Windows junction → rmdir. Both act on the link itself.
648
- try {
649
- unlinkSync(p);
650
- } catch {
651
- rmdirSync(p);
652
- }
653
- removed.push(rel);
654
- } catch { /* a real, non-empty directory — leave it alone */ }
655
- }
656
- return removed;
657
- }
658
-
659
- // Safe to remove only once backed up. `node_modules` is not here: regenerable and too large to copy.
660
- const IGNORED_SHIELDABLE_PREFIXES = ['.morph/'];
661
-
662
- /** PROVES it: exactly the sibling's feature.json, parseable, and `worktree.path` an existing dir. */
663
- function isLiveSiblingWorktreeRegistration(relPath, root, feature) {
664
- const m = relPath.match(/^\.morph\/features\/([^/]+)\/feature\.json$/);
665
- if (!m || m[1] === feature) return false;
666
- try {
667
- const fj = JSON.parse(readFileSync(join(root, relPath), 'utf8'));
668
- const wtPath = fj?.worktree?.path;
669
- return typeof wtPath === 'string' && wtPath.length > 0 && existsSync(wtPath);
670
- } catch {
671
- return false;
672
- }
673
- }
674
-
675
- /**
676
- * `git worktree remove` deletes gitignored files and `git status --porcelain` omits them. shieldable:
677
- * backed up first; discarded: build artifacts and replicas of the root; blocking: enumeration failed.
678
- */
679
- export function classifyIgnoredLeftovers(worktreePath, rootPath, options = {}) {
680
- let out;
681
- try {
682
- // `-z` + execFile: NUL-delimited, no shell quoting. `=matching`: otherwise a dir ignored only through
683
- // its children (`MyProj/` via `bin/`, `obj/`) collapses into one entry, hiding the artifact names.
684
- out = execFileSync('git', ['status', '--porcelain', '--ignored=matching', '-z'], { cwd: worktreePath, stdio: 'pipe' }).toString();
685
- } catch {
686
- return { shieldable: [], blocking: ['<git status --ignored falhou — não foi possível enumerar o que seria destruído>'], discarded: [], replicable: [] };
687
- }
688
-
689
- const morphOwned = [];
690
- const rest = [];
691
- for (const record of out.split('\0')) {
692
- if (!record || record.length < 4) continue;
693
- if (record.slice(0, 2) !== '!!') continue; // only ignored entries; the rest is the clean-check's job
694
- const p = record.slice(3).replace(/\\/g, '/');
695
- if (IGNORED_SHIELDABLE_PREFIXES.some((prefix) => p.startsWith(prefix))) morphOwned.push(p);
696
- else rest.push(p);
697
- }
698
-
699
- const { replicable, disposable, exclusive } = triageIgnoredPaths({ worktreePath, rootPath, paths: rest });
700
- const shieldable = [...morphOwned, ...exclusive];
701
-
702
- // Consent = SKIP THE BACKUP, not widen what dies; the list is still reported.
703
- if (options.discardIgnored) {
704
- return { shieldable: [], blocking: [], discarded: [...disposable, ...replicable, ...shieldable], replicable };
705
- }
706
- return { shieldable, blocking: [], discarded: [...disposable, ...replicable], replicable };
707
- }
708
-
709
- /** Backs up FIRST, then discards: safe without being right about what is in scope. */
710
- export function shedRootFeatureScope(root, feature, { stamp } = {}) {
711
- const featPathspec = `.morph/features/${feature}`;
712
- let dirtyInScope = '';
713
- try {
714
- dirtyInScope = execFileSync('git', ['status', '--porcelain', '-uall', '--', featPathspec], { cwd: root, stdio: 'pipe' }).toString();
715
- } catch {}
716
-
717
- if (dirtyInScope.trim() === '') return { shedBackup: null };
718
-
719
- const shedBackup = writeFeatureScopeBackup({ root, feature, stamp });
720
- // No backup, no shed. Falling through leaves the root dirty, so the caller's
721
- // clean-check refuses — the exact fail-closed behaviour from before any shed.
722
- if (shedBackup) {
723
- try { execFileSync('git', ['checkout', '--', featPathspec], { cwd: root, stdio: 'pipe' }); } catch {}
724
- try { execFileSync('git', ['clean', '-fdq', '--', featPathspec], { cwd: root, stdio: 'pipe' }); } catch {}
725
- }
726
- return { shedBackup };
727
- }
728
-
729
- /**
730
- * `exemptOwnScope` forgives `.morph/features/{feature}/` so `finish` can ask before the shed runs;
731
- * callers must keep the post-shed check, the authoritative gate. `ok:false` = the status call failed.
732
- */
733
- export function primaryRootUnexplainedDirt(root, feature, opts = {}) {
734
- let rootStatusRaw;
735
- try {
736
- // `--untracked-files=all`: the default collapses an untracked dir into one entry that never
737
- // matches the exact `.../feature.json` path.
738
- rootStatusRaw = execFileSync('git', ['status', '--porcelain', '--untracked-files=all', '-z'], { cwd: root, stdio: 'pipe' }).toString();
739
- } catch {
740
- return { ok: false, dirt: [] };
741
- }
742
- const ownScope = `.morph/features/${feature}/`;
743
- const dirt = rootStatusRaw.split('\0').filter((record) => {
744
- if (!record || record.length < 4) return false;
745
- const p = record.slice(3).replace(/\\/g, '/');
746
- if (opts.exemptOwnScope && p.startsWith(ownScope)) return false;
747
- if (record.startsWith('?? ') && isTestArtifact(p)) return false;
748
- return !isLiveSiblingWorktreeRegistration(p, root, feature);
749
- });
750
- return { ok: true, dirt };
751
- }
752
-
753
- /**
754
- * Written DIRECTLY, never via saveState (which re-persists every sibling and can dirty the root
755
- * outside this pathspec). An untracked scaffold is never committed. Fail-open.
756
- */
757
- export async function clearRootWorktreeRegistration(root, feature, { stamp } = {}) {
758
- const featPathspec = `.morph/features/${feature}`;
759
- const gitOpts = { cwd: root, stdio: 'pipe' };
760
- try {
761
- const rootFjPath = join(root, '.morph', 'features', feature, 'feature.json');
762
- if (existsSync(rootFjPath)) {
763
- const fj = JSON.parse(readFileSync(rootFjPath, 'utf8'));
764
- if (fj.worktree) {
765
- delete fj.worktree;
766
- const { atomicWriteJson } = await import('../../core/state/state-manager.js');
767
- atomicWriteJson(rootFjPath, fj);
768
- }
769
- }
770
- } catch {}
771
-
772
- try {
773
- const tracked = execFileSync('git', ['ls-files', '--', featPathspec], gitOpts).toString().trim() !== '';
774
- if (!tracked) {
775
- if (!existsSync(join(root, '.morph', 'archive', feature))) return { shedBackup: null };
776
- return shedRootFeatureScope(root, feature, { stamp });
777
- }
778
- let unchanged = true;
779
- try { execFileSync('git', ['diff', '--quiet', 'HEAD', '--', featPathspec], gitOpts); } catch { unchanged = false; }
780
- if (!unchanged) {
781
- execFileSync('git', ['commit', '-m', `chore(morph): clear ${feature} worktree registration`, '--', featPathspec], gitOpts);
782
- }
783
- } catch { /* fail-open — a dirty root is a nuisance, not a reason to fail */ }
784
- return { shedBackup: null };
785
- }
786
-
787
- /** Only when the named path is gone: a LIVE registration is the anti-dupe guard's and `verify`'s only signal. */
788
- export async function clearDanglingWorktreeRegistration(root, feature) {
789
- try {
790
- const rootFjPath = join(root, '.morph', 'features', feature, 'feature.json');
791
- if (!existsSync(rootFjPath)) return { cleared: false };
792
- const fj = JSON.parse(readFileSync(rootFjPath, 'utf8'));
793
- const path = fj?.worktree?.path;
794
- if (!path || existsSync(path)) return { cleared: false };
795
- await clearRootWorktreeRegistration(root, feature);
796
- return { cleared: true };
797
- } catch {
798
- return { cleared: false };
799
- }
800
- }
801
-
802
- /** `in-use` (a process holding the dir on Windows) needs a human, so it is named apart. */
803
- function classifyRemovalError(stderr) {
804
- const text = String(stderr || '').trim();
805
- const inUse = /permission denied|EPERM|EBUSY|being used by another process|resource busy|access is denied|is locked/i.test(text);
806
- // First stderr line only: the rest is git's usual advice block, and this lands
807
- // in a JSON field a human reads.
808
- const detail = text.split(/\r?\n/).find((l) => l.trim()) || '';
809
- return { kind: inUse ? 'in-use' : 'unknown', detail: detail.slice(0, 200) };
810
- }
811
-
812
- /**
813
- * One retry for transient Windows handles (antivirus/indexer); it does not help `in-use`.
814
- * `--force` is safe only here: the caller proved there are no blockers.
815
- */
816
- async function attemptWorktreeRemoval(worktreePath, root) {
817
- const stderrs = [];
818
- for (let round = 0; round < 2; round++) {
819
- for (const args of [['worktree', 'remove', worktreePath], ['worktree', 'remove', '--force', worktreePath]]) {
820
- try {
821
- execFileSync('git', args, { cwd: root, stdio: 'pipe' });
822
- return { removed: true, failure: null };
823
- } catch (err) {
824
- stderrs.push(err?.stderr ? String(err.stderr) : (err?.message || ''));
825
- }
826
- }
827
- if (round === 0) await new Promise((r) => setTimeout(r, 200));
828
- }
829
- return { removed: false, failure: pickRemovalFailure(stderrs) };
830
- }
831
-
832
- /** A lock anywhere wins, else the first REAL error: later attempts only echo "is not a working tree". */
833
- export function pickRemovalFailure(stderrs) {
834
- const list = (stderrs || []).map((s) => String(s || '')).filter((s) => s.trim());
835
- const notAWorktree = (s) => /is not a working tree/i.test(s);
836
- const classified = list.map(classifyRemovalError);
837
- const firstReal = list.findIndex((s) => !notAWorktree(s));
838
- const chosen = classified.find((c) => c.kind === 'in-use')
839
- || (firstReal >= 0 ? classified[firstReal] : classified[classified.length - 1])
840
- || { kind: 'unknown', detail: '' };
841
- // Git dropped the registration BETWEEN attempts: a failure for another reason
842
- // followed by "is not a working tree". Only the directory is left.
843
- const alreadyDeregistered = firstReal >= 0 && list.slice(firstReal + 1).some(notAWorktree);
844
- return { ...chosen, alreadyDeregistered };
845
- }
846
-
847
- /**
848
- * PROVE-or-DECLINE. `refused` (proved unsafe) restores the junctions; a git FAILURE leaves them down
849
- * (`infraLeftUnlinked`).
850
- */
851
- export async function teardownWorktree(worktreePath, { root, feature, branch, options = {}, deleteBranch = true, addressByTarget = false, stamp }) {
852
- // ORDER IS LOAD-BEARING: unlink the junctions BEFORE git touches the dir. `git worktree remove`
853
- // follows them and deletes the root's installation; a declined path is repaired by the rollback below.
854
- const unlinked = unlinkWorktreeInfraLinks(worktreePath, root);
855
-
856
- const scan = findReparsePoints(worktreePath);
857
- const ignored = classifyIgnoredLeftovers(worktreePath, root, options);
858
- const blockers = [...scan.points, ...scan.unprovable];
859
-
860
- // Back up only once removal is cleared: `blockers.length === 0` proves no reparse point, and
861
- // cpSync follows junctions (it could copy an unbounded out-of-repo tree).
862
- let ignoredBackup = null;
863
- const clearedToRemove = blockers.length === 0 && ignored.blocking.length === 0;
864
- if (clearedToRemove && ignored.shieldable.length) {
865
- ignoredBackup = writeWorktreeIgnoredBackup({ worktreePath, root, feature, rels: ignored.shieldable, stamp });
866
- }
867
- const canRemove = clearedToRemove && (!ignored.shieldable.length || ignoredBackup !== null);
868
-
869
- let worktreeRemoved = false;
870
- let removalFailure = null;
871
- let rootShedBackup = null;
872
- if (canRemove) {
873
- const attempt = await attemptWorktreeRemoval(worktreePath, root);
874
- worktreeRemoved = attempt.removed;
875
- removalFailure = attempt.failure;
876
- }
877
-
878
- if (worktreeRemoved) {
879
- // `--pr` removes the worktree but keeps the branch the open PR needs.
880
- if (deleteBranch) {
881
- try { execFileSync('git', ['branch', '-d', branch], { cwd: root, stdio: 'pipe' }); } catch {}
882
- }
883
- try { execFileSync('git', ['worktree', 'prune'], { cwd: root, stdio: 'pipe' }); } catch {}
884
- try {
885
- const { releaseEnvBlock } = await import('../../lib/worktree/env-allocator.js');
886
- const common = execSync('git rev-parse --git-common-dir', { cwd: root, stdio: 'pipe' }).toString().trim();
887
- if (common) releaseEnvBlock(feature, { gitCommonDir: resolve(root, common) });
888
- } catch {}
889
- ({ shedBackup: rootShedBackup } = await clearRootWorktreeRegistration(root, feature, { stamp }));
890
- }
891
-
892
- // Relink ONLY on a REFUSAL: on a FAILURE removal was intended and only a lock remains; relinking
893
- // would make the next retry (or a raw `--force`) follow the junctions out.
894
- const refused = !canRemove;
895
- let relinked = false;
896
- if (refused && unlinked.length && existsSync(worktreePath)) {
897
- try {
898
- setupInfraLinks(worktreePath, root);
899
- relinked = true;
900
- } catch { relinked = false; }
901
- }
902
- const infraLeftUnlinked = (!worktreeRemoved && !refused && !relinked) ? unlinked : [];
903
-
904
- // Every hint names `morph-spec worktree remove`, NEVER `git worktree remove`: a frustrated reader
905
- // copies what was printed. A tree with no feature identity is addressed by `--target` path.
906
- const removeCmd = (addressByTarget || !isValidFeatureName(feature))
907
- ? `morph-spec worktree remove --target "${worktreePath}"`
908
- : `morph-spec worktree remove ${feature}`;
909
- const backupDir = finishBackupDir(root);
910
- const sample = (list) => `${list.slice(0, 5).join(', ')}${list.length > 5 ? `, +${list.length - 5}` : ''}`;
911
- const declineReason = worktreeRemoved
912
- ? null
913
- : ignored.blocking.length
914
- ? `worktree NÃO removido: não foi possível enumerar os arquivos gitignored (${sample(ignored.blocking)}), então não dá para provar que a remoção não destrói nada. Rode \`git status --ignored\` dentro do worktree para ver o que está travando e tente de novo com \`${removeCmd}\``
915
- : blockers.length
916
- ? `worktree NÃO removido: ainda contém link(s)/caminho(s) não verificáveis (${blockers.join(', ')}) que a remoção seguiria para fora, apagando o alvo na raiz. Remova-os e rode \`${removeCmd}\``
917
- : ignored.shieldable.length && ignoredBackup === null
918
- ? `worktree NÃO removido: o backup falhou. Estes arquivos existem só neste worktree e a remoção os apagaria: ${sample(ignored.shieldable)}. `
919
- + (ignored.replicable.length ? `(${sample(ignored.replicable)} são idênticos aos da raiz — esses não são o problema.) ` : '')
920
- + `O backup iria para \`${backupDir}\`; libere espaço/permissão ali e rode \`${removeCmd}\`, ou copie os arquivos você mesmo e rode \`${removeCmd} --discard-ignored\` para pular o backup`
921
- : removalFailure?.alreadyDeregistered
922
- ? `worktree NÃO removido por inteiro: a 1ª tentativa do git já apagou o conteúdo e desregistrou o worktree, mas o diretório "${worktreePath}" ficou`
923
- + (removalFailure.kind === 'in-use' ? ' — EM USO por outro processo (instância do Claude Code, VS Code, dev server ou terminal com cwd nele)' : '')
924
- + `${removalFailure.detail ? ` (${removalFailure.detail})` : ''}. Feche o que o usa e rode \`morph-spec worktree remove --target "${worktreePath}"\`: desmonta as junctions e apaga a pasta, sem recursão`
925
- : removalFailure?.kind === 'in-use'
926
- ? `worktree NÃO removido: o diretório está EM USO por outro processo (instância do Claude Code, VS Code, dev server ou terminal com cwd em "${worktreePath}"). `
927
- + (relinked
928
- ? `A infra compartilhada foi RESTAURADA — o worktree segue utilizável. Feche o que está usando o diretório e rode \`${removeCmd}\``
929
- : `A infra compartilhada ficou DESMONTADA de propósito — feche o que está usando o diretório e rode \`${removeCmd}\`. Se preferir continuar trabalhando nele, restaure a infra com \`morph-spec worktree link --all\``)
930
- : `worktree NÃO removido: a remoção falhou${removalFailure?.detail ? ` (${removalFailure.detail})` : ''}. `
931
- + (relinked
932
- ? `A infra compartilhada foi RESTAURADA — o worktree segue utilizável. Rode \`${removeCmd}\` para tentar de novo`
933
- : `A infra compartilhada ficou DESMONTADA de propósito — rode \`${removeCmd}\` para tentar de novo, ou \`morph-spec worktree link --all\` para voltar a trabalhar nele`);
934
-
935
- return {
936
- worktreeRemoved,
937
- ignoredBackup,
938
- discarded: ignored.discarded,
939
- replicable: ignored.replicable,
940
- // Reported: the proof the root's real `.claude/` was unlinked, never followed.
941
- unlinked,
942
- blockers,
943
- ignoredBlocking: ignored.blocking,
944
- shieldable: ignored.shieldable,
945
- declineReason,
946
- relinked,
947
- refused,
948
- infraLeftUnlinked,
949
- removalFailure,
950
- rootShedBackup,
951
- };
952
- }
953
-
954
- /** Windows locks a process's cwd: removing from inside fails after the merge, so refuse up front. */
955
- /**
956
- * On Windows a folder that is any process's cwd (a shell, an editor terminal) cannot be renamed, and
957
- * `git worktree remove` would fail the same way AFTER the archive. A rename there and back finds it first.
958
- */
959
- export function worktreeHeldElsewhere(worktreePath) {
960
- if (process.platform !== 'win32') return false;
961
- const probe = `${worktreePath}.finish-probe`;
962
- try {
963
- renameSync(worktreePath, probe);
964
- } catch (err) {
965
- return ['EBUSY', 'EPERM', 'EACCES'].includes(err.code);
966
- }
967
- renameSync(probe, worktreePath);
968
- return false;
969
- }
970
-
971
- export function cwdIsInsideWorktree(cwd, worktreePath) {
972
- const cwdNorm = resolve(cwd).replace(/\\/g, '/');
973
- const wtNorm = resolve(worktreePath).replace(/\\/g, '/');
974
- return cwdNorm === wtNorm || cwdNorm.startsWith(`${wtNorm}/`);
975
- }
976
-
977
- /**
978
- * The SESSION anchor, not the process cwd: tearing down the session's worktree kills every later hook
979
- * (MODULE_NOT_FOUND). Read from MORPH_SESSION_PROJECT_DIR (set by worktree-env-inject) or CLAUDE_PROJECT_DIR.
980
- */
981
- export function sessionAnchoredInWorktree(worktreePath, env = process.env) {
982
- const anchor = env.MORPH_SESSION_PROJECT_DIR || env.CLAUDE_PROJECT_DIR || '';
983
- return anchor ? cwdIsInsideWorktree(anchor, worktreePath) : false;
984
- }
985
-
986
- // Every link is removed as a link (unlink/rmdir act on the link, never its target) and nothing is
987
- // removed recursively: a real file left inside refuses before anything is touched.
988
- function removeOrphanFolder(path, root) {
989
- const links = [];
990
- const dirs = [];
991
- const files = [];
992
- const walk = (abs, rel) => {
993
- for (const name of readdirSync(abs)) {
994
- const childAbs = join(abs, name);
995
- const childRel = rel ? `${rel}/${name}` : name;
996
- const st = lstatSync(childAbs);
997
- if (st.isSymbolicLink()) links.push(childAbs);
998
- else if (st.isDirectory()) { walk(childAbs, childRel); dirs.push(childAbs); }
999
- else if (childRel === '.git') links.push(childAbs);
1000
- else files.push(childRel);
1001
- }
1002
- };
1003
- try {
1004
- walk(path, '');
1005
- } catch (err) {
1006
- return { out: { removed: false, error: 'orphan-unreadable', path, root, hint: `não consegui ler ${path} (${err.code || err.message}); nada foi removido` }, code: 1 };
1007
- }
1008
- if (files.length) {
1009
- return { out: { removed: false, error: 'orphan-not-empty', path, root, files: files.slice(0, 20),
1010
- hint: `a pasta órfã ainda tem arquivo(s) de verdade (${files.slice(0, 5).join(', ')}): mova o que importa e rode de novo. Nada foi removido` }, code: 1 };
1011
- }
1012
- try {
1013
- for (const link of links) {
1014
- try { unlinkSync(link); } catch { rmdirSync(link); }
1015
- }
1016
- for (const dir of dirs) rmdirSync(dir);
1017
- rmdirSync(path);
1018
- } catch (err) {
1019
- return { out: { removed: false, error: 'orphan-in-use', path, root, unlinked: links.length,
1020
- hint: `a pasta está em uso (${err.code || err.message}): feche o terminal, editor ou sessão com cwd nela e rode \`morph-spec worktree remove --target "${path}"\` de novo. As junctions já foram desmontadas` }, code: 1 };
1021
- }
1022
- return { out: { removed: true, path, orphan: true, unlinked: links.length }, code: 0 };
1023
- }
1024
-
1025
- /** Non-exiting core of `worktree remove`: removes ONLY, the branch survives by default. */
1026
- export async function runWorktreeRemove(featureArg, options = {}) {
1027
- const cwdArg = options.cwd || process.cwd();
1028
- const outcome = (out, code) => ({ out, code });
1029
-
1030
- if (!isGitRepo(cwdArg)) return outcome({ removed: false, error: 'not-a-git-repo' }, 1);
1031
- const root = resolvePrimaryRoot(cwdArg);
1032
-
1033
- let worktreePath = null;
1034
- let feature = featureArg || null;
1035
- let branch = null;
1036
- let featureAddressable = !options.target;
1037
-
1038
- if (options.target) {
1039
- worktreePath = resolve(options.target).replace(/\\/g, '/');
1040
- // Must be a registered worktree: `--target ../..` is a path traversal otherwise.
1041
- const entry = parseWorktreeList(root).find((e) => e.path === worktreePath);
1042
- if (!entry) {
1043
- if (existsSync(worktreePath) && isInContainer(root, worktreePath) && !cwdIsInsideWorktree(cwdArg, worktreePath)) {
1044
- return removeOrphanFolder(worktreePath, root);
1045
- }
1046
- return outcome({ removed: false, error: 'not-a-registered-worktree', target: worktreePath, root,
1047
- hint: 'o path precisa ser um worktree registrado neste repo, ou uma pasta órfã dentro de worktrees/ — confira `morph-spec worktree list`' }, 1);
1048
- }
1049
- if (worktreePath === root) {
1050
- return outcome({ removed: false, error: 'refuses-primary-root', path: worktreePath,
1051
- hint: 'a raiz primária nunca é removível por este comando' }, 1);
1052
- }
1053
- branch = entry.branch ? entry.branch.replace(/^refs\/heads\//, '') : null;
1054
- if (!feature && branch?.startsWith('morph/')) {
1055
- feature = branch.slice('morph/'.length);
1056
- featureAddressable = isValidFeatureName(feature);
1057
- }
1058
- } else {
1059
- if (!isValidFeatureName(feature)) {
1060
- return outcome({ removed: false, error: 'invalid-feature-name', feature: feature ?? null,
1061
- hint: 'informe <feature> (kebab-case) ou use --target <path>' }, 1);
1062
- }
1063
- const found = findWorktreeForFeature(feature, root);
1064
- if (!found || found.path.replace(/\\/g, '/') === root) {
1065
- return outcome({ removed: false, error: 'no-worktree-for-feature', feature, root,
1066
- hint: `nenhum worktree separado para "${feature}" — confira \`morph-spec worktree list\`` }, 1);
1067
- }
1068
- worktreePath = found.path;
1069
- branch = found.branch;
1070
- }
1071
-
1072
- if (cwdIsInsideWorktree(cwdArg, worktreePath)) {
1073
- return outcome({ removed: false, error: 'cwd-inside-worktree', path: worktreePath, root,
1074
- hint: `saia do worktree antes de removê-lo — o processo trava o próprio diretório de trabalho. Rode de novo a partir de "${root}"` }, 1);
1075
- }
1076
-
1077
- // The SESSION's anchor: refusing before the junctions are touched leaves its hooks intact.
1078
- if (sessionAnchoredInWorktree(worktreePath)) {
1079
- const again = featureAddressable && feature ? `morph-spec worktree remove ${feature}` : `morph-spec worktree remove --target "${worktreePath}"`;
1080
- return outcome({ removed: false, error: 'session-anchored-in-worktree', path: worktreePath, root,
1081
- hint: `a sessão do Claude Code que rodou este comando está ancorada neste worktree — os hooks dela resolvem \`.morph/framework\` por ele, e desmontá-lo quebraria todo tool call seguinte (e o diretório seguiria travado pela sessão). Feche esta sessão e rode \`${again}\` de uma sessão aberta em "${root}"` }, 1);
1082
- }
1083
-
1084
- // `--if-clean` (WorktreeRemove hook): any uncommitted file refuses BEFORE the junctions are touched.
1085
- // Infra links and the env manifest are excluded from git, so they never count.
1086
- if (options.ifClean) {
1087
- let status;
1088
- try {
1089
- status = execFileSync('git', ['status', '--porcelain', '--untracked-files=all'], { cwd: worktreePath, stdio: 'pipe' }).toString();
1090
- } catch {
1091
- return outcome({ removed: false, error: 'status-failed', path: worktreePath, root,
1092
- hint: 'não foi possível provar que o worktree está limpo — nada foi removido' }, 1);
1093
- }
1094
- const dirt = withoutLeftoverIgnore(worktreePath, status.split(/\r?\n/).filter((l) => l.trim()));
1095
- if (dirt.length) {
1096
- return outcome({ removed: false, error: 'worktree-dirty', path: worktreePath, root, dirt: dirt.slice(0, 20),
1097
- hint: `o worktree tem trabalho não commitado — commit ou descarte antes, ou rode \`morph-spec worktree remove --target "${worktreePath}"\` sem --if-clean para remover com backup` }, 1);
1098
- }
1099
- }
1100
-
1101
- // Leftover temp .graphifyignore: deleted only after every refusal, so a refused removal leaves the tree as it was.
1102
- dropLeftoverIgnore(worktreePath);
1103
-
1104
- // Read BEFORE the teardown: the entry is gone from `git worktree list` afterwards.
1105
- const envKey = envKeyForWorktree(worktreePath, root);
1106
-
1107
- // Compose stack down BEFORE the tree: a bind-mounted container holds the dir on Windows.
1108
- // A `morph/{f}` volume survives for the finish that reclaims it; a `morph-task/*` one has no later owner.
1109
- const volumes = /^morph-task\//.test(branch ?? '');
1110
- let e2e = null;
1111
- try {
1112
- const { tearDownFeatureStack } = await import('../../lib/e2e/stack-teardown.js');
1113
- e2e = tearDownFeatureStack(envKey || feature || basename(worktreePath), { root, worktreePath, volumes, _exec: options._exec });
1114
- } catch { e2e = null; }
1115
-
1116
- // The stamp this removal's backup is written under — protected from the
1117
- // retention that runs after it.
1118
- const stamp = newBackupStamp();
1119
- const teardown = await teardownWorktree(worktreePath, {
1120
- root,
1121
- feature: feature || envKey || 'worktree',
1122
- stamp,
1123
- branch,
1124
- options: { discardIgnored: options.discardIgnored === true },
1125
- // The branch is the work: deleting it would discard unintegrated commits. Opt-in only.
1126
- deleteBranch: options.deleteBranch === true,
1127
- // Re-run advice must address the worktree the way it was addressable here:
1128
- // a `--target` worktree has no feature name that would resolve.
1129
- addressByTarget: !featureAddressable,
1130
- });
1131
-
1132
- const out = {
1133
- removed: teardown.worktreeRemoved,
1134
- path: worktreePath,
1135
- ...(branch ? { branch } : {}),
1136
- ...(feature ? { feature } : {}),
1137
- };
1138
- if (teardown.unlinked.length) out.unlinked = teardown.unlinked;
1139
- if (e2e?.attempted || e2e?.hostServices) {
1140
- out.e2e = { status: e2e.status, cwd: e2e.cwd, volumes, ...(e2e.hostServices ? { hostServices: e2e.hostServices } : {}) };
1141
- }
1142
- if (teardown.worktreeRemoved) {
1143
- if (teardown.discarded.length) out.discardedIgnored = teardown.discarded;
1144
- if (teardown.replicable.length) out.replicatedInRoot = teardown.replicable;
1145
- if (teardown.ignoredBackup) out.ignoredBackup = teardown.ignoredBackup;
1146
- if (teardown.shieldable.length) out.backedUp = teardown.shieldable;
1147
- if (teardown.rootShedBackup) out.shedBackup = teardown.rootShedBackup;
1148
- } else {
1149
- out.refused = teardown.refused;
1150
- if (teardown.blockers.length) out.reparsePoints = teardown.blockers;
1151
- if (teardown.ignoredBlocking.length) out.ignoredFiles = teardown.ignoredBlocking;
1152
- if (teardown.shieldable.length) out.exclusiveIgnored = teardown.shieldable;
1153
- if (teardown.replicable.length) out.replicatedInRoot = teardown.replicable;
1154
- if (teardown.infraLeftUnlinked.length) out.infraLeftUnlinked = teardown.infraLeftUnlinked;
1155
- out.hint = teardown.declineReason;
1156
- }
1157
- // After the new backup, never before — and never the new backup itself.
1158
- if (teardown.ignoredBackup) {
1159
- const retention = enforceBackupRetention(root, { protectStamps: [stamp] });
1160
- if (retention) out.backupRetention = retention;
1161
- }
1162
- return outcome(out, teardown.worktreeRemoved ? 0 : 1);
1163
- }
1164
-
1165
- export async function worktreeRemoveCommand(featureArg, options = {}) {
1166
- const { out, code } = await runWorktreeRemove(featureArg, options);
1167
- console.log(JSON.stringify(out));
1168
- process.exit(code);
1169
- }
1170
-
1171
- export async function worktreeListCommand(options = {}) {
1172
- const cwd = options.cwd || process.cwd();
1173
-
1174
- if (!isGitRepo(cwd)) {
1175
- printWorktreeList([], options);
1176
- process.exit(0);
1177
- }
1178
-
1179
- const root = resolvePrimaryRoot(cwd);
1180
- const entries = parseWorktreeList(root);
1181
-
1182
- const worktrees = [];
1183
- if (entries.length) {
1184
- const { derivePhaseForFeature, getPendingGates, getFeature } =
1185
- await import('../../../framework/hooks/shared/state-reader.js');
1186
-
1187
- for (const entry of entries) {
1188
- const m = entry.branch && entry.branch.match(/^refs\/heads\/morph\/(.+)$/);
1189
- if (!m) continue;
1190
- const feature = m[1];
1191
-
1192
- let phase = 'plan';
1193
- let status = 'unknown';
1194
- let pendingGates = [];
1195
- try {
1196
- const featureObj = getFeature(feature, entry.path);
1197
- status = featureObj?.status || 'unknown';
1198
- phase = derivePhaseForFeature(feature, entry.path);
1199
- pendingGates = getPendingGates(feature, entry.path);
1200
- } catch { /* leave defaults — a corrupt feature.json must never crash list */ }
1201
-
1202
- worktrees.push({
1203
- feature,
1204
- branch: entry.branch.replace(/^refs\/heads\//, ''),
1205
- phase,
1206
- status,
1207
- pendingGates,
1208
- path: entry.path,
1209
- });
1210
- }
1211
- }
1212
-
1213
- printWorktreeList(worktrees, options);
1214
- process.exit(0);
1215
- }
1216
-
1217
- function printWorktreeList(worktrees, options) {
1218
- if (options.json) {
1219
- console.log(JSON.stringify({ worktrees }));
1220
- return;
1221
- }
1222
-
1223
- if (worktrees.length === 0) {
1224
- console.log(chalk.gray('No active feature worktrees.'));
1225
- return;
1226
- }
1227
-
1228
- const col = (s, w) => String(s).padEnd(w);
1229
- console.log(chalk.white.bold(col('FEATURE', 22) + col('BRANCH', 26) + col('PHASE', 12) + col('STATUS', 14) + col('PENDING GATES', 24) + 'PATH'));
1230
- for (const w of worktrees) {
1231
- const gates = w.pendingGates.length ? w.pendingGates.join(',') : '-';
1232
- console.log(col(w.feature, 22) + col(w.branch, 26) + col(w.phase, 12) + col(w.status, 14) + col(gates, 24) + w.path);
1233
- }
1234
- }