@polymorphism-tech/morph-spec 10.12.1 → 11.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (323) hide show
  1. package/CLAUDE.md +27 -57
  2. package/README.md +53 -338
  3. package/bin/morph-spec.js +22 -373
  4. package/docs/CHEATSHEET.md +37 -166
  5. package/docs/QUICKSTART.md +14 -74
  6. package/framework/CLAUDE.md +15 -26
  7. package/framework/MORPH.md +34 -101
  8. package/framework/agents.json +12 -9
  9. package/framework/commands/morph-apply.md +5 -5
  10. package/framework/commands/morph-infra.md +1 -1
  11. package/framework/docs/CLI.md +74 -886
  12. package/framework/evals/review-checklist.md +14 -14
  13. package/framework/hooks/README.md +21 -189
  14. package/framework/hooks/claude-code/core/README.md +2 -5
  15. package/framework/hooks/claude-code/core/conventional-commit.js +2 -2
  16. package/framework/hooks/claude-code/core/denylist.json +3 -3
  17. package/framework/hooks/claude-code/core/graph-refresh-kick.js +2 -2
  18. package/framework/hooks/claude-code/core/masked-exit.js +6 -6
  19. package/framework/hooks/claude-code/core/pre-bash-denylist.js +2 -2
  20. package/framework/hooks/claude-code/core/protect-spec-files.js +17 -61
  21. package/framework/hooks/claude-code/core/stack-changed.js +35 -0
  22. package/framework/hooks/claude-code/core/validate-completion.js +32 -87
  23. package/framework/hooks/shared/{heavy-command.js → command-kind.js} +6 -79
  24. package/framework/hooks/shared/command-tokens.js +0 -139
  25. package/framework/hooks/shared/contract.js +14 -0
  26. package/framework/hooks/shared/feature-slug.js +21 -0
  27. package/framework/hooks/shared/frontend-locations.js +0 -1
  28. package/framework/hooks/shared/git-paths.js +0 -15
  29. package/framework/hooks/shared/graph-freshness.js +0 -19
  30. package/framework/hooks/shared/hook-response.js +0 -7
  31. package/framework/hooks/shared/morph-cli.js +2 -81
  32. package/framework/hooks/shared/owner-words.js +2 -120
  33. package/framework/hooks/shared/payload-utils.js +0 -39
  34. package/framework/hooks/shared/report-progress.js +7 -101
  35. package/framework/hooks/statusline.js +16 -60
  36. package/framework/mcp/registry.json +2 -2
  37. package/framework/rules/ai-agents-standards.md +1 -1
  38. package/framework/rules/asaas-standards.md +1 -1
  39. package/framework/rules/ef-standards.md +1 -1
  40. package/framework/rules/gsap-standards.md +1 -1
  41. package/framework/rules/hangfire-standards.md +1 -1
  42. package/framework/rules/implement-report.md +3 -3
  43. package/framework/rules/neon-auth-standards.md +1 -1
  44. package/framework/rules/nextjs-standards.md +1 -1
  45. package/framework/rules/plan-grammar.md +15 -13
  46. package/framework/rules/resend-standards.md +1 -1
  47. package/framework/rules/ui-design.md +5 -1
  48. package/framework/schemas/config.schema.json +95 -310
  49. package/framework/skills/README.md +12 -32
  50. package/framework/skills/core/create-umbraco-lp/SKILL.md +1 -1
  51. package/framework/skills/core/migrate-lp-to-umbraco/SKILL.md +1 -1
  52. package/framework/skills/core/morph-apply/SKILL.md +21 -46
  53. package/framework/skills/core/morph-plan/SKILL.md +28 -63
  54. package/framework/skills/core/morph-uiux/SKILL.md +23 -25
  55. package/framework/{templates/docs/ui-mockups.md → skills/core/morph-uiux/references/mockups.md} +4 -4
  56. package/framework/standards/STANDARDS.json +10 -11
  57. package/framework/standards/STANDARDS.meta.json +1 -1
  58. package/framework/standards/ai-agents/evals-with-cache.md +18 -32
  59. package/framework/standards/ai-agents/observability-patterns.md +2 -2
  60. package/framework/standards/architecture/code-comments.md +2 -5
  61. package/framework/standards/architecture/engineering-lens.md +1 -1
  62. package/framework/standards/backend/dotnet/testing.md +4 -4
  63. package/framework/standards/frontend/nextjs/lint.md +24 -10
  64. package/framework/standards/frontend/nextjs/testing.md +2 -2
  65. package/framework/standards/infrastructure/docker/local-compose-isolation.md +14 -30
  66. package/framework/templates/CLAUDE.md.core.guide.md +2 -2
  67. package/framework/templates/README.md +1 -1
  68. package/framework/templates/REGISTRY.json +3 -33
  69. package/framework/templates/docs/plan.md +3 -2
  70. package/framework/templates/dotnet/ai-kit/README.md +2 -4
  71. package/framework/templates/dotnet/ai-kit/src/Morph.AiKit/Evals/EvalCacheMissException.cs +1 -1
  72. package/framework/templates/dotnet/ai-kit/src/Morph.AiKit/Evals/EvalFixture.cs +1 -1
  73. package/package.json +1 -2
  74. package/src/commands/graph/explain.js +2 -1
  75. package/src/commands/graph/status.js +2 -1
  76. package/src/commands/mcp/mcp-setup.js +1 -2
  77. package/src/commands/project/doctor.js +13 -342
  78. package/src/commands/project/env.js +21 -52
  79. package/src/commands/project/init-contract.js +47 -0
  80. package/src/commands/project/init.js +36 -66
  81. package/src/commands/project/stack-scan.js +1 -1
  82. package/src/commands/project/update.js +16 -53
  83. package/src/commands/validation/check.js +128 -0
  84. package/src/commands/validation/plan-check.js +41 -64
  85. package/src/commands/validation/prove-red.js +1 -1
  86. package/src/core/paths/output-schema.js +0 -22
  87. package/src/core/templates/template-renderer.js +0 -14
  88. package/src/lib/ai/ai-project-scan.js +1 -6
  89. package/src/lib/check/attempts.js +38 -0
  90. package/src/lib/check/signals.js +145 -0
  91. package/src/lib/config/project-config.js +13 -0
  92. package/src/lib/contract/apply.js +62 -0
  93. package/src/lib/contract/defaults.js +96 -0
  94. package/src/lib/contract/merge.js +79 -0
  95. package/src/lib/contract/ports.js +43 -0
  96. package/src/lib/contract/scan.js +102 -0
  97. package/src/lib/detectors/claude-config-detector.js +7 -0
  98. package/src/lib/{procs → detectors}/mcp-config.js +1 -37
  99. package/src/lib/diff/diff-lines.js +64 -0
  100. package/src/lib/generators/architecture-scanner.js +1 -1
  101. package/src/lib/generators/scaffold-generator.js +0 -7
  102. package/src/lib/git/default-branch.js +0 -122
  103. package/src/lib/graph/diff-tree.js +2 -1
  104. package/src/lib/graph/god-nodes.js +2 -1
  105. package/src/lib/graph/graphify-runtime.js +0 -1
  106. package/src/lib/graph/graphifyignore.js +1 -1
  107. package/src/lib/graph/sanitize.js +2 -8
  108. package/src/lib/installers/memory-installer.js +15 -30
  109. package/src/lib/installers/stack-sync.js +16 -9
  110. package/src/lib/plan/checks.js +20 -64
  111. package/src/lib/plan/media.js +1 -1
  112. package/src/lib/plan/plan-parser.js +5 -5
  113. package/src/lib/review-reports.js +3 -77
  114. package/src/lib/scan/worktree-dirs.js +3 -0
  115. package/src/lib/specs/adr-index.js +2 -2
  116. package/src/lib/stack/dotnet-build-ignores.js +10 -2
  117. package/src/lib/stack/stack-scan.js +2 -2
  118. package/src/lib/stack-filter.js +3 -2
  119. package/src/lib/tests-audit/audit.js +1 -1
  120. package/src/scripts/setup-infra.js +6 -59
  121. package/src/utils/agents-installer.js +13 -37
  122. package/src/utils/atomic-json.js +27 -0
  123. package/src/utils/file-copier.js +24 -24
  124. package/src/utils/hooks-installer.js +9 -107
  125. package/claude-plugin.json +0 -14
  126. package/framework/commands/morph-archive.md +0 -46
  127. package/framework/commands/morph-hotfix.md +0 -17
  128. package/framework/commands/morph-preflight.md +0 -180
  129. package/framework/commands/morph-review.md +0 -15
  130. package/framework/commands/morph-status.md +0 -37
  131. package/framework/hooks/claude-code/core/block-destructive-worktree-removal.js +0 -80
  132. package/framework/hooks/claude-code/core/block-raw-worktree-add.js +0 -72
  133. package/framework/hooks/claude-code/core/enforce-phase-writes.js +0 -100
  134. package/framework/hooks/claude-code/core/gate-guard.js +0 -148
  135. package/framework/hooks/claude-code/core/heavy-gate.js +0 -78
  136. package/framework/hooks/claude-code/core/heavy-release.js +0 -23
  137. package/framework/hooks/claude-code/core/loop-detect.js +0 -79
  138. package/framework/hooks/claude-code/core/state-sync.js +0 -214
  139. package/framework/hooks/claude-code/core/telemetry-log.js +0 -259
  140. package/framework/hooks/claude-code/core/test-budget.js +0 -29
  141. package/framework/hooks/claude-code/core/worktree-context.js +0 -249
  142. package/framework/hooks/claude-code/core/worktree-create.js +0 -119
  143. package/framework/hooks/claude-code/core/worktree-env-inject.js +0 -68
  144. package/framework/hooks/claude-code/core/worktree-remove.js +0 -55
  145. package/framework/hooks/shared/build-check.js +0 -120
  146. package/framework/hooks/shared/claim-registry.js +0 -125
  147. package/framework/hooks/shared/e2e-check.js +0 -1022
  148. package/framework/hooks/shared/feature-locator.js +0 -82
  149. package/framework/hooks/shared/gate-event.js +0 -18
  150. package/framework/hooks/shared/gate-question.js +0 -20
  151. package/framework/hooks/shared/heavy-config.js +0 -113
  152. package/framework/hooks/shared/heavy-holders.js +0 -85
  153. package/framework/hooks/shared/heavy-slots.js +0 -280
  154. package/framework/hooks/shared/host-services.js +0 -440
  155. package/framework/hooks/shared/next-step.js +0 -181
  156. package/framework/hooks/shared/redact-secrets.js +0 -44
  157. package/framework/hooks/shared/reparse-scan.js +0 -40
  158. package/framework/hooks/shared/state-reader.js +0 -220
  159. package/framework/hooks/shared/state-writer.js +0 -112
  160. package/framework/hooks/shared/telemetry-logger.js +0 -101
  161. package/framework/hooks/shared/transcript-usage.js +0 -58
  162. package/framework/hooks/shared/worktree-root.js +0 -71
  163. package/framework/phases.json +0 -92
  164. package/framework/schemas/feature.schema.json +0 -242
  165. package/framework/skills/core/morph-apply/references/hotfix.md +0 -46
  166. package/framework/skills/core/morph-apply/references/machine.md +0 -30
  167. package/framework/skills/core/morph-apply/references/review.md +0 -77
  168. package/framework/skills/core/morph-plan/references/critique.md +0 -51
  169. package/framework/skills/core/morph-plan/references/interview.md +0 -37
  170. package/framework/templates/state.template.json +0 -17
  171. package/src/commands/dashboard/dashboard.js +0 -74
  172. package/src/commands/e2e/e2e.js +0 -400
  173. package/src/commands/observability/cost.js +0 -283
  174. package/src/commands/project/branch.js +0 -129
  175. package/src/commands/project/claim.js +0 -132
  176. package/src/commands/project/doctor-procs.js +0 -162
  177. package/src/commands/project/fleet.js +0 -66
  178. package/src/commands/project/heavy.js +0 -81
  179. package/src/commands/project/install-plugin-cmd.js +0 -27
  180. package/src/commands/project/status.js +0 -61
  181. package/src/commands/project/worktree.js +0 -1234
  182. package/src/commands/state/advance.js +0 -248
  183. package/src/commands/state/approve.js +0 -303
  184. package/src/commands/state/archive.js +0 -231
  185. package/src/commands/state/auto-approval.js +0 -67
  186. package/src/commands/state/create.js +0 -274
  187. package/src/commands/state/delete.js +0 -192
  188. package/src/commands/state/finish.js +0 -1247
  189. package/src/commands/state/gate-check.js +0 -244
  190. package/src/commands/state/gate-decision.js +0 -122
  191. package/src/commands/state/list.js +0 -244
  192. package/src/commands/state/next.js +0 -24
  193. package/src/commands/state/recap.js +0 -80
  194. package/src/commands/state/report-check.js +0 -244
  195. package/src/commands/state/retype.js +0 -110
  196. package/src/commands/validation/verify.js +0 -421
  197. package/src/core/state/feature-identity.js +0 -10
  198. package/src/core/state/gate-order.js +0 -23
  199. package/src/core/state/lifecycle-audit.js +0 -171
  200. package/src/core/state/state-manager.js +0 -523
  201. package/src/core/templates/template-seed.js +0 -21
  202. package/src/core/work-types.js +0 -44
  203. package/src/dashboard/app/App.jsx +0 -84
  204. package/src/dashboard/app/components/ActivityFeed.jsx +0 -166
  205. package/src/dashboard/app/components/CommandPalette.jsx +0 -144
  206. package/src/dashboard/app/components/DetailPanel.jsx +0 -43
  207. package/src/dashboard/app/components/EntityLink.jsx +0 -42
  208. package/src/dashboard/app/components/ErrorBoundary.jsx +0 -47
  209. package/src/dashboard/app/components/FlowGraph.jsx +0 -19
  210. package/src/dashboard/app/components/GatePauses.jsx +0 -116
  211. package/src/dashboard/app/components/KnowledgeMarkdown.jsx +0 -42
  212. package/src/dashboard/app/components/Markdown.jsx +0 -38
  213. package/src/dashboard/app/components/PhaseRail.jsx +0 -100
  214. package/src/dashboard/app/components/SearchFilter.jsx +0 -36
  215. package/src/dashboard/app/components/SessionMap.jsx +0 -77
  216. package/src/dashboard/app/components/Sidebar.jsx +0 -147
  217. package/src/dashboard/app/hooks/useMorphQuery.js +0 -44
  218. package/src/dashboard/app/hooks/usePref.js +0 -34
  219. package/src/dashboard/app/lib/format.js +0 -69
  220. package/src/dashboard/app/lib/phases.js +0 -75
  221. package/src/dashboard/app/lib/project.js +0 -38
  222. package/src/dashboard/app/main.jsx +0 -13
  223. package/src/dashboard/app/pages/Activity.jsx +0 -28
  224. package/src/dashboard/app/pages/AgentMap.jsx +0 -363
  225. package/src/dashboard/app/pages/FeatureDetail.jsx +0 -579
  226. package/src/dashboard/app/pages/Features.jsx +0 -393
  227. package/src/dashboard/app/pages/Guide.jsx +0 -145
  228. package/src/dashboard/app/pages/HookInspector.jsx +0 -444
  229. package/src/dashboard/app/pages/PhasePipeline.jsx +0 -273
  230. package/src/dashboard/app/pages/Portfolio.jsx +0 -190
  231. package/src/dashboard/app/pages/RulesMap.jsx +0 -285
  232. package/src/dashboard/app/pages/SkillsLibrary.jsx +0 -468
  233. package/src/dashboard/app/pages/Standards.jsx +0 -392
  234. package/src/dashboard/app/styles/index.css +0 -187
  235. package/src/dashboard/index.html +0 -14
  236. package/src/dashboard/package.json +0 -32
  237. package/src/dashboard/scanner/activity-scanner.js +0 -321
  238. package/src/dashboard/scanner/agents-scanner.js +0 -67
  239. package/src/dashboard/scanner/docs-scanner.js +0 -34
  240. package/src/dashboard/scanner/feature-status.js +0 -7
  241. package/src/dashboard/scanner/features-scanner.js +0 -397
  242. package/src/dashboard/scanner/hooks-scanner.js +0 -96
  243. package/src/dashboard/scanner/index.js +0 -21
  244. package/src/dashboard/scanner/phases-scanner.js +0 -14
  245. package/src/dashboard/scanner/portfolio.js +0 -129
  246. package/src/dashboard/scanner/project-api.js +0 -160
  247. package/src/dashboard/scanner/rules-scanner.js +0 -46
  248. package/src/dashboard/scanner/skills-scanner.js +0 -104
  249. package/src/dashboard/scanner/standards-scanner.js +0 -38
  250. package/src/dashboard/vite-plugin-morph-data.js +0 -120
  251. package/src/dashboard/vite.config.js +0 -26
  252. package/src/lib/ci/ci-verify.js +0 -30
  253. package/src/lib/ci/github-ci.js +0 -52
  254. package/src/lib/ci/pr-checks.js +0 -76
  255. package/src/lib/e2e/applicability.js +0 -39
  256. package/src/lib/e2e/compose-env.js +0 -80
  257. package/src/lib/e2e/stack-teardown.js +0 -96
  258. package/src/lib/git/branch-classifier.js +0 -104
  259. package/src/lib/git/evidence-staleness.js +0 -40
  260. package/src/lib/git/gh.js +0 -15
  261. package/src/lib/git/pending-prs.js +0 -58
  262. package/src/lib/git/pr-files.js +0 -31
  263. package/src/lib/git/pr-index.js +0 -39
  264. package/src/lib/git/tree-fingerprint.js +0 -58
  265. package/src/lib/git/tree-state.js +0 -125
  266. package/src/lib/heavy/cleanup.js +0 -72
  267. package/src/lib/heavy/gate.js +0 -168
  268. package/src/lib/heavy/live-stacks.js +0 -64
  269. package/src/lib/heavy/reclaim.js +0 -107
  270. package/src/lib/heavy/watchdog.js +0 -46
  271. package/src/lib/next-step.js +0 -12
  272. package/src/lib/plan/critique.js +0 -67
  273. package/src/lib/plan/plan-template.js +0 -18
  274. package/src/lib/procs/classify.js +0 -91
  275. package/src/lib/procs/list.js +0 -124
  276. package/src/lib/procs/prune.js +0 -47
  277. package/src/lib/procs/wslconfig.js +0 -70
  278. package/src/lib/projects/registry.js +0 -121
  279. package/src/lib/recap/piper.js +0 -36
  280. package/src/lib/recap/recap.js +0 -259
  281. package/src/lib/review-confirmation.js +0 -66
  282. package/src/lib/risk/diff-risk.js +0 -137
  283. package/src/lib/risk-detector.js +0 -638
  284. package/src/lib/specs/design-seed.js +0 -18
  285. package/src/lib/specs/screen-checklist.js +0 -315
  286. package/src/lib/stack/stack-profile.js +0 -69
  287. package/src/lib/tasks/eval-node.js +0 -293
  288. package/src/lib/tasks/linux-runner.js +0 -200
  289. package/src/lib/tasks/test-nodes.js +0 -414
  290. package/src/lib/tasks/test-runner.js +0 -569
  291. package/src/lib/telemetry/metrics.js +0 -384
  292. package/src/lib/telemetry/telemetry-reader.js +0 -276
  293. package/src/lib/telemetry/verify-event.js +0 -57
  294. package/src/lib/validators/code-budget/code-budget-validator.js +0 -170
  295. package/src/lib/validators/contracts/contract-compliance-validator.js +0 -219
  296. package/src/lib/validators/nextjs/next-component-validator.js +0 -142
  297. package/src/lib/validators/packages/package-validator.js +0 -310
  298. package/src/lib/validators/reuse/reuse-validator.js +0 -202
  299. package/src/lib/validators/reuse/symbol-scanner.js +0 -64
  300. package/src/lib/validators/validation-runner.js +0 -188
  301. package/src/lib/validators/verify-cache.js +0 -63
  302. package/src/lib/validators/verify-runner.js +0 -971
  303. package/src/lib/verify/affected.js +0 -143
  304. package/src/lib/verify/detached.js +0 -159
  305. package/src/lib/view/feature-html.js +0 -480
  306. package/src/lib/view/feature-page.client.js +0 -109
  307. package/src/lib/view/feature-page.css +0 -278
  308. package/src/lib/view/feature-view.js +0 -113
  309. package/src/lib/view/flow-layers.js +0 -79
  310. package/src/lib/view/flow-svg.js +0 -63
  311. package/src/lib/view/tokens.css +0 -18
  312. package/src/lib/work-type-detector.js +0 -81
  313. package/src/lib/worktree/dirs.js +0 -3
  314. package/src/lib/worktree/docker-audit.js +0 -175
  315. package/src/lib/worktree/env-allocator.js +0 -177
  316. package/src/lib/worktree/feature-truth.js +0 -145
  317. package/src/lib/worktree/finish-backup.js +0 -529
  318. package/src/lib/worktree/fleet-scanner.js +0 -223
  319. package/src/lib/worktree/ignored-triage.js +0 -136
  320. package/src/lib/worktree/vscode-settings.js +0 -112
  321. package/src/lib/worktree/worktree-audit.js +0 -323
  322. package/src/lib/worktree/worktree-include.js +0 -44
  323. package/src/scripts/install-plugin.js +0 -114
