@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,160 +0,0 @@
1
- /**
2
- * Two caches with two lifetimes: an agent appends to `events.jsonl` on every tool
3
- * call, so a log change drops only the event cache, never the feature scan.
4
- */
5
-
6
- import { join } from 'path';
7
- import { existsSync, readdirSync } from 'fs';
8
- import { scanFeatures, readFeatureDetail, readFeatureFile } from './features-scanner.js';
9
- import { createEventStore, buildFeed, lastActivityByFeature, sessionMap, ALL_KINDS, DEFAULT_KINDS } from './activity-scanner.js';
10
- import { containerDirs } from '../../../framework/hooks/shared/worktree-root.js';
11
- import { isFinished } from './feature-status.js';
12
- import { resolveFeatureTree } from '../../lib/worktree/feature-truth.js';
13
- import { computeMetrics } from '../../lib/telemetry/metrics.js';
14
-
15
- const TREE_TTL_MS = 60_000;
16
-
17
- /** `.morph/framework/` is the installed framework copy and never changes what this API returns. */
18
- export function classifyChange(path) {
19
- const p = String(path).replace(/\\/g, '/');
20
- if (!p.includes('/.morph/') && !p.endsWith('/.morph')) return null;
21
- if (p.includes('/.morph/framework/') || p.endsWith('/.morph/framework')) return null;
22
- if (p.includes('/.morph/logs/')) return 'activity';
23
- if (/\/\.morph\/(features|archive|config)(\/|$)/.test(p) || p.endsWith('/.morph/state.json')) return 'features';
24
- return null;
25
- }
26
-
27
- /** Vite would full-reload for a `.html` under `.morph/`; the dashboard's code never lives there. */
28
- export function isMorphDataReload(path) {
29
- return typeof path === 'string' && path.replace(/\\/g, '/').includes('/.morph/');
30
- }
31
-
32
- /** Never a whole worktree: its node_modules. */
33
- export function watchTargets(projectDir) {
34
- const morphDirs = [join(projectDir, '.morph')];
35
- for (const container of containerDirs(projectDir)) {
36
- let entries = [];
37
- try { entries = readdirSync(container, { withFileTypes: true }); } catch { continue; }
38
- for (const e of entries) {
39
- if (e.isDirectory()) morphDirs.push(join(container, e.name, '.morph'));
40
- }
41
- }
42
- const targets = [];
43
- for (const dir of morphDirs) {
44
- for (const sub of ['features', 'archive', 'logs', 'config', 'state.json']) {
45
- const p = join(dir, sub);
46
- if (existsSync(p)) targets.push(p);
47
- }
48
- }
49
- return targets;
50
- }
51
-
52
- function json(status, body) {
53
- return { status, body };
54
- }
55
-
56
- export function createProjectApi(projectDir, deps = {}) {
57
- const scan = deps.scanFeatures || scanFeatures;
58
- const detail = deps.readFeatureDetail || readFeatureDetail;
59
- const file = deps.readFeatureFile || readFeatureFile;
60
- const store = createEventStore(projectDir, deps.loadEvents
61
- ? { loadTrees: () => [{ tree: 'root', path: projectDir, events: deps.loadEvents(projectDir) }] }
62
- : {});
63
- const cache = { features: null };
64
-
65
- // Which tree owns a feature costs git calls (~0.3 s each on Windows) and only
66
- // changes on add/remove, never on a rewrite: remembered until a structural event or TTL_MS.
67
- const resolveTree = deps.resolveTree || resolveFeatureTree;
68
- const now = deps.now || Date.now;
69
- const trees = new Map();
70
- const rememberedTree = (name, dir) => {
71
- const hit = trees.get(name);
72
- if (hit && now() - hit.at < TREE_TTL_MS) return hit.value;
73
- const value = resolveTree(name, dir);
74
- trees.set(name, { value, at: now() });
75
- return value;
76
- };
77
-
78
- const features = () => (cache.features ||= scan(projectDir, { resolveTree: rememberedTree }));
79
- const events = () => store.events();
80
- let gatesCache = { from: null, length: -1, gates: null };
81
- const known = (name) => features().features?.find((f) => f.name === name) || undefined;
82
-
83
- /** Any `event` but 'change' may move a feature to another tree. */
84
- function invalidate(scope, path, event) {
85
- if (scope === 'features' || scope === 'all') cache.features = null;
86
- if (scope === 'all' || (scope === 'features' && event !== 'change')) trees.clear();
87
- if (scope === 'all') store.reset();
88
- else if (scope === 'activity') store.changed(path);
89
- }
90
-
91
- function handle(url) {
92
- const u = new URL(url, 'http://local');
93
- const parts = u.pathname.split('/').filter(Boolean).map(decodeURIComponent);
94
- try {
95
- if (parts[0] === 'features' && parts.length === 1) {
96
- const scan = features();
97
- const last = lastActivityByFeature(events());
98
- return json(200, { ...scan, features: scan.features.map((f) => ({ ...f, lastActivity: last[f.name] || null })) });
99
- }
100
- if (parts[0] === 'features' && parts.length === 2) {
101
- const d = detail(projectDir, parts[1], { known: known(parts[1]), resolveTree: rememberedTree });
102
- return d ? json(200, d) : json(404, { error: `feature "${parts[1]}" não encontrada` });
103
- }
104
- if (parts[0] === 'file' && parts.length === 1) {
105
- const name = u.searchParams.get('feature') || '';
106
- const r = file(projectDir, name, u.searchParams.get('path') || '', { known: known(name), resolveTree: rememberedTree });
107
- return r.error ? json(r.status, { error: r.error }) : json(200, r);
108
- }
109
- if (parts[0] === 'activity' && parts.length === 1) {
110
- const feature = u.searchParams.get('feature') || undefined;
111
- const kindsParam = u.searchParams.get('kinds');
112
- const kinds = kindsParam ? kindsParam.split(',').filter((k) => ALL_KINDS.includes(k)) : DEFAULT_KINDS;
113
- const limit = Math.min(Number(u.searchParams.get('limit')) || 100, 500);
114
- const all = events();
115
- const feed = buildFeed(all, { feature, kinds, before: u.searchParams.get('before') || undefined, limit });
116
- const titles = new Map(features().features.map((f) => [f.name, f.title]));
117
- feed.items = (feed.items ?? []).map((i) => (i.feature ? { ...i, featureTitle: titles.get(i.feature) ?? i.feature } : i));
118
- return json(200, { ...feed, kinds, cost: feature ? store.cost(feature) : null, session: feature ? sessionMap(all, feature) : null });
119
- }
120
- if (parts[0] === 'gates' && parts.length === 1) {
121
- const all = events();
122
- if (gatesCache.from !== all || gatesCache.length !== all.length) {
123
- gatesCache = { from: all, length: all.length, gates: computeMetrics(all.filter((e) => e?.event === 'Gate')).gates };
124
- }
125
- return json(200, { gates: gatesCache.gates });
126
- }
127
- return json(404, { error: 'rota desconhecida' });
128
- } catch (err) {
129
- return json(500, { error: err?.message || String(err) });
130
- }
131
- }
132
-
133
- function warm() {
134
- try { features(); events(); } catch { /* the first request will report it */ }
135
- }
136
-
137
- function ready() {
138
- return cache.features !== null && store.ready();
139
- }
140
-
141
- function summary() {
142
- const scan = features();
143
- const last = lastActivityByFeature(events());
144
- const active = scan.features.filter((f) => !isFinished(f)).map((f) => ({ ...f, lastActivity: last[f.name] || null }));
145
- const lastTs = Object.values(last).reduce((m, a) => (a.ts > m ? a.ts : m), '');
146
- return {
147
- name: scan.project.name,
148
- stack: scan.project.stack,
149
- trust: scan.project.trust,
150
- legacyStateOnly: scan.project.legacyStateOnly,
151
- total: scan.features.length,
152
- active: active.length,
153
- awaiting: active.filter((f) => f.awaiting).length,
154
- activeFeatures: active,
155
- lastActivityTs: lastTs || null,
156
- };
157
- }
158
-
159
- return { handle, invalidate, warm, ready, summary };
160
- }
@@ -1,46 +0,0 @@
1
- import { readFileSync, readdirSync, existsSync } from 'fs';
2
- import { join, basename } from 'path';
3
-
4
- function parseFrontmatter(content) {
5
- const match = content.match(/^---\n([\s\S]*?)\n---/);
6
- if (!match) return { paths: [], stacks: [] };
7
- const yaml = match[1];
8
- const paths = []; const stacks = []; let currentList = null;
9
- for (const line of yaml.split('\n')) {
10
- if (line.startsWith('paths:')) { currentList = paths; continue; }
11
- if (line.startsWith('stacks:')) { currentList = stacks; continue; }
12
- if (line.match(/^\w/)) { currentList = null; continue; }
13
- if (currentList !== null) {
14
- const m = line.match(/^\s+-\s+"?(.+?)"?\s*$/);
15
- if (m) currentList.push(m[1]);
16
- }
17
- }
18
- return { paths, stacks };
19
- }
20
-
21
- const ROUTE_LINE = /^- \*\*([a-z0-9-]+)\*\* \(`([^`]+\.md)`\)/;
22
-
23
- // An `@path` import inside .claude/rules resolves relative to the rule file and never loads.
24
- export function parseStandardRoutes(content) {
25
- const routes = [];
26
- for (const line of content.split(/\r?\n/)) {
27
- const m = ROUTE_LINE.exec(line);
28
- if (m) routes.push({ id: m[1], path: m[2] });
29
- }
30
- return routes;
31
- }
32
-
33
- // RulesMap keys one edge per ref, so a repeated path would collide.
34
- export function extractStandardRefs(content) {
35
- return [...new Set(parseStandardRoutes(content).map((r) => r.path))];
36
- }
37
-
38
- export function scanRules(frameworkDir) {
39
- const dir = join(frameworkDir, 'rules');
40
- if (!existsSync(dir)) return [];
41
- return readdirSync(dir).filter(f => f.endsWith('.md')).map(f => {
42
- const content = readFileSync(join(dir, f), 'utf8');
43
- const { paths, stacks } = parseFrontmatter(content);
44
- return { name: basename(f, '.md'), filename: f, paths, stacks, content, standardRefs: extractStandardRefs(content) };
45
- });
46
- }
@@ -1,104 +0,0 @@
1
- import { readFileSync, readdirSync, existsSync } from 'fs';
2
- import { join } from 'path';
3
-
4
- /** CRLF-safe: a checkout with autocrlf is still read. */
5
- export function parseFrontmatter(content) {
6
- const match = /^---\r?\n([\s\S]*?)\r?\n---/.exec(content);
7
- if (!match) return {};
8
- const out = {};
9
- for (const line of match[1].split(/\r?\n/)) {
10
- const idx = line.indexOf(':');
11
- if (idx === -1) continue;
12
- const key = line.slice(0, idx).trim();
13
- let value = line.slice(idx + 1).trim().replace(/^["']|["']$/g, '');
14
- if (value === 'true') value = true;
15
- else if (value === 'false') value = false;
16
- out[key] = value;
17
- }
18
- return out;
19
- }
20
-
21
- const FENCE = /^(\s*)```/;
22
- const DISPATCH_HINT = /dispatch|despach|subagent_type|Template do prompt/i;
23
- const PERSONA_REF = /morph-(\{id\}|\{task\.agent\}|[a-z][a-z-]*[a-z])/g;
24
- const BUILTIN_AGENT = /`(Explore|general-purpose|Plan)`/g;
25
- const NOT_PERSONA = /^(spec|proposal|brainstorming|stack-scan|uiux|plan|implement|apply|review|eval|hotfix|standards|media|task)$/;
26
-
27
- export function extractDispatchPrompts(content) {
28
- const lines = content.split(/\r?\n/);
29
- const out = [];
30
- for (let i = 0; i < lines.length; i++) {
31
- const open = FENCE.exec(lines[i]);
32
- if (!open) continue;
33
- let j = i + 1;
34
- while (j < lines.length && !FENCE.test(lines[j])) j++;
35
- const body = lines.slice(i + 1, j);
36
- const text = body.map((l) => l.slice(Math.min(open[1].length, l.length - l.trimStart().length))).join('\n');
37
- // Only the sentence that introduces the block counts: a paragraph further up
38
- // that mentions a dispatch is not this block's.
39
- let k = i - 1;
40
- while (k >= 0 && lines[k].trim() === '') k--;
41
- const before = k >= 0 && i - k <= 2 ? lines[k] : '';
42
- const builtin = [...before.matchAll(BUILTIN_AGENT)].map((m) => m[1]);
43
- const isDispatch = /^\s*dispatch\s+Agent/i.test(body[0] || '')
44
- || (DISPATCH_HINT.test(before) && (/morph-/.test(before + text) || builtin.length > 0));
45
- if (isDispatch) {
46
- const refsIn = (str) => [...str.matchAll(PERSONA_REF)].map((m) => m[1]);
47
- const personasOf = (refs) => [...new Set(refs.filter((r) => !r.startsWith('{') && !NOT_PERSONA.test(r)))];
48
- const refs = refsIn(`${before}\n${text}`);
49
- const generic = refs.some((r) => r.startsWith('{'));
50
- let personas = personasOf(refs);
51
- // "Template do prompt:" names no one; the step that introduces it does.
52
- if (!generic && personas.length === 0 && builtin.length === 0) {
53
- personas = personasOf(refsIn(lines.slice(Math.max(0, k - 8), k).join('\n')));
54
- }
55
- const others = !generic && personas.length === 0 ? [...new Set(builtin)] : [];
56
- out.push({ index: out.length, personas, generic, builtin: others, context: before.trim().slice(0, 240), text });
57
- }
58
- i = j;
59
- }
60
- return out;
61
- }
62
-
63
- export function scanSkills(frameworkDir, phases = []) {
64
- const skillsDir = join(frameworkDir, 'skills');
65
- if (!existsSync(skillsDir)) return [];
66
- const phaseOf = new Map(phases.filter((p) => p.skill).map((p) => [p.skill, p.id]));
67
- const skills = [];
68
- for (const levelDir of readdirSync(skillsDir, { withFileTypes: true })) {
69
- if (!levelDir.isDirectory()) continue;
70
- const levelPath = join(skillsDir, levelDir.name);
71
- for (const skillDir of readdirSync(levelPath, { withFileTypes: true })) {
72
- if (!skillDir.isDirectory()) continue;
73
- const skillPath = join(levelPath, skillDir.name, 'SKILL.md');
74
- if (!existsSync(skillPath)) continue;
75
- const content = readFileSync(skillPath, 'utf8');
76
- const fm = parseFrontmatter(content);
77
- const invocable = fm['user-invocable'];
78
- skills.push({
79
- id: skillDir.name,
80
- name: fm.name || skillDir.name,
81
- description: fm.description || '',
82
- whenToUse: fm.when_to_use || '',
83
- level: levelDir.name,
84
- userInvocable: invocable === true || invocable === 'true',
85
- stacks: typeof fm.stacks === 'string' ? fm.stacks.replace(/[[\]]/g, '').split(',').map((s) => s.trim()).filter(Boolean) : [],
86
- allowedTools: typeof fm['allowed-tools'] === 'string' ? fm['allowed-tools'].split(',').map((t) => t.trim()) : [],
87
- phase: phaseOf.get(skillDir.name) || null,
88
- dispatches: skillDispatches(join(levelPath, skillDir.name), content),
89
- content,
90
- });
91
- }
92
- }
93
- return skills.sort((a, b) => a.id.localeCompare(b.id));
94
- }
95
-
96
- function skillDispatches(skillDir, content) {
97
- const refsDir = join(skillDir, 'references');
98
- const refs = existsSync(refsDir)
99
- ? readdirSync(refsDir).filter((f) => f.endsWith('.md')).sort().map((f) => readFileSync(join(refsDir, f), 'utf8'))
100
- : [];
101
- return [content, ...refs]
102
- .flatMap((text) => extractDispatchPrompts(text))
103
- .map((d, index) => ({ ...d, index }));
104
- }
@@ -1,38 +0,0 @@
1
- import { readFileSync, existsSync } from 'fs';
2
- import { join } from 'path';
3
- import { personaStandardIds } from '../../utils/agents-installer.js';
4
- import { loadStandardsRegistry } from '../../lib/standards/registry.js';
5
-
6
- export function scanStandards(frameworkDir, agents) {
7
- const standardsJsonPath = join(frameworkDir, 'standards', 'STANDARDS.json');
8
- if (!existsSync(standardsJsonPath)) return { version: 'unknown', list: [] };
9
- const sJson = loadStandardsRegistry(standardsJsonPath);
10
- const refMap = {};
11
- for (const agent of agents) {
12
- for (const std of personaStandardIds(agent)) {
13
- // agents.json stores standards as id strings; the `{ id }` object form is
14
- // still accepted so a mixed agents.json does not lose edges.
15
- const id = typeof std === 'string' ? std : std?.id;
16
- if (!id) continue;
17
- if (!refMap[id]) refMap[id] = [];
18
- refMap[id].push({
19
- agentId: agent.id,
20
- scope: typeof std === 'string' ? null : (std.scope ?? null),
21
- priority: typeof std === 'string' ? null : (std.priority ?? null),
22
- });
23
- }
24
- }
25
- const list = sJson.standards.map(std => {
26
- const mdPath = join(frameworkDir, 'standards', std.path);
27
- return {
28
- id: std.id, name: std.name, path: std.path, category: std.category,
29
- subcategory: std.subcategory || null, tags: std.tags || [],
30
- digest: std.digest || '', stacks: std.stacks || [],
31
- aliases: std.aliases || [], anchors: std.anchors || {},
32
- provedBy: std.provedBy || [], verifiedAgainst: std.verifiedAgainst || null,
33
- content: existsSync(mdPath) ? readFileSync(mdPath, 'utf8') : '',
34
- referencedBy: refMap[std.id] || [],
35
- };
36
- });
37
- return { version: sJson.version, list };
38
- }
@@ -1,120 +0,0 @@
1
- import { scanAll } from './scanner/index.js';
2
- import { classifyChange, watchTargets, isMorphDataReload } from './scanner/project-api.js';
3
- import { createPortfolio } from './scanner/portfolio.js';
4
-
5
- const VIRTUAL_MODULE_ID = 'virtual:morph-data';
6
- const RESOLVED_VIRTUAL_ID = '\0' + VIRTUAL_MODULE_ID;
7
- const DEBOUNCE_MS = 300;
8
- const RESCAN_MS = 30_000;
9
- const WARM_GAP_MS = 400;
10
- const MAX_BODY = 64 * 1024;
11
-
12
- function readBody(req) {
13
- return new Promise((resolveBody) => {
14
- let size = 0;
15
- const chunks = [];
16
- req.on('data', (c) => { size += c.length; if (size <= MAX_BODY) chunks.push(c); });
17
- req.on('end', () => {
18
- try { resolveBody(chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : null); } catch { resolveBody(null); }
19
- });
20
- req.on('error', () => resolveBody(null));
21
- });
22
- }
23
-
24
- export default function morphDataPlugin(frameworkDir, projectDir) {
25
- return {
26
- name: 'vite-plugin-morph-data',
27
- resolveId(id) { if (id === VIRTUAL_MODULE_ID) return RESOLVED_VIRTUAL_ID; },
28
- load(id) {
29
- if (id === RESOLVED_VIRTUAL_ID) {
30
- const data = scanAll(frameworkDir);
31
- return `export default ${JSON.stringify(data)}`;
32
- }
33
- },
34
- configureServer(server) {
35
- const portfolio = createPortfolio({ launchDir: projectDir });
36
- const push = (data) => server.ws.send({ type: 'custom', event: 'morph:changed', data });
37
-
38
- // Vite 6 full-reloads any changed .html it watches even when handleHotUpdate
39
- // returns [], and a project's .morph/ carries .html design sources.
40
- const clientHot = server.environments?.client?.hot;
41
- if (clientHot?.send) {
42
- const send = clientHot.send.bind(clientHot);
43
- clientHot.send = (payload, ...rest) => {
44
- if (payload?.type === 'full-reload' && isMorphDataReload(payload.path)) return;
45
- send(payload, ...rest);
46
- };
47
- }
48
-
49
- const watched = new Set();
50
- function watchNew() {
51
- const fresh = portfolio.list().flatMap((p) => watchTargets(p.dir)).filter((p) => !watched.has(p));
52
- for (const p of fresh) watched.add(p);
53
- if (fresh.length) server.watcher.add(fresh);
54
- }
55
-
56
- // One project at a time, WARM_GAP_MS apart: a read blocks the event loop for
57
- // seconds, and the reads a push just caused are served first.
58
- let warming = false;
59
- function warmSoon() {
60
- if (warming) return;
61
- warming = true;
62
- const step = () => {
63
- const warmed = portfolio.warmNext();
64
- if (!warmed) { warming = false; return; }
65
- push({ scope: 'projects' });
66
- setTimeout(step, WARM_GAP_MS);
67
- };
68
- setTimeout(step, WARM_GAP_MS);
69
- }
70
-
71
- server.middlewares.use('/api/morph', async (req, res) => {
72
- const body = req.method === 'POST' ? await readBody(req) : null;
73
- const { status, body: out } = portfolio.handle(req.method || 'GET', req.url || '/', body);
74
- res.statusCode = status;
75
- res.setHeader('Content-Type', 'application/json; charset=utf-8');
76
- res.setHeader('Cache-Control', 'no-store');
77
- res.end(JSON.stringify(out));
78
- if (req.method !== 'GET' && status === 200) { watchNew(); push({ scope: 'projects' }); warmSoon(); }
79
- });
80
-
81
- watchNew();
82
- warmSoon();
83
- const rescan = setInterval(watchNew, RESCAN_MS);
84
- rescan.unref?.();
85
-
86
- const timers = new Map();
87
- const changed = new Map();
88
- const onFsEvent = (event, path) => {
89
- const scope = classifyChange(path);
90
- if (!scope) return;
91
- const project = portfolio.ownerOf(path);
92
- if (!project) return;
93
- const key = `${project.id}:${scope}`;
94
- if (!changed.has(key)) changed.set(key, new Map());
95
- const seen = changed.get(key);
96
- // A path added then changed in one window is still an add.
97
- if (!seen.has(path) || seen.get(path) === 'change') seen.set(path, event);
98
- clearTimeout(timers.get(key));
99
- timers.set(key, setTimeout(() => {
100
- timers.delete(key);
101
- const paths = changed.get(key) || new Map();
102
- changed.delete(key);
103
- for (const [p, event] of paths) portfolio.invalidate(project, scope, p, event);
104
- if (scope === 'features') watchNew();
105
- push({ scope, project: project.id });
106
- // A log append is tailed on read, so the portfolio can refresh now; a
107
- // feature change is re-read in the background first, then pushed.
108
- if (scope === 'activity') push({ scope: 'projects' });
109
- else warmSoon();
110
- }, DEBOUNCE_MS));
111
- };
112
- for (const evt of ['add', 'change', 'unlink', 'addDir', 'unlinkDir']) server.watcher.on(evt, (path) => onFsEvent(evt, path));
113
- server.httpServer?.once('close', () => clearInterval(rescan));
114
- },
115
- // A changed `.morph/` file is data, not a module: never let it reach HMR.
116
- handleHotUpdate(ctx) {
117
- if (classifyChange(ctx.file)) return [];
118
- },
119
- };
120
- }
@@ -1,26 +0,0 @@
1
- import { defineConfig } from 'vite';
2
- import react from '@vitejs/plugin-react';
3
- import tailwindcss from '@tailwindcss/vite';
4
- import morphDataPlugin from './vite-plugin-morph-data.js';
5
- import { fileURLToPath } from 'url';
6
- import { dirname, resolve } from 'path';
7
-
8
- const __filename = fileURLToPath(import.meta.url);
9
- const __dirname = dirname(__filename);
10
-
11
- const frameworkDir = resolve(__dirname, '..', '..', 'framework');
12
- const projectDir = process.env.MORPH_PROJECT_DIR || process.cwd();
13
-
14
- export default defineConfig({
15
- root: __dirname,
16
- plugins: [
17
- react(),
18
- tailwindcss(),
19
- morphDataPlugin(frameworkDir, projectDir),
20
- ],
21
- server: {
22
- port: 3200,
23
- // The client imports the owner vocabulary from framework/hooks/shared, outside this package root.
24
- fs: { allow: [__dirname, frameworkDir] },
25
- },
26
- });
@@ -1,30 +0,0 @@
1
- import { getHeadSha } from '../git/default-branch.js';
2
- import { treeMovedSince } from '../git/evidence-staleness.js';
3
- import { ciAvailability, uncommittedCode } from './github-ci.js';
4
- import { prProofConfig } from './pr-checks.js';
5
- import { resolveTestNodes } from '../tasks/test-nodes.js';
6
- import { selectAffected } from '../verify/affected.js';
7
-
8
- // The last green stamp still proves the tree if nothing moved since it and nothing is uncommitted
9
- // (treeMovedSince sees only commits). A null sha or HEAD would read as "not moved", so both are required.
10
- export function reusableLocalStamp(root, stamp) {
11
- if (stamp?.status !== 'pass' || !stamp.sha) return null;
12
- const head = getHeadSha(root);
13
- if (!head) return null;
14
- const dirty = uncommittedCode(root);
15
- if (dirty === null || dirty.length > 0) return null;
16
- return treeMovedSince(root, stamp.sha, head) ? null : stamp;
17
- }
18
-
19
- /**
20
- * `covers` = suites the PR's own checks prove, left out of the local run. `local` = run everything here,
21
- * with the reason. Null = the project declared no PR proof. What the affected run would escalate stays local.
22
- */
23
- export function resolvePrProof(root, featureName, config, { select = selectAffected } = {}) {
24
- const proof = prProofConfig(config);
25
- if (!proof) return null;
26
- const avail = ciAvailability(root, featureName, config);
27
- if (!avail.ok) return { local: avail.reason };
28
- const selection = select({ projectPath: root, nodes: resolveTestNodes(root).nodes });
29
- return selection.scope === 'full' ? { local: selection.reason } : proof;
30
- }
@@ -1,52 +0,0 @@
1
- import { execFileSync, spawnSync } from 'child_process';
2
- import { resolveGh } from '../git/gh.js';
3
-
4
- const git = (cwd, args) => execFileSync('git', args, { cwd, stdio: 'pipe' }).toString();
5
-
6
- export function currentBranch(root) {
7
- try {
8
- return git(root, ['rev-parse', '--abbrev-ref', 'HEAD']).trim();
9
- } catch {
10
- return null;
11
- }
12
- }
13
-
14
- function originUrl(root) {
15
- try {
16
- return git(root, ['config', '--get', 'remote.origin.url']).trim();
17
- } catch {
18
- return null;
19
- }
20
- }
21
-
22
- function ghAuthOk(root) {
23
- const { bin, prefix } = resolveGh();
24
- const res = spawnSync(bin, [...prefix, 'auth', 'status'], { cwd: root, stdio: 'pipe', timeout: 10000 });
25
- return !res.error && res.status === 0;
26
- }
27
-
28
- /** Never throws: every "no" is a reason the caller prints before running everything locally. */
29
- export function ciAvailability(root, featureName, config) {
30
- if (config?.project?.ci === false) return { ok: false, reason: 'project.ci = false no config.json' };
31
- const url = originUrl(root);
32
- if (!url) return { ok: false, reason: 'sem remote origin' };
33
- if (!/github\.com/i.test(url)) return { ok: false, reason: 'origin não é GitHub' };
34
- const branch = currentBranch(root);
35
- if (branch !== `morph/${featureName}`) {
36
- return { ok: false, reason: `branch atual "${branch}" não é morph/${featureName}` };
37
- }
38
- if (!ghAuthOk(root)) return { ok: false, reason: 'gh ausente ou não autenticado' };
39
- return { ok: true, branch };
40
- }
41
-
42
- /** Uncommitted or untracked files outside `.morph/`, plus the config; null when git did not answer. */
43
- export function uncommittedCode(root) {
44
- let out;
45
- try {
46
- out = git(root, ['status', '--porcelain', '-z', '--untracked-files=all', '--no-renames']);
47
- } catch {
48
- return null;
49
- }
50
- return out.split('\0').filter(Boolean).map((line) => line.slice(3))
51
- .filter((path) => !path.startsWith('.morph/') || path === '.morph/config/config.json');
52
- }
@@ -1,76 +0,0 @@
1
- import { execFileSync } from 'child_process';
2
- import { resolveGh } from '../git/gh.js';
3
-
4
- const FAILED = new Set(['FAILURE', 'TIMED_OUT']);
5
- const PASSED = new Set(['SUCCESS', 'SKIPPED', 'NEUTRAL']);
6
-
7
- // A job killed by exhausted Actions quota fails within seconds without running a step.
8
- const MIN_JUDGED_MS = 30 * 1000;
9
-
10
- export const PR_WAIT_MS = 50 * 60 * 1000;
11
-
12
- /** The PR proof a project declared; null when it closes by merge, opted out of CI or declared nothing. */
13
- export function prProofConfig(config) {
14
- if (config?.project?.ci === false || config?.finish?.mode === 'merge') return null;
15
- const { workflows, covers } = config?.project?.prChecks ?? {};
16
- const filled = (list) => Array.isArray(list) && list.length > 0;
17
- return filled(workflows) && filled(covers) ? { workflows, covers } : null;
18
- }
19
-
20
- function neverRan(check) {
21
- const elapsed = Date.parse(check.completedAt) - Date.parse(check.startedAt);
22
- return !Number.isFinite(elapsed) || elapsed < MIN_JUDGED_MS;
23
- }
24
-
25
- /** Only a declared workflow counts: a green lint or deploy run says nothing about the suite. */
26
- export function judgeChecks(rollup, workflows) {
27
- const checks = (rollup ?? []).filter((check) => workflows.includes(check.workflowName));
28
- if (checks.length === 0) return { state: 'absent' };
29
- if (checks.some((check) => check.status !== 'COMPLETED')) return { state: 'running' };
30
-
31
- const failed = checks.filter((check) => FAILED.has(check.conclusion));
32
- const real = failed.filter((check) => !neverRan(check));
33
- if (real.length > 0) return { state: 'fail', failed: real };
34
- if (failed.length > 0) return { state: 'no-verdict', reason: `${failed[0].workflowName} morreu sem rodar (cota do Actions?)` };
35
-
36
- const undecided = checks.find((check) => !PASSED.has(check.conclusion));
37
- if (undecided) return { state: 'no-verdict', reason: `${undecided.workflowName}: ${undecided.conclusion}` };
38
- if (!checks.some((check) => check.conclusion === 'SUCCESS')) return { state: 'no-verdict', reason: 'nenhum check julgou o código' };
39
- return { state: 'pass' };
40
- }
41
-
42
- function readPr(root, branch) {
43
- try {
44
- const { bin, prefix } = resolveGh();
45
- return JSON.parse(execFileSync(bin, [...prefix, 'pr', 'view', branch, '--json', 'headRefOid,statusCheckRollup'], { cwd: root, stdio: 'pipe', timeout: 15000 }).toString());
46
- } catch {
47
- return null;
48
- }
49
- }
50
-
51
- /**
52
- * Waits `appearMs` even when the first workflow already settled: the others may not have been created yet.
53
- * @returns {Promise<{ state: 'pass'|'fail'|'no-verdict'|'pending', failed?: object[], reason?: string }>}
54
- */
55
- export async function waitForPrChecks(root, { branch, sha, workflows, timeoutMs = PR_WAIT_MS,
56
- appearMs = Number(process.env.MORPH_CI_APPEAR_MS ?? 90 * 1000), pollMs = 15000,
57
- sleep = (ms) => new Promise((r) => setTimeout(r, ms)), now = Date.now, read = readPr }) {
58
- const start = now();
59
- let misses = 0;
60
- for (;;) {
61
- const elapsed = now() - start;
62
- const pr = read(root, branch);
63
- if (pr === null) {
64
- if (++misses >= 3) return { state: 'no-verdict', reason: 'gh pr view não respondeu' };
65
- } else {
66
- misses = 0;
67
- const verdict = pr.headRefOid === sha ? judgeChecks(pr.statusCheckRollup, workflows) : { state: 'absent' };
68
- if (elapsed >= appearMs) {
69
- if (verdict.state === 'absent') return { state: 'no-verdict', reason: `nenhum check de ${workflows.join(', ')} neste commit` };
70
- if (verdict.state !== 'running') return verdict;
71
- }
72
- }
73
- if (elapsed >= timeoutMs) return { state: 'pending', reason: `checks não terminaram em ${Math.round(timeoutMs / 60000)} min` };
74
- await sleep(pollMs);
75
- }
76
- }