@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,529 +0,0 @@
1
- // Folders with the SAME stamp are one backup; `task/` has its own count budget.
2
- // A backup without manifest predates retention: only the explicit `--prune` touches it.
3
- // Deletion is prove-or-decline: a backup holding a reparse point is never removed.
4
- import {
5
- cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync,
6
- rmdirSync, rmSync, unlinkSync,
7
- } from 'fs';
8
- import { dirname, join, relative, isAbsolute } from 'path';
9
- import { isDisposableBuildArtifact } from './ignored-triage.js';
10
- import { atomicWriteJson, CONFIG_FILE_NAME } from '../../core/state/state-manager.js';
11
- import { scanForBlockers } from '../../../framework/hooks/shared/reparse-scan.js';
12
-
13
- export const FINISH_BACKUP_RETENTION_DEFAULTS = Object.freeze({
14
- maxCount: 20,
15
- maxAgeDays: null,
16
- secretMaxAgeDays: 7,
17
- });
18
-
19
- const NULLABLE_RETENTION_KEYS = new Set(['maxAgeDays']);
20
-
21
- const DAY_MS = 86_400_000;
22
- const WORKTREE_IGNORED_SUFFIX = '-worktree-ignored';
23
- const MANIFEST_SUFFIX = '.manifest.json';
24
- const NAME_RE = /^(.+)-(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z(-worktree-ignored)?$/;
25
- const SAMPLE = 5;
26
-
27
- export function morphSpecStoreDir(root) {
28
- return join(root, '.git', 'morph-spec');
29
- }
30
-
31
- export function finishBackupDir(root) {
32
- return join(morphSpecStoreDir(root), 'finish-backup');
33
- }
34
-
35
- export function newBackupStamp(date = new Date()) {
36
- return date.toISOString().replace(/[:.]/g, '-');
37
- }
38
-
39
- export function isSecretFileName(name) {
40
- return name.startsWith('.env');
41
- }
42
-
43
- export function parseBackupName(name) {
44
- const m = NAME_RE.exec(name);
45
- if (!m) return null;
46
- const [, feature, date, hh, mm, ss, ms, suffix] = m;
47
- const createdAt = Date.parse(`${date}T${hh}:${mm}:${ss}.${ms}Z`);
48
- if (Number.isNaN(createdAt)) return null;
49
- return {
50
- base: suffix ? name.slice(0, -WORKTREE_IGNORED_SUFFIX.length) : name,
51
- feature,
52
- stamp: `${date}T${hh}-${mm}-${ss}-${ms}Z`,
53
- kind: suffix ? 'worktree-ignored' : 'feature-scope',
54
- createdAt,
55
- };
56
- }
57
-
58
- function stampToIso(stamp) {
59
- const parsed = parseBackupName(`x-${stamp}`);
60
- return new Date(parsed ? parsed.createdAt : Date.now()).toISOString();
61
- }
62
-
63
- const RETENTION_KEYS = Object.keys(FINISH_BACKUP_RETENTION_DEFAULTS);
64
- const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
65
- const shown = (v) => JSON.stringify(v) ?? String(v);
66
- const skippedPolicy = (reason) => ({ enabled: false, skipped: reason, ...FINISH_BACKUP_RETENTION_DEFAULTS });
67
-
68
- // A value this cannot recognise SKIPS the prune instead of falling back to the
69
- // defaults: the operation deletes, and `"false"` or `maxCount: 0` may mean "keep all".
70
- export function resolveBackupRetention(config) {
71
- const d = FINISH_BACKUP_RETENTION_DEFAULTS;
72
- const skip = skippedPolicy;
73
- const section = config?.finishBackup;
74
- if (section === undefined) return { enabled: true, ...d };
75
- if (!isPlainObject(section)) return skip(`finishBackup não é um objeto (${shown(section)})`);
76
- const raw = section.retention;
77
- if (raw === undefined) return { enabled: true, ...d };
78
- if (raw === false) return { enabled: false, ...d };
79
- if (!isPlainObject(raw)) {
80
- return skip(`finishBackup.retention não reconhecida (${shown(raw)}) — use false ou { ${RETENTION_KEYS.join(', ')} }`);
81
- }
82
- const policy = { enabled: true, ...d };
83
- for (const [key, value] of Object.entries(raw)) {
84
- if (!RETENTION_KEYS.includes(key)) return skip(`finishBackup.retention.${key} não existe — as chaves são ${RETENTION_KEYS.join(', ')}`);
85
- if (value === null && NULLABLE_RETENTION_KEYS.has(key)) { policy[key] = null; continue; }
86
- if (!Number.isInteger(value) || value < 1) {
87
- return skip(`finishBackup.retention.${key} inválido (${shown(value)}) — inteiro ≥ 1${NULLABLE_RETENTION_KEYS.has(key) ? ' ou null (sem limite)' : ''}`);
88
- }
89
- policy[key] = value;
90
- }
91
- return policy;
92
- }
93
-
94
- // Unlike `readMorphConfig`, an unparseable config.json is not "no config": the
95
- // defaults would turn on a prune its author may have switched off.
96
- export function readBackupRetention(root) {
97
- const path = join(root, CONFIG_FILE_NAME);
98
- if (!existsSync(path)) return resolveBackupRetention(null);
99
- let config;
100
- try {
101
- config = JSON.parse(readFileSync(path, 'utf8').replace(/^\uFEFF/, ''));
102
- } catch (err) {
103
- return skippedPolicy(`config.json ilegível (${String(err?.message || err).slice(0, 80)})`);
104
- }
105
- return resolveBackupRetention(config);
106
- }
107
-
108
- function isRealDir(path) {
109
- try {
110
- return lstatSync(path).isDirectory();
111
- } catch {
112
- return false;
113
- }
114
- }
115
-
116
- function isRealFile(path) {
117
- try {
118
- return lstatSync(path).isFile();
119
- } catch {
120
- return false;
121
- }
122
- }
123
-
124
- function isStrictlyInside(parent, child) {
125
- const rel = relative(parent, child);
126
- return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel);
127
- }
128
-
129
- export function secretFilesIn(dir) {
130
- const out = [];
131
- const stack = [''];
132
- while (stack.length) {
133
- const rel = stack.pop();
134
- let entries;
135
- try {
136
- entries = readdirSync(join(dir, rel), { withFileTypes: true });
137
- } catch {
138
- continue;
139
- }
140
- for (const e of entries) {
141
- const childRel = rel ? `${rel}/${e.name}` : e.name;
142
- if (e.isSymbolicLink()) continue;
143
- if (e.isDirectory()) stack.push(childRel);
144
- else if (e.isFile() && isSecretFileName(e.name)) out.push(childRel);
145
- }
146
- }
147
- return out.sort();
148
- }
149
-
150
- /** By lstat: a link counts as itself. `null` when the walk could not start. */
151
- export function measureDir(dir) {
152
- if (!isRealDir(dir)) return null;
153
- let bytes = 0;
154
- let files = 0;
155
- const stack = [dir];
156
- while (stack.length) {
157
- const current = stack.pop();
158
- let entries;
159
- try {
160
- entries = readdirSync(current, { withFileTypes: true });
161
- } catch {
162
- continue;
163
- }
164
- for (const e of entries) {
165
- const p = join(current, e.name);
166
- if (e.isDirectory() && !e.isSymbolicLink()) { stack.push(p); continue; }
167
- try { bytes += lstatSync(p).size; files += 1; } catch {}
168
- }
169
- }
170
- return { bytes, files };
171
- }
172
-
173
- export function manifestPathFor(backupPath) {
174
- return `${backupPath}${MANIFEST_SUFFIX}`;
175
- }
176
-
177
- function readManifest(backupPath) {
178
- try {
179
- return JSON.parse(readFileSync(manifestPathFor(backupPath), 'utf8'));
180
- } catch {
181
- return null;
182
- }
183
- }
184
-
185
- // Fail-open: a backup whose manifest failed reads as legacy, the safe side.
186
- function writeManifest(backupPath, manifest) {
187
- try {
188
- atomicWriteJson(manifestPathFor(backupPath), { version: 1, ...manifest });
189
- } catch {}
190
- }
191
-
192
- // Caches are excluded at every depth: git reports an ignored dir as ONE entry,
193
- // so `apps/x/` would drag its `node_modules/` along.
194
- /** `null` if ANY copy failed — the caller must then decline the removal. */
195
- export function writeWorktreeIgnoredBackup({ worktreePath, root, feature, rels, stamp = newBackupStamp() }) {
196
- const dest = join(finishBackupDir(root), `${feature}-${stamp}${WORKTREE_IGNORED_SUFFIX}`);
197
- const copied = [];
198
- const excludedCaches = [];
199
- const relOf = (abs) => relative(worktreePath, abs).replace(/\\/g, '/');
200
- try {
201
- for (const rel of rels) {
202
- const src = join(worktreePath, rel);
203
- if (!existsSync(src)) continue;
204
- if (isDisposableBuildArtifact(relOf(src))) {
205
- excludedCaches.push(relOf(src));
206
- continue;
207
- }
208
- const target = join(dest, rel);
209
- mkdirSync(dirname(target), { recursive: true });
210
- cpSync(src, target, {
211
- recursive: true,
212
- filter: (from) => {
213
- const r = relOf(from);
214
- if (!isDisposableBuildArtifact(r)) return true;
215
- excludedCaches.push(r);
216
- return false;
217
- },
218
- });
219
- copied.push(rel);
220
- }
221
- if (!copied.length && !excludedCaches.length) return null;
222
- mkdirSync(dest, { recursive: true });
223
- } catch {
224
- return null;
225
- }
226
- writeManifest(dest, {
227
- kind: 'worktree-ignored',
228
- feature,
229
- createdAt: stampToIso(stamp),
230
- source: worktreePath.replace(/\\/g, '/'),
231
- copied,
232
- excludedCaches,
233
- secrets: secretFilesIn(dest),
234
- });
235
- return dest;
236
- }
237
-
238
- // Under `.git/` so it never dirties the `git status` the next validation reads.
239
- /** `null` if the copy failed: the caller must not shed. */
240
- export function writeFeatureScopeBackup({ root, feature, stamp = newBackupStamp() }) {
241
- const src = join(root, '.morph', 'features', feature);
242
- if (!existsSync(src)) return null;
243
- const dest = join(finishBackupDir(root), `${feature}-${stamp}`);
244
- try {
245
- mkdirSync(dirname(dest), { recursive: true });
246
- cpSync(src, dest, { recursive: true });
247
- } catch {
248
- return null;
249
- }
250
- writeManifest(dest, {
251
- kind: 'feature-scope',
252
- feature,
253
- createdAt: stampToIso(stamp),
254
- source: src.replace(/\\/g, '/'),
255
- secrets: secretFilesIn(dest),
256
- });
257
- return dest;
258
- }
259
-
260
- // Any other first-level directory that is not a backup is not ours: never removed.
261
- const BACKUP_NAMESPACES = new Set(['task']);
262
-
263
- /** `managed` = has its manifest; without one the backup predates retention. */
264
- export function listFinishBackups(root) {
265
- const base = finishBackupDir(root);
266
- if (!isRealDir(base)) return [];
267
- const out = [];
268
- const visit = (dir, namespace) => {
269
- let entries;
270
- try {
271
- entries = readdirSync(dir, { withFileTypes: true });
272
- } catch {
273
- return;
274
- }
275
- for (const e of entries) {
276
- const path = join(dir, e.name);
277
- if (!isRealDir(path)) continue;
278
- const parsed = parseBackupName(e.name);
279
- if (parsed) {
280
- const prefix = namespace ? `${namespace}/` : '';
281
- out.push({
282
- name: `${prefix}${e.name}`,
283
- path,
284
- namespace,
285
- set: `${prefix}${parsed.base}`,
286
- feature: `${prefix}${parsed.feature}`,
287
- stamp: parsed.stamp,
288
- kind: parsed.kind,
289
- createdAt: parsed.createdAt,
290
- managed: isRealFile(manifestPathFor(path)),
291
- });
292
- } else if (!namespace && BACKUP_NAMESPACES.has(e.name)) {
293
- visit(path, e.name);
294
- }
295
- }
296
- };
297
- visit(base, '');
298
- return out;
299
- }
300
-
301
- // Sets stamped after `now` (clock ran ahead) stay and take no place in the count,
302
- // or a handful of them would evict every new backup the moment it is written.
303
- export function planBackupRetention(backups, retention, now, { protectStamps = [], includeLegacy = false } = {}) {
304
- const sets = new Map();
305
- for (const b of backups) {
306
- const s = sets.get(b.set) ?? { set: b.set, namespace: b.namespace, stamp: b.stamp, createdAt: b.createdAt, managed: true, members: [] };
307
- s.createdAt = Math.min(s.createdAt, b.createdAt);
308
- s.managed = s.managed && b.managed;
309
- s.members.push(b);
310
- sets.set(b.set, s);
311
- }
312
- const all = [...sets.values()];
313
- const plan = { sets: sets.size, legacy: all.filter((s) => !s.managed).length, remove: [], stripSecrets: [], adopt: [] };
314
- if (!retention.enabled) return plan;
315
-
316
- const isProtected = (s) => protectStamps.includes(s.stamp);
317
- const byNamespace = new Map();
318
- for (const s of all) {
319
- if (!s.managed && !includeLegacy) continue;
320
- if (s.createdAt > now) {
321
- if (!s.managed) plan.adopt.push(s);
322
- continue;
323
- }
324
- const list = byNamespace.get(s.namespace) ?? [];
325
- list.push(s);
326
- byNamespace.set(s.namespace, list);
327
- }
328
- const maxAgeMs = retention.maxAgeDays == null ? Infinity : retention.maxAgeDays * DAY_MS;
329
- for (const list of byNamespace.values()) {
330
- list.sort((a, b) => b.createdAt - a.createdAt || (a.set < b.set ? 1 : -1));
331
- list.forEach((s, index) => {
332
- const age = now - s.createdAt;
333
- const dropped = index >= retention.maxCount || age > maxAgeMs;
334
- if (dropped && !isProtected(s)) {
335
- plan.remove.push(s);
336
- return;
337
- }
338
- if (age > retention.secretMaxAgeDays * DAY_MS) plan.stripSecrets.push(s);
339
- if (!s.managed) plan.adopt.push(s);
340
- });
341
- }
342
- return plan;
343
- }
344
-
345
- // A backup whose removal is declined still loses its `.env*`. Never throws:
346
- // a failed retention must never be the reason a `finish` fails.
347
- export function applyBackupRetention(root, { now = Date.now(), retention, protectStamps = [], includeLegacy = false } = {}) {
348
- const result = { enabled: true, removed: [], secretsStripped: [], declined: [], legacyPending: 0, adopted: [] };
349
- try {
350
- const policy = retention ?? readBackupRetention(root);
351
- result.enabled = policy.enabled;
352
- if (policy.skipped) result.skipped = policy.skipped;
353
- if (!policy.enabled) return result;
354
- const base = finishBackupDir(root);
355
- if (!isRealDir(base)) return result;
356
- const plan = planBackupRetention(listFinishBackups(root), policy, now, { protectStamps, includeLegacy });
357
- if (!includeLegacy) result.legacyPending = plan.legacy;
358
- const toStrip = plan.stripSecrets.flatMap((s) => s.members);
359
-
360
- for (const s of plan.remove) {
361
- for (const m of s.members) {
362
- if (!isStrictlyInside(base, m.path)) {
363
- result.declined.push({ backup: m.name, reason: 'outside-backup-dir' });
364
- continue;
365
- }
366
- const scan = scanForBlockers(m.path);
367
- if (!scan.safe) {
368
- result.declined.push({ backup: m.name, reason: `reparse-point: ${scan.blockers.slice(0, SAMPLE).join(', ')}` });
369
- toStrip.push(m);
370
- continue;
371
- }
372
- try {
373
- rmSync(m.path, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
374
- } catch (err) {
375
- result.declined.push({ backup: m.name, reason: (err?.code || err?.message || 'rm-failed').toString().slice(0, 120) });
376
- toStrip.push(m);
377
- continue;
378
- }
379
- try { rmSync(manifestPathFor(m.path), { force: true }); } catch {}
380
- result.removed.push(m.name);
381
- }
382
- }
383
-
384
- for (const m of toStrip) {
385
- const stripped = [];
386
- for (const rel of secretFilesIn(m.path)) {
387
- try {
388
- unlinkSync(join(m.path, rel));
389
- stripped.push(rel);
390
- } catch {}
391
- }
392
- if (!stripped.length) continue;
393
- const manifest = readManifest(m.path) ?? { kind: m.kind, feature: m.feature, createdAt: new Date(m.createdAt).toISOString() };
394
- const secrets = [...new Set([...(manifest.secrets || []), ...stripped])].sort();
395
- writeManifest(m.path, { ...manifest, secrets, secretsStrippedAt: new Date(now).toISOString() });
396
- result.secretsStripped.push({ backup: m.name, files: stripped });
397
- }
398
-
399
- for (const m of plan.adopt.flatMap((s) => s.members)) {
400
- if (m.managed) continue;
401
- const manifest = readManifest(m.path)
402
- ?? { kind: m.kind, feature: m.feature, createdAt: new Date(m.createdAt).toISOString(), secrets: secretFilesIn(m.path) };
403
- writeManifest(m.path, { ...manifest, legacy: true, adoptedAt: new Date(now).toISOString() });
404
- result.adopted.push(m.name);
405
- }
406
-
407
- for (const name of BACKUP_NAMESPACES) {
408
- const p = join(base, name);
409
- if (isRealDir(p)) {
410
- try { rmdirSync(p); } catch {}
411
- }
412
- }
413
- } catch {}
414
- return result;
415
- }
416
-
417
- export function inspectFinishBackups(root, { now = Date.now(), retention, includeLegacy = false } = {}) {
418
- const policy = retention ?? readBackupRetention(root);
419
- const backups = listFinishBackups(root);
420
- const plan = planBackupRetention(backups, policy, now, { includeLegacy });
421
- const overdueSecrets = plan.stripSecrets.flatMap((s) => s.members.flatMap((m) => secretFilesIn(m.path).map((f) => `${m.name}/${f}`)));
422
- return {
423
- policy,
424
- sets: plan.sets,
425
- folders: backups.length,
426
- legacy: plan.legacy,
427
- outsideRetention: plan.remove.length,
428
- overdueSecrets,
429
- };
430
- }
431
-
432
- function pendingParts(report, { long = false } = {}) {
433
- const { maxCount, maxAgeDays, secretMaxAgeDays } = report.policy;
434
- const parts = [];
435
- if (report.legacy) {
436
- parts.push(long
437
- ? `${report.legacy} backup(s) sem manifesto (anteriores à retenção) — a poda automática não os toca`
438
- : `${report.legacy} sem manifesto aguardando --prune`);
439
- }
440
- if (report.outsideRetention) {
441
- const age = maxAgeDays == null ? '' : ` ou com mais de ${maxAgeDays} dias`;
442
- parts.push(long
443
- ? `--prune apagaria ${report.outsideRetention} backup(s) fora do teto de ${maxCount} por namespace${age}`
444
- : `${report.outsideRetention} fora da retenção`);
445
- }
446
- if (report.overdueSecrets.length) {
447
- parts.push(long
448
- ? `${report.overdueSecrets.length} arquivo(s) .env* com mais de ${secretMaxAgeDays} dias (${report.overdueSecrets.slice(0, SAMPLE).join(', ')})`
449
- : `${report.overdueSecrets.length} .env* com mais de ${secretMaxAgeDays} dias`);
450
- }
451
- return parts;
452
- }
453
-
454
- function formatSize(bytes) {
455
- if (bytes < 1024) return `${bytes} B`;
456
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
457
- return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
458
- }
459
-
460
- // The size rides in the NAME because the doctor prints only the name of an `ok` line.
461
- export function morphStoreCheck(root, { now = Date.now() } = {}) {
462
- let store;
463
- let report;
464
- try {
465
- store = measureDir(morphSpecStoreDir(root));
466
- if (!store) return null;
467
- report = inspectFinishBackups(root, { now, includeLegacy: true });
468
- } catch {
469
- return null;
470
- }
471
- const name = `.git/morph-spec (${formatSize(store.bytes)} · ${report.sets} backup(s) do finish)`;
472
- if (report.policy.skipped) return { name, status: 'warn', msg: `retenção pulada: ${report.policy.skipped}` };
473
- const pending = pendingParts(report);
474
- if (!report.policy.enabled || !pending.length) return { name, status: 'ok' };
475
- return { name, status: 'warn', msg: `${pending.join(', ')} — rode morph-spec doctor --worktrees --prune` };
476
- }
477
-
478
- export function auditFinishBackups(root, opts = {}) {
479
- let report;
480
- try {
481
- report = inspectFinishBackups(root, { ...opts, includeLegacy: true });
482
- } catch {
483
- return [];
484
- }
485
- const detailOf = (text) => `${finishBackupDir(root).replace(/\\/g, '/')}: ${text}`;
486
- if (report.policy.skipped) {
487
- if (!report.folders) return [];
488
- return [{
489
- type: 'finish-backup-retention',
490
- severity: 'warn',
491
- detail: detailOf(`retenção pulada — ${report.policy.skipped}`),
492
- fix: 'corrija `finishBackup.retention` no config.json (false desliga; { maxCount, maxAgeDays, secretMaxAgeDays } ajusta)',
493
- }];
494
- }
495
- const parts = report.policy.enabled ? pendingParts(report, { long: true }) : [];
496
- if (!parts.length) return [];
497
- return [{
498
- type: 'finish-backup-retention',
499
- severity: 'warn',
500
- detail: detailOf(parts.join('; ')),
501
- fix: 'rode `morph-spec doctor --worktrees --prune` — a única via que poda os backups sem manifesto; os com manifesto o próximo `finish` já poda',
502
- }];
503
- }
504
-
505
- /** `null` when the run changed nothing and nothing waits for the explicit prune. */
506
- export function summarizeRetention(result) {
507
- if (!result) return null;
508
- if (result.skipped) return { skipped: result.skipped };
509
- const files = result.secretsStripped.reduce((n, s) => n + s.files.length, 0);
510
- const out = {
511
- ...(result.removed.length ? { removed: result.removed.length, removedSample: result.removed.slice(0, SAMPLE) } : {}),
512
- ...(files ? { secretsStripped: files } : {}),
513
- ...(result.declined.length ? { declined: result.declined.slice(0, SAMPLE) } : {}),
514
- ...(result.adopted?.length ? { adopted: result.adopted.length } : {}),
515
- ...(result.legacyPending
516
- ? { legacyPending: result.legacyPending, legacyHint: 'backups sem manifesto (anteriores à retenção) só são podados por `morph-spec doctor --worktrees --prune`' }
517
- : {}),
518
- };
519
- return Object.keys(out).length ? out : null;
520
- }
521
-
522
- /** `protectStamps`: the stamp the caller just wrote its backup under, never pruned by this run. */
523
- export function enforceBackupRetention(root, { protectStamps = [] } = {}) {
524
- try {
525
- return summarizeRetention(applyBackupRetention(root, { protectStamps }));
526
- } catch {
527
- return null;
528
- }
529
- }