@polymorphism-tech/morph-spec 10.12.1 → 11.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (323) hide show
  1. package/CLAUDE.md +27 -57
  2. package/README.md +51 -340
  3. package/bin/morph-spec.js +22 -373
  4. package/docs/CHEATSHEET.md +37 -166
  5. package/docs/QUICKSTART.md +14 -74
  6. package/framework/CLAUDE.md +15 -26
  7. package/framework/MORPH.md +34 -101
  8. package/framework/agents.json +8 -8
  9. package/framework/commands/morph-apply.md +5 -5
  10. package/framework/commands/morph-infra.md +1 -1
  11. package/framework/docs/CLI.md +74 -886
  12. package/framework/evals/review-checklist.md +14 -14
  13. package/framework/hooks/README.md +21 -189
  14. package/framework/hooks/claude-code/core/README.md +2 -5
  15. package/framework/hooks/claude-code/core/conventional-commit.js +2 -2
  16. package/framework/hooks/claude-code/core/denylist.json +3 -3
  17. package/framework/hooks/claude-code/core/graph-refresh-kick.js +2 -2
  18. package/framework/hooks/claude-code/core/masked-exit.js +6 -6
  19. package/framework/hooks/claude-code/core/pre-bash-denylist.js +2 -2
  20. package/framework/hooks/claude-code/core/protect-spec-files.js +17 -61
  21. package/framework/hooks/claude-code/core/stack-changed.js +35 -0
  22. package/framework/hooks/claude-code/core/validate-completion.js +32 -87
  23. package/framework/hooks/shared/{heavy-command.js → command-kind.js} +6 -79
  24. package/framework/hooks/shared/command-tokens.js +0 -139
  25. package/framework/hooks/shared/contract.js +14 -0
  26. package/framework/hooks/shared/feature-slug.js +21 -0
  27. package/framework/hooks/shared/frontend-locations.js +0 -1
  28. package/framework/hooks/shared/git-paths.js +0 -15
  29. package/framework/hooks/shared/graph-freshness.js +0 -19
  30. package/framework/hooks/shared/hook-response.js +0 -7
  31. package/framework/hooks/shared/morph-cli.js +2 -81
  32. package/framework/hooks/shared/owner-words.js +2 -120
  33. package/framework/hooks/shared/payload-utils.js +0 -39
  34. package/framework/hooks/shared/report-progress.js +7 -101
  35. package/framework/hooks/statusline.js +16 -60
  36. package/framework/mcp/registry.json +2 -2
  37. package/framework/rules/ai-agents-standards.md +1 -1
  38. package/framework/rules/asaas-standards.md +1 -1
  39. package/framework/rules/ef-standards.md +1 -1
  40. package/framework/rules/gsap-standards.md +1 -1
  41. package/framework/rules/hangfire-standards.md +1 -1
  42. package/framework/rules/implement-report.md +3 -3
  43. package/framework/rules/neon-auth-standards.md +1 -1
  44. package/framework/rules/nextjs-standards.md +1 -1
  45. package/framework/rules/plan-grammar.md +13 -11
  46. package/framework/rules/resend-standards.md +1 -1
  47. package/framework/rules/ui-design.md +4 -0
  48. package/framework/schemas/config.schema.json +95 -310
  49. package/framework/skills/README.md +12 -32
  50. package/framework/skills/core/create-umbraco-lp/SKILL.md +1 -1
  51. package/framework/skills/core/migrate-lp-to-umbraco/SKILL.md +1 -1
  52. package/framework/skills/core/morph-apply/SKILL.md +21 -46
  53. package/framework/skills/core/morph-plan/SKILL.md +28 -63
  54. package/framework/skills/core/morph-uiux/SKILL.md +23 -25
  55. package/framework/{templates/docs/ui-mockups.md → skills/core/morph-uiux/references/mockups.md} +4 -4
  56. package/framework/standards/STANDARDS.json +10 -11
  57. package/framework/standards/STANDARDS.meta.json +1 -1
  58. package/framework/standards/ai-agents/evals-with-cache.md +18 -32
  59. package/framework/standards/ai-agents/observability-patterns.md +2 -2
  60. package/framework/standards/architecture/code-comments.md +2 -5
  61. package/framework/standards/architecture/engineering-lens.md +1 -1
  62. package/framework/standards/backend/dotnet/testing.md +4 -4
  63. package/framework/standards/frontend/nextjs/lint.md +24 -10
  64. package/framework/standards/frontend/nextjs/testing.md +2 -2
  65. package/framework/standards/infrastructure/docker/local-compose-isolation.md +14 -30
  66. package/framework/templates/CLAUDE.md.core.guide.md +2 -2
  67. package/framework/templates/README.md +1 -1
  68. package/framework/templates/REGISTRY.json +3 -33
  69. package/framework/templates/docs/plan.md +3 -2
  70. package/framework/templates/dotnet/ai-kit/README.md +2 -4
  71. package/framework/templates/dotnet/ai-kit/src/Morph.AiKit/Evals/EvalCacheMissException.cs +1 -1
  72. package/framework/templates/dotnet/ai-kit/src/Morph.AiKit/Evals/EvalFixture.cs +1 -1
  73. package/package.json +1 -2
  74. package/src/commands/graph/explain.js +2 -1
  75. package/src/commands/graph/status.js +2 -1
  76. package/src/commands/mcp/mcp-setup.js +1 -2
  77. package/src/commands/project/doctor.js +5 -341
  78. package/src/commands/project/env.js +21 -52
  79. package/src/commands/project/init-contract.js +47 -0
  80. package/src/commands/project/init.js +36 -66
  81. package/src/commands/project/stack-scan.js +1 -1
  82. package/src/commands/project/update.js +15 -50
  83. package/src/commands/validation/check.js +128 -0
  84. package/src/commands/validation/plan-check.js +41 -64
  85. package/src/commands/validation/prove-red.js +1 -1
  86. package/src/core/paths/output-schema.js +0 -22
  87. package/src/core/templates/template-renderer.js +0 -14
  88. package/src/lib/ai/ai-project-scan.js +1 -6
  89. package/src/lib/check/attempts.js +38 -0
  90. package/src/lib/check/signals.js +145 -0
  91. package/src/lib/config/project-config.js +13 -0
  92. package/src/lib/contract/apply.js +62 -0
  93. package/src/lib/contract/defaults.js +96 -0
  94. package/src/lib/contract/merge.js +79 -0
  95. package/src/lib/contract/ports.js +43 -0
  96. package/src/lib/contract/scan.js +102 -0
  97. package/src/lib/detectors/claude-config-detector.js +7 -0
  98. package/src/lib/{procs → detectors}/mcp-config.js +1 -37
  99. package/src/lib/diff/diff-lines.js +64 -0
  100. package/src/lib/generators/architecture-scanner.js +1 -1
  101. package/src/lib/generators/scaffold-generator.js +0 -7
  102. package/src/lib/git/default-branch.js +0 -122
  103. package/src/lib/graph/diff-tree.js +2 -1
  104. package/src/lib/graph/god-nodes.js +2 -1
  105. package/src/lib/graph/graphify-runtime.js +0 -1
  106. package/src/lib/graph/graphifyignore.js +1 -1
  107. package/src/lib/graph/sanitize.js +2 -8
  108. package/src/lib/installers/memory-installer.js +15 -30
  109. package/src/lib/installers/stack-sync.js +16 -9
  110. package/src/lib/plan/checks.js +20 -64
  111. package/src/lib/plan/media.js +1 -1
  112. package/src/lib/plan/plan-parser.js +5 -5
  113. package/src/lib/review-reports.js +3 -77
  114. package/src/lib/scan/worktree-dirs.js +3 -0
  115. package/src/lib/specs/adr-index.js +2 -2
  116. package/src/lib/stack/dotnet-build-ignores.js +10 -2
  117. package/src/lib/stack/stack-scan.js +2 -2
  118. package/src/lib/stack-filter.js +3 -2
  119. package/src/lib/tests-audit/audit.js +1 -1
  120. package/src/scripts/setup-infra.js +6 -59
  121. package/src/utils/agents-installer.js +1 -34
  122. package/src/utils/atomic-json.js +27 -0
  123. package/src/utils/file-copier.js +4 -12
  124. package/src/utils/hooks-installer.js +9 -107
  125. package/claude-plugin.json +0 -14
  126. package/framework/commands/morph-archive.md +0 -46
  127. package/framework/commands/morph-hotfix.md +0 -17
  128. package/framework/commands/morph-preflight.md +0 -180
  129. package/framework/commands/morph-review.md +0 -15
  130. package/framework/commands/morph-status.md +0 -37
  131. package/framework/hooks/claude-code/core/block-destructive-worktree-removal.js +0 -80
  132. package/framework/hooks/claude-code/core/block-raw-worktree-add.js +0 -72
  133. package/framework/hooks/claude-code/core/enforce-phase-writes.js +0 -100
  134. package/framework/hooks/claude-code/core/gate-guard.js +0 -148
  135. package/framework/hooks/claude-code/core/heavy-gate.js +0 -78
  136. package/framework/hooks/claude-code/core/heavy-release.js +0 -23
  137. package/framework/hooks/claude-code/core/loop-detect.js +0 -79
  138. package/framework/hooks/claude-code/core/state-sync.js +0 -214
  139. package/framework/hooks/claude-code/core/telemetry-log.js +0 -259
  140. package/framework/hooks/claude-code/core/test-budget.js +0 -29
  141. package/framework/hooks/claude-code/core/worktree-context.js +0 -249
  142. package/framework/hooks/claude-code/core/worktree-create.js +0 -119
  143. package/framework/hooks/claude-code/core/worktree-env-inject.js +0 -68
  144. package/framework/hooks/claude-code/core/worktree-remove.js +0 -55
  145. package/framework/hooks/shared/build-check.js +0 -120
  146. package/framework/hooks/shared/claim-registry.js +0 -125
  147. package/framework/hooks/shared/e2e-check.js +0 -1022
  148. package/framework/hooks/shared/feature-locator.js +0 -82
  149. package/framework/hooks/shared/gate-event.js +0 -18
  150. package/framework/hooks/shared/gate-question.js +0 -20
  151. package/framework/hooks/shared/heavy-config.js +0 -113
  152. package/framework/hooks/shared/heavy-holders.js +0 -85
  153. package/framework/hooks/shared/heavy-slots.js +0 -280
  154. package/framework/hooks/shared/host-services.js +0 -440
  155. package/framework/hooks/shared/next-step.js +0 -181
  156. package/framework/hooks/shared/redact-secrets.js +0 -44
  157. package/framework/hooks/shared/reparse-scan.js +0 -40
  158. package/framework/hooks/shared/state-reader.js +0 -220
  159. package/framework/hooks/shared/state-writer.js +0 -112
  160. package/framework/hooks/shared/telemetry-logger.js +0 -101
  161. package/framework/hooks/shared/transcript-usage.js +0 -58
  162. package/framework/hooks/shared/worktree-root.js +0 -71
  163. package/framework/phases.json +0 -92
  164. package/framework/schemas/feature.schema.json +0 -242
  165. package/framework/skills/core/morph-apply/references/hotfix.md +0 -46
  166. package/framework/skills/core/morph-apply/references/machine.md +0 -30
  167. package/framework/skills/core/morph-apply/references/review.md +0 -77
  168. package/framework/skills/core/morph-plan/references/critique.md +0 -51
  169. package/framework/skills/core/morph-plan/references/interview.md +0 -37
  170. package/framework/templates/state.template.json +0 -17
  171. package/src/commands/dashboard/dashboard.js +0 -74
  172. package/src/commands/e2e/e2e.js +0 -400
  173. package/src/commands/observability/cost.js +0 -283
  174. package/src/commands/project/branch.js +0 -129
  175. package/src/commands/project/claim.js +0 -132
  176. package/src/commands/project/doctor-procs.js +0 -162
  177. package/src/commands/project/fleet.js +0 -66
  178. package/src/commands/project/heavy.js +0 -81
  179. package/src/commands/project/install-plugin-cmd.js +0 -27
  180. package/src/commands/project/status.js +0 -61
  181. package/src/commands/project/worktree.js +0 -1234
  182. package/src/commands/state/advance.js +0 -248
  183. package/src/commands/state/approve.js +0 -303
  184. package/src/commands/state/archive.js +0 -231
  185. package/src/commands/state/auto-approval.js +0 -67
  186. package/src/commands/state/create.js +0 -274
  187. package/src/commands/state/delete.js +0 -192
  188. package/src/commands/state/finish.js +0 -1247
  189. package/src/commands/state/gate-check.js +0 -244
  190. package/src/commands/state/gate-decision.js +0 -122
  191. package/src/commands/state/list.js +0 -244
  192. package/src/commands/state/next.js +0 -24
  193. package/src/commands/state/recap.js +0 -80
  194. package/src/commands/state/report-check.js +0 -244
  195. package/src/commands/state/retype.js +0 -110
  196. package/src/commands/validation/verify.js +0 -421
  197. package/src/core/state/feature-identity.js +0 -10
  198. package/src/core/state/gate-order.js +0 -23
  199. package/src/core/state/lifecycle-audit.js +0 -171
  200. package/src/core/state/state-manager.js +0 -523
  201. package/src/core/templates/template-seed.js +0 -21
  202. package/src/core/work-types.js +0 -44
  203. package/src/dashboard/app/App.jsx +0 -84
  204. package/src/dashboard/app/components/ActivityFeed.jsx +0 -166
  205. package/src/dashboard/app/components/CommandPalette.jsx +0 -144
  206. package/src/dashboard/app/components/DetailPanel.jsx +0 -43
  207. package/src/dashboard/app/components/EntityLink.jsx +0 -42
  208. package/src/dashboard/app/components/ErrorBoundary.jsx +0 -47
  209. package/src/dashboard/app/components/FlowGraph.jsx +0 -19
  210. package/src/dashboard/app/components/GatePauses.jsx +0 -116
  211. package/src/dashboard/app/components/KnowledgeMarkdown.jsx +0 -42
  212. package/src/dashboard/app/components/Markdown.jsx +0 -38
  213. package/src/dashboard/app/components/PhaseRail.jsx +0 -100
  214. package/src/dashboard/app/components/SearchFilter.jsx +0 -36
  215. package/src/dashboard/app/components/SessionMap.jsx +0 -77
  216. package/src/dashboard/app/components/Sidebar.jsx +0 -147
  217. package/src/dashboard/app/hooks/useMorphQuery.js +0 -44
  218. package/src/dashboard/app/hooks/usePref.js +0 -34
  219. package/src/dashboard/app/lib/format.js +0 -69
  220. package/src/dashboard/app/lib/phases.js +0 -75
  221. package/src/dashboard/app/lib/project.js +0 -38
  222. package/src/dashboard/app/main.jsx +0 -13
  223. package/src/dashboard/app/pages/Activity.jsx +0 -28
  224. package/src/dashboard/app/pages/AgentMap.jsx +0 -363
  225. package/src/dashboard/app/pages/FeatureDetail.jsx +0 -579
  226. package/src/dashboard/app/pages/Features.jsx +0 -393
  227. package/src/dashboard/app/pages/Guide.jsx +0 -145
  228. package/src/dashboard/app/pages/HookInspector.jsx +0 -444
  229. package/src/dashboard/app/pages/PhasePipeline.jsx +0 -273
  230. package/src/dashboard/app/pages/Portfolio.jsx +0 -190
  231. package/src/dashboard/app/pages/RulesMap.jsx +0 -285
  232. package/src/dashboard/app/pages/SkillsLibrary.jsx +0 -468
  233. package/src/dashboard/app/pages/Standards.jsx +0 -392
  234. package/src/dashboard/app/styles/index.css +0 -187
  235. package/src/dashboard/index.html +0 -14
  236. package/src/dashboard/package.json +0 -32
  237. package/src/dashboard/scanner/activity-scanner.js +0 -321
  238. package/src/dashboard/scanner/agents-scanner.js +0 -67
  239. package/src/dashboard/scanner/docs-scanner.js +0 -34
  240. package/src/dashboard/scanner/feature-status.js +0 -7
  241. package/src/dashboard/scanner/features-scanner.js +0 -397
  242. package/src/dashboard/scanner/hooks-scanner.js +0 -96
  243. package/src/dashboard/scanner/index.js +0 -21
  244. package/src/dashboard/scanner/phases-scanner.js +0 -14
  245. package/src/dashboard/scanner/portfolio.js +0 -129
  246. package/src/dashboard/scanner/project-api.js +0 -160
  247. package/src/dashboard/scanner/rules-scanner.js +0 -46
  248. package/src/dashboard/scanner/skills-scanner.js +0 -104
  249. package/src/dashboard/scanner/standards-scanner.js +0 -38
  250. package/src/dashboard/vite-plugin-morph-data.js +0 -120
  251. package/src/dashboard/vite.config.js +0 -26
  252. package/src/lib/ci/ci-verify.js +0 -30
  253. package/src/lib/ci/github-ci.js +0 -52
  254. package/src/lib/ci/pr-checks.js +0 -76
  255. package/src/lib/e2e/applicability.js +0 -39
  256. package/src/lib/e2e/compose-env.js +0 -80
  257. package/src/lib/e2e/stack-teardown.js +0 -96
  258. package/src/lib/git/branch-classifier.js +0 -104
  259. package/src/lib/git/evidence-staleness.js +0 -40
  260. package/src/lib/git/gh.js +0 -15
  261. package/src/lib/git/pending-prs.js +0 -58
  262. package/src/lib/git/pr-files.js +0 -31
  263. package/src/lib/git/pr-index.js +0 -39
  264. package/src/lib/git/tree-fingerprint.js +0 -58
  265. package/src/lib/git/tree-state.js +0 -125
  266. package/src/lib/heavy/cleanup.js +0 -72
  267. package/src/lib/heavy/gate.js +0 -168
  268. package/src/lib/heavy/live-stacks.js +0 -64
  269. package/src/lib/heavy/reclaim.js +0 -107
  270. package/src/lib/heavy/watchdog.js +0 -46
  271. package/src/lib/next-step.js +0 -12
  272. package/src/lib/plan/critique.js +0 -67
  273. package/src/lib/plan/plan-template.js +0 -18
  274. package/src/lib/procs/classify.js +0 -91
  275. package/src/lib/procs/list.js +0 -124
  276. package/src/lib/procs/prune.js +0 -47
  277. package/src/lib/procs/wslconfig.js +0 -70
  278. package/src/lib/projects/registry.js +0 -121
  279. package/src/lib/recap/piper.js +0 -36
  280. package/src/lib/recap/recap.js +0 -259
  281. package/src/lib/review-confirmation.js +0 -66
  282. package/src/lib/risk/diff-risk.js +0 -137
  283. package/src/lib/risk-detector.js +0 -638
  284. package/src/lib/specs/design-seed.js +0 -18
  285. package/src/lib/specs/screen-checklist.js +0 -315
  286. package/src/lib/stack/stack-profile.js +0 -69
  287. package/src/lib/tasks/eval-node.js +0 -293
  288. package/src/lib/tasks/linux-runner.js +0 -200
  289. package/src/lib/tasks/test-nodes.js +0 -414
  290. package/src/lib/tasks/test-runner.js +0 -569
  291. package/src/lib/telemetry/metrics.js +0 -384
  292. package/src/lib/telemetry/telemetry-reader.js +0 -276
  293. package/src/lib/telemetry/verify-event.js +0 -57
  294. package/src/lib/validators/code-budget/code-budget-validator.js +0 -170
  295. package/src/lib/validators/contracts/contract-compliance-validator.js +0 -219
  296. package/src/lib/validators/nextjs/next-component-validator.js +0 -142
  297. package/src/lib/validators/packages/package-validator.js +0 -310
  298. package/src/lib/validators/reuse/reuse-validator.js +0 -202
  299. package/src/lib/validators/reuse/symbol-scanner.js +0 -64
  300. package/src/lib/validators/validation-runner.js +0 -188
  301. package/src/lib/validators/verify-cache.js +0 -63
  302. package/src/lib/validators/verify-runner.js +0 -971
  303. package/src/lib/verify/affected.js +0 -143
  304. package/src/lib/verify/detached.js +0 -159
  305. package/src/lib/view/feature-html.js +0 -480
  306. package/src/lib/view/feature-page.client.js +0 -109
  307. package/src/lib/view/feature-page.css +0 -278
  308. package/src/lib/view/feature-view.js +0 -113
  309. package/src/lib/view/flow-layers.js +0 -79
  310. package/src/lib/view/flow-svg.js +0 -63
  311. package/src/lib/view/tokens.css +0 -18
  312. package/src/lib/work-type-detector.js +0 -81
  313. package/src/lib/worktree/dirs.js +0 -3
  314. package/src/lib/worktree/docker-audit.js +0 -175
  315. package/src/lib/worktree/env-allocator.js +0 -177
  316. package/src/lib/worktree/feature-truth.js +0 -145
  317. package/src/lib/worktree/finish-backup.js +0 -529
  318. package/src/lib/worktree/fleet-scanner.js +0 -223
  319. package/src/lib/worktree/ignored-triage.js +0 -136
  320. package/src/lib/worktree/vscode-settings.js +0 -112
  321. package/src/lib/worktree/worktree-audit.js +0 -323
  322. package/src/lib/worktree/worktree-include.js +0 -44
  323. package/src/scripts/install-plugin.js +0 -114