@@ -1,125 +0,0 @@
1
- import { existsSync } from 'fs';
2
- import { join } from 'path';
3
- import { OUTSIDE_MORPH, treeFingerprint, git as gitBuffer } from './tree-fingerprint.js';
4
- import { detectDefaultBranch } from './default-branch.js';
5
- import { resolveBaseRef } from './branch-classifier.js';
6
-
7
- const MAX_LISTED = 50;
8
- const MAX_COMMITS = 10;
9
-
10
- function git(cwd, args, input) {
11
- return gitBuffer(cwd, args, input).toString();
12
- }
13
-
14
- function headSha(cwd) {
15
- try { return git(cwd, ['rev-parse', 'HEAD']).trim(); } catch { return null; }
16
- }
17
-
18
- function changedFiles(cwd) {
19
- return parsePorcelain(git(cwd, ['status', '--porcelain=v1', '-z', '--untracked-files=all', ...OUTSIDE_MORPH]))
20
- .map((e) => e.path);
21
- }
22
-
23
- function diskBlobs(cwd, paths) {
24
- const present = paths.filter((p) => existsSync(join(cwd, p)));
25
- const ids = present.length ? git(cwd, ['hash-object', '--stdin-paths'], present.join('\n')).split('\n') : [];
26
- const out = Object.fromEntries(paths.map((p) => [p, null]));
27
- present.forEach((p, i) => { out[p] = ids[i].trim(); });
28
- return out;
29
- }
30
-
31
- function commitBlobs(cwd, commit, paths) {
32
- const out = Object.fromEntries(paths.map((p) => [p, null]));
33
- if (!commit || !paths.length) return out;
34
- const lines = git(cwd, ['cat-file', '--batch-check=%(objectname)'], paths.map((p) => `${commit}:${p}`).join('\n')).split('\n');
35
- paths.forEach((p, i) => { out[p] = /^[0-9a-f]{40,64}$/.test(lines[i]?.trim()) ? lines[i].trim() : null; });
36
- return out;
37
- }
38
-
39
- /**
40
- * HEAD plus the blob of every file that differs from it, kept on disk so a resumed
41
- * session compares against the tree before the dispatch, not its own start.
42
- * @returns {{ at: string, head: string|null, files: Object<string, string|null> }|null}
43
- */
44
- export function snapshotTree(cwd) {
45
- try {
46
- return { at: new Date().toISOString(), head: headSha(cwd), files: diskBlobs(cwd, changedFiles(cwd)) };
47
- } catch {
48
- return null;
49
- }
50
- }
51
-
52
- /**
53
- * Compares content, not status: an edit committed since shows up, and a file
54
- * committed unchanged does not.
55
- * @returns {{ at: string, headChanged: boolean, changed: string[], changedCount: number }}
56
- */
57
- export function compareToSnapshot(cwd, snapshot) {
58
- const head = headSha(cwd);
59
- const candidates = new Set([...Object.keys(snapshot.files || {}), ...changedFiles(cwd)]);
60
- if (snapshot.head && head && snapshot.head !== head) {
61
- for (const p of git(cwd, ['diff', '--name-only', '-z', snapshot.head, head, ...OUTSIDE_MORPH]).split('\0')) {
62
- if (p) candidates.add(p);
63
- }
64
- }
65
- const paths = [...candidates];
66
- const now = diskBlobs(cwd, paths);
67
- const unlisted = paths.filter((p) => !(p in (snapshot.files || {})));
68
- const before = { ...commitBlobs(cwd, snapshot.head, unlisted), ...snapshot.files };
69
- const changed = paths.filter((p) => before[p] !== now[p]).sort();
70
- return { at: snapshot.at, headChanged: snapshot.head !== head, changed: changed.slice(0, MAX_LISTED), changedCount: changed.length };
71
- }
72
-
73
- // With `-z`, a rename or copy carries its old path as an extra entry.
74
- function parsePorcelain(out) {
75
- const entries = [];
76
- const parts = out.split('\0');
77
- for (let i = 0; i < parts.length; i++) {
78
- const item = parts[i];
79
- if (!item) continue;
80
- const status = item.slice(0, 2);
81
- entries.push({ status: status.trim(), path: item.slice(3) });
82
- if (status[0] === 'R' || status[0] === 'C') i++;
83
- }
84
- return entries;
85
- }
86
-
87
- function diffstat(cwd) {
88
- const stat = { files: 0, insertions: 0, deletions: 0 };
89
- for (const line of git(cwd, ['diff', 'HEAD', '--numstat', ...OUTSIDE_MORPH]).split('\n')) {
90
- const [ins, del] = line.split('\t');
91
- if (del === undefined) continue;
92
- stat.files += 1;
93
- stat.insertions += Number(ins) || 0;
94
- stat.deletions += Number(del) || 0;
95
- }
96
- return stat;
97
- }
98
-
99
- function commitsOnTop(cwd) {
100
- const base = resolveBaseRef(detectDefaultBranch(cwd), cwd);
101
- if (!base) return null;
102
- return git(cwd, ['log', `--max-count=${MAX_COMMITS}`, '--format=%h %s', `${base}..HEAD`])
103
- .split('\n').filter(Boolean);
104
- }
105
-
106
- /** @returns {object|null} null when git cannot answer: unknown, never a clean tree. */
107
- export function treeState(cwd, { snapshot = null } = {}) {
108
- try {
109
- const dirty = parsePorcelain(git(cwd, ['status', '--porcelain=v1', '-z', ...OUTSIDE_MORPH]));
110
- let head = null;
111
- try { head = git(cwd, ['rev-parse', '--short', 'HEAD']).trim(); } catch { /* no commit yet */ }
112
- return {
113
- head,
114
- branch: head ? git(cwd, ['rev-parse', '--abbrev-ref', 'HEAD']).trim() : null,
115
- fingerprint: treeFingerprint(cwd),
116
- dirty: dirty.slice(0, MAX_LISTED),
117
- dirtyCount: dirty.length,
118
- diffstat: head ? diffstat(cwd) : null,
119
- commits: head ? commitsOnTop(cwd) : null,
120
- sinceBeforeEval: snapshot ? compareToSnapshot(cwd, snapshot) : null,
121
- };
122
- } catch {
123
- return null;
124
- }
125
- }
@@ -1,72 +0,0 @@
1
- import { readdirSync } from 'node:fs';
2
- import { freemem } from 'node:os';
3
- import { getBuildSteps } from '../../../framework/hooks/shared/build-check.js';
4
- import { listProcesses, defaultProcExec } from '../procs/list.js';
5
- import { readProjectConfig } from '../../../framework/hooks/shared/heavy-config.js';
6
- import { heavyDir, runExclusive } from '../../../framework/hooks/shared/heavy-slots.js';
7
-
8
- const DOTNET_ACTIVE = /\bdotnet(?:\.exe)?["']?\s+(?:build|test|publish|pack|msbuild|restore|run|watch|vstest)\b/i;
9
- const IDLE_WORKER = /\/nodemode:\d|vbcscompiler|razorserver/i;
10
- const SHUTDOWN_TIMEOUT_MS = 30_000;
11
- const TAIL_CHARS = 400;
12
- const GB = 1024 ** 3;
13
-
14
- function hasDotnet(projectPath) {
15
- const config = readProjectConfig(projectPath);
16
- const stack = config?.project?.stack;
17
- try {
18
- if (stack && getBuildSteps(stack, { cwd: projectPath }).some((s) => /\bdotnet\b/.test(s.command))) return true;
19
- } catch {}
20
- try {
21
- return readdirSync(projectPath).some((n) => /\.(sln|slnx|csproj)$/i.test(n));
22
- } catch {
23
- return false;
24
- }
25
- }
26
-
27
- export function dotnetBusy(procs) {
28
- return procs.some((p) => {
29
- if (p.name === 'testhost') return true;
30
- const cmd = p.cmd ?? '';
31
- if (p.name === 'vbcscompiler' || IDLE_WORKER.test(cmd)) return false;
32
- if (p.name === 'msbuild') return true;
33
- return p.name === 'dotnet' && DOTNET_ACTIVE.test(cmd);
34
- });
35
- }
36
-
37
- export function afterHeavyRun({ projectPath, config, env = process.env, onlyUnderPressure = false, deps = {} }) {
38
- const {
39
- exec = defaultProcExec, list = listProcesses, dotnet = hasDotnet, exclusive = runExclusive, freeMem = freemem,
40
- } = deps;
41
-
42
- if (!config.enabled) return { status: 'skipped', reason: 'semáforo desligado: sem ele nada prova que outra sessão não está compilando' };
43
- if (!config.shutdownBuildServer) return { status: 'skipped', reason: 'desligado em heavy.shutdownBuildServer' };
44
- if (!dotnet(projectPath)) return { status: 'skipped', reason: 'projeto sem .NET' };
45
- // A warm compiler is what makes the next round short; twice the floor keeps the next queue open.
46
- if (onlyUnderPressure && freeMem() / GB >= config.minFreeMemGb * 2) {
47
- return { status: 'skipped', reason: 'RAM livre de sobra: o compilador fica quente para a próxima rodada' };
48
- }
49
-
50
- const guarded = exclusive({
51
- dir: heavyDir(env), label: 'build-server-shutdown', maxHoldMs: config.maxHoldMinutes * 60_000, env,
52
- }, () => {
53
- const listing = list();
54
- if (listing.procs === null) return { status: 'skipped', reason: `não consegui listar processos (${listing.reason})` };
55
- if (dotnetBusy(listing.procs)) return { status: 'skipped', reason: 'há dotnet build/test vivo fora do semáforo' };
56
-
57
- const res = exec('dotnet', ['build-server', 'shutdown'], { timeout: SHUTDOWN_TIMEOUT_MS });
58
- if (res.missing) return { status: 'skipped', reason: 'dotnet indisponível no PATH' };
59
- if (res.code !== 0) {
60
- return { status: 'failed', reason: `dotnet build-server shutdown saiu ${res.code}`, output: String(res.output ?? '').slice(-TAIL_CHARS) };
61
- }
62
- return { status: 'ran' };
63
- });
64
-
65
- if (!guarded.ran) {
66
- const why = guarded.reason === 'holders'
67
- ? 'outra sessão segura slot do semáforo pesado'
68
- : `semáforo indisponível (${guarded.reason})`;
69
- return { status: 'skipped', reason: why };
70
- }
71
- return guarded.result;
72
- }
@@ -1,168 +0,0 @@
1
- import { freemem } from 'node:os';
2
- import { CPU_SHARE_ENVS, cpuShareOf, minFreeMemFor, readHeavyConfig } from '../../../framework/hooks/shared/heavy-config.js';
3
- import { heavyClass } from '../../../framework/hooks/shared/heavy-command.js';
4
- import { GB, readHolders } from '../../../framework/hooks/shared/heavy-holders.js';
5
- import { pidAlive } from '../../../framework/hooks/shared/process-alive.js';
6
- import {
7
- acquireHeavy, awaitFreeMemory, describeBusy, enterVerifySuite, heavyDir, isVerifySuite, releaseHeavy, updateLease,
8
- } from '../../../framework/hooks/shared/heavy-slots.js';
9
- import { reclaimUnlessDisabled } from './reclaim.js';
10
-
11
- export class HeavyBusyError extends Error {
12
- constructor(result, config) {
13
- super(HeavyBusyError.message(result, config));
14
- this.name = 'HeavyBusyError';
15
- this.code = 'heavy-busy';
16
- this.reason = result.reason;
17
- this.holders = result.holders;
18
- this.freeGb = result.freeGb;
19
- this.minFreeMemGb = result.minFreeMemGb ?? null;
20
- this.kind = result.kind ?? null;
21
- this.waitedMs = result.waitedMs;
22
- }
23
-
24
- static message(result, config) {
25
- return describeBusy(result, config);
26
- }
27
- }
28
-
29
- const NODE_REUSE_ENV = 'MSBUILDDISABLENODEREUSE';
30
- const LEASE_ENV = 'MORPH_HEAVY_LEASE';
31
-
32
- export function createHeavyGate({
33
- projectPath, label = 'verify', feature = null, config = readHeavyConfig(projectPath),
34
- env = process.env, deps = {}, log = (m) => process.stderr.write(`${m}\n`),
35
- } = {}) {
36
- let entered = false;
37
- let lease = null;
38
- let admittedGb = 0;
39
- let waitedMs = 0;
40
- let suiteEntered = false;
41
- let exitHandler = null;
42
- let saved = null;
43
- let reclaimed = false;
44
- let cpuShare = null;
45
- const politeRun = config.enabled && config.yieldToUser;
46
-
47
- // Judged at each node: a run alone takes nearly the machine, and steps back once another one is in.
48
- const applyCpuShare = () => {
49
- if (!politeRun) return;
50
- const { holders = readHolders } = deps;
51
- const live = holders(heavyDir(env), { now: Date.now, isAlive: pidAlive, maxHoldMs: config.maxHoldMinutes * 60_000 });
52
- cpuShare = cpuShareOf(config.slots, { alone: !live.some((h) => h.pid !== process.pid) });
53
- for (const name of CPU_SHARE_ENVS) env[name] = String(cpuShare);
54
- };
55
-
56
- const reclaimBelow = (floor) => {
57
- const { freeMem = freemem, reclaim = reclaimUnlessDisabled } = deps;
58
- if (reclaimed || !config.reclaimIdleMinutes || freeMem() / GB >= floor) return;
59
- reclaimed = true;
60
- try {
61
- const { freed, containers = [] } = reclaim({ projectPath, feature, config, env });
62
- const gone = [...freed, ...containers];
63
- if (gone.length) log(`heavy: RAM abaixo do piso, derrubei stacks paradas: ${gone.join(', ')}`);
64
- } catch {}
65
- };
66
-
67
- const restoreEnv = () => {
68
- if (!saved) return;
69
- for (const [key, value] of Object.entries(saved)) {
70
- if (value === undefined) delete env[key];
71
- else env[key] = value;
72
- }
73
- saved = null;
74
- };
75
-
76
- const release = () => {
77
- if (exitHandler) process.removeListener('exit', exitHandler);
78
- exitHandler = null;
79
- releaseHeavy(lease);
80
- lease = null;
81
- restoreEnv();
82
- entered = false;
83
- suiteEntered = false;
84
- };
85
-
86
- const raiseFloor = (kind) => {
87
- const floor = minFreeMemFor(config, kind);
88
- if (!lease || floor <= admittedGb) return;
89
- reclaimBelow(floor);
90
- const result = awaitFreeMemory({
91
- minFreeMemGb: floor, waitTimeoutMs: config.waitTimeoutSec * 1000, kind, log, ...deps,
92
- });
93
- if (result.status === 'busy') throw new HeavyBusyError(result, config);
94
- waitedMs += result.waitedMs;
95
- admittedGb = floor;
96
- };
97
-
98
- const awaitSuite = () => {
99
- const result = enterVerifySuite({
100
- dir: heavyDir(env),
101
- lease,
102
- slots: config.slots,
103
- waitTimeoutMs: config.waitTimeoutSec * 1000,
104
- maxHoldMs: config.maxHoldMinutes * 60_000,
105
- log,
106
- ...deps,
107
- });
108
- if (result.status === 'busy') throw new HeavyBusyError(result, config);
109
- waitedMs += result.waitedMs;
110
- suiteEntered = true;
111
- };
112
-
113
- return {
114
- config,
115
- get waitedMs() { return waitedMs; },
116
- get cpuShare() { return cpuShare; },
117
-
118
- enter(node, kind = heavyClass(node)) {
119
- const suite = isVerifySuite({ label, node });
120
- if (entered) {
121
- if (suite && lease && !suiteEntered) awaitSuite();
122
- raiseFloor(kind);
123
- updateLease(lease, { node });
124
- applyCpuShare();
125
- return;
126
- }
127
- for (const warning of config.warnings ?? []) log(`heavy: ${warning}`);
128
-
129
- if (config.enabled) {
130
- const minFreeMemGb = minFreeMemFor(config, kind);
131
- reclaimBelow(minFreeMemGb);
132
- const result = acquireHeavy({
133
- dir: heavyDir(env),
134
- slots: config.slots,
135
- label,
136
- feature,
137
- node,
138
- kind,
139
- suite,
140
- cwd: projectPath,
141
- minFreeMemGb,
142
- waitTimeoutMs: config.waitTimeoutSec * 1000,
143
- maxHoldMs: config.maxHoldMinutes * 60_000,
144
- env,
145
- log,
146
- ...deps,
147
- });
148
- if (result.status === 'busy') throw new HeavyBusyError(result, config);
149
- lease = result.lease;
150
- suiteEntered = suite;
151
- admittedGb = minFreeMemGb;
152
- waitedMs = result.waitedMs;
153
- }
154
-
155
- saved = Object.fromEntries([NODE_REUSE_ENV, LEASE_ENV, ...CPU_SHARE_ENVS].map((name) => [name, env[name]]));
156
- if (config.disableNodeReuse) env[NODE_REUSE_ENV] = '1';
157
- applyCpuShare();
158
- if (lease) env[LEASE_ENV] = String(process.pid);
159
- entered = true;
160
- if (lease) {
161
- exitHandler = release;
162
- process.once('exit', exitHandler);
163
- }
164
- },
165
-
166
- release,
167
- };
168
- }
@@ -1,64 +0,0 @@
1
- import { readdirSync } from 'node:fs';
2
- import { basename, dirname, join } from 'node:path';
3
- import { composeProjectName, defaultExec } from '../../../framework/hooks/shared/e2e-check.js';
4
- import {
5
- MORPH_PROJECT_PREFIX, parseDockerJson, resolveGitCommonDir, stackBelongsTo,
6
- } from '../worktree/docker-audit.js';
7
-
8
- // Runs right after a full queue wait: a hung daemon must not add another one.
9
- const LS_TIMEOUT_MS = 10_000;
10
-
11
- // Stacks of every worktree live under the main checkout, and so does `.morph/archive`.
12
- export function repoMainRoot(cwd) {
13
- const common = resolveGitCommonDir(cwd);
14
- return common && basename(common) === '.git' ? dirname(common) : cwd;
15
- }
16
-
17
- function dirNames(dir) {
18
- try {
19
- return readdirSync(dir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name);
20
- } catch {
21
- return [];
22
- }
23
- }
24
-
25
- export function liveE2eStacks(cwd, { exec = defaultExec, root = repoMainRoot(cwd) } = {}) {
26
- try {
27
- const ls = exec('docker', ['compose', 'ls', '--format', 'json'], { cwd: root, timeout: LS_TIMEOUT_MS });
28
- if (ls.code !== 0) return [];
29
- const projects = parseDockerJson(ls.output);
30
- if (!projects) return [];
31
-
32
- const active = dirNames(join(root, '.morph', 'features'));
33
- const owners = new Map(active.map((f) => [composeProjectName(f), { feature: f, state: 'active' }]));
34
- for (const f of dirNames(join(root, '.morph', 'archive'))) {
35
- const project = composeProjectName(f);
36
- if (!owners.has(project)) owners.set(project, { feature: f, state: 'archived' });
37
- }
38
-
39
- return projects
40
- .filter((p) => String(p?.Name ?? '').startsWith(MORPH_PROJECT_PREFIX) && stackBelongsTo(p, root))
41
- .map((p) => {
42
- const project = String(p.Name);
43
- return { project, status: p.Status ?? null, ...(owners.get(project) ?? { feature: null, state: 'unknown' }) };
44
- });
45
- } catch {
46
- return [];
47
- }
48
- }
49
-
50
- function stackLine(s) {
51
- if (s.state === 'archived') return ` • ${s.project}: feature ${s.feature} já arquivada — \`morph-spec e2e down ${s.feature}\` devolve a RAM`;
52
- if (s.state === 'unknown') return ` • ${s.project}: nenhuma feature deste repo responde por ela — \`docker compose -p ${s.project} down\``;
53
- return ` • ${s.project}: feature ${s.feature} em andamento`;
54
- }
55
-
56
- export function describeLiveStacks(stacks) {
57
- if (!stacks.length) return '';
58
- return `stacks e2e de pé neste repo (seguram RAM):\n${stacks.map(stackLine).join('\n')}`;
59
- }
60
-
61
- export function memoryBusyHint(err, cwd, deps = {}) {
62
- if (err?.reason !== 'memory') return '';
63
- return describeLiveStacks(liveE2eStacks(cwd, deps));
64
- }
@@ -1,107 +0,0 @@
1
- import { statSync } from 'node:fs';
2
- import { join } from 'node:path';
3
- import { defaultExec } from '../../../framework/hooks/shared/e2e-check.js';
4
- import { heavyDir, readHolders } from '../../../framework/hooks/shared/heavy-holders.js';
5
- import { pidAlive } from '../../../framework/hooks/shared/process-alive.js';
6
- import { EVENTS_FILE } from '../../../framework/hooks/shared/telemetry-logger.js';
7
- import { tearDownFeatureStack } from '../e2e/stack-teardown.js';
8
- import { projectKey, readRegistry } from '../projects/registry.js';
9
- import { resolveFeatureTree } from '../worktree/feature-truth.js';
10
- import { afterHeavyRun } from './cleanup.js';
11
- import { liveE2eStacks, repoMainRoot } from './live-stacks.js';
12
-
13
- const DOCKER_TIMEOUT_MS = 10_000;
14
-
15
- function lastActivityMs(tree) {
16
- try {
17
- return statSync(join(tree, EVENTS_FILE)).mtimeMs;
18
- } catch {
19
- return null;
20
- }
21
- }
22
-
23
- function liveHolders(config, env, now) {
24
- return readHolders(heavyDir(env), { now, isAlive: pidAlive, maxHoldMs: config.maxHoldMinutes * 60_000 });
25
- }
26
-
27
- function registeredRoots() {
28
- try {
29
- return readRegistry().projects.map((p) => p.dir);
30
- } catch {
31
- return [];
32
- }
33
- }
34
-
35
- const uniqueRoots = (roots) => [...new Map(roots.map((r) => [projectKey(r), r])).values()];
36
-
37
- // One daemon answers for every project: asking it once per project would add a hung timeout each.
38
- function onceByArgs(exec) {
39
- const seen = new Map();
40
- return (file, args, opts) => {
41
- const key = args.join(' ');
42
- if (!seen.has(key)) seen.set(key, exec(file, args, opts));
43
- return seen.get(key);
44
- };
45
- }
46
-
47
- function reclaimStacks({ root, feature, held, idleMs, now, stacks, treeOf, activityOf, tearDown, exec }) {
48
- const freed = [];
49
- for (const stack of stacks(root, { exec })) {
50
- if (!stack.feature || stack.state === 'unknown' || stack.feature === feature || held.has(stack.feature)) continue;
51
- const archived = stack.state === 'archived';
52
- // A feature without a worktree lives in the root that listed it.
53
- const tree = archived ? null : treeOf(stack.feature, root) ?? root;
54
- if (!archived) {
55
- // Unknown activity counts as live: another session's verifier may be navigating this stack.
56
- const last = activityOf(tree);
57
- if (last === null || now() - last < idleMs) continue;
58
- }
59
- // An active feature keeps its data: the next `e2e up` only rebuilds.
60
- const result = tearDown(stack.feature, { root, worktreePath: tree, volumes: archived });
61
- if (result?.status !== 'fail') freed.push(stack.feature);
62
- }
63
- return freed;
64
- }
65
-
66
- function reclaimContainers(prefixes, exec) {
67
- const removed = [];
68
- for (const prefix of prefixes) {
69
- const ps = exec('docker', ['ps', '-a', '--filter', `name=^${prefix}`, '--format', '{{.Names}}'], { timeout: DOCKER_TIMEOUT_MS });
70
- if (ps.code !== 0) continue;
71
- for (const name of String(ps.output ?? '').split(/\r?\n/).map((n) => n.trim()).filter(Boolean)) {
72
- if (exec('docker', ['rm', '-f', name], { timeout: DOCKER_TIMEOUT_MS }).code === 0) removed.push(name);
73
- }
74
- }
75
- return removed;
76
- }
77
-
78
- /** The entry every real caller uses: a test suite faking low RAM must never reach this machine's stacks. */
79
- export function reclaimUnlessDisabled(options) {
80
- if (process.env.MORPH_HEAVY_RECLAIM === 'off') return { freed: [], containers: [] };
81
- return reclaimMemory(options);
82
- }
83
-
84
- export function reclaimMemory({ projectPath, feature = null, config, env = process.env, deps = {} }) {
85
- const {
86
- stacks = liveE2eStacks, tearDown = tearDownFeatureStack, treeOf = (f, root) => resolveFeatureTree(f, root).tree,
87
- activityOf = lastActivityMs, holders = liveHolders, buildServer = afterHeavyRun, now = Date.now,
88
- roots = registeredRoots, exec = defaultExec,
89
- } = deps;
90
- if (!config.reclaimIdleMinutes) return { freed: [], containers: [] };
91
-
92
- const cachedExec = onceByArgs(exec);
93
- const live = holders(config, env, now);
94
- const held = new Set(live.map((h) => h.feature).filter(Boolean));
95
- const idleMs = config.reclaimIdleMinutes * 60_000;
96
-
97
- const freed = uniqueRoots([repoMainRoot(projectPath), ...roots()]).flatMap((root) => reclaimStacks({
98
- root, feature, held, idleMs, now, stacks, treeOf, activityOf, tearDown, exec: cachedExec,
99
- }));
100
-
101
- // A test container has no owner to ask: any holder that may be testing protects them all.
102
- const testing = live.some((h) => h.node === 'tests' || !h.node);
103
- const containers = testing ? [] : reclaimContainers(config.reclaimContainers, exec);
104
-
105
- buildServer({ projectPath, config, env, onlyUnderPressure: true });
106
- return { freed, containers };
107
- }
@@ -1,46 +0,0 @@
1
- import { appendFileSync, existsSync, writeFileSync } from 'node:fs';
2
- import { freemem } from 'node:os';
3
- import { setTimeout as sleep } from 'node:timers/promises';
4
- import { GB } from '../../../framework/hooks/shared/heavy-holders.js';
5
- import { pidAlive } from '../../../framework/hooks/shared/process-alive.js';
6
- import { stopTree } from '../procs/prune.js';
7
- import { reclaimUnlessDisabled } from './reclaim.js';
8
-
9
- const SAMPLE_MS = 10_000;
10
- const LOW_SAMPLES_TO_STOP = 6;
11
- const EXIT_BUSY = '3';
12
-
13
- /** The floor judges only the start of a node; this judges the middle of one. It only ever stops its own run. */
14
- export async function watchRun({
15
- workerPid, exitFile, errFile, projectPath, feature, config, env = process.env, deps = {},
16
- }) {
17
- const {
18
- freeMem = freemem, isAlive = pidAlive, wait = sleep, sampleMs = SAMPLE_MS, reclaim = reclaimUnlessDisabled,
19
- list, kill,
20
- } = deps;
21
- if (!config.criticalFreeMemGb) return 'off';
22
-
23
- let low = 0;
24
- while (isAlive(workerPid) && !existsSync(exitFile)) {
25
- const freeGb = freeMem() / GB;
26
- if (freeGb >= config.criticalFreeMemGb) {
27
- low = 0;
28
- } else {
29
- low += 1;
30
- if (low === 1) {
31
- try {
32
- reclaim({ projectPath, feature, config, env });
33
- } catch {}
34
- }
35
- if (low >= LOW_SAMPLES_TO_STOP) {
36
- if (existsSync(exitFile)) return 'finished';
37
- stopTree(workerPid, { list, kill });
38
- appendFileSync(errFile, `verify parado: ${freeGb.toFixed(1)} GB livres, abaixo de heavy.criticalFreeMemGb (${config.criticalFreeMemGb}) por ${LOW_SAMPLES_TO_STOP} leituras. Não é vermelho.\n`);
39
- writeFileSync(exitFile, EXIT_BUSY);
40
- return 'stopped';
41
- }
42
- }
43
- await wait(sampleMs);
44
- }
45
- return 'finished';
46
- }
@@ -1,12 +0,0 @@
1
- import { collectNextSignals, decideNext, retratoOf } from '../../framework/hooks/shared/next-step.js';
2
- import { treeMovedSince } from './git/evidence-staleness.js';
3
-
4
- /** The CLI collector: the hook-readable facts plus verify staleness (git). Null without feature.json. */
5
- export function nextStepFor(featureName, tree) {
6
- const signals = collectNextSignals(featureName, tree);
7
- if (!signals) return null;
8
- signals.verificationStale = treeMovedSince(tree, signals.verification?.sha);
9
- signals.affectedStale = treeMovedSince(tree, signals.affected?.sha);
10
- const next = decideNext(signals);
11
- return { ...next, phase: signals.phase, failStreak: signals.failStreak, retrato: retratoOf(signals, next) };
12
- }
@@ -1,67 +0,0 @@
1
- import { existsSync, readFileSync } from 'fs';
2
- import { getAbsoluteOutputPath } from '../../core/paths/output-schema.js';
3
- import { featureGeneratesMedia } from './media.js';
4
- import { SENSITIVE_LINE } from '../risk/diff-risk.js';
5
- import { RUNG_SAY, scenarioLabel } from '../../../framework/hooks/shared/owner-words.js';
6
-
7
- export const CRITIQUE_EXEMPT_WORK_TYPES = ['chore', 'hotfix'];
8
-
9
- const SMALL_PLAN_MAX_CHECKS = 3;
10
- const SMALL_PLAN_PROOFS = ['teste', 'leitura'];
11
-
12
- /** A plan this size has little for a fresh reader to catch; a rung or a proof outside the code does. */
13
- export function isSmallPlan(checks, planText = '') {
14
- const scenarios = checks?.checks ?? [];
15
- return scenarios.length > 0
16
- && scenarios.length <= SMALL_PLAN_MAX_CHECKS
17
- && scenarios.every((scenario) => SMALL_PLAN_PROOFS.includes(scenario.proof) && !scenario.rung)
18
- && !featureGeneratesMedia(planText);
19
- }
20
-
21
- /**
22
- * Who writes `critica.md`. By default the session, with the grep checklist of morph-plan
23
- * (references/critique.md): the premises it catches are what a grep confirms. A rung, generated
24
- * media or a sensitive theme (PII, permission, sending to a third party, payment) asks for the
25
- * fresh-context agent, whose blind spot is not the planner's.
26
- */
27
- export function critiqueByAgent(checks, planText = '') {
28
- const reasons = [];
29
- const rungs = (checks?.checks ?? []).filter((c) => c.rung)
30
- .map((c) => `${scenarioLabel(c)} ${RUNG_SAY[c.rung] ?? c.rung}`);
31
- reasons.push(...rungs);
32
- if (featureGeneratesMedia(planText)) reasons.push('a feature gera imagem, áudio ou vídeo');
33
- const sensitive = String(planText).split(/\r?\n/).find((line) => SENSITIVE_LINE.test(line));
34
- if (sensitive) reasons.push(`assunto sensível: ${sensitive.trim().replace(/^[-*\d.\s]+/, '').slice(0, 80)}`);
35
- return { agent: reasons.length > 0, reasons };
36
- }
37
-
38
- const PLAN_HASH_RE = /^\*\*Plan-Hash:\*\*\s*`?([0-9a-f]{64})`?\s*$/m;
39
- const APPLIED_RE = /^\*\*Aplicado-em:\*\*\s*`?([0-9a-f]{64})`?\s*$/gm;
40
-
41
- // A critique counts for the plan it read or for the plan the session wrote after applying it:
42
- // otherwise every fix it asks for would demand a new critique.
43
- export function critiqueStatus(text, currentHash) {
44
- if (typeof text !== 'string') return 'missing';
45
- const read = PLAN_HASH_RE.exec(text)?.[1];
46
- if (!read) return 'no-hash';
47
- const applied = [...text.matchAll(APPLIED_RE)].map((m) => m[1]);
48
- const valid = applied.length ? applied[applied.length - 1] : read;
49
- return currentHash === read || currentHash === valid ? 'fresh' : 'stale';
50
- }
51
-
52
- export function readPlanCritique(cwd, featureName, { workType, planChecks }) {
53
- if (CRITIQUE_EXEMPT_WORK_TYPES.includes(workType)) return 'exempt';
54
- const currentHash = planChecks?.status === 'fresh' ? planChecks.checks?.planHash : null;
55
- if (!currentHash) return null;
56
- if (isSmallPlan(planChecks.checks, readText(getAbsoluteOutputPath(cwd, featureName, 'plan')) ?? '')) return 'exempt';
57
- const path = getAbsoluteOutputPath(cwd, featureName, 'planCritique');
58
- return critiqueStatus(readText(path), currentHash);
59
- }
60
-
61
- function readText(path) {
62
- try {
63
- return existsSync(path) ? readFileSync(path, 'utf8') : null;
64
- } catch {
65
- return null;
66
- }
67
- }