@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,259 +0,0 @@
1
- import { execFileSync } from 'child_process';
2
- import { existsSync, readFileSync } from 'fs';
3
- import { join } from 'path';
4
- import { parsePlan } from '../plan/plan-parser.js';
5
- import { stateMachineSvg } from '../view/flow-svg.js';
6
- import { reviewReportsFromDir } from '../review-reports.js';
7
- import { loadGraph, getFreshness } from '../graph/graph-loader.js';
8
- import { parseDiff, buildDiffTree, declarationDrift } from '../graph/diff-tree.js';
9
- import { detectDefaultBranch } from '../git/default-branch.js';
10
- import { CHECK_RESULT_SAY, GATE_NAME, featureName, scenarioLabel, scenarioTitle } from '../../../framework/hooks/shared/owner-words.js';
11
-
12
- const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
13
-
14
- const readJson = (path) => { try { return JSON.parse(readFileSync(path, 'utf8')); } catch { return null; } };
15
- const readText = (path) => { try { return readFileSync(path, 'utf8'); } catch { return null; } };
16
- const git = (cwd, ...args) => execFileSync('git', args, { cwd, stdio: 'pipe', maxBuffer: 64 << 20 }).toString();
17
-
18
- /**
19
- * What changed on the branch: the call tree when the graph is of HEAD and its lines hold, else the
20
- * plain file and line counts. Never throws; outside git it is null.
21
- */
22
- export function changeSummary(cwd, { base = null, statOnly = false } = {}) {
23
- let from = base;
24
- try {
25
- from ??= git(cwd, 'merge-base', detectDefaultBranch(cwd) || 'main', 'HEAD').trim();
26
- } catch {
27
- return null;
28
- }
29
- let stat = null;
30
- try {
31
- const m = /(\d+) files? changed(?:, (\d+) insertions?\(\+\))?(?:, (\d+) deletions?\(-\))?/.exec(git(cwd, 'diff', '--shortstat', from, 'HEAD'));
32
- stat = { files: Number(m?.[1] ?? 0), added: Number(m?.[2] ?? 0), removed: Number(m?.[3] ?? 0) };
33
- } catch {
34
- return null;
35
- }
36
- if (statOnly) return { stat, tree: null };
37
- const loaded = loadGraph(cwd);
38
- if (!loaded.ok || getFreshness(cwd, loaded.graph).state !== 'fresh') return { stat, tree: null };
39
- try {
40
- const tree = buildDiffTree(loaded.graph, parseDiff(git(cwd, 'diff', '-U0', '--no-renames', '--no-color', from, 'HEAD')));
41
- const drift = declarationDrift(tree, (f) => { try { return git(cwd, 'show', `HEAD:${f}`).split(/\r?\n/); } catch { return []; } });
42
- return { stat, tree: drift.length ? null : tree };
43
- } catch {
44
- return { stat, tree: null };
45
- }
46
- }
47
-
48
- export function buildRecap(featureDir, feature, { changes = null, now = new Date() } = {}) {
49
- const fj = readJson(join(featureDir, 'feature.json')) ?? {};
50
- const planText = readText(join(featureDir, '2-plan', 'plan.md'));
51
- const plan = planText ? parsePlan(planText) : null;
52
- const verifier = reviewReportsFromDir(featureDir).verifier;
53
- const proved = new Map((verifier?.checks ?? []).map((c) => [c.id, c]));
54
- const scenarios = (plan?.scenarios ?? []).map((c) => ({ id: c.id, title: scenarioTitle(c) || null, text: c.text, status: proved.get(c.id)?.status ?? null, evidence: proved.get(c.id)?.evidence ?? '' }));
55
- const gates = Object.entries(fj.approvalGates ?? {})
56
- .filter(([gate]) => GATE_NAME[gate])
57
- .map(([gate, g]) => ({
58
- gate, approved: g === true || g?.approved === true, approvedBy: g?.approvedBy ?? null,
59
- paused: fj.gateDecisions?.[gate]?.pause === true, reason: fj.gateDecisions?.[gate]?.reason ?? null,
60
- }));
61
- const started = Date.parse(fj.createdAt ?? '');
62
- const s = plan?.summary ?? {};
63
- const summary = { name: s.name ?? null, today: s.today ?? null, after: s.after ?? null, watch: s.watch ?? [] };
64
- return {
65
- feature,
66
- name: featureName(feature, fj, summary),
67
- summary,
68
- description: fj.description ?? null,
69
- workType: fj.workType ?? null,
70
- days: Number.isNaN(started) ? null : Math.max(0, Math.round((now - started) / 86400000)),
71
- scenarios,
72
- transitions: plan?.states?.transitions ?? [],
73
- gates,
74
- changes,
75
- };
76
- }
77
-
78
- function flatten(tree, limit) {
79
- const out = [];
80
- const walk = (n, depth) => {
81
- if (out.length >= limit) return;
82
- out.push({ depth, mark: n.mark, label: n.label, file: n.file, again: n.repeat || n.cycle });
83
- n.children.forEach((c) => walk(c, depth + 1));
84
- };
85
- tree.roots.forEach((r) => walk(r, 0));
86
- return out;
87
- }
88
-
89
- const sentence = (t) => { const s = String(t ?? '').trim(); return s && !/[.!?…]$/.test(s) ? `${s}.` : s; };
90
- const PROOF_MARK = { PROVADO: ['ok', '✓'], FALHA: ['bad', '✕'], 'NÃO PROVADO': ['warn', '!'] };
91
-
92
- /**
93
- * One scene per part of the story, in the owner's order: what changed for whoever uses it, the
94
- * proof, where it paused, then the technical part. `narration` is spoken and shown as the caption.
95
- */
96
- export function recapScenes(r) {
97
- const scenes = [];
98
- const name = r.name ?? r.feature;
99
- const after = r.summary?.after ?? null;
100
- const today = r.summary?.today ?? null;
101
- const took = r.days !== null ? `Do início ao fim, ${r.days === 0 ? 'menos de um dia' : `${r.days} dia${r.days > 1 ? 's' : ''}`}.` : '';
102
- scenes.push({
103
- id: 'abertura',
104
- title: name,
105
- narration: [sentence(name), after ? `O que muda para quem usa: ${sentence(after)}` : sentence(r.description), took].filter(Boolean).join(' ').replace(/\s+/g, ' ').trim(),
106
- body: `${today || after
107
- ? `<p class="lead">${today ? `<b>Hoje:</b> ${esc(today)}<br>` : ''}${after ? `<b>Depois:</b> ${esc(after)}` : ''}</p>`
108
- : `<p class="lead">${esc(r.description ?? '')}</p>`}${r.days !== null ? `<p class="big">${r.days === 0 ? '< 1' : r.days} <span>dia${r.days <= 1 ? '' : 's'}</span></p>` : ''}`,
109
- });
110
- if (r.scenarios.length) {
111
- const ok = r.scenarios.filter((c) => c.status === 'PROVADO').length;
112
- const total = r.scenarios.length;
113
- const judged = r.scenarios.some((c) => c.status);
114
- const proof = judged
115
- ? `${ok} de ${total} ${total === 1 ? 'cenário conferido' : 'cenários conferidos'} pela revisão independente.`
116
- : `${total} ${total === 1 ? 'cenário' : 'cenários'}, sem conferência cenário a cenário da revisão independente.`;
117
- scenes.push({
118
- id: 'cenarios',
119
- title: 'A prova',
120
- narration: `${proof} ${r.scenarios.slice(0, 4).map((c) => `${sentence(scenarioLabel(c))}`).join(' ')}`.trim(),
121
- body: `<ul class="checks">${r.scenarios.map((c, i) => {
122
- const [tone, glyph] = PROOF_MARK[c.status] ?? ['warn', '·'];
123
- const said = CHECK_RESULT_SAY[c.status] ?? 'sem conferência';
124
- return `<li style="--i:${i}"><b class="${tone}">${glyph}</b><span>${esc(scenarioLabel(c))} <small>${esc(said)}${c.evidence ? `: ${esc(c.evidence)}` : ''}</small></span></li>`;
125
- }).join('')}</ul>`,
126
- });
127
- }
128
- if (r.gates.length) {
129
- const human = r.gates.filter((g) => g.paused);
130
- const approved = r.gates.filter((g) => g.approved).length;
131
- scenes.push({
132
- id: 'gates',
133
- title: 'Por onde passou',
134
- narration: `${approved} ${approved === 1 ? 'aprovação' : 'aprovações'} no caminho. ${human.length ? `Parou para você em ${human.map((g) => GATE_NAME[g.gate]).join(' e ')}.` : 'Nenhuma parada para você.'}`,
135
- body: `<ol class="gates">${r.gates.map((g, i) => `<li style="--i:${i}"><b class="${g.approved ? 'ok' : 'warn'}">${g.approved ? '✓' : '·'}</b> ${esc(GATE_NAME[g.gate])}${g.approvedBy ? ` <small>por ${esc(g.approvedBy)}</small>` : ''}${g.paused && g.reason ? `<small class="why">parou porque: ${esc(g.reason)}</small>` : ''}</li>`).join('')}</ol>`,
136
- });
137
- }
138
- if (r.transitions.length) {
139
- const states = new Set(r.transitions.flatMap((t) => [t.from, t.to]));
140
- scenes.push({
141
- id: 'estados',
142
- title: 'Como os estados andam',
143
- narration: `${states.size} estados e ${r.transitions.length} transições. ${r.transitions.slice(0, 4).map((t) => `De ${t.from} para ${t.to}, quando ${t.trigger}.`).join(' ')}`,
144
- body: `<div class="machine-box">${stateMachineSvg(r.transitions)}</div>`,
145
- });
146
- }
147
- if (r.changes) {
148
- const { stat, tree } = r.changes;
149
- const rows = tree ? flatten(tree, 14) : [];
150
- scenes.push({
151
- id: 'mudancas',
152
- title: 'O que mudou no código',
153
- narration: tree
154
- ? `${tree.counts.added} símbolos novos e ${tree.counts.modified} alterados em ${stat.files} arquivos. ${tree.roots.slice(0, 3).map((n) => n.label.replace(/\(\)$/, '')).join(', ')} são os pontos de entrada.`
155
- : `${stat.files} arquivos, ${stat.added} linhas a mais e ${stat.removed} a menos.`,
156
- body: `<p class="stat"><b>${stat.files}</b> arquivos <b class="ok">+${stat.added}</b> <b class="bad">−${stat.removed}</b></p>${rows.length
157
- ? `<ul class="tree">${rows.map((n, i) => `<li style="--i:${i};--d:${n.depth}"><b class="${n.mark === '+' ? 'ok' : 'warn'}">${n.mark}</b> ${esc(n.label)}${n.again ? ' <small>↑</small>' : ''} <small>${esc(n.file)}</small></li>`).join('')}</ul>`
158
- : ''}`,
159
- });
160
- }
161
- return scenes;
162
- }
163
-
164
- const SCENE_MS = 9000;
165
- const TOKENS = readFileSync(new URL('../view/tokens.css', import.meta.url), 'utf8');
166
-
167
- /** `audio`: optional `{ [sceneId]: dataUri }`; without it the page narrates with the system voice. */
168
- export function renderRecapHtml(r, { audio = null } = {}) {
169
- const scenes = recapScenes(r);
170
- const data = JSON.stringify(scenes.map((s) => ({ id: s.id, narration: s.narration, audio: audio?.[s.id] ?? null }))).replace(/</g, '\\u003c');
171
- return `<!doctype html>
172
- <html lang="pt-BR">
173
- <head>
174
- <meta charset="utf-8">
175
- <meta name="viewport" content="width=device-width, initial-scale=1">
176
- <title>Recap — ${esc(r.name ?? r.feature)}</title>
177
- <style>
178
- ${TOKENS}:root { --bg:var(--paper); --card:var(--panel); --fg:var(--ink); --hair:var(--rule); --accent:var(--route); }
179
- * { box-sizing:border-box; }
180
- body { margin:0; min-height:100vh; background:var(--bg); color:var(--fg); font:16px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; display:flex; flex-direction:column; }
181
- .stage { flex:1; position:relative; max-width:960px; width:100%; margin:0 auto; padding:40px 16px 16px; }
182
- .scene { position:absolute; inset:40px 16px 16px; opacity:0; transform:translateY(12px); transition:opacity .6s, transform .6s; pointer-events:none; overflow:auto; }
183
- .scene.on { opacity:1; transform:none; pointer-events:auto; }
184
- h1 { font-size:clamp(26px, 5vw, 44px); margin:0 0 20px; letter-spacing:-.02em; }
185
- .lead { font-size:20px; color:var(--dim); max-width:60ch; }
186
- .big { font-size:72px; font-weight:700; margin:24px 0 0; } .big span { font-size:20px; color:var(--faint); font-weight:400; }
187
- ul, ol { list-style:none; padding:0; margin:0; }
188
- .on li { animation:rise .5s both; animation-delay:calc(var(--i) * 120ms + 300ms); }
189
- @keyframes rise { from { opacity:0; transform:translateY(8px); } }
190
- @media (prefers-reduced-motion: reduce) { .scene, .on li { transition:none; animation:none; } }
191
- .checks li, .gates li { display:flex; gap:12px; padding:10px 0; border-bottom:1px solid var(--hair); }
192
- .checks em { font-style:normal; font-weight:600; color:var(--accent); margin-right:6px; }
193
- small { display:block; color:var(--faint); font-size:13px; }
194
- .tree li small, .gates li small { display:inline; margin-left:6px; }
195
- .gates .why { display:block; margin:4px 0 0; }
196
- .tree li { padding:4px 0 4px calc(var(--d) * 22px); font:14px/1.5 ui-monospace, monospace; }
197
- .stat { font-size:22px; } .stat b { margin-right:4px; }
198
- .ok { color:var(--ok); } .warn { color:var(--warn); } .bad { color:var(--bad); }
199
- .machine-box { background:var(--card); border:1px solid var(--hair); border-radius:12px; padding:12px; overflow-x:auto; }
200
- .machine .state rect { fill:var(--bg); stroke:var(--accent); stroke-width:1.5; } .machine .state text { fill:var(--fg); font:600 13px system-ui; }
201
- .machine .edge { fill:none; stroke:var(--faint); stroke-width:1.5; } .machine .arrow-head { fill:var(--faint); }
202
- .machine .edge-label { fill:var(--dim); font:12px system-ui; paint-order:stroke; stroke:var(--card); stroke-width:4px; }
203
- .bar { position:sticky; bottom:0; background:var(--card); border-top:1px solid var(--hair); }
204
- .caption { max-width:960px; margin:0 auto; padding:12px 16px 4px; color:var(--dim); min-height:3.2em; }
205
- .controls { max-width:960px; margin:0 auto; padding:4px 16px 12px; display:flex; gap:8px; align-items:center; flex-wrap:wrap; }
206
- button { background:transparent; color:var(--fg); border:1px solid var(--hair); border-radius:999px; padding:6px 14px; font:inherit; font-size:14px; cursor:pointer; min-height:36px; }
207
- button[aria-pressed="true"] { border-color:var(--accent); color:var(--accent); }
208
- .dots { margin-left:auto; display:flex; gap:6px; } .dots i { width:8px; height:8px; border-radius:50%; background:var(--hair); } .dots i.on { background:var(--accent); }
209
- </style>
210
- </head>
211
- <body>
212
- <main class="stage">
213
- ${scenes.map((s, i) => `<section class="scene${i === 0 ? ' on' : ''}" data-scene="${i}" aria-hidden="${i !== 0}"><h1>${esc(s.title)}</h1>${s.body}</section>`).join('\n')}
214
- </main>
215
- <div class="bar">
216
- <p class="caption" aria-live="polite"></p>
217
- <div class="controls">
218
- <button id="play">▶ Tocar</button><button id="prev">←</button><button id="next">→</button><button id="voice" aria-pressed="true">Narração</button>
219
- <span class="dots">${scenes.map(() => '<i></i>').join('')}</span>
220
- </div>
221
- </div>
222
- <script>
223
- const SCENES = ${data};
224
- const els = [...document.querySelectorAll('.scene')], dots = [...document.querySelectorAll('.dots i')];
225
- const caption = document.querySelector('.caption'), voiceBtn = document.getElementById('voice'), playBtn = document.getElementById('play');
226
- let at = 0, playing = false, timer = null, clip = null;
227
- const voiceOn = () => voiceBtn.getAttribute('aria-pressed') === 'true';
228
- function stopSound() { clearTimeout(timer); if (clip) { clip.pause(); clip = null; } if (window.speechSynthesis) speechSynthesis.cancel(); }
229
- function advance() { if (playing && at < SCENES.length - 1) show(at + 1); else { playing = false; playBtn.textContent = '▶ Tocar'; } }
230
- function speak(s) {
231
- if (!playing) return;
232
- if (voiceOn() && s.audio) { clip = new Audio(s.audio); clip.onended = advance; clip.play().catch(() => { timer = setTimeout(advance, ${SCENE_MS}); }); return; }
233
- if (voiceOn() && window.speechSynthesis) {
234
- const u = new SpeechSynthesisUtterance(s.narration); u.lang = 'pt-BR';
235
- const v = speechSynthesis.getVoices().find((x) => x.lang && x.lang.toLowerCase().startsWith('pt'));
236
- if (v) u.voice = v;
237
- u.onend = advance; u.onerror = () => { timer = setTimeout(advance, ${SCENE_MS}); };
238
- speechSynthesis.speak(u); return;
239
- }
240
- timer = setTimeout(advance, ${SCENE_MS});
241
- }
242
- function show(i) {
243
- stopSound(); at = i;
244
- els.forEach((e, k) => { e.classList.toggle('on', k === i); e.setAttribute('aria-hidden', String(k !== i)); });
245
- dots.forEach((d, k) => d.classList.toggle('on', k === i));
246
- caption.textContent = SCENES[i].narration;
247
- speak(SCENES[i]);
248
- }
249
- playBtn.onclick = () => { playing = !playing; playBtn.textContent = playing ? '❚❚ Pausar' : '▶ Tocar'; if (playing) show(at); else stopSound(); };
250
- document.getElementById('prev').onclick = () => show(Math.max(0, at - 1));
251
- document.getElementById('next').onclick = () => show(Math.min(SCENES.length - 1, at + 1));
252
- voiceBtn.onclick = () => { voiceBtn.setAttribute('aria-pressed', String(!voiceOn())); if (!voiceOn()) stopSound(); };
253
- document.addEventListener('keydown', (e) => { if (e.key === 'ArrowRight') document.getElementById('next').click(); if (e.key === 'ArrowLeft') document.getElementById('prev').click(); if (e.key === ' ') { e.preventDefault(); playBtn.click(); } });
254
- caption.textContent = SCENES[0].narration; dots[0].classList.add('on');
255
- </script>
256
- </body>
257
- </html>
258
- `;
259
- }
@@ -1,66 +0,0 @@
1
- import { execFileSync } from 'child_process';
2
- import { basename } from 'path';
3
- import { treeMovedSince } from './git/evidence-staleness.js';
4
- import { isTestOnly, securityReviewFor } from './risk-detector.js';
5
- import { deltaRisk } from './risk/diff-risk.js';
6
-
7
- function resolveCommit(cwd, ref) {
8
- try {
9
- return execFileSync('git', ['rev-parse', '--verify', `${ref}^{commit}`], { cwd, stdio: 'pipe' }).toString().trim();
10
- } catch {
11
- return null;
12
- }
13
- }
14
-
15
- function changedBetween(cwd, from, to) {
16
- try {
17
- return execFileSync('git', ['diff', '--name-only', '--no-renames', from, to, '--', '.', ':(exclude).morph'], { cwd, stdio: 'pipe' })
18
- .toString().split('\n').map((line) => line.trim()).filter(Boolean);
19
- } catch {
20
- return null;
21
- }
22
- }
23
-
24
- function citedByBlockers(reports) {
25
- return Object.values(reports)
26
- .flatMap((report) => report.rounds ?? [])
27
- .flatMap((round) => round.blockers ?? [])
28
- .map((blocker) => `${blocker.where} ${blocker.evidence}`)
29
- .join('\n');
30
- }
31
-
32
- const openedBlockers = (report) => (report.rounds ?? []).some((round) => (round.blockers ?? []).length > 0);
33
- const isCleanShip = (report) => report.verdict === 'SHIP' && (report.blockers ?? []).length === 0;
34
-
35
- function deltaIsNarrow(role, delta, cited) {
36
- if (delta === null) return false;
37
- if (role === 'security') return !securityReviewFor(delta).required;
38
- return delta.every((file) => isTestOnly(file) || cited.includes(file) || cited.includes(basename(file)));
39
- }
40
-
41
- /**
42
- * The one oracle of "this review is stale", read by `approve` and by `report-check` alike. A delta that
43
- * touches only `.morph/`, docs, config, imports or comments (`deltaRisk` trivial) moves no role. Otherwise a
44
- * role that shipped clean need not return when the delta stays inside what the blockers named or in
45
- * tests (security: no sensitive path), and only once a role that opened blockers re-judged `head`.
46
- */
47
- export function reviewConfirmation(cwd, reports, head) {
48
- const cited = citedByBlockers(reports);
49
- const behind = [];
50
- let confirmed = false;
51
-
52
- for (const [role, report] of Object.entries(reports)) {
53
- if (report.status === 'missing' || !report.reviewedSha) continue;
54
- const reviewed = resolveCommit(cwd, report.reviewedSha);
55
- if (!reviewed) continue;
56
- if (!treeMovedSince(cwd, reviewed, head) || deltaRisk(cwd, reviewed, head)?.trivial) {
57
- if (openedBlockers(report)) confirmed = true;
58
- continue;
59
- }
60
- behind.push({ role, reviewed, narrow: isCleanShip(report) && deltaIsNarrow(role, changedBetween(cwd, reviewed, head), cited) });
61
- }
62
-
63
- const anyBlockers = Object.values(reports).some(openedBlockers);
64
- const moved = behind.map(({ narrow, ...m }) => ({ ...m, skippable: narrow && (confirmed || !anyBlockers) }));
65
- return { moved, confirmed };
66
- }
@@ -1,137 +0,0 @@
1
- import { execFileSync } from 'child_process';
2
- import { minimatch } from 'minimatch';
3
- import { readMorphConfig } from '../tasks/test-runner.js';
4
- import { isTestPath } from '../graph/sanitize.js';
5
- import { contractsTouched, migrationsTouched, securityReviewFor } from '../risk-detector.js';
6
-
7
- const DOC_PATH = /(^|\/)docs\/|\.(md|mdx|txt|rst|adoc|png|jpe?g|gif|svg|webp|ico)$/i;
8
- const CONFIG_PATH = /\.(json|jsonc|ya?ml|toml|ini|xml|editorconfig|env\.example)$|(^|\/)\.(gitignore|gitattributes|npmrc|nvmrc|prettierrc|eslintignore)$/i;
9
- // Resolves or compiles everything: a change here reaches code the diff does not name.
10
- const WIDE_PATH = /(^|\/)(package(-lock)?\.json|pnpm-lock\.yaml|yarn\.lock|global\.json|Directory\.(Build|Packages)\.(props|targets)|tsconfig[^/]*\.json|[^/]+\.(csproj|sln|slnx|props|targets))$/i;
11
- const TRIVIAL_LINE = /^\s*(|\/\/.*|#(?!include).*|\/\*.*|\*.*|\*\/|--.*|(import|using|export\s+\*\s+from|#include)\b.*|.*\brequire\(['"][^'"]+['"]\);?\s*)$/;
12
- // PII, permission, sending to a third party, payment, contract: what turns a diff into a security review.
13
- export const SENSITIVE_LINE = /\b(pii|lgpd|gdpr|cpf|cnpj|redact\w*|anonimi\w*|opt.?out|dnd|consent\w*|permiss\w*|authoriz\w*|autoriza\w*|requirerole|isadmin|password|senha|secret|apikey|api_key|whatsapp|sendmessage|sendtemplate|sms|webhook|smtp|sendemail|payment|pagamento|cobran\w*|invoice|fatura|checkout|refund|estorno|stripe|asaas|contrato)\b/i;
14
-
15
- const camelSplit = (path) => path.replace(/([a-z0-9])([A-Z])/g, '$1-$2');
16
-
17
- function git(cwd, args) {
18
- return execFileSync('git', args, { cwd, stdio: 'pipe', maxBuffer: 256 * 1024 * 1024 }).toString();
19
- }
20
-
21
- // An agent reads these as instructions: a changed sentence is changed behaviour, whatever the extension.
22
- const PROMPT_PATH = /(^|\/)(prompts?|agents?|skills?|playbooks?|personas?|instructions?|\.claude)\/|(^|\/)(CLAUDE|AGENTS|GEMINI|MORPH|SKILL|copilot-instructions)\.md$|prompt[^/]*$/i;
23
-
24
- export function isPromptPath(path, promptGlobs = []) {
25
- return PROMPT_PATH.test(path) || promptGlobs.some((g) => minimatch(path, g));
26
- }
27
-
28
- export function fileClass(path, promptGlobs = []) {
29
- if (path.startsWith('.morph/')) return 'state';
30
- if (isPromptPath(path, promptGlobs)) return 'code';
31
- if (DOC_PATH.test(path)) return 'doc';
32
- if (CONFIG_PATH.test(path) && !WIDE_PATH.test(path)) return 'config';
33
- return isTestPath(path) || /(^|\/)e2e\//.test(path) ? 'test' : 'code';
34
- }
35
-
36
- /** Per file: `added`/`removed` lines and `deleted` (the whole file went away). */
37
- export function diffLines(cwd, from, to = null) {
38
- const range = to ? [from, to] : [from];
39
- const text = git(cwd, ['-c', 'core.quotepath=off', 'diff', '-U0', '--no-color', '--no-ext-diff', '--no-renames', ...range, '--', '.']);
40
- const files = new Map();
41
- let current = null;
42
- for (const line of text.split('\n')) {
43
- if (line.startsWith('diff --git ')) {
44
- const path = line.split(' b/').pop();
45
- current = { path, added: [], removed: [], deleted: false };
46
- files.set(path, current);
47
- } else if (!current) {
48
- continue;
49
- } else if (line.startsWith('deleted file mode')) {
50
- current.deleted = true;
51
- } else if (line.startsWith('+') && !line.startsWith('+++')) {
52
- current.added.push(line.slice(1));
53
- } else if (line.startsWith('-') && !line.startsWith('---')) {
54
- current.removed.push(line.slice(1));
55
- }
56
- }
57
- if (!to) {
58
- for (const path of git(cwd, ['ls-files', '--others', '--exclude-standard']).split('\n').filter(Boolean)) {
59
- files.set(path, { path, added: [''], removed: [], deleted: false, untracked: true });
60
- }
61
- }
62
- return [...files.values()];
63
- }
64
-
65
- /** `trivial` = only imports, comments, blank lines; `removal` = logic only taken out; `logic` = logic added. */
66
- export function changeKind(file) {
67
- // A prompt has no comments: a heading or a bullet is an instruction.
68
- if (file.prompt) return [...file.added, ...file.removed].some((l) => l.trim()) || file.deleted ? 'logic' : 'trivial';
69
- if (file.deleted) return 'removal';
70
- if (file.untracked) return 'logic';
71
- if (file.added.some((l) => !TRIVIAL_LINE.test(l))) return 'logic';
72
- return file.removed.some((l) => !TRIVIAL_LINE.test(l)) ? 'removal' : 'trivial';
73
- }
74
-
75
- /** `low`: docs, `.morph/`, config, removals, imports. `normal`: logic in code or tests. `security` rides on either. */
76
- export function classifyFiles(files, { promptGlobs = [] } = {}) {
77
- const reasons = [];
78
- const relevant = files
79
- .filter((f) => fileClass(f.path, promptGlobs) !== 'state')
80
- .map((f) => ({ ...f, prompt: isPromptPath(f.path, promptGlobs) }));
81
- const fileClassOf = (f) => (f.prompt ? 'code' : fileClass(f.path));
82
- const logic = relevant.filter((f) => ['code', 'test'].includes(fileClassOf(f)) && changeKind(f) === 'logic');
83
- const wide = relevant.filter((f) => WIDE_PATH.test(f.path));
84
- const paths = relevant.map((f) => f.path);
85
- if (logic.length) reasons.push(`lógica em ${logic.slice(0, 3).map((f) => f.path).join(', ')}${logic.length > 3 ? ` (+${logic.length - 3})` : ''}`);
86
- if (wide.length) reasons.push(`arquivo que alcança o projeto inteiro: ${wide[0].path}`);
87
- const migration = migrationsTouched(paths);
88
- const contract = contractsTouched(paths);
89
- if (migration.length) reasons.push(`migration: ${migration[0]}`);
90
-
91
- const securityReasons = [...securityReviewFor(paths.map(camelSplit)).reasons];
92
- if (contract.length) securityReasons.push(`contrato: ${contract[0]}`);
93
- const sensitive = relevant.find((f) => fileClassOf(f) === 'code' && f.added.some((l) => SENSITIVE_LINE.test(l)));
94
- if (sensitive) {
95
- const line = sensitive.added.find((l) => SENSITIVE_LINE.test(l)).trim();
96
- securityReasons.push(`linha sensível em ${sensitive.path}: ${line.slice(0, 80)}`);
97
- }
98
-
99
- const level = relevant.length === 0 ? 'none' : reasons.length || securityReasons.length ? 'normal' : 'low';
100
- const trivial = level !== 'normal' && relevant.every((f) => !['code', 'test'].includes(fileClassOf(f)) || changeKind(f) === 'trivial');
101
- return { level, trivial, reasons, security: { required: securityReasons.length > 0, reasons: securityReasons } };
102
- }
103
-
104
- // The paths the project declared for its evals are its prompts and models.
105
- function promptGlobsOf(cwd) {
106
- const watch = readMorphConfig(cwd)?.project?.evals?.watch;
107
- return Array.isArray(watch) ? watch.filter((g) => typeof g === 'string' && g.trim()) : [];
108
- }
109
-
110
- function mergeBase(cwd, defaultBranch) {
111
- for (const ref of [`origin/${defaultBranch}`, defaultBranch]) {
112
- try {
113
- return git(cwd, ['merge-base', 'HEAD', ref]).trim() || null;
114
- } catch { /* next ref */ }
115
- }
116
- return null;
117
- }
118
-
119
- /** The feature's diff from the merge-base with the default, working tree included; null when git cannot tell. */
120
- export function featureDiffRisk(cwd, defaultBranch) {
121
- const base = defaultBranch ? mergeBase(cwd, defaultBranch) : null;
122
- if (!base) return null;
123
- try {
124
- return { base, ...classifyFiles(diffLines(cwd, base), { promptGlobs: promptGlobsOf(cwd) }) };
125
- } catch {
126
- return null;
127
- }
128
- }
129
-
130
- /** The delta between two commits; `trivial` (no logic added or removed) never asks for a second review. */
131
- export function deltaRisk(cwd, from, to) {
132
- try {
133
- return classifyFiles(diffLines(cwd, from, to), { promptGlobs: promptGlobsOf(cwd) });
134
- } catch {
135
- return null;
136
- }
137
- }