@@ -1,18 +0,0 @@
1
- import { readFileSync } from 'fs';
2
- import { templateSourcePath, writeIfAbsent } from '../../core/templates/template-seed.js';
3
- import { getAbsoluteOutputPath } from '../../core/paths/output-schema.js';
4
-
5
- const FEATURE_PLACEHOLDER = /\{\{FEATURE_NAME\}\}/g;
6
-
7
- export function planTemplatePath(cwd = process.cwd()) {
8
- return templateSourcePath('plan', cwd);
9
- }
10
-
11
- export function renderPlanSkeleton(featureName, cwd = process.cwd()) {
12
- return readFileSync(planTemplatePath(cwd), 'utf8').replace(FEATURE_PLACEHOLDER, featureName);
13
- }
14
-
15
- /** @returns {{ path: string, written: boolean }} `written: false` when the file already existed. */
16
- export function writePlanSkeleton(featureName, cwd = process.cwd()) {
17
- return writeIfAbsent(getAbsoluteOutputPath(cwd, featureName, 'plan'), renderPlanSkeleton(featureName, cwd));
18
- }
@@ -1,91 +0,0 @@
1
- export const MIN_ORPHAN_AGE_MS = 15 * 60 * 1000;
2
-
3
- const PLAIN_CANDIDATES = new Set(['node', 'dotnet', 'testhost', 'esbuild']);
4
- const CHROME_NAMES = new Set(['chrome', 'chromium', 'msedge', 'chrome-headless-shell']);
5
- const BUILD_SERVER_NAMES = new Set(['vbcscompiler', 'msbuild']);
6
- const BUILD_SERVER_CMD = /vbcscompiler|\/nodemode:\d|msbuild(?:taskhost)?\.dll|razorserver/i;
7
- const AUTOMATION_CHROME = /--headless|--remote-debugging-pipe|playwright|puppeteer/i;
8
- const CLAUDE_CLI = /@anthropic-ai[\\/]claude-code/i;
9
-
10
- export function normalizeCmd(cmd) {
11
- return String(cmd ?? '').toLowerCase().replace(/\\/g, '/');
12
- }
13
-
14
- export function categorize(proc) {
15
- const cmd = proc.cmd ?? '';
16
- if (BUILD_SERVER_NAMES.has(proc.name)) return 'build-server';
17
- if (proc.name === 'dotnet' && BUILD_SERVER_CMD.test(cmd)) return 'build-server';
18
- if (CHROME_NAMES.has(proc.name)) {
19
- return AUTOMATION_CHROME.test(cmd) && !/--type=/.test(cmd) ? 'chrome-headless' : null;
20
- }
21
- return PLAIN_CANDIDATES.has(proc.name) ? proc.name : null;
22
- }
23
-
24
- export function isClaudeSession(proc) {
25
- return proc.name === 'claude' || CLAUDE_CLI.test(proc.cmd ?? '');
26
- }
27
-
28
- function protectionReason(proc, { mcpTokens, holderPids }) {
29
- if (holderPids.has(proc.pid)) return 'segura slot do semáforo pesado';
30
- const cmd = normalizeCmd(proc.cmd);
31
- if (/graph-refresh\.js/.test(cmd) && /--run\b/.test(cmd)) return 'worker de refresh do grafo';
32
- const token = mcpTokens.find((t) => cmd.includes(t));
33
- if (token) return `linha de comando de MCP configurado (${token})`;
34
- return null;
35
- }
36
-
37
- export function classifyProcs(procs, { now = Date.now(), mcpTokens = [], holderPids = [], minAgeMs = MIN_ORPHAN_AGE_MS } = {}) {
38
- const byPid = new Map(procs.map((p) => [p.pid, p]));
39
- const tokens = mcpTokens.map((t) => String(t).toLowerCase());
40
- const holders = new Set(holderPids);
41
-
42
- const liveParent = (p) => {
43
- const parent = byPid.get(p.ppid);
44
- if (!parent) return null;
45
- if (parent.startedMs !== null && p.startedMs !== null && parent.startedMs > p.startedMs) return null;
46
- return parent;
47
- };
48
-
49
- const rows = [];
50
- for (const proc of procs) {
51
- const category = categorize(proc);
52
- if (!category) continue;
53
- const orphan = proc.ppid > 4 && liveParent(proc) === null;
54
- const ageMs = proc.startedMs === null ? null : Math.max(0, now - proc.startedMs);
55
- const row = {
56
- pid: proc.pid,
57
- ppid: proc.ppid,
58
- name: proc.name,
59
- category,
60
- cmd: proc.cmd,
61
- rssMb: Math.round(proc.rss / (1024 * 1024)),
62
- startedMs: proc.startedMs,
63
- ageMs,
64
- orphan,
65
- verdict: 'alive-parent',
66
- reason: null,
67
- };
68
- if (orphan) {
69
- const protectedBy = category === 'build-server' ? null : protectionReason(proc, { mcpTokens: tokens, holderPids: holders });
70
- if (category === 'build-server') {
71
- row.verdict = 'build-server';
72
- row.reason = 'nó de build reutilizável pode servir outra sessão; encerre com `dotnet build-server shutdown` quando ocioso';
73
- } else if (protectedBy) {
74
- row.verdict = 'protected';
75
- row.reason = protectedBy;
76
- } else if (ageMs === null) {
77
- row.verdict = 'protected';
78
- row.reason = 'idade desconhecida';
79
- } else if (ageMs < minAgeMs) {
80
- row.verdict = 'protected';
81
- row.reason = `mais novo que ${Math.round(minAgeMs / 60000)} min`;
82
- } else {
83
- row.verdict = 'orphan';
84
- }
85
- }
86
- rows.push(row);
87
- }
88
-
89
- const sessions = procs.filter(isClaudeSession).length;
90
- return { rows, sessions };
91
- }
@@ -1,124 +0,0 @@
1
- import { execFileSync } from 'node:child_process';
2
- import { readFileSync } from 'node:fs';
3
-
4
- const PS_PROJECTION = "[pscustomobject]@{ pid = $_.ProcessId; ppid = $_.ParentProcessId; name = $_.Name; cmd = $_.CommandLine; rss = [int64]$_.WorkingSetSize; started = if ($_.CreationDate) { $_.CreationDate.ToUniversalTime().ToString('o') } else { $null } }";
5
- const PS_PREFIX = '[Console]::OutputEncoding = [Text.Encoding]::UTF8; ';
6
-
7
- export function defaultProcExec(file, args, { timeout = 30000 } = {}) {
8
- try {
9
- const output = execFileSync(file, args, {
10
- encoding: 'utf8',
11
- timeout,
12
- windowsHide: true,
13
- maxBuffer: 64 * 1024 * 1024,
14
- stdio: ['ignore', 'pipe', 'pipe'],
15
- });
16
- return { code: 0, output };
17
- } catch (err) {
18
- return {
19
- code: err.status ?? 1,
20
- output: `${err.stdout ?? ''}${err.stderr ?? ''}`,
21
- missing: err.code === 'ENOENT',
22
- };
23
- }
24
- }
25
-
26
- export function normalizeProcName(name) {
27
- return String(name ?? '').toLowerCase().replace(/\.exe$/, '');
28
- }
29
-
30
- function toProc(p) {
31
- const startedMs = typeof p.startedMs === 'number' ? p.startedMs : p.started ? Date.parse(p.started) : null;
32
- return {
33
- pid: Number(p.pid),
34
- ppid: Number(p.ppid ?? 0),
35
- name: normalizeProcName(p.name),
36
- cmd: typeof p.cmd === 'string' && p.cmd.length ? p.cmd : null,
37
- rss: Number(p.rss ?? 0),
38
- startedMs: Number.isFinite(startedMs) ? startedMs : null,
39
- };
40
- }
41
-
42
- export function parseWindowsProcs(text) {
43
- const trimmed = String(text ?? '').trim();
44
- if (!trimmed) return [];
45
- const raw = JSON.parse(trimmed);
46
- return (Array.isArray(raw) ? raw : [raw]).filter((p) => p && Number.isInteger(p.pid)).map(toProc);
47
- }
48
-
49
- export function parseEtime(etime) {
50
- const m = /^(?:(?:(\d+)-)?(\d+):)?(\d+):(\d+)$/.exec(String(etime).trim());
51
- if (!m) return null;
52
- const [, d = 0, h = 0, min, s] = m;
53
- return ((Number(d) * 24 + Number(h)) * 60 + Number(min)) * 60 + Number(s);
54
- }
55
-
56
- export function parsePosixProcs(text, now = Date.now()) {
57
- const procs = [];
58
- for (const line of String(text ?? '').split(/\r?\n/)) {
59
- const m = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(\d+)\s+(\S+)\s*(.*)$/.exec(line);
60
- if (!m) continue;
61
- const seconds = parseEtime(m[3]);
62
- procs.push(toProc({
63
- pid: Number(m[1]),
64
- ppid: Number(m[2]),
65
- name: m[5].split('/').pop(),
66
- cmd: m[6] || m[5],
67
- rss: Number(m[4]) * 1024,
68
- startedMs: seconds === null ? null : now - seconds * 1000,
69
- }));
70
- }
71
- return procs;
72
- }
73
-
74
- function fromFixture(path) {
75
- const raw = JSON.parse(readFileSync(path, 'utf8').replace(/^/, ''));
76
- return (Array.isArray(raw) ? raw : []).map(toProc);
77
- }
78
-
79
- function windowsScript(filter) {
80
- const query = filter ? `Get-CimInstance Win32_Process -Filter "${filter}"` : 'Get-CimInstance Win32_Process';
81
- return `${PS_PREFIX}${query} | ForEach-Object { ${PS_PROJECTION} } | ConvertTo-Json -Compress`;
82
- }
83
-
84
- const POSIX_COLUMNS = 'pid=,ppid=,etime=,rss=,comm=,args=';
85
-
86
- function runList({ pid = null, exec, platform, now }) {
87
- if (platform === 'win32') {
88
- const filter = pid === null ? '' : `ProcessId=${Number(pid)}`;
89
- const res = exec('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', windowsScript(filter)]);
90
- if (res.code !== 0) return { procs: null, reason: `PowerShell falhou (exit ${res.code})` };
91
- try {
92
- return { procs: parseWindowsProcs(res.output), reason: null };
93
- } catch {
94
- return { procs: null, reason: 'saída do PowerShell ilegível' };
95
- }
96
- }
97
- if (platform === 'linux' || platform === 'darwin') {
98
- const args = pid === null ? ['-eo', POSIX_COLUMNS] : ['-p', String(Number(pid)), '-o', POSIX_COLUMNS];
99
- const res = exec('ps', args);
100
- if (res.code !== 0 && pid === null) return { procs: null, reason: `ps falhou (exit ${res.code})` };
101
- return { procs: parsePosixProcs(res.output, now), reason: null };
102
- }
103
- return { procs: null, reason: `plataforma ${platform} sem listador de processos` };
104
- }
105
-
106
- export function listProcesses({ exec = defaultProcExec, platform = process.platform, now = Date.now(), env = process.env } = {}) {
107
- if (env.MORPH_PROCS_FIXTURE) {
108
- try {
109
- return { procs: fromFixture(env.MORPH_PROCS_FIXTURE), reason: null };
110
- } catch {
111
- return { procs: null, reason: 'MORPH_PROCS_FIXTURE ilegível' };
112
- }
113
- }
114
- return runList({ exec, platform, now });
115
- }
116
-
117
- export function readProcess(pid, { exec = defaultProcExec, platform = process.platform, now = Date.now(), env = process.env } = {}) {
118
- if (env.MORPH_PROCS_FIXTURE) {
119
- const { procs } = listProcesses({ env });
120
- return procs?.find((p) => p.pid === pid) ?? null;
121
- }
122
- const { procs } = runList({ pid, exec, platform, now });
123
- return procs?.find((p) => p.pid === pid) ?? null;
124
- }
@@ -1,47 +0,0 @@
1
- import { listProcesses, readProcess } from './list.js';
2
-
3
- export function descendantsOf(pid, procs) {
4
- const found = [];
5
- const queue = [pid];
6
- while (queue.length) {
7
- const parent = queue.shift();
8
- for (const child of procs.filter((p) => p.ppid === parent && !found.includes(p.pid))) {
9
- found.push(child.pid);
10
- queue.push(child.pid);
11
- }
12
- }
13
- return found;
14
- }
15
-
16
- export function stopTree(pid, { list = listProcesses, kill = (target) => process.kill(target) } = {}) {
17
- const { procs } = list();
18
- for (const target of [...descendantsOf(pid, procs ?? []).reverse(), pid]) {
19
- try {
20
- kill(target);
21
- } catch {}
22
- }
23
- }
24
-
25
- export function pruneOrphans(rows, { read = readProcess, kill = (pid) => process.kill(pid) } = {}) {
26
- const results = [];
27
- for (const row of rows) {
28
- if (row.verdict !== 'orphan') continue;
29
- const fresh = read(row.pid);
30
- const base = { pid: row.pid, name: row.name };
31
- if (!fresh) {
32
- results.push({ ...base, outcome: 'skipped', reason: 'já encerrado' });
33
- continue;
34
- }
35
- if (fresh.startedMs !== row.startedMs || fresh.cmd !== row.cmd || fresh.name !== row.name) {
36
- results.push({ ...base, outcome: 'skipped', reason: 'o PID foi reaproveitado por outro processo' });
37
- continue;
38
- }
39
- try {
40
- kill(row.pid);
41
- results.push({ ...base, outcome: 'killed' });
42
- } catch (err) {
43
- results.push({ ...base, outcome: 'failed', reason: err?.code ?? err?.message ?? 'erro desconhecido' });
44
- }
45
- }
46
- return results;
47
- }
@@ -1,70 +0,0 @@
1
- import { existsSync, readFileSync } from 'node:fs';
2
- import { join } from 'node:path';
3
- import { homedir, totalmem } from 'node:os';
4
-
5
- const GB = 1024 ** 3;
6
-
7
- export function parseWslConfig(text) {
8
- const sections = {};
9
- let current = null;
10
- for (const raw of String(text).replace(/^/, '').split(/\r?\n/)) {
11
- const line = raw.trim();
12
- if (!line || line.startsWith('#') || line.startsWith(';')) continue;
13
- const header = /^\[([^\]]+)\]$/.exec(line);
14
- if (header) {
15
- current = header[1].trim().toLowerCase();
16
- sections[current] ??= {};
17
- continue;
18
- }
19
- const eq = line.indexOf('=');
20
- if (eq < 0 || current === null) continue;
21
- sections[current][line.slice(0, eq).trim().toLowerCase()] = line.slice(eq + 1).trim();
22
- }
23
- return sections;
24
- }
25
-
26
- export function suggestedMemoryGb(totalMemBytes) {
27
- return Math.max(4, Math.floor((totalMemBytes / GB) * 0.4));
28
- }
29
-
30
- function suggestion({ memory, reclaim, totalMemBytes }) {
31
- const lines = [];
32
- if (!memory) lines.push('[wsl2]', `memory=${suggestedMemoryGb(totalMemBytes)}GB`);
33
- if (!reclaim) lines.push('[experimental]', 'autoMemoryReclaim=gradual');
34
- return lines.length ? lines.join('\n') : null;
35
- }
36
-
37
- export function inspectWslConfig({
38
- home = homedir(),
39
- platform = process.platform,
40
- totalMemBytes = totalmem(),
41
- exists = existsSync,
42
- read = (p) => readFileSync(p, 'utf8'),
43
- } = {}) {
44
- if (platform !== 'win32') return { status: 'skip', reason: 'WSL só existe no Windows' };
45
- const path = join(home, '.wslconfig');
46
- if (!exists(path)) {
47
- return {
48
- status: 'missing',
49
- path,
50
- memory: null,
51
- autoMemoryReclaim: null,
52
- suggestion: suggestion({ memory: null, reclaim: null, totalMemBytes }),
53
- };
54
- }
55
- let sections;
56
- try {
57
- sections = parseWslConfig(read(path));
58
- } catch {
59
- return { status: 'skip', reason: `${path} ilegível` };
60
- }
61
- const memory = sections.wsl2?.memory ?? null;
62
- const autoMemoryReclaim = sections.experimental?.automemoryreclaim ?? null;
63
- return {
64
- status: 'present',
65
- path,
66
- memory,
67
- autoMemoryReclaim,
68
- suggestion: suggestion({ memory, reclaim: autoMemoryReclaim, totalMemBytes }),
69
- };
70
- }
@@ -1,121 +0,0 @@
1
- // Paths under the system temp dir are never registered: test suites run `init`/`update` there by the
2
- // hundred, through spawned CLIs that keep the real home. The home is read at call time so isolating it works.
3
-
4
- import { existsSync, readFileSync, readdirSync } from 'fs';
5
- import { homedir, tmpdir } from 'os';
6
- import { join, resolve, basename, dirname } from 'path';
7
- import { atomicWriteJson } from '../../core/state/state-manager.js';
8
- import { canonicalPath, isInside } from '../tasks/test-runner.js';
9
- import { WORKTREE_DIR_NAMES } from '../worktree/dirs.js';
10
-
11
- export const REGISTRY_VERSION = 1;
12
-
13
- export function registryPath() {
14
- return process.env.MORPH_PROJECTS_REGISTRY || join(homedir(), '.morph-spec', 'projects.json');
15
- }
16
-
17
- /** One spelling per directory: canonical, forward slashes (the registry is read back on any OS). */
18
- export function projectKey(dir) {
19
- return canonicalPath(resolve(dir)).replace(/\\/g, '/');
20
- }
21
-
22
- const sameDir = (a, b) => (process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b);
23
-
24
- export function isMorphProject(dir) {
25
- return existsSync(join(dir, '.morph', 'config', 'config.json'));
26
- }
27
-
28
- /** A worktree checkout is part of its repo's project, never a project of its own. */
29
- function insideWorktreeContainer(dir) {
30
- if (WORKTREE_DIR_NAMES.includes(basename(dirname(dir)))) return true;
31
- try {
32
- return /[\\/]\.git[\\/]worktrees[\\/][^\\/]+\s*$/.test(readFileSync(join(dir, '.git'), 'utf8'));
33
- } catch {
34
- return false;
35
- }
36
- }
37
-
38
- function projectName(dir) {
39
- try {
40
- const config = JSON.parse(readFileSync(join(dir, '.morph', 'config', 'config.json'), 'utf8'));
41
- const name = config?.project?.name;
42
- // Some configs carry the project path as its name; the folder reads better.
43
- return typeof name === 'string' && name.trim() && !/[\\/]/.test(name) ? name.trim() : basename(dir);
44
- } catch {
45
- return basename(dir);
46
- }
47
- }
48
-
49
- /** Folders that were deleted or lost `.morph/` drop out on read. */
50
- export function readRegistry() {
51
- let data = null;
52
- try {
53
- const path = registryPath();
54
- if (existsSync(path)) data = JSON.parse(readFileSync(path, 'utf8'));
55
- } catch {}
56
- const projects = Array.isArray(data?.projects) ? data.projects : [];
57
- return {
58
- version: REGISTRY_VERSION,
59
- projects: projects.filter((p) => typeof p?.dir === 'string' && isMorphProject(p.dir)),
60
- };
61
- }
62
-
63
- function write(projects) {
64
- atomicWriteJson(registryPath(), { version: REGISTRY_VERSION, projects });
65
- }
66
-
67
- /** Idempotent, never throws; `tempRoot` is the test seam for the never-registered folder. */
68
- export function registerProject(dir, source, { tempRoot = tmpdir() } = {}) {
69
- try {
70
- const key = projectKey(dir);
71
- if (isInside(canonicalPath(key), canonicalPath(tempRoot))) return false;
72
- if (!isMorphProject(key) || insideWorktreeContainer(key)) return false;
73
- const now = new Date().toISOString();
74
- const { projects } = readRegistry();
75
- const found = projects.find((p) => sameDir(p.dir, key));
76
- if (found) {
77
- found.lastSeenAt = now;
78
- found.name = projectName(key);
79
- } else {
80
- projects.push({ dir: key, name: projectName(key), addedAt: now, lastSeenAt: now, source });
81
- }
82
- write(projects);
83
- return true;
84
- } catch {
85
- return false;
86
- }
87
- }
88
-
89
- /** Never throws; the project's files are not touched. */
90
- export function unregisterProject(dir) {
91
- try {
92
- const key = projectKey(dir);
93
- const { projects } = readRegistry();
94
- const kept = projects.filter((p) => !sameDir(p.dir, key));
95
- if (kept.length !== projects.length) write(kept);
96
- return kept.length !== projects.length;
97
- } catch {
98
- return false;
99
- }
100
- }
101
-
102
- /** Unregistered projects one level under each root: deeper would walk node_modules and worktrees. */
103
- export function discoverProjects(roots) {
104
- const registered = readRegistry().projects.map((p) => p.dir);
105
- const out = [];
106
- const seen = new Set();
107
- for (const root of roots) {
108
- let entries = [];
109
- try { entries = readdirSync(root, { withFileTypes: true }); } catch { continue; }
110
- for (const e of entries) {
111
- if (!e.isDirectory() || e.name.startsWith('.') || e.name === 'node_modules') continue;
112
- const dir = join(root, e.name);
113
- if (!isMorphProject(dir)) continue;
114
- const key = projectKey(dir);
115
- if (seen.has(key.toLowerCase()) || registered.some((r) => sameDir(r, key))) continue;
116
- seen.add(key.toLowerCase());
117
- out.push({ dir: key, name: projectName(key) });
118
- }
119
- }
120
- return out.sort((a, b) => a.name.localeCompare(b.name));
121
- }
@@ -1,36 +0,0 @@
1
- import { spawnSync } from 'child_process';
2
- import { existsSync, mkdtempSync, readFileSync, rmSync } from 'fs';
3
- import { homedir, tmpdir } from 'os';
4
- import { join } from 'path';
5
- import { findFirstOnPath } from '../../../framework/hooks/shared/morph-cli.js';
6
-
7
- export const PIPER_MODEL_DIR = join(homedir(), '.morph-spec', 'piper');
8
-
9
- /** The piper binary and a voice model, or why narration falls back to the system voice. */
10
- export function resolvePiper(env = process.env) {
11
- const bin = findFirstOnPath(process.platform === 'win32' ? ['piper.exe'] : ['piper'], env);
12
- if (!bin) return { ok: false, reason: 'piper fora do PATH (pip install piper-tts)' };
13
- const model = env.MORPH_PIPER_MODEL
14
- || [join(PIPER_MODEL_DIR, 'pt_BR-faber-medium.onnx')].find((m) => existsSync(m));
15
- if (!model || !existsSync(model)) {
16
- return { ok: false, reason: `sem modelo de voz: baixe pt_BR-faber-medium.onnx (+ .onnx.json) para ${PIPER_MODEL_DIR}, ou aponte MORPH_PIPER_MODEL` };
17
- }
18
- return { ok: true, bin, model };
19
- }
20
-
21
- /** `{ [sceneId]: dataUri }`, or null when piper fails on any scene: half-narrated is worse than the system voice. */
22
- export function narrateWithPiper(scenes, piper, { run = spawnSync } = {}) {
23
- const dir = mkdtempSync(join(tmpdir(), 'morph-recap-'));
24
- try {
25
- const audio = {};
26
- for (const s of scenes) {
27
- const out = join(dir, `${s.id}.wav`);
28
- const r = run(piper.bin, ['--model', piper.model, '--output_file', out], { input: s.narration, windowsHide: true, stdio: ['pipe', 'ignore', 'pipe'] });
29
- if (r.status !== 0 || !existsSync(out)) return null;
30
- audio[s.id] = `data:audio/wav;base64,${readFileSync(out).toString('base64')}`;
31
- }
32
- return audio;
33
- } finally {
34
- rmSync(dir, { recursive: true, force: true });
35
- }
36
- }