@pareto4/pp-core 1.5.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 (618) hide show
  1. package/.claude-plugin/plugin.json +23 -0
  2. package/GEMINI.md +53 -0
  3. package/LICENSE +22 -0
  4. package/README.md +100 -0
  5. package/agents/pp-advisor-researcher.md +108 -0
  6. package/agents/pp-ai-researcher.md +114 -0
  7. package/agents/pp-assumptions-analyzer.md +105 -0
  8. package/agents/pp-code-fixer.md +669 -0
  9. package/agents/pp-code-reviewer.md +387 -0
  10. package/agents/pp-codebase-mapper.md +853 -0
  11. package/agents/pp-debug-session-manager.md +315 -0
  12. package/agents/pp-debugger.md +1453 -0
  13. package/agents/pp-doc-classifier.md +168 -0
  14. package/agents/pp-doc-synthesizer.md +204 -0
  15. package/agents/pp-doc-verifier.md +217 -0
  16. package/agents/pp-doc-writer.md +616 -0
  17. package/agents/pp-domain-researcher.md +147 -0
  18. package/agents/pp-eval-auditor.md +191 -0
  19. package/agents/pp-eval-planner.md +154 -0
  20. package/agents/pp-executor.md +808 -0
  21. package/agents/pp-framework-selector.md +160 -0
  22. package/agents/pp-integration-checker.md +470 -0
  23. package/agents/pp-intel-updater.md +339 -0
  24. package/agents/pp-mempalace-curator.md +47 -0
  25. package/agents/pp-nyquist-auditor.md +204 -0
  26. package/agents/pp-pattern-mapper.md +335 -0
  27. package/agents/pp-phase-researcher.md +867 -0
  28. package/agents/pp-plan-checker.md +988 -0
  29. package/agents/pp-planner.md +1052 -0
  30. package/agents/pp-project-researcher.md +612 -0
  31. package/agents/pp-research-synthesizer.md +260 -0
  32. package/agents/pp-roadmapper.md +741 -0
  33. package/agents/pp-security-auditor.md +156 -0
  34. package/agents/pp-ui-auditor.md +495 -0
  35. package/agents/pp-ui-checker.md +309 -0
  36. package/agents/pp-ui-researcher.md +375 -0
  37. package/agents/pp-user-profiler.md +171 -0
  38. package/agents/pp-verifier.md +967 -0
  39. package/assets/gsd-logo-2000-transparent.png +0 -0
  40. package/assets/gsd-logo-2000-transparent.svg +17 -0
  41. package/assets/gsd-logo-2000.png +0 -0
  42. package/assets/gsd-logo-2000.svg +21 -0
  43. package/assets/terminal.svg +68 -0
  44. package/bin/install.js +12370 -0
  45. package/bin/lib/ui-safety-gate.cjs +107 -0
  46. package/commands/pp-add-tests.md +42 -0
  47. package/commands/pp-ai-integration-phase.md +37 -0
  48. package/commands/pp-audit-fix.md +34 -0
  49. package/commands/pp-audit-milestone.md +37 -0
  50. package/commands/pp-audit-uat.md +24 -0
  51. package/commands/pp-autonomous.md +51 -0
  52. package/commands/pp-capture.md +62 -0
  53. package/commands/pp-cleanup.md +24 -0
  54. package/commands/pp-code-review.md +59 -0
  55. package/commands/pp-complete-milestone.md +143 -0
  56. package/commands/pp-config.md +56 -0
  57. package/commands/pp-debug.md +52 -0
  58. package/commands/pp-discovery.md +34 -0
  59. package/commands/pp-discuss-phase.md +77 -0
  60. package/commands/pp-docs-update.md +49 -0
  61. package/commands/pp-eval-review.md +33 -0
  62. package/commands/pp-execute-phase.md +65 -0
  63. package/commands/pp-explore.md +27 -0
  64. package/commands/pp-extract-learnings.md +23 -0
  65. package/commands/pp-fast.md +31 -0
  66. package/commands/pp-forensics.md +57 -0
  67. package/commands/pp-graphify.md +204 -0
  68. package/commands/pp-health.md +31 -0
  69. package/commands/pp-help.md +28 -0
  70. package/commands/pp-import.md +45 -0
  71. package/commands/pp-inbox.md +39 -0
  72. package/commands/pp-ingest-docs.md +42 -0
  73. package/commands/pp-manager.md +45 -0
  74. package/commands/pp-map-codebase.md +83 -0
  75. package/commands/pp-mempalace-capture.md +71 -0
  76. package/commands/pp-mempalace-recall.md +102 -0
  77. package/commands/pp-milestone-summary.md +51 -0
  78. package/commands/pp-mvp-phase.md +45 -0
  79. package/commands/pp-new-milestone.md +45 -0
  80. package/commands/pp-new-project.md +47 -0
  81. package/commands/pp-ns-context.md +25 -0
  82. package/commands/pp-ns-ideate.md +24 -0
  83. package/commands/pp-ns-manage.md +36 -0
  84. package/commands/pp-ns-project.md +27 -0
  85. package/commands/pp-ns-review.md +29 -0
  86. package/commands/pp-ns-workflow.md +35 -0
  87. package/commands/pp-pause-work.md +43 -0
  88. package/commands/pp-phase.md +56 -0
  89. package/commands/pp-plan-phase.md +63 -0
  90. package/commands/pp-plan-review-convergence.md +60 -0
  91. package/commands/pp-pr-branch.md +26 -0
  92. package/commands/pp-profile-user.md +46 -0
  93. package/commands/pp-progress.md +49 -0
  94. package/commands/pp-quick.md +174 -0
  95. package/commands/pp-resume-work.md +30 -0
  96. package/commands/pp-review-backlog.md +63 -0
  97. package/commands/pp-review.md +42 -0
  98. package/commands/pp-secure-phase.md +36 -0
  99. package/commands/pp-settings.md +29 -0
  100. package/commands/pp-ship.md +24 -0
  101. package/commands/pp-sketch.md +60 -0
  102. package/commands/pp-spec-phase.md +63 -0
  103. package/commands/pp-spike.md +57 -0
  104. package/commands/pp-stats.md +20 -0
  105. package/commands/pp-surface.md +162 -0
  106. package/commands/pp-thread.md +24 -0
  107. package/commands/pp-ui-phase.md +35 -0
  108. package/commands/pp-ui-review.md +33 -0
  109. package/commands/pp-ultraplan-phase.md +34 -0
  110. package/commands/pp-undo.md +35 -0
  111. package/commands/pp-update.md +49 -0
  112. package/commands/pp-validate-phase.md +36 -0
  113. package/commands/pp-verify-work.md +39 -0
  114. package/commands/pp-workspace.md +52 -0
  115. package/commands/pp-workstreams.md +70 -0
  116. package/gemini-extension.json +6 -0
  117. package/hooks/dist/lib/git-cmd.js +150 -0
  118. package/hooks/dist/lib/pp-graphify-rebuild.sh +65 -0
  119. package/hooks/dist/managed-hooks-registry.cjs +39 -0
  120. package/hooks/dist/pp-check-update-worker.js +108 -0
  121. package/hooks/dist/pp-check-update.js +66 -0
  122. package/hooks/dist/pp-config-reload.js +133 -0
  123. package/hooks/dist/pp-context-monitor.js +196 -0
  124. package/hooks/dist/pp-cursor-post-tool.js +75 -0
  125. package/hooks/dist/pp-cursor-session-start.js +52 -0
  126. package/hooks/dist/pp-ensure-canonical-path.js +305 -0
  127. package/hooks/dist/pp-graphify-update.sh +158 -0
  128. package/hooks/dist/pp-phase-boundary.sh +47 -0
  129. package/hooks/dist/pp-prompt-guard.js +97 -0
  130. package/hooks/dist/pp-read-guard.js +101 -0
  131. package/hooks/dist/pp-read-injection-scanner.js +203 -0
  132. package/hooks/dist/pp-session-state.sh +59 -0
  133. package/hooks/dist/pp-statusline.js +566 -0
  134. package/hooks/dist/pp-update-banner.js +138 -0
  135. package/hooks/dist/pp-validate-commit.sh +57 -0
  136. package/hooks/dist/pp-workflow-guard.js +167 -0
  137. package/hooks/dist/pp-worktree-path-guard.js +185 -0
  138. package/hooks/hooks.json +70 -0
  139. package/hooks/lib/git-cmd.js +150 -0
  140. package/hooks/lib/pp-graphify-rebuild.sh +65 -0
  141. package/hooks/managed-hooks-registry.cjs +39 -0
  142. package/hooks/pp-check-update-worker.js +108 -0
  143. package/hooks/pp-check-update.js +66 -0
  144. package/hooks/pp-config-reload.js +133 -0
  145. package/hooks/pp-context-monitor.js +196 -0
  146. package/hooks/pp-cursor-post-tool.js +75 -0
  147. package/hooks/pp-cursor-session-start.js +52 -0
  148. package/hooks/pp-ensure-canonical-path.js +305 -0
  149. package/hooks/pp-graphify-update.sh +158 -0
  150. package/hooks/pp-phase-boundary.sh +47 -0
  151. package/hooks/pp-prompt-guard.js +97 -0
  152. package/hooks/pp-read-guard.js +101 -0
  153. package/hooks/pp-read-injection-scanner.js +203 -0
  154. package/hooks/pp-session-state.sh +59 -0
  155. package/hooks/pp-statusline.js +566 -0
  156. package/hooks/pp-update-banner.js +138 -0
  157. package/hooks/pp-validate-commit.sh +57 -0
  158. package/hooks/pp-workflow-guard.js +167 -0
  159. package/hooks/pp-worktree-path-guard.js +185 -0
  160. package/package.json +125 -0
  161. package/pp-core/bin/check-latest-version.cjs +161 -0
  162. package/pp-core/bin/lib/active-workstream-store.cjs +297 -0
  163. package/pp-core/bin/lib/adr-parser.cjs +399 -0
  164. package/pp-core/bin/lib/agent-command-router.cjs +68 -0
  165. package/pp-core/bin/lib/agent-install-check.cjs +143 -0
  166. package/pp-core/bin/lib/artifacts.cjs +51 -0
  167. package/pp-core/bin/lib/audit-command-router.cjs +61 -0
  168. package/pp-core/bin/lib/audit.cjs +743 -0
  169. package/pp-core/bin/lib/capability-activation.cjs +113 -0
  170. package/pp-core/bin/lib/capability-registry.cjs +3727 -0
  171. package/pp-core/bin/lib/capability-state.cjs +497 -0
  172. package/pp-core/bin/lib/capability-writer.cjs +355 -0
  173. package/pp-core/bin/lib/check-command-router.cjs +800 -0
  174. package/pp-core/bin/lib/cjs-command-router-adapter.cjs +81 -0
  175. package/pp-core/bin/lib/cli-exit.cjs +61 -0
  176. package/pp-core/bin/lib/clock.cjs +95 -0
  177. package/pp-core/bin/lib/clusters.cjs +131 -0
  178. package/pp-core/bin/lib/code-review-flags.cjs +59 -0
  179. package/pp-core/bin/lib/command-aliases.cjs +809 -0
  180. package/pp-core/bin/lib/command-arg-projection.cjs +55 -0
  181. package/pp-core/bin/lib/command-roster.cjs +19 -0
  182. package/pp-core/bin/lib/command-routing-hub.cjs +300 -0
  183. package/pp-core/bin/lib/commands.cjs +1244 -0
  184. package/pp-core/bin/lib/config-loader.cjs +714 -0
  185. package/pp-core/bin/lib/config-schema.cjs +58 -0
  186. package/pp-core/bin/lib/config-types.cjs +20 -0
  187. package/pp-core/bin/lib/config.cjs +796 -0
  188. package/pp-core/bin/lib/configuration.cjs +209 -0
  189. package/pp-core/bin/lib/context-utilization.cjs +48 -0
  190. package/pp-core/bin/lib/core-utils.cjs +198 -0
  191. package/pp-core/bin/lib/decisions.cjs +136 -0
  192. package/pp-core/bin/lib/docs.cjs +264 -0
  193. package/pp-core/bin/lib/drift.cjs +364 -0
  194. package/pp-core/bin/lib/edge-probe.cjs +196 -0
  195. package/pp-core/bin/lib/fallow-runner.cjs +153 -0
  196. package/pp-core/bin/lib/federated-config.cjs +182 -0
  197. package/pp-core/bin/lib/frontmatter.cjs +494 -0
  198. package/pp-core/bin/lib/gap-checker.cjs +260 -0
  199. package/pp-core/bin/lib/git-base-branch.cjs +220 -0
  200. package/pp-core/bin/lib/graphify-command-router.cjs +72 -0
  201. package/pp-core/bin/lib/graphify.cjs +472 -0
  202. package/pp-core/bin/lib/gsd2-import.cjs +456 -0
  203. package/pp-core/bin/lib/init-command-router.cjs +62 -0
  204. package/pp-core/bin/lib/init.cjs +1912 -0
  205. package/pp-core/bin/lib/install-profiles.cjs +814 -0
  206. package/pp-core/bin/lib/installer-migration-authoring.cjs +122 -0
  207. package/pp-core/bin/lib/installer-migration-report.cjs +351 -0
  208. package/pp-core/bin/lib/installer-migrations/000-first-time-baseline.cjs +225 -0
  209. package/pp-core/bin/lib/installer-migrations/001-legacy-orphan-files.cjs +48 -0
  210. package/pp-core/bin/lib/installer-migrations/002-codex-legacy-hooks-json.cjs +94 -0
  211. package/pp-core/bin/lib/installer-migrations/003-rename-get-shit-done-to-gsd-core.cjs +108 -0
  212. package/pp-core/bin/lib/installer-migrations/004-prune-stale-pristine-snapshots.cjs +123 -0
  213. package/pp-core/bin/lib/installer-migrations/005-rename-gsd-core-to-pp-core.cjs +109 -0
  214. package/pp-core/bin/lib/installer-migrations/006-rename-gsd-command-namespace.cjs +135 -0
  215. package/pp-core/bin/lib/installer-migrations.cjs +823 -0
  216. package/pp-core/bin/lib/intel-command-router.cjs +119 -0
  217. package/pp-core/bin/lib/intel.cjs +584 -0
  218. package/pp-core/bin/lib/io.cjs +220 -0
  219. package/pp-core/bin/lib/learnings.cjs +270 -0
  220. package/pp-core/bin/lib/legacy-cleanup.cjs +253 -0
  221. package/pp-core/bin/lib/loop-host-contract.cjs +105 -0
  222. package/pp-core/bin/lib/loop-resolver.cjs +479 -0
  223. package/pp-core/bin/lib/milestone.cjs +381 -0
  224. package/pp-core/bin/lib/model-catalog.cjs +154 -0
  225. package/pp-core/bin/lib/model-profiles.cjs +24 -0
  226. package/pp-core/bin/lib/model-resolver.cjs +467 -0
  227. package/pp-core/bin/lib/observability/event.cjs +51 -0
  228. package/pp-core/bin/lib/observability/logger.cjs +146 -0
  229. package/pp-core/bin/lib/observability/redaction.cjs +48 -0
  230. package/pp-core/bin/lib/package-identity.cjs +35 -0
  231. package/pp-core/bin/lib/package-legitimacy.cjs +368 -0
  232. package/pp-core/bin/lib/phase-command-router.cjs +209 -0
  233. package/pp-core/bin/lib/phase-id.cjs +213 -0
  234. package/pp-core/bin/lib/phase-lifecycle.cjs +74 -0
  235. package/pp-core/bin/lib/phase-locator.cjs +145 -0
  236. package/pp-core/bin/lib/phase.cjs +1446 -0
  237. package/pp-core/bin/lib/phases-command-router.cjs +43 -0
  238. package/pp-core/bin/lib/plan-drift-guard.cjs +117 -0
  239. package/pp-core/bin/lib/plan-scan.cjs +91 -0
  240. package/pp-core/bin/lib/planning-workspace.cjs +245 -0
  241. package/pp-core/bin/lib/probe-core.cjs +402 -0
  242. package/pp-core/bin/lib/profile-output.cjs +1164 -0
  243. package/pp-core/bin/lib/profile-pipeline-command-router.cjs +138 -0
  244. package/pp-core/bin/lib/profile-pipeline.cjs +519 -0
  245. package/pp-core/bin/lib/prohibition-enforcement.cjs +660 -0
  246. package/pp-core/bin/lib/project-root.cjs +119 -0
  247. package/pp-core/bin/lib/prompt-budget.cjs +305 -0
  248. package/pp-core/bin/lib/research-provider.cjs +137 -0
  249. package/pp-core/bin/lib/research-store.cjs +167 -0
  250. package/pp-core/bin/lib/review-reviewer-selection.cjs +121 -0
  251. package/pp-core/bin/lib/roadmap-command-router.cjs +166 -0
  252. package/pp-core/bin/lib/roadmap-parser.cjs +456 -0
  253. package/pp-core/bin/lib/roadmap-upgrade.cjs +476 -0
  254. package/pp-core/bin/lib/roadmap.cjs +738 -0
  255. package/pp-core/bin/lib/runtime-artifact-conversion.cjs +1966 -0
  256. package/pp-core/bin/lib/runtime-artifact-layout.cjs +342 -0
  257. package/pp-core/bin/lib/runtime-config-adapter-registry.cjs +103 -0
  258. package/pp-core/bin/lib/runtime-homes.cjs +272 -0
  259. package/pp-core/bin/lib/runtime-hooks-surface.cjs +1460 -0
  260. package/pp-core/bin/lib/runtime-name-policy.cjs +97 -0
  261. package/pp-core/bin/lib/runtime-slash.cjs +137 -0
  262. package/pp-core/bin/lib/schema-detect.cjs +159 -0
  263. package/pp-core/bin/lib/secrets.cjs +34 -0
  264. package/pp-core/bin/lib/security.cjs +480 -0
  265. package/pp-core/bin/lib/semver-compare.cjs +42 -0
  266. package/pp-core/bin/lib/shell-command-projection.cjs +550 -0
  267. package/pp-core/bin/lib/state-command-router.cjs +172 -0
  268. package/pp-core/bin/lib/state-document.cjs +312 -0
  269. package/pp-core/bin/lib/state.cjs +2587 -0
  270. package/pp-core/bin/lib/surface.cjs +505 -0
  271. package/pp-core/bin/lib/task-command-router.cjs +85 -0
  272. package/pp-core/bin/lib/teams-status.cjs +74 -0
  273. package/pp-core/bin/lib/template.cjs +246 -0
  274. package/pp-core/bin/lib/uat-predicate.cjs +329 -0
  275. package/pp-core/bin/lib/uat.cjs +359 -0
  276. package/pp-core/bin/lib/ui-safety-gate.cjs +98 -0
  277. package/pp-core/bin/lib/update-context.cjs +221 -0
  278. package/pp-core/bin/lib/validate-command-router.cjs +91 -0
  279. package/pp-core/bin/lib/validate.cjs +122 -0
  280. package/pp-core/bin/lib/verification-command-router.cjs +31 -0
  281. package/pp-core/bin/lib/verification.cjs +196 -0
  282. package/pp-core/bin/lib/verify-command-router.cjs +44 -0
  283. package/pp-core/bin/lib/verify.cjs +1932 -0
  284. package/pp-core/bin/lib/workstream-inventory-builder.cjs +81 -0
  285. package/pp-core/bin/lib/workstream-inventory.cjs +147 -0
  286. package/pp-core/bin/lib/workstream-name-policy.cjs +91 -0
  287. package/pp-core/bin/lib/workstream.cjs +386 -0
  288. package/pp-core/bin/lib/worktree-base-ref.cjs +350 -0
  289. package/pp-core/bin/lib/worktree-safety.cjs +985 -0
  290. package/pp-core/bin/pp-tools.cjs +2239 -0
  291. package/pp-core/bin/pp_run +20 -0
  292. package/pp-core/bin/shared/config-defaults.manifest.json +97 -0
  293. package/pp-core/bin/shared/config-schema.manifest.json +176 -0
  294. package/pp-core/bin/shared/model-catalog.json +160 -0
  295. package/pp-core/bin/shared/runtime-aliases.manifest.json +79 -0
  296. package/pp-core/bin/verify-reapply-patches.cjs +400 -0
  297. package/pp-core/contexts/dev.md +21 -0
  298. package/pp-core/contexts/research.md +22 -0
  299. package/pp-core/contexts/review.md +23 -0
  300. package/pp-core/references/agent-contracts.md +79 -0
  301. package/pp-core/references/ai-evals.md +156 -0
  302. package/pp-core/references/ai-frameworks.md +186 -0
  303. package/pp-core/references/artifact-types.md +131 -0
  304. package/pp-core/references/autonomous-smart-discuss.md +277 -0
  305. package/pp-core/references/checkpoints.md +814 -0
  306. package/pp-core/references/common-bug-patterns.md +114 -0
  307. package/pp-core/references/context-budget.md +85 -0
  308. package/pp-core/references/continuation-format.md +253 -0
  309. package/pp-core/references/debugger-philosophy.md +76 -0
  310. package/pp-core/references/decimal-phase-calculation.md +64 -0
  311. package/pp-core/references/doc-conflict-engine.md +91 -0
  312. package/pp-core/references/domain-probes.md +125 -0
  313. package/pp-core/references/edge-probe-fixtures/01-round-half-even/expected-coverage.json +7 -0
  314. package/pp-core/references/edge-probe-fixtures/01-round-half-even/requirements.json +1 -0
  315. package/pp-core/references/edge-probe-fixtures/02-merge-intervals/expected-coverage.json +8 -0
  316. package/pp-core/references/edge-probe-fixtures/02-merge-intervals/requirements.json +1 -0
  317. package/pp-core/references/edge-probe-fixtures/03-truncate-graphemes/expected-coverage.json +7 -0
  318. package/pp-core/references/edge-probe-fixtures/03-truncate-graphemes/requirements.json +1 -0
  319. package/pp-core/references/edge-probe-fixtures/04-money-rounding/expected-coverage.json +7 -0
  320. package/pp-core/references/edge-probe-fixtures/04-money-rounding/requirements.json +1 -0
  321. package/pp-core/references/edge-probe-fixtures/05-list-dedupe/expected-coverage.json +8 -0
  322. package/pp-core/references/edge-probe-fixtures/05-list-dedupe/requirements.json +1 -0
  323. package/pp-core/references/edge-probe-fixtures/06-resolved-mixed/expected-coverage.json +8 -0
  324. package/pp-core/references/edge-probe-fixtures/06-resolved-mixed/requirements.json +1 -0
  325. package/pp-core/references/edge-probe-fixtures/06-resolved-mixed/resolutions.json +4 -0
  326. package/pp-core/references/edge-probe.md +272 -0
  327. package/pp-core/references/execute-mvp-tdd.md +81 -0
  328. package/pp-core/references/executor-examples.md +110 -0
  329. package/pp-core/references/few-shot-examples/plan-checker.md +73 -0
  330. package/pp-core/references/few-shot-examples/verifier.md +109 -0
  331. package/pp-core/references/gate-prompts.md +100 -0
  332. package/pp-core/references/gates.md +70 -0
  333. package/pp-core/references/git-integration.md +298 -0
  334. package/pp-core/references/git-planning-commit.md +40 -0
  335. package/pp-core/references/ios-scaffold.md +123 -0
  336. package/pp-core/references/loop-hook-dispatch.md +61 -0
  337. package/pp-core/references/mandatory-initial-read.md +2 -0
  338. package/pp-core/references/model-profile-resolution.md +38 -0
  339. package/pp-core/references/model-profiles.md +245 -0
  340. package/pp-core/references/mvp-concepts.md +49 -0
  341. package/pp-core/references/phase-argument-parsing.md +61 -0
  342. package/pp-core/references/planner-antipatterns.md +176 -0
  343. package/pp-core/references/planner-chunked.md +49 -0
  344. package/pp-core/references/planner-gap-closure.md +62 -0
  345. package/pp-core/references/planner-graphify-auto-update.md +67 -0
  346. package/pp-core/references/planner-guidance.md +186 -0
  347. package/pp-core/references/planner-human-verify-mode.md +57 -0
  348. package/pp-core/references/planner-interface-context.md +62 -0
  349. package/pp-core/references/planner-load-graph-context.md +36 -0
  350. package/pp-core/references/planner-mvp-mode.md +53 -0
  351. package/pp-core/references/planner-reviews.md +42 -0
  352. package/pp-core/references/planner-revision.md +87 -0
  353. package/pp-core/references/planner-source-audit.md +73 -0
  354. package/pp-core/references/planning-config.md +477 -0
  355. package/pp-core/references/prohibition-probe-fixtures/01-streak-reminder/expected.json +14 -0
  356. package/pp-core/references/prohibition-probe-fixtures/02-clean-utility/expected.json +4 -0
  357. package/pp-core/references/prohibition-probe-fixtures/03-multi-prohibition/expected.json +32 -0
  358. package/pp-core/references/prohibition-probe.md +326 -0
  359. package/pp-core/references/project-skills-discovery.md +19 -0
  360. package/pp-core/references/questioning.md +162 -0
  361. package/pp-core/references/research-documentation-lookup.md +29 -0
  362. package/pp-core/references/research-philosophy.md +29 -0
  363. package/pp-core/references/research-verification-protocol.md +27 -0
  364. package/pp-core/references/revision-loop.md +97 -0
  365. package/pp-core/references/scout-codebase.md +51 -0
  366. package/pp-core/references/skeleton-template.md +48 -0
  367. package/pp-core/references/sketch-interactivity.md +41 -0
  368. package/pp-core/references/sketch-theme-system.md +94 -0
  369. package/pp-core/references/sketch-tooling.md +45 -0
  370. package/pp-core/references/sketch-variant-patterns.md +81 -0
  371. package/pp-core/references/spidr-splitting.md +69 -0
  372. package/pp-core/references/tdd.md +330 -0
  373. package/pp-core/references/thinking-models-debug.md +44 -0
  374. package/pp-core/references/thinking-models-execution.md +50 -0
  375. package/pp-core/references/thinking-models-planning.md +62 -0
  376. package/pp-core/references/thinking-models-research.md +50 -0
  377. package/pp-core/references/thinking-models-verification.md +55 -0
  378. package/pp-core/references/thinking-partner.md +96 -0
  379. package/pp-core/references/ui-brand.md +162 -0
  380. package/pp-core/references/universal-anti-patterns.md +63 -0
  381. package/pp-core/references/user-profiling.md +681 -0
  382. package/pp-core/references/user-story-template.md +58 -0
  383. package/pp-core/references/verification-overrides.md +227 -0
  384. package/pp-core/references/verification-patterns.md +612 -0
  385. package/pp-core/references/verify-mvp-mode.md +85 -0
  386. package/pp-core/references/workstream-flag.md +111 -0
  387. package/pp-core/references/worktree-branch-check.md +44 -0
  388. package/pp-core/references/worktree-path-safety.md +67 -0
  389. package/pp-core/templates/AI-SPEC.md +246 -0
  390. package/pp-core/templates/DEBUG.md +169 -0
  391. package/pp-core/templates/README.md +77 -0
  392. package/pp-core/templates/SECURITY.md +61 -0
  393. package/pp-core/templates/UAT.md +265 -0
  394. package/pp-core/templates/UI-SPEC.md +100 -0
  395. package/pp-core/templates/VALIDATION.md +76 -0
  396. package/pp-core/templates/claude-md.md +145 -0
  397. package/pp-core/templates/codebase/architecture.md +255 -0
  398. package/pp-core/templates/codebase/concerns.md +310 -0
  399. package/pp-core/templates/codebase/conventions.md +307 -0
  400. package/pp-core/templates/codebase/integrations.md +280 -0
  401. package/pp-core/templates/codebase/stack.md +186 -0
  402. package/pp-core/templates/codebase/structure.md +285 -0
  403. package/pp-core/templates/codebase/testing.md +480 -0
  404. package/pp-core/templates/config.json +62 -0
  405. package/pp-core/templates/context.md +352 -0
  406. package/pp-core/templates/continue-here.md +78 -0
  407. package/pp-core/templates/copilot-instructions.md +7 -0
  408. package/pp-core/templates/debug-subagent-prompt.md +91 -0
  409. package/pp-core/templates/dev-preferences.md +21 -0
  410. package/pp-core/templates/discovery.md +146 -0
  411. package/pp-core/templates/discussion-log.md +63 -0
  412. package/pp-core/templates/milestone-archive.md +123 -0
  413. package/pp-core/templates/milestone.md +115 -0
  414. package/pp-core/templates/phase-prompt.md +610 -0
  415. package/pp-core/templates/planner-subagent-prompt.md +117 -0
  416. package/pp-core/templates/project.md +203 -0
  417. package/pp-core/templates/requirements.md +231 -0
  418. package/pp-core/templates/research-project/ARCHITECTURE.md +204 -0
  419. package/pp-core/templates/research-project/FEATURES.md +147 -0
  420. package/pp-core/templates/research-project/PITFALLS.md +200 -0
  421. package/pp-core/templates/research-project/STACK.md +120 -0
  422. package/pp-core/templates/research-project/SUMMARY.md +170 -0
  423. package/pp-core/templates/research.md +592 -0
  424. package/pp-core/templates/retrospective.md +54 -0
  425. package/pp-core/templates/roadmap.md +202 -0
  426. package/pp-core/templates/spec.md +333 -0
  427. package/pp-core/templates/state.md +195 -0
  428. package/pp-core/templates/summary-complex.md +60 -0
  429. package/pp-core/templates/summary-minimal.md +42 -0
  430. package/pp-core/templates/summary-standard.md +49 -0
  431. package/pp-core/templates/summary.md +249 -0
  432. package/pp-core/templates/user-profile.md +146 -0
  433. package/pp-core/templates/user-setup.md +311 -0
  434. package/pp-core/templates/verification-report.md +335 -0
  435. package/pp-core/workflows/_runtime-launcher.snippet.sh +1 -0
  436. package/pp-core/workflows/add-backlog.md +91 -0
  437. package/pp-core/workflows/add-phase.md +113 -0
  438. package/pp-core/workflows/add-tests.md +355 -0
  439. package/pp-core/workflows/add-todo.md +161 -0
  440. package/pp-core/workflows/ai-integration-phase.md +295 -0
  441. package/pp-core/workflows/analyze-dependencies.md +96 -0
  442. package/pp-core/workflows/audit-fix.md +178 -0
  443. package/pp-core/workflows/audit-milestone.md +362 -0
  444. package/pp-core/workflows/audit-uat.md +110 -0
  445. package/pp-core/workflows/autonomous.md +886 -0
  446. package/pp-core/workflows/check-todos.md +180 -0
  447. package/pp-core/workflows/cleanup.md +195 -0
  448. package/pp-core/workflows/code-review-fix.md +506 -0
  449. package/pp-core/workflows/code-review.md +696 -0
  450. package/pp-core/workflows/complete-milestone.md +857 -0
  451. package/pp-core/workflows/debug.md +237 -0
  452. package/pp-core/workflows/diagnose-issues.md +245 -0
  453. package/pp-core/workflows/discovery-phase.md +291 -0
  454. package/pp-core/workflows/discovery-sprint.md +1546 -0
  455. package/pp-core/workflows/discuss-phase/modes/advisor.md +176 -0
  456. package/pp-core/workflows/discuss-phase/modes/all.md +28 -0
  457. package/pp-core/workflows/discuss-phase/modes/analyze.md +44 -0
  458. package/pp-core/workflows/discuss-phase/modes/auto.md +57 -0
  459. package/pp-core/workflows/discuss-phase/modes/batch.md +52 -0
  460. package/pp-core/workflows/discuss-phase/modes/chain.md +98 -0
  461. package/pp-core/workflows/discuss-phase/modes/default.md +141 -0
  462. package/pp-core/workflows/discuss-phase/modes/power.md +44 -0
  463. package/pp-core/workflows/discuss-phase/modes/text.md +55 -0
  464. package/pp-core/workflows/discuss-phase/templates/checkpoint.json +18 -0
  465. package/pp-core/workflows/discuss-phase/templates/context.md +136 -0
  466. package/pp-core/workflows/discuss-phase/templates/discussion-log.md +50 -0
  467. package/pp-core/workflows/discuss-phase-assumptions.md +675 -0
  468. package/pp-core/workflows/discuss-phase-power.md +291 -0
  469. package/pp-core/workflows/discuss-phase.md +520 -0
  470. package/pp-core/workflows/do.md +111 -0
  471. package/pp-core/workflows/docs-update.md +1168 -0
  472. package/pp-core/workflows/edit-phase.md +295 -0
  473. package/pp-core/workflows/eval-review.md +159 -0
  474. package/pp-core/workflows/execute-phase/steps/codebase-drift-gate.md +95 -0
  475. package/pp-core/workflows/execute-phase/steps/per-plan-worktree-gate.md +94 -0
  476. package/pp-core/workflows/execute-phase/steps/post-merge-gate.md +117 -0
  477. package/pp-core/workflows/execute-phase/steps/worktree-recovery-policy.md +9 -0
  478. package/pp-core/workflows/execute-phase.md +1707 -0
  479. package/pp-core/workflows/execute-plan.md +541 -0
  480. package/pp-core/workflows/explore.md +146 -0
  481. package/pp-core/workflows/extract-learnings.md +243 -0
  482. package/pp-core/workflows/fast.md +124 -0
  483. package/pp-core/workflows/forensics.md +279 -0
  484. package/pp-core/workflows/graduation.md +196 -0
  485. package/pp-core/workflows/health.md +224 -0
  486. package/pp-core/workflows/help/modes/brief.md +22 -0
  487. package/pp-core/workflows/help/modes/default.md +50 -0
  488. package/pp-core/workflows/help/modes/full.md +791 -0
  489. package/pp-core/workflows/help/modes/topic.md +74 -0
  490. package/pp-core/workflows/help.md +24 -0
  491. package/pp-core/workflows/import.md +256 -0
  492. package/pp-core/workflows/inbox.md +387 -0
  493. package/pp-core/workflows/ingest-docs.md +340 -0
  494. package/pp-core/workflows/insert-phase.md +152 -0
  495. package/pp-core/workflows/list-phase-assumptions.md +178 -0
  496. package/pp-core/workflows/list-workspaces.md +57 -0
  497. package/pp-core/workflows/manager.md +435 -0
  498. package/pp-core/workflows/map-codebase.md +444 -0
  499. package/pp-core/workflows/milestone-summary.md +224 -0
  500. package/pp-core/workflows/mvp-phase.md +222 -0
  501. package/pp-core/workflows/new-milestone.md +643 -0
  502. package/pp-core/workflows/new-project.md +1563 -0
  503. package/pp-core/workflows/new-workspace.md +240 -0
  504. package/pp-core/workflows/next.md +347 -0
  505. package/pp-core/workflows/node-repair.md +92 -0
  506. package/pp-core/workflows/note.md +158 -0
  507. package/pp-core/workflows/pause-work.md +250 -0
  508. package/pp-core/workflows/plan-milestone-gaps.md +281 -0
  509. package/pp-core/workflows/plan-phase.md +1755 -0
  510. package/pp-core/workflows/plan-review-convergence.md +369 -0
  511. package/pp-core/workflows/plant-seed.md +230 -0
  512. package/pp-core/workflows/pr-branch.md +159 -0
  513. package/pp-core/workflows/profile-user.md +455 -0
  514. package/pp-core/workflows/progress.md +756 -0
  515. package/pp-core/workflows/quick.md +1045 -0
  516. package/pp-core/workflows/reapply-patches.md +443 -0
  517. package/pp-core/workflows/remove-phase.md +156 -0
  518. package/pp-core/workflows/remove-workspace.md +108 -0
  519. package/pp-core/workflows/resume-project.md +348 -0
  520. package/pp-core/workflows/review.md +765 -0
  521. package/pp-core/workflows/scan.md +107 -0
  522. package/pp-core/workflows/secure-phase.md +184 -0
  523. package/pp-core/workflows/session-report.md +146 -0
  524. package/pp-core/workflows/settings-advanced.md +816 -0
  525. package/pp-core/workflows/settings-integrations.md +312 -0
  526. package/pp-core/workflows/settings.md +592 -0
  527. package/pp-core/workflows/ship.md +465 -0
  528. package/pp-core/workflows/sketch-wrap-up.md +286 -0
  529. package/pp-core/workflows/sketch.md +361 -0
  530. package/pp-core/workflows/spec-phase.md +495 -0
  531. package/pp-core/workflows/spike-wrap-up.md +307 -0
  532. package/pp-core/workflows/spike.md +453 -0
  533. package/pp-core/workflows/stats.md +80 -0
  534. package/pp-core/workflows/sync-skills.md +182 -0
  535. package/pp-core/workflows/thread.md +222 -0
  536. package/pp-core/workflows/transition.md +694 -0
  537. package/pp-core/workflows/ui-phase.md +328 -0
  538. package/pp-core/workflows/ui-review.md +193 -0
  539. package/pp-core/workflows/ultraplan-phase.md +199 -0
  540. package/pp-core/workflows/undo.md +314 -0
  541. package/pp-core/workflows/update.md +501 -0
  542. package/pp-core/workflows/validate-phase.md +183 -0
  543. package/pp-core/workflows/verify-phase.md +569 -0
  544. package/pp-core/workflows/verify-work.md +804 -0
  545. package/scripts/affected-tests-lib.cjs +554 -0
  546. package/scripts/audit-workflow-script-paths.cjs +73 -0
  547. package/scripts/base64-scan.sh +351 -0
  548. package/scripts/build-hooks.js +254 -0
  549. package/scripts/changeset/README.md +129 -0
  550. package/scripts/changeset/cli.cjs +597 -0
  551. package/scripts/changeset/github-release-notes.cjs +199 -0
  552. package/scripts/changeset/lint.cjs +147 -0
  553. package/scripts/changeset/new.cjs +151 -0
  554. package/scripts/changeset/parse.cjs +114 -0
  555. package/scripts/changeset/render.cjs +34 -0
  556. package/scripts/changeset/serialize.cjs +130 -0
  557. package/scripts/check-alias-drift.cjs +114 -0
  558. package/scripts/check-env.cjs +312 -0
  559. package/scripts/check-npm-integrity.cjs +215 -0
  560. package/scripts/ci-guard-runner.cjs +22 -0
  561. package/scripts/ci-prepare-test-scope.cjs +93 -0
  562. package/scripts/ci-rebase-check.cjs +86 -0
  563. package/scripts/ci-test-scope.cjs +441 -0
  564. package/scripts/command-contract-helpers.cjs +64 -0
  565. package/scripts/diff-touches-shipped-paths.cjs +149 -0
  566. package/scripts/fix-slash-commands.cjs +161 -0
  567. package/scripts/gen-capability-registry.cjs +2646 -0
  568. package/scripts/gen-commands-reference.cjs +139 -0
  569. package/scripts/gen-inventory-manifest.cjs +114 -0
  570. package/scripts/gen-loop-host-contract.cjs +526 -0
  571. package/scripts/gen-research-agents.cjs +276 -0
  572. package/scripts/generate-package-identity.cjs +134 -0
  573. package/scripts/issue-dedupe.cjs +278 -0
  574. package/scripts/issue-version-gate.cjs +140 -0
  575. package/scripts/lib/allowlist-ratchet.cjs +236 -0
  576. package/scripts/lib/cli-exit.cjs +56 -0
  577. package/scripts/lint-allow-test-rule-refs.allowlist.json +328 -0
  578. package/scripts/lint-allow-test-rule-refs.cjs +162 -0
  579. package/scripts/lint-command-contract.cjs +118 -0
  580. package/scripts/lint-descriptions.cjs +87 -0
  581. package/scripts/lint-docs-required.cjs +222 -0
  582. package/scripts/lint-legacy-dir-name.cjs +166 -0
  583. package/scripts/lint-package-identity-drift.cjs +141 -0
  584. package/scripts/lint-pr-check-project-dir.cjs +99 -0
  585. package/scripts/lint-regression-test-names.allowlist.json +269 -0
  586. package/scripts/lint-regression-test-names.cjs +117 -0
  587. package/scripts/lint-shell-command-projection-drift.cjs +62 -0
  588. package/scripts/lint-skill-deps.cjs +185 -0
  589. package/scripts/lint-test-file-count.allowlist.json +181 -0
  590. package/scripts/lint-test-file-count.cjs +246 -0
  591. package/scripts/lint-windows-test-portability.cjs +178 -0
  592. package/scripts/mutation-matrix.cjs +323 -0
  593. package/scripts/pr-target-policy.cjs +63 -0
  594. package/scripts/pr-template-policy.cjs +268 -0
  595. package/scripts/prompt-injection-scan.sh +207 -0
  596. package/scripts/registry-smoke.cjs +337 -0
  597. package/scripts/release-notes/discord-release-summary.cjs +373 -0
  598. package/scripts/release-notes/format-github-release-notes.cjs +261 -0
  599. package/scripts/release-tarball-smoke.cjs +763 -0
  600. package/scripts/research-profiles.cjs +149 -0
  601. package/scripts/run-affected-tests.cjs +7 -0
  602. package/scripts/run-tests.cjs +589 -0
  603. package/scripts/secret-scan-lint.sh +231 -0
  604. package/scripts/secret-scan.sh +358 -0
  605. package/scripts/setup-branch-protection.sh +234 -0
  606. package/scripts/strip-prose-atrefs.cjs +106 -0
  607. package/scripts/sync-manifest-versions.cjs +119 -0
  608. package/scripts/sync-next-version.cjs +133 -0
  609. package/scripts/sync-rulesets.sh +34 -0
  610. package/scripts/sync-runtime-launcher.cjs +425 -0
  611. package/scripts/test-failure-reasons.cjs +34 -0
  612. package/scripts/update-size-baseline.cjs +68 -0
  613. package/scripts/verify-npm-publish.cjs +240 -0
  614. package/scripts/verify-opengsd-sweep.cjs +288 -0
  615. package/scripts/verify-phase-02-rename.sh +258 -0
  616. package/scripts/verify-phase-03-rename.sh +376 -0
  617. package/scripts/workflow-policy.cjs +483 -0
  618. package/scripts/workflow-size.cjs +90 -0
@@ -0,0 +1,2646 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * gen-capability-registry.cjs — generates pp-core/bin/lib/capability-registry.cjs
6
+ * from every capabilities/<id>/capability.json declaration.
7
+ *
8
+ * Usage:
9
+ * node scripts/gen-capability-registry.cjs # print to stdout
10
+ * node scripts/gen-capability-registry.cjs --write # write capability-registry.cjs
11
+ * node scripts/gen-capability-registry.cjs --check # exit 1 if committed registry is stale
12
+ *
13
+ * ADR-894 phase 3a-impl. Validates each capability against the schema, enforces
14
+ * cross-capability invariants, materializes hook ordering, and emits a role-
15
+ * partitioned CommonJS registry module.
16
+ */
17
+
18
+ const fs = require('node:fs');
19
+ const path = require('node:path');
20
+
21
+ const { ExitError, runMain } = require('./lib/cli-exit.cjs');
22
+
23
+ const ROOT = path.resolve(__dirname, '..');
24
+ const CAPABILITIES_DIR = path.join(ROOT, 'capabilities');
25
+ const REGISTRY_PATH = path.join(ROOT, 'pp-core', 'bin', 'lib', 'capability-registry.cjs');
26
+ const CONFIG_SCHEMA_PATH = path.join(ROOT, 'pp-core', 'bin', 'shared', 'config-schema.manifest.json');
27
+
28
+ const SCHEMA_VERSION = '1';
29
+
30
+ // ─── Loop Host Contract ───────────────────────────────────────────────────────
31
+ //
32
+ // Generated from workflow markers by scripts/gen-loop-host-contract.cjs (ADR-894 §3).
33
+ // Require the committed pp-core/bin/lib/loop-host-contract.cjs artifact so the
34
+ // registry generator and the loop-host-contract generator share one source of truth.
35
+ const { LOOP_HOST_CONTRACT } = require('../pp-core/bin/lib/loop-host-contract.cjs');
36
+
37
+ // Wired-points helper — tells us which points actually have render-hooks call sites.
38
+ const { getWiredLoopPoints } = require('./gen-loop-host-contract.cjs');
39
+
40
+ // Canonical point order — explicit constant (do NOT rely on Set insertion order).
41
+ // Used for point-ordering semantics in consumes-satisfiability validation and topo-sort.
42
+ const POINT_ORDER = [
43
+ 'discuss:pre',
44
+ 'discuss:post',
45
+ 'plan:pre',
46
+ 'plan:post',
47
+ 'execute:pre',
48
+ 'execute:wave:pre',
49
+ 'execute:wave:post',
50
+ 'execute:post',
51
+ 'verify:pre',
52
+ 'verify:post',
53
+ 'ship:pre',
54
+ 'ship:post',
55
+ ];
56
+
57
+ // C1: Artifact availability — host-produced artifacts become available at their step's :post
58
+ // point. Build a map: artifact → earliest POINT_ORDER index at which it is available.
59
+ // (discuss produces CONTEXT.md → discuss:post = index 1;
60
+ // plan produces PLAN.md → plan:post = index 3;
61
+ // execute produces SUMMARY.md → execute:post = index 7;
62
+ // verify produces UAT.md → verify:post = index 9)
63
+ //
64
+ // NOTE: this map covers ONLY host artifacts. Hook-produced artifacts are handled per-run
65
+ // during consumes-satisfiability validation (C2 global pass).
66
+ const HOST_ARTIFACT_EARLIEST_POINT_IDX = (() => {
67
+ const m = Object.create(null);
68
+ for (const entry of LOOP_HOST_CONTRACT) {
69
+ // The :post point is the last point in each step's points array.
70
+ const postPoint = entry.points[entry.points.length - 1];
71
+ const postIdx = POINT_ORDER.indexOf(postPoint);
72
+ for (const artifact of entry.coreArtifacts.produces) {
73
+ // Only record the earliest (should be unique, but take min to be safe).
74
+ if (m[artifact] === undefined || postIdx < m[artifact]) {
75
+ m[artifact] = postIdx;
76
+ }
77
+ }
78
+ }
79
+ return m;
80
+ })();
81
+
82
+ // Flatten all valid loop points into a Set for O(1) validation
83
+ const VALID_LOOP_POINTS = new Set(POINT_ORDER);
84
+
85
+ // Map point → step contract (agentRoles + coreArtifacts)
86
+ const POINT_TO_CONTRACT = new Map();
87
+ for (const entry of LOOP_HOST_CONTRACT) {
88
+ for (const point of entry.points) {
89
+ POINT_TO_CONTRACT.set(point, entry);
90
+ }
91
+ }
92
+
93
+ // ─── Central config-schema loader ────────────────────────────────────────────
94
+
95
+ /**
96
+ * Loads the set of keys from the central config-schema manifest.
97
+ * Returns a Set<string>. Used for collision detection.
98
+ *
99
+ * Contract:
100
+ * - ENOENT (file not found): returns empty Set silently — legitimate absent case.
101
+ * - Any other read error OR JSON parse error: writes a prominent warning to stderr
102
+ * naming the schema path and the underlying error, then throws ExitError(1).
103
+ * A parse error clearly states the schema is broken (not merely absent).
104
+ *
105
+ * @param {string} [schemaPath] Path to the config-schema manifest. Defaults to
106
+ * CONFIG_SCHEMA_PATH (the real production path).
107
+ * Overridable for unit testing with fixture paths.
108
+ * @returns {Set<string>}
109
+ */
110
+ function loadCentralConfigKeys(schemaPath = CONFIG_SCHEMA_PATH) {
111
+ let raw;
112
+ try {
113
+ raw = fs.readFileSync(schemaPath, 'utf8');
114
+ } catch (err) {
115
+ if (err.code === 'ENOENT') {
116
+ return new Set();
117
+ }
118
+ process.stderr.write(
119
+ ' ERROR Failed to read config-schema manifest at ' + schemaPath + ': ' + err.message + '\n',
120
+ );
121
+ throw new ExitError(1, 'could not read config-schema manifest');
122
+ }
123
+
124
+ let manifest;
125
+ try {
126
+ manifest = JSON.parse(raw);
127
+ } catch (err) {
128
+ process.stderr.write(
129
+ ' ERROR Config-schema manifest at ' + schemaPath + ' is broken (JSON parse error): ' + err.message + '\n',
130
+ );
131
+ throw new ExitError(1, 'config-schema manifest JSON is malformed');
132
+ }
133
+
134
+ return new Set(Array.isArray(manifest.validKeys) ? manifest.validKeys : []);
135
+ }
136
+
137
+ // ─── Config-slice validation ──────────────────────────────────────────────────
138
+
139
+ const VALID_CONFIG_SLICE_TYPES = new Set(['boolean', 'string', 'number', 'enum']);
140
+
141
+ /**
142
+ * Validate a single config-slice entry (one key's { type, default, description }).
143
+ * Returns an array of error strings. Empty = valid.
144
+ *
145
+ * @param {string} capId Capability id (for error messages)
146
+ * @param {string} key Config key (for error messages)
147
+ * @param {object} slice The slice object from cap.config[key]
148
+ * @returns {string[]}
149
+ */
150
+ function validateConfigSliceEntry(capId, key, slice) {
151
+ const errors = [];
152
+
153
+ if (typeof slice !== 'object' || slice === null || Array.isArray(slice)) {
154
+ errors.push('capability "' + capId + '" config["' + key + '"]: slice must be a non-null object');
155
+ return errors;
156
+ }
157
+
158
+ // type must be one of the allowed set
159
+ if (!VALID_CONFIG_SLICE_TYPES.has(slice.type)) {
160
+ errors.push(
161
+ 'capability "' + capId + '" config["' + key + '"]: type must be one of ' +
162
+ [...VALID_CONFIG_SLICE_TYPES].join(', ') + ' (got: ' + JSON.stringify(slice.type) + ')',
163
+ );
164
+ }
165
+
166
+ // default must be present
167
+ if (!Object.prototype.hasOwnProperty.call(slice, 'default')) {
168
+ errors.push(
169
+ 'capability "' + capId + '" config["' + key + '"]: default is required',
170
+ );
171
+ } else {
172
+ // type-consistency check
173
+ const def = slice.default;
174
+ if (slice.type === 'boolean') {
175
+ if (typeof def !== 'boolean') {
176
+ errors.push(
177
+ 'capability "' + capId + '" config["' + key + '"]: default must be a boolean for type:"boolean" (got: ' + typeof def + ')',
178
+ );
179
+ }
180
+ } else if (slice.type === 'string') {
181
+ if (typeof def !== 'string') {
182
+ errors.push(
183
+ 'capability "' + capId + '" config["' + key + '"]: default must be a string for type:"string" (got: ' + typeof def + ')',
184
+ );
185
+ }
186
+ } else if (slice.type === 'number') {
187
+ if (typeof def !== 'number') {
188
+ errors.push(
189
+ 'capability "' + capId + '" config["' + key + '"]: default must be a number for type:"number" (got: ' + typeof def + ')',
190
+ );
191
+ } else if (!Number.isFinite(def)) {
192
+ // FIX 6a: Reject NaN and non-finite number defaults
193
+ errors.push(
194
+ 'capability "' + capId + '" config["' + key + '"]: default for type:"number" must be a finite number (got: ' + String(def) + ')',
195
+ );
196
+ }
197
+ } else if (slice.type === 'enum') {
198
+ // FIX 5a: enum REQUIRES a non-empty values array (all strings), and default must be in it
199
+ if (!Array.isArray(slice.values) || slice.values.length === 0) {
200
+ errors.push(
201
+ 'capability "' + capId + '" config["' + key + '"]: type:"enum" requires a non-empty "values" array of strings',
202
+ );
203
+ } else if (!slice.values.every((v) => typeof v === 'string')) {
204
+ errors.push(
205
+ 'capability "' + capId + '" config["' + key + '"]: type:"enum" values array must contain only strings',
206
+ );
207
+ }
208
+ if (typeof def !== 'string') {
209
+ errors.push(
210
+ 'capability "' + capId + '" config["' + key + '"]: default must be a string for type:"enum" (got: ' + typeof def + ')',
211
+ );
212
+ } else if (Array.isArray(slice.values) && slice.values.length > 0 && !slice.values.includes(def)) {
213
+ errors.push(
214
+ 'capability "' + capId + '" config["' + key + '"]: default "' + def +
215
+ '" is not one of the declared enum values [' + slice.values.join(', ') + ']',
216
+ );
217
+ }
218
+ }
219
+ }
220
+
221
+ // description must be a non-empty string
222
+ if (typeof slice.description !== 'string' || slice.description.length === 0) {
223
+ errors.push(
224
+ 'capability "' + capId + '" config["' + key + '"]: description must be a non-empty string (got: ' + JSON.stringify(slice.description) + ')',
225
+ );
226
+ }
227
+
228
+ return errors;
229
+ }
230
+
231
+ // ─── Per-capability validation ────────────────────────────────────────────────
232
+
233
+ const KEBAB_RE = /^[a-z][a-z0-9-]*$/;
234
+ const VALID_ROLES = new Set(['feature', 'runtime']);
235
+ const VALID_TIERS = new Set(['core', 'standard', 'full']);
236
+ const VALID_ON_ERROR = new Set(['skip', 'halt']);
237
+ const RUNTIME_COMPAT_WILDCARD = '*';
238
+
239
+ /**
240
+ * Validate a single capability declaration.
241
+ *
242
+ * @param {object} cap The parsed JSON object.
243
+ * @param {string} folderId The folder name (must equal cap.id).
244
+ * @returns {string[]} Array of error strings; empty = valid.
245
+ */
246
+ function validateCapability(cap, folderId) {
247
+ const errors = [];
248
+
249
+ if (typeof cap !== 'object' || cap === null || Array.isArray(cap)) {
250
+ return ['capability must be a JSON object'];
251
+ }
252
+
253
+ // ── Common envelope ────────────────────────────────────────────────────────
254
+
255
+ if (typeof cap.id !== 'string' || !KEBAB_RE.test(cap.id)) {
256
+ errors.push('id must be a kebab-case string');
257
+ } else if (cap.id !== folderId) {
258
+ errors.push('id "' + cap.id + '" must equal the folder name "' + folderId + '"');
259
+ }
260
+
261
+ if (!VALID_ROLES.has(cap.role)) {
262
+ errors.push('role must be one of: feature, runtime (got: ' + cap.role + ')');
263
+ }
264
+
265
+ if (typeof cap.title !== 'string' || cap.title.length === 0) {
266
+ errors.push('title must be a non-empty string');
267
+ }
268
+
269
+ // C4: description is required
270
+ if (typeof cap.description !== 'string' || cap.description.length === 0) {
271
+ errors.push('description must be a non-empty string');
272
+ }
273
+
274
+ if (!VALID_TIERS.has(cap.tier)) {
275
+ errors.push('tier must be one of: core, standard, full (got: ' + cap.tier + ')');
276
+ }
277
+
278
+ if (!Array.isArray(cap.requires)) {
279
+ errors.push('requires must be an array of capability ids');
280
+ } else {
281
+ for (const req of cap.requires) {
282
+ if (typeof req !== 'string') {
283
+ errors.push('requires entries must be strings (got: ' + JSON.stringify(req) + ')');
284
+ }
285
+ }
286
+ }
287
+
288
+ // ── Role-specific body ────────────────────────────────────────────────────
289
+
290
+ if (cap.role === 'feature') {
291
+ errors.push(...validateFeatureBody(cap));
292
+ } else if (cap.role === 'runtime') {
293
+ errors.push(...validateRuntimeBody(cap));
294
+ }
295
+
296
+ return errors;
297
+ }
298
+
299
+ /**
300
+ * ADR-959: Validate a single commands[] entry on a feature-role capability.
301
+ * { family: string, module: string, router: string, subcommands?: string[] }
302
+ *
303
+ * - family: non-empty string, no reserved names
304
+ * - module: non-empty string, no path traversal, no absolute paths, no "/"
305
+ * segments other than a bare basename (expected form: "foo.cjs")
306
+ * - router: non-empty string
307
+ * - subcommands: optional array of strings (doc/introspection only)
308
+ *
309
+ * @param {string} capId Capability id (for error messages)
310
+ * @param {*} entry The entry to validate
311
+ * @param {string} prefix Path prefix (e.g. "commands[0]")
312
+ * @returns {string[]} Array of error strings; empty = valid.
313
+ */
314
+ function validateCommandEntry(capId, entry, prefix) {
315
+ const errors = [];
316
+ const ctx = 'capability "' + capId + '" ' + prefix;
317
+
318
+ if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
319
+ errors.push(ctx + ' must be an object with family, module, and router');
320
+ return errors;
321
+ }
322
+
323
+ // family: non-empty string, no reserved names
324
+ if (typeof entry.family !== 'string' || entry.family.length === 0) {
325
+ errors.push(ctx + '.family must be a non-empty string');
326
+ } else if (entry.family === '__proto__' || entry.family === 'constructor' || entry.family === 'prototype') {
327
+ // S2a: inline literal reserved-name guard (CodeQL barrier)
328
+ errors.push(ctx + '.family "' + entry.family + '" is a reserved name');
329
+ }
330
+
331
+ // module: must be a safe bare basename matching /^[A-Za-z0-9._-]+\.cjs$/ —
332
+ // no path separators, no "..", no NUL bytes, no absolute paths, ends in .cjs.
333
+ // This conservative pattern subsumes all earlier traversal/absolute/separator checks.
334
+ if (typeof entry.module !== 'string' || entry.module.length === 0) {
335
+ errors.push(ctx + '.module must be a non-empty string');
336
+ } else {
337
+ const mod = entry.module;
338
+ const SAFE_BASENAME = /^[A-Za-z0-9._-]+\.cjs$/;
339
+ if (!SAFE_BASENAME.test(mod)) {
340
+ errors.push(
341
+ ctx + '.module must be a safe bare basename (pattern: /^[A-Za-z0-9._-]+\\.cjs$/, no path separators, no "..", no NUL bytes, must end in ".cjs"); got: ' +
342
+ JSON.stringify(mod),
343
+ );
344
+ }
345
+ }
346
+
347
+ // router: non-empty string
348
+ if (typeof entry.router !== 'string' || entry.router.length === 0) {
349
+ errors.push(ctx + '.router must be a non-empty string');
350
+ }
351
+
352
+ // subcommands: optional array of non-empty strings (doc/introspection only)
353
+ if (entry.subcommands !== undefined) {
354
+ if (!Array.isArray(entry.subcommands)) {
355
+ errors.push(ctx + '.subcommands must be an array of strings if present');
356
+ } else {
357
+ for (let i = 0; i < entry.subcommands.length; i++) {
358
+ if (typeof entry.subcommands[i] !== 'string') {
359
+ errors.push(ctx + '.subcommands[' + i + '] must be a string');
360
+ } else if (entry.subcommands[i].length === 0) {
361
+ errors.push(ctx + '.subcommands[' + i + '] must be a non-empty string');
362
+ }
363
+ }
364
+ }
365
+ }
366
+
367
+ return errors;
368
+ }
369
+
370
+ function validateRuntimeCompat(capId, runtimeCompat) {
371
+ const errors = [];
372
+ const ctx = 'capability "' + capId + '" runtimeCompat';
373
+
374
+ if (typeof runtimeCompat !== 'object' || runtimeCompat === null || Array.isArray(runtimeCompat)) {
375
+ errors.push(ctx + ' must be an object with supported and unsupported arrays');
376
+ return errors;
377
+ }
378
+
379
+ const validateRuntimeArray = (field, { allowWildcard }) => {
380
+ const value = runtimeCompat[field];
381
+ if (!Array.isArray(value)) {
382
+ errors.push(ctx + '.' + field + ' must be an array of runtime ids' + (allowWildcard ? ' or ["*"]' : ''));
383
+ return;
384
+ }
385
+ if (field === 'supported' && value.length === 0) {
386
+ errors.push(ctx + '.supported must be a non-empty array');
387
+ }
388
+ let hasWildcard = false;
389
+ for (let i = 0; i < value.length; i++) {
390
+ const entry = value[i];
391
+ if (typeof entry !== 'string' || entry.length === 0) {
392
+ errors.push(ctx + '.' + field + '[' + i + '] must be a non-empty string');
393
+ continue;
394
+ }
395
+ if (entry === '__proto__' || entry === 'constructor' || entry === 'prototype') {
396
+ errors.push(ctx + '.' + field + '[' + i + '] "' + entry + '" is a reserved name');
397
+ }
398
+ if (entry === RUNTIME_COMPAT_WILDCARD) {
399
+ if (!allowWildcard) {
400
+ errors.push(ctx + '.' + field + ' must not include wildcard "*"');
401
+ }
402
+ hasWildcard = true;
403
+ } else if (!KEBAB_RE.test(entry)) {
404
+ errors.push(ctx + '.' + field + '[' + i + '] must be a kebab-case runtime id or "*"');
405
+ }
406
+ }
407
+ if (hasWildcard && value.length > 1) {
408
+ errors.push(ctx + '.' + field + ' wildcard "*" cannot be mixed with runtime ids');
409
+ }
410
+ };
411
+
412
+ validateRuntimeArray('supported', { allowWildcard: true });
413
+ validateRuntimeArray('unsupported', { allowWildcard: false });
414
+
415
+ if (runtimeCompat.notes !== undefined) {
416
+ if (typeof runtimeCompat.notes !== 'object' || runtimeCompat.notes === null || Array.isArray(runtimeCompat.notes)) {
417
+ errors.push(ctx + '.notes must be an object of runtime id to string if present');
418
+ } else {
419
+ for (const [key, value] of Object.entries(runtimeCompat.notes)) {
420
+ if (key !== RUNTIME_COMPAT_WILDCARD && !KEBAB_RE.test(key)) {
421
+ errors.push(ctx + '.notes key "' + key + '" must be a kebab-case runtime id or "*"');
422
+ }
423
+ if (typeof value !== 'string' || value.length === 0) {
424
+ errors.push(ctx + '.notes["' + key + '"] must be a non-empty string');
425
+ }
426
+ }
427
+ }
428
+ }
429
+
430
+ return errors;
431
+ }
432
+
433
+ function validateFeatureBody(cap) {
434
+ const errors = [];
435
+
436
+ errors.push(...validateRuntimeCompat(cap.id || '(unknown)', cap.runtimeCompat));
437
+
438
+ if (!Array.isArray(cap.skills)) {
439
+ errors.push('skills must be an array of strings');
440
+ } else {
441
+ for (const s of cap.skills) {
442
+ if (typeof s !== 'string') {
443
+ errors.push('skills entries must be strings');
444
+ } else if (s === '__proto__' || s === 'constructor' || s === 'prototype') {
445
+ // S2a: inline literal reserved-name guard (CodeQL barrier)
446
+ errors.push('skills entry "' + s + '" is a reserved name');
447
+ }
448
+ }
449
+ }
450
+
451
+ // ADR-959: optional commands array
452
+ if (cap.commands !== undefined) {
453
+ if (!Array.isArray(cap.commands)) {
454
+ errors.push('commands must be an array of {family, module, router} objects');
455
+ } else {
456
+ for (let i = 0; i < cap.commands.length; i++) {
457
+ errors.push(...validateCommandEntry(cap.id || cap.role, cap.commands[i], 'commands[' + i + ']'));
458
+ }
459
+ }
460
+ }
461
+
462
+ if (!Array.isArray(cap.agents)) {
463
+ errors.push('agents must be an array of strings');
464
+ } else {
465
+ for (const a of cap.agents) {
466
+ if (typeof a !== 'string') {
467
+ errors.push('agents entries must be strings');
468
+ } else if (a === '__proto__' || a === 'constructor' || a === 'prototype') {
469
+ // S2a: inline literal reserved-name guard (CodeQL barrier)
470
+ errors.push('agents entry "' + a + '" is a reserved name');
471
+ }
472
+ }
473
+ }
474
+
475
+ if (typeof cap.config !== 'object' || cap.config === null || Array.isArray(cap.config)) {
476
+ errors.push('config must be an object');
477
+ } else {
478
+ // C5: validate config key names and value shapes
479
+ for (const key of Object.keys(cap.config)) {
480
+ if (key === '' ) {
481
+ errors.push('config keys must be non-empty strings');
482
+ } else if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
483
+ // S2a: inline literal reserved-name guard (CodeQL barrier)
484
+ errors.push('config key "' + key + '" is a reserved name');
485
+ }
486
+ const val = cap.config[key];
487
+ if (val === null || typeof val !== 'object' || Array.isArray(val)) {
488
+ errors.push('config["' + key + '"] must be an object (got: ' + (val === null ? 'null' : typeof val) + ')');
489
+ } else if (typeof val.type !== 'string' || val.type.length === 0) {
490
+ errors.push('config["' + key + '"] must have a string "type" field (e.g. "boolean", "string", "number", "enum")');
491
+ }
492
+ }
493
+ }
494
+
495
+ // C4: hooks, when present, must be an array of {event: string, script: string}
496
+ if (cap.hooks !== undefined) {
497
+ if (!Array.isArray(cap.hooks)) {
498
+ errors.push('hooks must be an array of {event, script} objects');
499
+ } else {
500
+ for (let i = 0; i < cap.hooks.length; i++) {
501
+ const h = cap.hooks[i];
502
+ if (typeof h !== 'object' || h === null || Array.isArray(h)) {
503
+ errors.push('hooks[' + i + '] must be an object with event and script keys');
504
+ } else {
505
+ if (typeof h.event !== 'string' || h.event.length === 0) {
506
+ errors.push('hooks[' + i + '].event must be a non-empty string');
507
+ }
508
+ if (typeof h.script !== 'string' || h.script.length === 0) {
509
+ errors.push('hooks[' + i + '].script must be a non-empty string');
510
+ }
511
+ }
512
+ }
513
+ }
514
+ }
515
+
516
+ // Build the declared skill/agent sets for ref membership checks (used in validateStep).
517
+ // Only build these if the arrays are valid (already validated above).
518
+ const declaredSkills = Array.isArray(cap.skills) ? new Set(cap.skills.filter((s) => typeof s === 'string')) : null;
519
+ const declaredAgents = Array.isArray(cap.agents) ? new Set(cap.agents.filter((a) => typeof a === 'string')) : null;
520
+
521
+ if (!Array.isArray(cap.steps)) {
522
+ errors.push('steps must be an array');
523
+ } else {
524
+ for (let i = 0; i < cap.steps.length; i++) {
525
+ errors.push(...validateStep(cap.steps[i], 'steps[' + i + ']', declaredSkills, declaredAgents));
526
+ }
527
+ }
528
+
529
+ if (!Array.isArray(cap.contributions)) {
530
+ errors.push('contributions must be an array');
531
+ } else {
532
+ for (let i = 0; i < cap.contributions.length; i++) {
533
+ errors.push(...validateContribution(cap.contributions[i], 'contributions[' + i + ']'));
534
+ }
535
+ }
536
+
537
+ if (!Array.isArray(cap.gates)) {
538
+ errors.push('gates must be an array');
539
+ } else {
540
+ for (let i = 0; i < cap.gates.length; i++) {
541
+ errors.push(...validateGate(cap.gates[i], 'gates[' + i + ']'));
542
+ }
543
+ }
544
+
545
+ // activationKey: optional string naming the dotted config key that gates this capability.
546
+ // If present: must be a non-empty string that is declared in this capability's own config slice.
547
+ if (cap.activationKey !== undefined) {
548
+ if (typeof cap.activationKey !== 'string' || cap.activationKey.length === 0) {
549
+ errors.push(
550
+ 'capability "' + (cap.id || '(unknown)') + '" activationKey must be a non-empty string (got: ' +
551
+ JSON.stringify(cap.activationKey) + ')',
552
+ );
553
+ } else if (cap.activationKey === '__proto__' || cap.activationKey === 'constructor' || cap.activationKey === 'prototype') {
554
+ // Prototype-pollution guard (inline literal, CodeQL barrier)
555
+ errors.push(
556
+ 'capability "' + (cap.id || '(unknown)') + '" activationKey "' + cap.activationKey +
557
+ '" is a reserved JavaScript property name and cannot be used as an activationKey',
558
+ );
559
+ } else if (
560
+ typeof cap.config !== 'object' ||
561
+ cap.config === null ||
562
+ !Object.prototype.hasOwnProperty.call(cap.config, cap.activationKey)
563
+ ) {
564
+ errors.push(
565
+ 'capability "' + (cap.id || '(unknown)') + '" activationKey "' + cap.activationKey +
566
+ '" is not declared in this capability\'s config slice — add it to the "config" object or use a key that is declared there',
567
+ );
568
+ }
569
+ }
570
+
571
+ return errors;
572
+ }
573
+
574
+ // ADR-857 phase 5e: Closed ConverterName enum — complete set used across 16 runtime descriptors,
575
+ // all exported by bin/install.js (commands/skills) and src/runtime-artifact-conversion.cts (agents).
576
+ // Any ArtifactKind with a non-null converter must use one of these.
577
+ const VALID_CONVERTER_NAMES = new Set([
578
+ // commands / skills converters (pre-existing)
579
+ 'convertClaudeCommandToAntigravitySkill',
580
+ 'convertClaudeCommandToAugmentSkill',
581
+ 'convertClaudeCommandToClineSkill',
582
+ 'convertClaudeCommandToClaudeSkill',
583
+ 'convertClaudeCommandToCodebuddyCommand',
584
+ 'convertClaudeCommandToCodebuddySkill',
585
+ 'convertClaudeCommandToCodexSkill',
586
+ 'convertClaudeCommandToCopilotSkill',
587
+ 'convertClaudeCommandToCursorCommand',
588
+ 'convertClaudeCommandToCursorSkill',
589
+ 'convertClaudeCommandToKiloSkill',
590
+ 'convertClaudeCommandToKimiSkill',
591
+ 'convertClaudeCommandToOpencodeSkill',
592
+ 'convertClaudeCommandToTraeSkill',
593
+ 'convertClaudeCommandToWindsurfSkill',
594
+ // agent converters (#1173 — descriptor-driven agent conversion wiring)
595
+ 'convertClaudeAgentToCopilotAgent',
596
+ 'convertClaudeAgentToAntigravityAgent',
597
+ 'convertClaudeAgentToCursorAgent',
598
+ 'convertClaudeAgentToWindsurfAgent',
599
+ 'convertClaudeAgentToAugmentAgent',
600
+ 'convertClaudeAgentToTraeAgent',
601
+ 'convertClaudeAgentToCodebuddyAgent',
602
+ 'convertClaudeAgentToClineAgent',
603
+ 'convertClaudeAgentToCodexAgent',
604
+ ]);
605
+
606
+ // C3: Validate role:runtime body
607
+ const VALID_CONFIG_FORMATS = new Set(['settings-json', 'toml', 'markdown', 'markdown-dir', 'none']);
608
+ const VALID_CONFIG_HOME_KINDS = new Set(['dot-home', 'dot-home-nested', 'xdg', 'generic-agents-root']);
609
+ const VALID_COMMAND_STYLES = new Set(['slash-hyphen', 'shell-var']);
610
+ const VALID_HOOKS_SURFACES = new Set(['settings-json', 'codex-hooks-json', 'cursor-hooks-json', 'copilot-inline', 'cline-rules', 'none']);
611
+ const VALID_HOOK_EVENTS = new Set(['claude', 'gemini', 'opencode-subset']);
612
+ const VALID_SANDBOX_TIERS = new Set(['none', 'codex-agent-sandbox']);
613
+ const VALID_ARTIFACT_KIND_NAMES = new Set(['commands', 'agents', 'skills', 'kimi-agents']);
614
+ const VALID_ARTIFACT_NESTINGS = new Set(['flat', 'nested']);
615
+ const FEATURE_FIELDS_FORBIDDEN_ON_RUNTIME = ['skills', 'agents', 'steps', 'contributions', 'gates', 'hooks', 'activationKey'];
616
+ const VALID_INSTALL_SURFACES = new Set(['settings-json', 'codex-toml', 'copilot-instructions', 'cline-rules', 'cursor-hooks-json', 'profile-marker-only']);
617
+ const VALID_PERMISSION_WRITERS = new Set(['opencode', 'kilo']);
618
+ const VALID_EXTENDED_HOOK_EVENTS = new Set(['SubagentStop', 'Stop', 'PreCompact', 'FileChanged', 'BeforeAgent', 'AfterAgent', 'BeforeModel']);
619
+
620
+ // GATE A: installSurface → allowed hooksSurface values (DEFECT.GENERATIVE-FIX: parity invariant)
621
+ // Derived from the actual pairings in the 16 real runtime descriptors.
622
+ const INSTALL_SURFACE_TO_ALLOWED_HOOKS_SURFACES = new Map([
623
+ ['settings-json', new Set(['settings-json', 'none'])],
624
+ ['codex-toml', new Set(['codex-hooks-json'])],
625
+ ['copilot-instructions', new Set(['copilot-inline'])],
626
+ ['cline-rules', new Set(['cline-rules'])],
627
+ ['cursor-hooks-json', new Set(['cursor-hooks-json'])],
628
+ ['profile-marker-only', new Set(['none'])],
629
+ ]);
630
+
631
+ // GATE B: extended hook event families → required hookEvents value
632
+ // Gemini agent-events require hookEvents='gemini'; Claude-family events require hookEvents='claude'.
633
+ const GEMINI_AGENT_EVENTS = new Set(['BeforeAgent', 'AfterAgent', 'BeforeModel']);
634
+ const CLAUDE_FAMILY_EVENTS = new Set(['SubagentStop', 'Stop', 'PreCompact', 'FileChanged']);
635
+
636
+ /**
637
+ * Validate a runtime.configHome object per ADR-1016 Decision 1.
638
+ * Returns an array of error strings.
639
+ *
640
+ * @param {string} capId Capability id (for error messages)
641
+ * @param {*} ch The configHome value
642
+ * @returns {string[]}
643
+ */
644
+ function validateConfigHome(capId, ch) {
645
+ const errors = [];
646
+ const ctx = 'capability "' + capId + '" runtime.configHome';
647
+
648
+ if (typeof ch !== 'object' || ch === null || Array.isArray(ch)) {
649
+ errors.push(ctx + ' must be an object (got: ' + (ch === null ? 'null' : typeof ch) + ')');
650
+ return errors;
651
+ }
652
+
653
+ // kind — must be in closed vocab; inline literal guard (CodeQL barrier)
654
+ if (ch.kind === '__proto__' || ch.kind === 'constructor' || ch.kind === 'prototype') {
655
+ errors.push(ctx + '.kind "' + ch.kind + '" is a reserved name');
656
+ } else if (!VALID_CONFIG_HOME_KINDS.has(ch.kind)) {
657
+ errors.push(
658
+ ctx + '.kind must be one of: ' + [...VALID_CONFIG_HOME_KINDS].join(', ') +
659
+ ' (got: ' + JSON.stringify(ch.kind) + ')',
660
+ );
661
+ }
662
+
663
+ // name — required string
664
+ if (typeof ch.name !== 'string' || ch.name.length === 0) {
665
+ errors.push(ctx + '.name must be a non-empty string');
666
+ }
667
+
668
+ // parent — required when kind == dot-home-nested
669
+ if (ch.kind === 'dot-home-nested') {
670
+ if (typeof ch.parent !== 'string' || ch.parent.length === 0) {
671
+ errors.push(ctx + '.parent must be a non-empty string when kind is "dot-home-nested"');
672
+ }
673
+ }
674
+
675
+ // env — required; must be an array of strings (every runtime has ≥0 env overrides)
676
+ if (!Array.isArray(ch.env)) {
677
+ errors.push(ctx + '.env is required and must be an array of strings (got: ' + JSON.stringify(ch.env) + ')');
678
+ } else {
679
+ for (let i = 0; i < ch.env.length; i++) {
680
+ if (typeof ch.env[i] !== 'string') {
681
+ errors.push(ctx + '.env[' + i + '] must be a string');
682
+ }
683
+ }
684
+ }
685
+
686
+ // probe — optional; if present must be an array of strings
687
+ if (ch.probe !== undefined) {
688
+ if (!Array.isArray(ch.probe)) {
689
+ errors.push(ctx + '.probe must be an array of strings if present');
690
+ } else {
691
+ for (let i = 0; i < ch.probe.length; i++) {
692
+ if (typeof ch.probe[i] !== 'string') {
693
+ errors.push(ctx + '.probe[' + i + '] must be a string');
694
+ }
695
+ }
696
+ }
697
+ }
698
+
699
+ // probeExists — optional; if present must be a non-empty string (sub-path existence check for probe)
700
+ if (ch.probeExists !== undefined) {
701
+ if (typeof ch.probeExists !== 'string' || ch.probeExists.length === 0) {
702
+ errors.push(ctx + '.probeExists must be a non-empty string if present (got: ' + JSON.stringify(ch.probeExists) + ')');
703
+ }
704
+ }
705
+
706
+ // skillsHome — optional; if present must be a full valid configHome object (recursive validation)
707
+ if (ch.skillsHome !== undefined) {
708
+ // Recursive call: validate skillsHome as a nested configHome.
709
+ // Use a synthetic capId to surface the sub-path in error messages.
710
+ const skillsHomeErrors = validateConfigHome(capId + '.skillsHome', ch.skillsHome);
711
+ // Rewrite the inner ctx prefix so errors read as "...runtime.configHome.skillsHome..."
712
+ for (const e of skillsHomeErrors) {
713
+ errors.push(e.replace(
714
+ 'capability "' + capId + '.skillsHome" runtime.configHome',
715
+ ctx + '.skillsHome',
716
+ ));
717
+ }
718
+ }
719
+
720
+ return errors;
721
+ }
722
+
723
+ /**
724
+ * Validate a single ArtifactKind entry per ADR-1016 Decision 3.
725
+ * Returns an array of error strings.
726
+ *
727
+ * @param {string} capId Capability id (for error messages)
728
+ * @param {*} entry The ArtifactKind object
729
+ * @param {string} prefix Path prefix for error messages (e.g. "artifactLayout.global[0]")
730
+ * @returns {string[]}
731
+ */
732
+ function validateArtifactKindEntry(capId, entry, prefix) {
733
+ const errors = [];
734
+ const ctx = 'capability "' + capId + '" runtime.' + prefix;
735
+
736
+ if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
737
+ errors.push(ctx + ' must be an object');
738
+ return errors;
739
+ }
740
+
741
+ // kind — must be in closed vocab; inline literal guard (CodeQL barrier)
742
+ if (entry.kind === '__proto__' || entry.kind === 'constructor' || entry.kind === 'prototype') {
743
+ errors.push(ctx + '.kind "' + entry.kind + '" is a reserved name');
744
+ } else if (!VALID_ARTIFACT_KIND_NAMES.has(entry.kind)) {
745
+ errors.push(
746
+ ctx + '.kind must be one of: ' + [...VALID_ARTIFACT_KIND_NAMES].join(', ') +
747
+ ' (got: ' + JSON.stringify(entry.kind) + ')',
748
+ );
749
+ }
750
+
751
+ // destSubpath — required non-empty string
752
+ if (typeof entry.destSubpath !== 'string' || entry.destSubpath.length === 0) {
753
+ errors.push(ctx + '.destSubpath must be a non-empty string');
754
+ }
755
+
756
+ // nesting — required; must be in closed vocab (ADR-857 §5d: now drives install)
757
+ if (entry.nesting === undefined || entry.nesting === null) {
758
+ errors.push(ctx + '.nesting is required and must be one of: ' + [...VALID_ARTIFACT_NESTINGS].join(', '));
759
+ } else if (!VALID_ARTIFACT_NESTINGS.has(entry.nesting)) {
760
+ errors.push(
761
+ ctx + '.nesting must be one of: ' + [...VALID_ARTIFACT_NESTINGS].join(', ') +
762
+ ' (got: ' + JSON.stringify(entry.nesting) + ')',
763
+ );
764
+ }
765
+
766
+ // prefix — required; must be a string (may be empty string '')
767
+ if (entry.prefix === undefined || entry.prefix === null) {
768
+ errors.push(ctx + '.prefix is required (must be a string, may be empty)');
769
+ } else if (typeof entry.prefix !== 'string') {
770
+ errors.push(ctx + '.prefix must be a string (got: ' + typeof entry.prefix + ')');
771
+ }
772
+
773
+ // recursive — optional; if present must be a boolean
774
+ if (entry.recursive !== undefined) {
775
+ if (typeof entry.recursive !== 'boolean') {
776
+ errors.push(ctx + '.recursive must be a boolean if present (got: ' + typeof entry.recursive + ')');
777
+ }
778
+ }
779
+
780
+ // converter — required; must be a string or null (closed ConverterName enum — now enforced in phase 5e)
781
+ if (!Object.prototype.hasOwnProperty.call(entry, 'converter')) {
782
+ errors.push(ctx + '.converter is required (must be a string or null)');
783
+ } else if (entry.converter !== null && typeof entry.converter !== 'string') {
784
+ errors.push(ctx + '.converter must be a string or null (got: ' + typeof entry.converter + ')');
785
+ } else if (entry.converter !== null && typeof entry.converter === 'string' &&
786
+ !VALID_CONVERTER_NAMES.has(entry.converter)) {
787
+ // Closed ConverterName enum (ADR-857 phase 5e): reject unknown converter names
788
+ errors.push(ctx + '.converter "' + entry.converter + '" is not a known ConverterName');
789
+ }
790
+
791
+ return errors;
792
+ }
793
+
794
+ /**
795
+ * Validate runtime.artifactLayout per ADR-1016 Decision 3.
796
+ * Accepts the structured { global, local } shape.
797
+ * Returns an array of error strings.
798
+ *
799
+ * @param {string} capId Capability id (for error messages)
800
+ * @param {*} layout The artifactLayout value
801
+ * @returns {string[]}
802
+ */
803
+ function validateArtifactLayout(capId, layout) {
804
+ const errors = [];
805
+ const ctx = 'capability "' + capId + '" runtime.artifactLayout';
806
+
807
+ if (typeof layout !== 'object' || layout === null || Array.isArray(layout)) {
808
+ errors.push(ctx + ' must be an object with "global" and "local" arrays');
809
+ return errors;
810
+ }
811
+
812
+ for (const scope of ['global', 'local']) {
813
+ const arr = layout[scope];
814
+ if (!Array.isArray(arr)) {
815
+ errors.push(ctx + '.' + scope + ' must be an array');
816
+ } else {
817
+ for (let i = 0; i < arr.length; i++) {
818
+ errors.push(...validateArtifactKindEntry(capId, arr[i], 'artifactLayout.' + scope + '[' + i + ']'));
819
+ }
820
+ }
821
+ }
822
+
823
+ return errors;
824
+ }
825
+
826
+ function validateRuntimeBody(cap) {
827
+ const errors = [];
828
+
829
+ // C3: feature-only fields must NOT appear on a runtime cap
830
+ for (const field of FEATURE_FIELDS_FORBIDDEN_ON_RUNTIME) {
831
+ if (cap[field] !== undefined) {
832
+ errors.push('role:runtime capability must not have "' + field + '" (feature-only field)');
833
+ }
834
+ }
835
+
836
+ // C3: require a runtime object
837
+ if (typeof cap.runtime !== 'object' || cap.runtime === null || Array.isArray(cap.runtime)) {
838
+ errors.push('role:runtime capability must have a "runtime" object');
839
+ return errors; // can't validate further without the object
840
+ }
841
+
842
+ const r = cap.runtime;
843
+
844
+ // configHome — must be a structured object (ADR-1016 Decision 1)
845
+ errors.push(...validateConfigHome(cap.id || '(unknown)', r.configHome));
846
+
847
+ // configFormat — closed 5-enum (unchanged)
848
+ if (!VALID_CONFIG_FORMATS.has(r.configFormat)) {
849
+ errors.push('runtime.configFormat must be one of: ' + [...VALID_CONFIG_FORMATS].join(', ') + ' (got: ' + r.configFormat + ')');
850
+ }
851
+
852
+ // artifactLayout — structured { global, local } per ADR-1016 Decision 3
853
+ errors.push(...validateArtifactLayout(cap.id || '(unknown)', r.artifactLayout));
854
+
855
+ // commandStyle — closed 2-enum (ADR-1016 Decision 4); inline literal guard (CodeQL barrier)
856
+ if (r.commandStyle === '__proto__' || r.commandStyle === 'constructor' || r.commandStyle === 'prototype') {
857
+ errors.push('runtime.commandStyle "' + r.commandStyle + '" is a reserved name');
858
+ } else if (!VALID_COMMAND_STYLES.has(r.commandStyle)) {
859
+ errors.push(
860
+ 'runtime.commandStyle must be one of: ' + [...VALID_COMMAND_STYLES].join(', ') +
861
+ ' (got: ' + JSON.stringify(r.commandStyle) + ')',
862
+ );
863
+ }
864
+
865
+ // hooksSurface — closed 6-enum (ADR-1016 Decision 5); inline literal guard (CodeQL barrier)
866
+ if (r.hooksSurface === '__proto__' || r.hooksSurface === 'constructor' || r.hooksSurface === 'prototype') {
867
+ errors.push('runtime.hooksSurface "' + r.hooksSurface + '" is a reserved name');
868
+ } else if (!VALID_HOOKS_SURFACES.has(r.hooksSurface)) {
869
+ errors.push(
870
+ 'runtime.hooksSurface must be one of: ' + [...VALID_HOOKS_SURFACES].join(', ') +
871
+ ' (got: ' + JSON.stringify(r.hooksSurface) + ')',
872
+ );
873
+ }
874
+
875
+ // hookEvents — optional; if present must be in closed 3-enum (ADR-1016 Decision 5)
876
+ if (r.hookEvents !== undefined) {
877
+ if (r.hookEvents === '__proto__' || r.hookEvents === 'constructor' || r.hookEvents === 'prototype') {
878
+ errors.push('runtime.hookEvents "' + r.hookEvents + '" is a reserved name');
879
+ } else if (!VALID_HOOK_EVENTS.has(r.hookEvents)) {
880
+ errors.push(
881
+ 'runtime.hookEvents must be one of: ' + [...VALID_HOOK_EVENTS].join(', ') +
882
+ ' (got: ' + JSON.stringify(r.hookEvents) + ')',
883
+ );
884
+ }
885
+ }
886
+
887
+ // sandboxTier — closed 2-enum (ADR-1016 Decision 6); inline literal guard (CodeQL barrier)
888
+ if (r.sandboxTier === '__proto__' || r.sandboxTier === 'constructor' || r.sandboxTier === 'prototype') {
889
+ errors.push('runtime.sandboxTier "' + r.sandboxTier + '" is a reserved name');
890
+ } else if (!VALID_SANDBOX_TIERS.has(r.sandboxTier)) {
891
+ errors.push(
892
+ 'runtime.sandboxTier must be one of: ' + [...VALID_SANDBOX_TIERS].join(', ') +
893
+ ' (got: ' + JSON.stringify(r.sandboxTier) + ')',
894
+ );
895
+ }
896
+
897
+ // supportTier — 1 or 2 (unchanged)
898
+ if (r.supportTier !== 1 && r.supportTier !== 2) {
899
+ errors.push('runtime.supportTier must be 1 or 2 (got: ' + r.supportTier + ')');
900
+ }
901
+
902
+ // installSurface — required string in closed enum
903
+ if (!VALID_INSTALL_SURFACES.has(r.installSurface)) {
904
+ errors.push(
905
+ 'runtime.installSurface must be one of: ' + [...VALID_INSTALL_SURFACES].join(', ') +
906
+ ' (got: ' + JSON.stringify(r.installSurface) + ')',
907
+ );
908
+ }
909
+
910
+ // writesSharedSettings — required boolean
911
+ if (typeof r.writesSharedSettings !== 'boolean') {
912
+ errors.push(
913
+ 'runtime.writesSharedSettings must be a boolean (got: ' + JSON.stringify(r.writesSharedSettings) + ')',
914
+ );
915
+ }
916
+
917
+ // permissionWriter — required key; value must be null or a string in VALID_PERMISSION_WRITERS
918
+ if (!Object.prototype.hasOwnProperty.call(r, 'permissionWriter')) {
919
+ errors.push('runtime.permissionWriter is required (must be null or one of: ' + [...VALID_PERMISSION_WRITERS].join(', ') + ')');
920
+ } else if (r.permissionWriter !== null && !VALID_PERMISSION_WRITERS.has(r.permissionWriter)) {
921
+ errors.push(
922
+ 'runtime.permissionWriter must be null or one of: ' + [...VALID_PERMISSION_WRITERS].join(', ') +
923
+ ' (got: ' + JSON.stringify(r.permissionWriter) + ')',
924
+ );
925
+ }
926
+
927
+ // extendedHookEvents — required array; every element must be in closed enum
928
+ if (!Array.isArray(r.extendedHookEvents)) {
929
+ errors.push(
930
+ 'runtime.extendedHookEvents must be an array (got: ' + JSON.stringify(r.extendedHookEvents) + ')',
931
+ );
932
+ } else {
933
+ for (let i = 0; i < r.extendedHookEvents.length; i++) {
934
+ const ev = r.extendedHookEvents[i];
935
+ if (typeof ev !== 'string' || !VALID_EXTENDED_HOOK_EVENTS.has(ev)) {
936
+ errors.push(
937
+ 'runtime.extendedHookEvents[' + i + '] must be one of: ' + [...VALID_EXTENDED_HOOK_EVENTS].join(', ') +
938
+ ' (got: ' + JSON.stringify(ev) + ')',
939
+ );
940
+ }
941
+ }
942
+ }
943
+
944
+ // GATE A: installSurface ↔ hooksSurface consistency (DEFECT.GENERATIVE-FIX)
945
+ // Only check if both fields are valid strings (individual field validators above report type errors).
946
+ if (typeof r.installSurface === 'string' && typeof r.hooksSurface === 'string') {
947
+ const allowedHooksSurfaces = INSTALL_SURFACE_TO_ALLOWED_HOOKS_SURFACES.get(r.installSurface);
948
+ if (allowedHooksSurfaces !== undefined && !allowedHooksSurfaces.has(r.hooksSurface)) {
949
+ errors.push(
950
+ 'runtime.hooksSurface "' + r.hooksSurface + '" is not valid for installSurface "' + r.installSurface + '"' +
951
+ ' — allowed: ' + [...allowedHooksSurfaces].join(', ') +
952
+ ' (src: INSTALL_SURFACE_TO_ALLOWED_HOOKS_SURFACES in scripts/gen-capability-registry.cjs)',
953
+ );
954
+ }
955
+ }
956
+
957
+ // GATE B: extendedHookEvents ↔ hookEvents consistency (DEFECT.GENERATIVE-FIX)
958
+ // If extendedHookEvents contains Gemini agent-events, hookEvents must be 'gemini'.
959
+ // If it contains Claude-family events, hookEvents must be 'claude'.
960
+ // Empty extendedHookEvents imposes no constraint.
961
+ if (Array.isArray(r.extendedHookEvents) && r.extendedHookEvents.length > 0) {
962
+ const hasGeminiEvents = r.extendedHookEvents.some((ev) => GEMINI_AGENT_EVENTS.has(ev));
963
+ const hasClaudeEvents = r.extendedHookEvents.some((ev) => CLAUDE_FAMILY_EVENTS.has(ev));
964
+ if (hasGeminiEvents && r.hookEvents !== 'gemini') {
965
+ errors.push(
966
+ 'runtime.extendedHookEvents contains Gemini agent-events (' +
967
+ r.extendedHookEvents.filter((ev) => GEMINI_AGENT_EVENTS.has(ev)).join(', ') +
968
+ ') but runtime.hookEvents is "' + r.hookEvents + '" — must be "gemini"',
969
+ );
970
+ }
971
+ if (hasClaudeEvents && r.hookEvents !== 'claude') {
972
+ errors.push(
973
+ 'runtime.extendedHookEvents contains Claude-family events (' +
974
+ r.extendedHookEvents.filter((ev) => CLAUDE_FAMILY_EVENTS.has(ev)).join(', ') +
975
+ ') but runtime.hookEvents is "' + r.hookEvents + '" — must be "claude"',
976
+ );
977
+ }
978
+ }
979
+
980
+ return errors;
981
+ }
982
+
983
+ function materializeHookFragments(cap, capDir) {
984
+ const errors = [];
985
+ const hookGroups = [
986
+ ['steps', Array.isArray(cap.steps) ? cap.steps : []],
987
+ ['contributions', Array.isArray(cap.contributions) ? cap.contributions : []],
988
+ ];
989
+
990
+ for (const [groupName, hooks] of hookGroups) {
991
+ for (let i = 0; i < hooks.length; i++) {
992
+ const hook = hooks[i];
993
+ if (!hook || typeof hook !== 'object' || Array.isArray(hook)) continue;
994
+ const fragment = hook.fragment;
995
+ if (!fragment || typeof fragment !== 'object' || Array.isArray(fragment)) continue;
996
+ if (typeof fragment.inline === 'string') continue;
997
+ if (typeof fragment.path !== 'string') continue;
998
+
999
+ const abs = path.resolve(capDir, fragment.path);
1000
+ const capRoot = path.resolve(capDir);
1001
+ if (abs !== capRoot && !abs.startsWith(capRoot + path.sep)) {
1002
+ errors.push(
1003
+ cap.id + '/' + groupName + '[' + i + '].fragment.path escapes capability directory: ' +
1004
+ fragment.path,
1005
+ );
1006
+ continue;
1007
+ }
1008
+
1009
+ try {
1010
+ fragment.inline = fs.readFileSync(abs, 'utf8');
1011
+ } catch (err) {
1012
+ errors.push(
1013
+ cap.id + '/' + groupName + '[' + i + '].fragment.path could not be read: ' +
1014
+ fragment.path + ' (' + err.message + ')',
1015
+ );
1016
+ }
1017
+ }
1018
+ }
1019
+
1020
+ return errors;
1021
+ }
1022
+
1023
+ function validateFragment(fragment, prefix) {
1024
+ const errors = [];
1025
+
1026
+ if (typeof fragment !== 'object' || fragment === null || Array.isArray(fragment)) {
1027
+ errors.push(prefix + ' must be an object with path or inline key');
1028
+ return errors;
1029
+ }
1030
+
1031
+ const hasPath = Object.prototype.hasOwnProperty.call(fragment, 'path');
1032
+ const hasInline = Object.prototype.hasOwnProperty.call(fragment, 'inline');
1033
+ if (!hasPath && !hasInline) {
1034
+ errors.push(prefix + ' must have a "path" or "inline" key');
1035
+ }
1036
+ if (hasInline) {
1037
+ const inline = fragment.inline;
1038
+ if (typeof inline !== 'string') {
1039
+ errors.push(prefix + '.inline must be a string');
1040
+ } else if (inline === '') {
1041
+ errors.push(prefix + '.inline must be a non-empty string');
1042
+ }
1043
+ }
1044
+ // S1: fragment.path traversal guard — must be a relative path with no ".." segments
1045
+ if (hasPath) {
1046
+ const p = fragment.path;
1047
+ if (typeof p !== 'string' || p === '' || path.isAbsolute(p) || p.split(/[\\/]/).includes('..')) {
1048
+ errors.push(prefix + '.path must be a relative path with no ".." segments');
1049
+ }
1050
+ }
1051
+
1052
+ return errors;
1053
+ }
1054
+
1055
+ /**
1056
+ * Validate a single step entry.
1057
+ *
1058
+ * @param {object} step The step to validate.
1059
+ * @param {string} prefix Path prefix for error messages (e.g. "steps[0]").
1060
+ * @param {Set|null} declaredSkills Set of skill stems declared in this capability's skills array,
1061
+ * or null if the skills array was not valid (skip membership check).
1062
+ * @param {Set|null} declaredAgents Set of agent names declared in this capability's agents array,
1063
+ * or null if the agents array was not valid (skip membership check).
1064
+ * @returns {string[]}
1065
+ */
1066
+ function validateStep(step, prefix, declaredSkills, declaredAgents) {
1067
+ const errors = [];
1068
+
1069
+ if (!VALID_LOOP_POINTS.has(step.point)) {
1070
+ errors.push(prefix + '.point "' + step.point + '" is not a valid loop point');
1071
+ }
1072
+
1073
+ if (typeof step.ref !== 'object' || step.ref === null) {
1074
+ errors.push(prefix + '.ref must be an object with skill, agent, or command key');
1075
+ } else {
1076
+ const hasSkill = Object.prototype.hasOwnProperty.call(step.ref, 'skill');
1077
+ const hasAgent = Object.prototype.hasOwnProperty.call(step.ref, 'agent');
1078
+ const hasCommand = Object.prototype.hasOwnProperty.call(step.ref, 'command');
1079
+ const dispatchCount = [hasSkill, hasAgent, hasCommand].filter(Boolean).length;
1080
+ if (dispatchCount === 0) {
1081
+ errors.push(prefix + '.ref must have a "skill", "agent", or "command" key');
1082
+ } else if (dispatchCount > 1) {
1083
+ // ref must be exclusive: skill XOR agent XOR command
1084
+ errors.push(prefix + '.ref must have exactly one of "skill", "agent", or "command", not multiple');
1085
+ }
1086
+ if (hasSkill && typeof step.ref.skill !== 'string') {
1087
+ errors.push(prefix + '.ref.skill must be a string');
1088
+ } else if (hasSkill && typeof step.ref.skill === 'string' && step.ref.skill.startsWith('gsd-')) {
1089
+ // Double-prefix guard: ref.skill is an unprefixed stem (e.g. "ui-review").
1090
+ // Workflow dispatch prepends "gsd-" at runtime → "gsd-ui-review".
1091
+ // A stem that already starts with "gsd-" would produce "gsd-gsd-..." at dispatch.
1092
+ errors.push(
1093
+ prefix + '.ref.skill "' + step.ref.skill + '" must not start with "gsd-" ' +
1094
+ '(it is an unprefixed stem; the workflow prepends "gsd-" at dispatch — ' +
1095
+ 'starting with "gsd-" would produce "gsd-' + step.ref.skill + '")',
1096
+ );
1097
+ } else if (hasSkill && typeof step.ref.skill === 'string' && declaredSkills !== null && !declaredSkills.has(step.ref.skill)) {
1098
+ // Membership check: ref.skill must be declared in this capability's skills array.
1099
+ // This catches typos and ensures every dispatched skill is owned by this capability.
1100
+ errors.push(
1101
+ prefix + '.ref.skill "' + step.ref.skill + '" is not declared in this capability\'s skills: [' +
1102
+ [...declaredSkills].join(', ') + ']',
1103
+ );
1104
+ }
1105
+ if (hasAgent && typeof step.ref.agent !== 'string') {
1106
+ errors.push(prefix + '.ref.agent must be a string');
1107
+ } else if (hasAgent && typeof step.ref.agent === 'string' && declaredAgents !== null && !declaredAgents.has(step.ref.agent)) {
1108
+ // Membership check: ref.agent must be declared in this capability's agents array.
1109
+ errors.push(
1110
+ prefix + '.ref.agent "' + step.ref.agent + '" is not declared in this capability\'s agents: [' +
1111
+ [...declaredAgents].join(', ') + ']',
1112
+ );
1113
+ }
1114
+ if (hasCommand && typeof step.ref.command !== 'string') {
1115
+ errors.push(prefix + '.ref.command must be a string');
1116
+ }
1117
+ }
1118
+
1119
+ if (!Array.isArray(step.produces)) {
1120
+ errors.push(prefix + '.produces must be an array');
1121
+ } else {
1122
+ for (const p of step.produces) {
1123
+ if (typeof p !== 'string') errors.push(prefix + '.produces entries must be strings');
1124
+ }
1125
+ }
1126
+
1127
+ if (!Array.isArray(step.consumes)) {
1128
+ errors.push(prefix + '.consumes must be an array');
1129
+ } else {
1130
+ for (const c of step.consumes) {
1131
+ if (typeof c !== 'string') errors.push(prefix + '.consumes entries must be strings');
1132
+ }
1133
+ }
1134
+
1135
+ if (step.when !== undefined && typeof step.when !== 'string') {
1136
+ errors.push(prefix + '.when must be a string if present');
1137
+ }
1138
+
1139
+ if (step.fragment !== undefined) {
1140
+ errors.push(...validateFragment(step.fragment, prefix + '.fragment'));
1141
+ }
1142
+
1143
+ if (!VALID_ON_ERROR.has(step.onError)) {
1144
+ errors.push(prefix + '.onError must be "skip" or "halt" (got: ' + step.onError + ')');
1145
+ }
1146
+
1147
+ return errors;
1148
+ }
1149
+
1150
+ function validateContribution(contrib, prefix) {
1151
+ const errors = [];
1152
+
1153
+ if (!VALID_LOOP_POINTS.has(contrib.point)) {
1154
+ errors.push(prefix + '.point "' + contrib.point + '" is not a valid loop point');
1155
+ }
1156
+
1157
+ if (typeof contrib.into !== 'string') {
1158
+ errors.push(prefix + '.into must be a string (agent role name)');
1159
+ }
1160
+
1161
+ if (!Array.isArray(contrib.produces)) {
1162
+ errors.push(prefix + '.produces must be an array');
1163
+ } else {
1164
+ for (const p of contrib.produces) {
1165
+ if (typeof p !== 'string') errors.push(prefix + '.produces entries must be strings');
1166
+ }
1167
+ }
1168
+
1169
+ if (!Array.isArray(contrib.consumes)) {
1170
+ errors.push(prefix + '.consumes must be an array');
1171
+ } else {
1172
+ for (const c of contrib.consumes) {
1173
+ if (typeof c !== 'string') errors.push(prefix + '.consumes entries must be strings');
1174
+ }
1175
+ }
1176
+
1177
+ errors.push(...validateFragment(contrib.fragment, prefix + '.fragment'));
1178
+
1179
+ if (contrib.when !== undefined && typeof contrib.when !== 'string') {
1180
+ errors.push(prefix + '.when must be a string if present');
1181
+ }
1182
+
1183
+ if (contrib.onError !== undefined && !VALID_ON_ERROR.has(contrib.onError)) {
1184
+ errors.push(prefix + '.onError must be "skip" or "halt" if present');
1185
+ }
1186
+
1187
+ return errors;
1188
+ }
1189
+
1190
+ function validateGate(gate, prefix) {
1191
+ const errors = [];
1192
+
1193
+ if (!VALID_LOOP_POINTS.has(gate.point)) {
1194
+ errors.push(prefix + '.point "' + gate.point + '" is not a valid loop point');
1195
+ }
1196
+
1197
+ if (typeof gate.check !== 'object' || gate.check === null) {
1198
+ errors.push(prefix + '.check must be an object');
1199
+ } else {
1200
+ const hasQuery = Object.prototype.hasOwnProperty.call(gate.check, 'query');
1201
+ const hasPredicate = Object.prototype.hasOwnProperty.call(gate.check, 'predicate');
1202
+ const hasAgentVerdict = Object.prototype.hasOwnProperty.call(gate.check, 'agentVerdict');
1203
+ const count = [hasQuery, hasPredicate, hasAgentVerdict].filter(Boolean).length;
1204
+ if (count !== 1) {
1205
+ errors.push(prefix + '.check must have exactly one of: query, predicate, agentVerdict');
1206
+ }
1207
+ // agentVerdict forces blocking: false (advisory only)
1208
+ if (hasAgentVerdict && gate.blocking === true) {
1209
+ errors.push(
1210
+ prefix + '.check.agentVerdict forces blocking: false (non-deterministic checks may not halt the loop)',
1211
+ );
1212
+ }
1213
+ }
1214
+
1215
+ if (gate.when !== undefined && typeof gate.when !== 'string') {
1216
+ errors.push(prefix + '.when must be a string if present');
1217
+ }
1218
+
1219
+ if (typeof gate.blocking !== 'boolean') {
1220
+ errors.push(prefix + '.blocking must be a boolean');
1221
+ }
1222
+
1223
+ if (!VALID_ON_ERROR.has(gate.onError)) {
1224
+ errors.push(prefix + '.onError must be "skip" or "halt" (got: ' + gate.onError + ')');
1225
+ }
1226
+
1227
+ return errors;
1228
+ }
1229
+
1230
+ // ─── Contract validation ──────────────────────────────────────────────────────
1231
+
1232
+ /**
1233
+ * Validate per-capability contract constraints against the Loop Host Contract.
1234
+ * This covers:
1235
+ * - contribution.into ∈ step's agentRoles
1236
+ * - when references a config key in cap.config
1237
+ *
1238
+ * NOTE: step.consumes satisfiability is NOT checked here — it requires the full
1239
+ * set of validated capabilities (cross-capability produces). It runs in
1240
+ * validateConsumesGlobal() after loadAndValidate builds capMap.
1241
+ *
1242
+ * @param {object} cap Validated capability object
1243
+ * @param {string} capId Capability id (for error messages)
1244
+ */
1245
+ function validateAgainstContract(cap, capId) {
1246
+ if (cap.role !== 'feature') return [];
1247
+ const errors = [];
1248
+ const prefix = 'capability "' + capId + '"';
1249
+
1250
+ // contribution.into must be in the step's agentRoles
1251
+ for (const contrib of cap.contributions) {
1252
+ if (!VALID_LOOP_POINTS.has(contrib.point)) continue; // already reported
1253
+ const contract = POINT_TO_CONTRACT.get(contrib.point);
1254
+ if (contract && !contract.agentRoles.includes(contrib.into)) {
1255
+ errors.push(
1256
+ prefix + ' contribution.into "' + contrib.into + '" at point "' + contrib.point +
1257
+ '" is not in the step\'s agentRoles [' + contract.agentRoles.join(', ') + ']',
1258
+ );
1259
+ }
1260
+ }
1261
+
1262
+ // when references a plausibly-valid config key (string — we require it's in cap.config)
1263
+ for (const step of cap.steps) {
1264
+ if (step.when !== undefined) {
1265
+ if (typeof step.when !== 'string') continue; // already reported above
1266
+ if (
1267
+ typeof cap.config === 'object' &&
1268
+ cap.config !== null &&
1269
+ !Object.prototype.hasOwnProperty.call(cap.config, step.when)
1270
+ ) {
1271
+ errors.push(
1272
+ prefix + ' step.when "' + step.when + '" is not defined in capability config keys',
1273
+ );
1274
+ }
1275
+ }
1276
+ }
1277
+
1278
+ for (const contrib of cap.contributions) {
1279
+ if (contrib.when !== undefined) {
1280
+ if (typeof contrib.when !== 'string') continue;
1281
+ if (
1282
+ typeof cap.config === 'object' &&
1283
+ cap.config !== null &&
1284
+ !Object.prototype.hasOwnProperty.call(cap.config, contrib.when)
1285
+ ) {
1286
+ errors.push(
1287
+ prefix + ' contribution.when "' + contrib.when + '" is not defined in capability config keys',
1288
+ );
1289
+ }
1290
+ }
1291
+ }
1292
+
1293
+ for (const gate of cap.gates) {
1294
+ if (gate.when !== undefined) {
1295
+ if (typeof gate.when !== 'string') continue;
1296
+ if (
1297
+ typeof cap.config === 'object' &&
1298
+ cap.config !== null &&
1299
+ !Object.prototype.hasOwnProperty.call(cap.config, gate.when)
1300
+ ) {
1301
+ errors.push(
1302
+ prefix + ' gate.when "' + gate.when + '" is not defined in capability config keys',
1303
+ );
1304
+ }
1305
+ }
1306
+ }
1307
+
1308
+ return errors;
1309
+ }
1310
+
1311
+ /**
1312
+ * C1+C2: Global consumes-satisfiability validation.
1313
+ *
1314
+ * A hook at point P consuming artifact A is satisfiable iff:
1315
+ * - A is a host-produced artifact available from its step's :post point (C1), and
1316
+ * that :post point's POINT_ORDER index ≤ P's index; OR
1317
+ * - A is produced by any capability hook step at a point whose POINT_ORDER index ≤ P's index
1318
+ * (same-point is OK — topoSortSteps enforces intra-point order); OR
1319
+ * - A is never produced anywhere → rejected.
1320
+ *
1321
+ * Runs after capMap is fully built so cross-capability produces are visible.
1322
+ *
1323
+ * @param {Map<string, object>} capMap Fully-validated capability map.
1324
+ * @returns {string[]} Array of error strings.
1325
+ */
1326
+ function validateConsumesGlobal(capMap) {
1327
+ const errors = [];
1328
+
1329
+ // Build producedAtPoint: artifact → earliest POINT_ORDER index at which it is produced.
1330
+ // Seed with host artifacts (C1: available from their step's :post point).
1331
+ // Host-artifact entries are tagged {pointIdx, isHost:true} so they are never excluded by
1332
+ // the self-consume check.
1333
+ const producedAtPoint = Object.create(null);
1334
+ for (const [artifact, postIdx] of Object.entries(HOST_ARTIFACT_EARLIEST_POINT_IDX)) {
1335
+ if (artifact === '__proto__' || artifact === 'constructor' || artifact === 'prototype') continue;
1336
+ producedAtPoint[artifact] = postIdx;
1337
+ }
1338
+
1339
+ // Build a richer per-artifact producer list for the self-consume check.
1340
+ // Each entry: { pointIdx, capId, stepIdx } — identifies which cap+step produced the artifact.
1341
+ // Host artifacts are seeded separately (no capId) and always satisfy the consume check.
1342
+ // capHookProducers[artifact] = [{pointIdx, capId, stepIdx}, ...]
1343
+ const capHookProducers = Object.create(null);
1344
+
1345
+ // Add hook-produced artifacts from all capabilities.
1346
+ for (const [capId, cap] of capMap) {
1347
+ if (cap.role !== 'feature') continue;
1348
+ for (let si = 0; si < (cap.steps || []).length; si++) {
1349
+ const step = cap.steps[si];
1350
+ if (!VALID_LOOP_POINTS.has(step.point)) continue;
1351
+ const pointIdx = POINT_ORDER.indexOf(step.point);
1352
+ for (const artifact of (step.produces || [])) {
1353
+ if (typeof artifact !== 'string') continue;
1354
+ if (artifact === '__proto__' || artifact === 'constructor' || artifact === 'prototype') continue;
1355
+ if (producedAtPoint[artifact] === undefined || pointIdx < producedAtPoint[artifact]) {
1356
+ producedAtPoint[artifact] = pointIdx;
1357
+ }
1358
+ if (!capHookProducers[artifact]) capHookProducers[artifact] = [];
1359
+ capHookProducers[artifact].push({ pointIdx, capId, stepIdx: si });
1360
+ }
1361
+ }
1362
+ }
1363
+
1364
+ // Duplicate-producer invariant: two capability steps may not produce the same artifact
1365
+ // at the same Loop Extension Point. Same-point dual production makes data-flow resolution
1366
+ // ambiguous and is rejected at gen time (Decision #6).
1367
+ for (const artifact of Object.keys(capHookProducers)) {
1368
+ if (artifact === '__proto__' || artifact === 'constructor' || artifact === 'prototype') continue;
1369
+ const producers = capHookProducers[artifact];
1370
+ // Group by pointIdx
1371
+ const byPoint = Object.create(null);
1372
+ for (const entry of producers) {
1373
+ if (!byPoint[entry.pointIdx]) byPoint[entry.pointIdx] = [];
1374
+ byPoint[entry.pointIdx].push(entry);
1375
+ }
1376
+ for (const pointIdxStr of Object.keys(byPoint)) {
1377
+ const group = byPoint[pointIdxStr];
1378
+ // Count distinct (capId, stepIdx) producer steps — a single step listing the same
1379
+ // artifact twice in its produces array pushes duplicate entries but represents only
1380
+ // ONE producer step and must not false-positive the cross-step gate.
1381
+ const distinctProducers = new Set(group.map((e) => e.capId + ' ' + e.stepIdx));
1382
+ if (distinctProducers.size >= 2) {
1383
+ const pointIdx = Number(pointIdxStr);
1384
+ const pointName = POINT_ORDER[pointIdx];
1385
+ const capIds = [...new Set(group.map((e) => e.capId))].sort().join(', ');
1386
+ throw new Error(
1387
+ 'duplicate-producer invariant violated: artifact "' + artifact + '" is produced by ' +
1388
+ 'two or more capability steps at the same Loop Extension Point "' + pointName + '" ' +
1389
+ '(capabilities: ' + capIds + '). ' +
1390
+ 'Two capability steps producing the same artifact at the same Loop Extension Point ' +
1391
+ 'makes data-flow resolution ambiguous and is rejected at gen time.',
1392
+ );
1393
+ }
1394
+ }
1395
+ }
1396
+
1397
+ // Now check every hook step's consumes.
1398
+ // Self-consume rule: a step H cannot satisfy its own consumes[A] from its own produces[A].
1399
+ // A is satisfiable for H iff:
1400
+ // (a) A is a host artifact with pointIdx <= stepPointIdx, OR
1401
+ // (b) A is produced by a DIFFERENT cap/step at pointIdx <= stepPointIdx.
1402
+ // "Different" means capId != H.capId OR stepIdx != H.stepIdx.
1403
+ for (const [capId, cap] of capMap) {
1404
+ if (cap.role !== 'feature') continue;
1405
+ const prefix = 'capability "' + capId + '"';
1406
+ for (let si = 0; si < (cap.steps || []).length; si++) {
1407
+ const step = cap.steps[si];
1408
+ if (!VALID_LOOP_POINTS.has(step.point)) continue;
1409
+ const stepPointIdx = POINT_ORDER.indexOf(step.point);
1410
+ for (const artifact of (step.consumes || [])) {
1411
+ if (typeof artifact !== 'string') continue;
1412
+
1413
+ // Check host-artifact satisfaction first (never excluded by self-consume).
1414
+ const hostIdx = HOST_ARTIFACT_EARLIEST_POINT_IDX[artifact];
1415
+ const hostSatisfied = hostIdx !== undefined && hostIdx <= stepPointIdx;
1416
+ if (hostSatisfied) continue; // fast-path: host artifact is available
1417
+
1418
+ // Check cap-hook producers, excluding this step itself.
1419
+ const producers = capHookProducers[artifact];
1420
+ if (!producers || producers.length === 0) {
1421
+ // Not a host artifact and never produced by any hook.
1422
+ errors.push(
1423
+ prefix + ' step at point "' + step.point + '" consumes "' + artifact +
1424
+ '" which is never produced by any host artifact or capability hook',
1425
+ );
1426
+ continue;
1427
+ }
1428
+
1429
+ // Find any non-self producer at pointIdx <= stepPointIdx.
1430
+ const otherEarliestIdx = producers.reduce((best, p) => {
1431
+ const isSelf = p.capId === capId && p.stepIdx === si;
1432
+ if (isSelf) return best;
1433
+ return (best === undefined || p.pointIdx < best) ? p.pointIdx : best;
1434
+ }, undefined);
1435
+
1436
+ if (otherEarliestIdx === undefined) {
1437
+ // Only producer is this step itself — self-consume violation.
1438
+ errors.push(
1439
+ prefix + ' step at point "' + step.point + '" consumes "' + artifact +
1440
+ '" which is only produced by this step itself (a step cannot consume its own output)',
1441
+ );
1442
+ } else if (otherEarliestIdx > stepPointIdx) {
1443
+ errors.push(
1444
+ prefix + ' step at point "' + step.point + '" consumes "' + artifact +
1445
+ '" which is only produced after this point (earliest available at POINT_ORDER index ' +
1446
+ otherEarliestIdx + ' = "' + POINT_ORDER[otherEarliestIdx] + '")',
1447
+ );
1448
+ }
1449
+ // else: satisfied by another cap/step at an earlier-or-same point — OK.
1450
+ }
1451
+ }
1452
+ }
1453
+
1454
+ return errors;
1455
+ }
1456
+
1457
+ // ─── Cross-capability invariants ──────────────────────────────────────────────
1458
+
1459
+ const TIER_RANK = { core: 0, standard: 1, full: 2 };
1460
+
1461
+ /**
1462
+ * Enforce cross-capability invariants.
1463
+ *
1464
+ * @param {Map<string, object>} capMap id → validated capability object
1465
+ * @param {Set<string>} centralKeys Set of keys in the central config-schema
1466
+ * @returns {string[]} Array of error strings; empty = all pass.
1467
+ */
1468
+ function validateCrossCapability(capMap, centralKeys) {
1469
+ const errors = [];
1470
+
1471
+ // Ownership: one owner per skill stem + agent name
1472
+ const skillOwner = new Map(); // skill → capId
1473
+ const agentOwner = new Map(); // agent → capId
1474
+ const familyOwner = new Map(); // command family → capId (ADR-959)
1475
+ for (const [capId, cap] of capMap) {
1476
+ if (cap.role !== 'feature') continue;
1477
+ for (const skill of cap.skills) {
1478
+ if (skillOwner.has(skill)) {
1479
+ errors.push(
1480
+ 'skill "' + skill + '" is owned by both "' + skillOwner.get(skill) + '" and "' + capId + '"',
1481
+ );
1482
+ } else {
1483
+ skillOwner.set(skill, capId);
1484
+ }
1485
+ }
1486
+ for (const agent of cap.agents) {
1487
+ if (agentOwner.has(agent)) {
1488
+ errors.push(
1489
+ 'agent "' + agent + '" is owned by both "' + agentOwner.get(agent) + '" and "' + capId + '"',
1490
+ );
1491
+ } else {
1492
+ agentOwner.set(agent, capId);
1493
+ }
1494
+ }
1495
+ // ADR-959: single family ownership across the whole registry
1496
+ if (Array.isArray(cap.commands)) {
1497
+ for (const cmd of cap.commands) {
1498
+ if (typeof cmd.family !== 'string' || cmd.family.length === 0) continue; // already reported
1499
+ if (cmd.family === '__proto__' || cmd.family === 'constructor' || cmd.family === 'prototype') continue;
1500
+ if (familyOwner.has(cmd.family)) {
1501
+ errors.push(
1502
+ 'command family "' + cmd.family + '" is owned by both "' + familyOwner.get(cmd.family) + '" and "' + capId + '"',
1503
+ );
1504
+ } else {
1505
+ familyOwner.set(cmd.family, capId);
1506
+ }
1507
+ }
1508
+ }
1509
+ }
1510
+
1511
+ // Config key ownership: exclusive AND absent from central schema
1512
+ const configKeyOwner = new Map(); // key → capId
1513
+ for (const [capId, cap] of capMap) {
1514
+ if (cap.role !== 'feature' || typeof cap.config !== 'object' || cap.config === null) continue;
1515
+ for (const key of Object.keys(cap.config)) {
1516
+ if (configKeyOwner.has(key)) {
1517
+ errors.push(
1518
+ 'config key "' + key + '" is owned by both "' + configKeyOwner.get(key) + '" and "' + capId + '"',
1519
+ );
1520
+ } else {
1521
+ configKeyOwner.set(key, capId);
1522
+ }
1523
+ if (centralKeys.has(key)) {
1524
+ errors.push(
1525
+ 'config key "' + key + '" is declared in capability "' + capId +
1526
+ '" AND exists in the central config-schema — migration mid-flight: ' +
1527
+ 'remove from central config-schema before adding to the capability',
1528
+ );
1529
+ }
1530
+ }
1531
+ }
1532
+
1533
+ // requires: all ids exist
1534
+ for (const [capId, cap] of capMap) {
1535
+ if (!Array.isArray(cap.requires)) continue;
1536
+ for (const req of cap.requires) {
1537
+ if (!capMap.has(req)) {
1538
+ errors.push(
1539
+ 'capability "' + capId + '" requires "' + req + '" which does not exist',
1540
+ );
1541
+ }
1542
+ }
1543
+ }
1544
+
1545
+ // runtimeCompat: explicit runtime ids must reference runtime capabilities.
1546
+ // The wildcard "*" means descriptor-backed runtimes are supported by default.
1547
+ const runtimeIds = new Set();
1548
+ for (const [id, cap] of capMap) {
1549
+ if (cap.role === 'runtime') runtimeIds.add(id);
1550
+ }
1551
+ for (const [capId, cap] of capMap) {
1552
+ if (cap.role !== 'feature' || typeof cap.runtimeCompat !== 'object' || cap.runtimeCompat === null) continue;
1553
+ for (const field of ['supported', 'unsupported']) {
1554
+ const entries = Array.isArray(cap.runtimeCompat[field]) ? cap.runtimeCompat[field] : [];
1555
+ for (const runtimeId of entries) {
1556
+ if (runtimeId === RUNTIME_COMPAT_WILDCARD) continue;
1557
+ if (typeof runtimeId !== 'string' || runtimeId.length === 0) continue;
1558
+ if (!runtimeIds.has(runtimeId)) {
1559
+ errors.push(
1560
+ 'capability "' + capId + '" runtimeCompat.' + field +
1561
+ ' references unknown runtime "' + runtimeId + '"',
1562
+ );
1563
+ }
1564
+ }
1565
+ }
1566
+ if (cap.runtimeCompat.notes && typeof cap.runtimeCompat.notes === 'object') {
1567
+ for (const runtimeId of Object.keys(cap.runtimeCompat.notes)) {
1568
+ if (runtimeId === RUNTIME_COMPAT_WILDCARD) continue;
1569
+ if (!runtimeIds.has(runtimeId)) {
1570
+ errors.push(
1571
+ 'capability "' + capId + '" runtimeCompat.notes references unknown runtime "' + runtimeId + '"',
1572
+ );
1573
+ }
1574
+ }
1575
+ }
1576
+ }
1577
+
1578
+ // requires: acyclic
1579
+ const cycleErrors = detectRequiresCycles(capMap);
1580
+ errors.push(...cycleErrors);
1581
+
1582
+ // requires: tier-monotone (core may not require standard/full; standard may not require full)
1583
+ for (const [capId, cap] of capMap) {
1584
+ if (!Array.isArray(cap.requires) || !VALID_TIERS.has(cap.tier)) continue;
1585
+ const myRank = TIER_RANK[cap.tier];
1586
+ for (const req of cap.requires) {
1587
+ const reqCap = capMap.get(req);
1588
+ if (!reqCap || !VALID_TIERS.has(reqCap.tier)) continue;
1589
+ const reqRank = TIER_RANK[reqCap.tier];
1590
+ if (reqRank > myRank) {
1591
+ errors.push(
1592
+ 'tier-monotone violation: capability "' + capId + '" (tier: ' + cap.tier +
1593
+ ') requires "' + req + '" (tier: ' + reqCap.tier +
1594
+ ') — a capability may not require a higher-tier capability',
1595
+ );
1596
+ }
1597
+ }
1598
+ }
1599
+
1600
+ return errors;
1601
+ }
1602
+
1603
+ /**
1604
+ * Detect cycles in the requires graph using DFS.
1605
+ */
1606
+ function detectRequiresCycles(capMap) {
1607
+ const errors = [];
1608
+ const WHITE = 0, GRAY = 1, BLACK = 2;
1609
+ const color = new Map([...capMap.keys()].map((k) => [k, WHITE]));
1610
+
1611
+ function dfs(id, stack) {
1612
+ if (color.get(id) === GRAY) {
1613
+ const cycleStr = [...stack, id].join(' → ');
1614
+ errors.push('requires cycle detected: ' + cycleStr);
1615
+ return;
1616
+ }
1617
+ if (color.get(id) === BLACK) return;
1618
+ color.set(id, GRAY);
1619
+ stack.push(id);
1620
+ const cap = capMap.get(id);
1621
+ if (cap && Array.isArray(cap.requires)) {
1622
+ for (const req of cap.requires) {
1623
+ if (capMap.has(req)) dfs(req, stack);
1624
+ }
1625
+ }
1626
+ stack.pop();
1627
+ color.set(id, BLACK);
1628
+ }
1629
+
1630
+ for (const id of capMap.keys()) {
1631
+ if (color.get(id) === WHITE) dfs(id, []);
1632
+ }
1633
+
1634
+ return errors;
1635
+ }
1636
+
1637
+ // ─── requiresClosure ─────────────────────────────────────────────────────────
1638
+
1639
+ /**
1640
+ * Compute the transitive requires closure for a capability id.
1641
+ * Returns a Set<string> of all transitively required capability ids.
1642
+ *
1643
+ * @param {string} id
1644
+ * @param {Map<string, object>} capMap
1645
+ */
1646
+ function computeRequiresClosure(id, capMap) {
1647
+ const visited = new Set();
1648
+ const queue = [id];
1649
+ while (queue.length > 0) {
1650
+ const current = queue.shift();
1651
+ const cap = capMap.get(current);
1652
+ if (!cap || !Array.isArray(cap.requires)) continue;
1653
+ for (const req of cap.requires) {
1654
+ if (!visited.has(req)) {
1655
+ visited.add(req);
1656
+ queue.push(req);
1657
+ }
1658
+ }
1659
+ }
1660
+ return visited;
1661
+ }
1662
+
1663
+ // ─── Topological ordering ─────────────────────────────────────────────────────
1664
+
1665
+ function topoSortHookEntries(entries, hookKey, hookKind) {
1666
+ if (entries.length <= 1) return entries;
1667
+
1668
+ // Build adjacency: entry A must come before entry B if B consumes something A produces
1669
+ const n = entries.length;
1670
+ const inDegree = new Array(n).fill(0);
1671
+ const adj = Array.from({ length: n }, () => []);
1672
+
1673
+ for (let i = 0; i < n; i++) {
1674
+ const producesI = new Set(entries[i][hookKey].produces || []);
1675
+ for (let j = 0; j < n; j++) {
1676
+ if (i === j) continue;
1677
+ const consumesJ = entries[j][hookKey].consumes || [];
1678
+ for (const artifact of consumesJ) {
1679
+ if (producesI.has(artifact)) {
1680
+ adj[i].push(j);
1681
+ inDegree[j]++;
1682
+ break;
1683
+ }
1684
+ }
1685
+ }
1686
+ }
1687
+
1688
+ // Kahn's algorithm with stable tiebreak on capId
1689
+ const queue = [];
1690
+ for (let i = 0; i < n; i++) {
1691
+ if (inDegree[i] === 0) queue.push(i);
1692
+ }
1693
+ // Sort queue by capId for determinism
1694
+ queue.sort((a, b) => entries[a].capId.localeCompare(entries[b].capId));
1695
+
1696
+ const result = [];
1697
+ while (queue.length > 0) {
1698
+ // Take the first (sorted) ready node
1699
+ const idx = queue.shift();
1700
+ result.push(entries[idx]);
1701
+ const newReady = [];
1702
+ for (const neighbor of adj[idx]) {
1703
+ inDegree[neighbor]--;
1704
+ if (inDegree[neighbor] === 0) newReady.push(neighbor);
1705
+ }
1706
+ newReady.sort((a, b) => entries[a].capId.localeCompare(entries[b].capId));
1707
+ queue.push(...newReady);
1708
+ }
1709
+
1710
+ // Fix #2: if result.length < n, Kahn's could not complete — there is a produces/consumes
1711
+ // cycle. Do NOT silently fall back to declaration order; throw a clear error.
1712
+ if (result.length < n) {
1713
+ const sortedIds = entries.map((e) => e.capId).join(', ');
1714
+ throw new Error(
1715
+ 'produces/consumes cycle detected in ' + hookKind + ' at point "' +
1716
+ (entries[0] && entries[0][hookKey] ? entries[0][hookKey].point : '?') +
1717
+ '" among capabilities [' + sortedIds + ']: ' +
1718
+ 'a cycle in hook produces/consumes prevents deterministic ordering',
1719
+ );
1720
+ }
1721
+ return result;
1722
+ }
1723
+
1724
+ /**
1725
+ * Topologically sort steps at a given point by produces/consumes.
1726
+ * Capability-id tiebreak for determinism.
1727
+ *
1728
+ * @param {{ capId: string, step: object }[]} entries
1729
+ * @returns {{ capId: string, step: object }[]}
1730
+ */
1731
+ function topoSortSteps(entries) {
1732
+ return topoSortHookEntries(entries, 'step', 'steps');
1733
+ }
1734
+
1735
+ function topoSortContributions(entries) {
1736
+ return topoSortHookEntries(entries, 'contrib', 'contributions');
1737
+ }
1738
+
1739
+ // ─── ADR-857 Phase 4a: Derived views ─────────────────────────────────────────
1740
+
1741
+ // FIX 5 (lazy requires): paths are declared at top level but the actual require()
1742
+ // calls are deferred into lazy accessor functions so importing this generator for
1743
+ // its other exports does NOT fail at module-load time on a fresh/unbuilt worktree.
1744
+ const INSTALL_PROFILES_PATH = path.join(ROOT, 'pp-core', 'bin', 'lib', 'install-profiles.cjs');
1745
+ const CLUSTERS_PATH = path.join(ROOT, 'pp-core', 'bin', 'lib', 'clusters.cjs');
1746
+
1747
+ let _installProfilesMod = null;
1748
+ let _clustersMod = null;
1749
+
1750
+ function getInstallProfiles() {
1751
+ if (!_installProfilesMod) _installProfilesMod = require(INSTALL_PROFILES_PATH);
1752
+ return _installProfilesMod;
1753
+ }
1754
+
1755
+ function getClusters() {
1756
+ if (!_clustersMod) _clustersMod = require(CLUSTERS_PATH);
1757
+ return _clustersMod;
1758
+ }
1759
+
1760
+ /**
1761
+ * Derive capabilityClusters: { <capId>: [<skill stems>] }
1762
+ * Each capability's own skills array, sorted for determinism.
1763
+ *
1764
+ * FIX 3: scope rule = "capabilities that own skills" (non-empty skills array).
1765
+ * Both capabilityClusters and profileMembership use this same predicate so a
1766
+ * future non-feature role carrying skills is treated identically in both, and a
1767
+ * feature cap with no skills appears in neither.
1768
+ *
1769
+ * @param {Map<string, object>} capMap
1770
+ * @returns {object} Object.create(null) — prototype-pollution safe
1771
+ */
1772
+ function deriveCapabilityClusters(capMap) {
1773
+ const result = Object.create(null);
1774
+ for (const [capId, cap] of capMap) {
1775
+ // S2b: inline literal guard at each write site (CodeQL barrier)
1776
+ if (capId === '__proto__' || capId === 'constructor' || capId === 'prototype') continue;
1777
+ // FIX 3: include any cap that owns skills (non-empty skills array), regardless of role
1778
+ if (!Array.isArray(cap.skills) || cap.skills.length === 0) continue;
1779
+ // Sort for determinism
1780
+ const sorted = [...cap.skills].sort();
1781
+ result[capId] = sorted;
1782
+ }
1783
+ return result;
1784
+ }
1785
+
1786
+ /**
1787
+ * Derive profileMembership: { <capId>: { tier: <t>, profiles: [<names>] } }
1788
+ * profiles = suffix of PROFILE_RANK starting at the capability's tier index.
1789
+ * tier 'core' → ['core', 'standard', 'full']
1790
+ * tier 'standard' → ['standard', 'full']
1791
+ * tier 'full' → ['full']
1792
+ *
1793
+ * FIX 3: scope rule = "capabilities that own skills" (non-empty skills array),
1794
+ * consistent with deriveCapabilityClusters. Both derived views cover the same set.
1795
+ *
1796
+ * FIX 5: tierIdx === -1 means VALID_TIERS and PROFILE_RANK have drifted; throw
1797
+ * loudly instead of silently producing ['full'] for the affected capability.
1798
+ *
1799
+ * @param {Map<string, object>} capMap
1800
+ * @returns {object} Object.create(null) — prototype-pollution safe
1801
+ */
1802
+ function deriveProfileMembership(capMap) {
1803
+ const { PROFILE_RANK } = getInstallProfiles();
1804
+ const result = Object.create(null);
1805
+ for (const [capId, cap] of capMap) {
1806
+ // S2b: inline literal guard at each write site (CodeQL barrier)
1807
+ if (capId === '__proto__' || capId === 'constructor' || capId === 'prototype') continue;
1808
+ if (!VALID_TIERS.has(cap.tier)) continue;
1809
+ // FIX 3: consistent scope — only capabilities that own skills (non-empty skills array)
1810
+ if (!Array.isArray(cap.skills) || cap.skills.length === 0) continue;
1811
+ const tierIdx = PROFILE_RANK.indexOf(cap.tier);
1812
+ // FIX 5: throw loudly on VALID_TIERS/PROFILE_RANK drift (was silent continue)
1813
+ if (tierIdx === -1) {
1814
+ throw new Error(
1815
+ 'deriveProfileMembership: capability "' + capId + '" tier "' + cap.tier +
1816
+ '" is in VALID_TIERS but not in PROFILE_RANK — VALID_TIERS/PROFILE_RANK drift detected',
1817
+ );
1818
+ }
1819
+ const profiles = PROFILE_RANK.slice(tierIdx);
1820
+ result[capId] = { tier: cap.tier, profiles: [...profiles] };
1821
+ }
1822
+ return result;
1823
+ }
1824
+
1825
+ /**
1826
+ * Run consistency gates:
1827
+ * - HARD: for each capId that matches a CLUSTERS key, derived skills must match
1828
+ * the hand-authored CLUSTERS[capId] set (order-insensitive). Throws on mismatch.
1829
+ * - SOFT: for each capability, for each skill not yet in all non-full profiles it
1830
+ * belongs to (closure-resolved), emit ONE pending-reconciliation warning listing
1831
+ * the missing profiles together. Warnings are collected and returned — NOT thrown.
1832
+ *
1833
+ * FIX 1: load the REAL skills manifest (same as bin/install.js) so resolveProfile
1834
+ * expands requires:-closure. Loaded once and reused across all capabilities.
1835
+ *
1836
+ * FIX 3: iterate capabilityClusters (which already covers "capabilities that own
1837
+ * skills") rather than profileMembership, so both derived views share one scope.
1838
+ *
1839
+ * FIX 4: one warning per (capability, skill) gap, listing all missing non-full
1840
+ * profiles together, instead of one warning per (capability, skill, profile).
1841
+ *
1842
+ * @param {object} capabilityClusters From deriveCapabilityClusters()
1843
+ * @param {object} profileMembership From deriveProfileMembership()
1844
+ * @param {Map<string, object>} capMap Original capMap for skill lists
1845
+ * @returns {string[]} Array of pending-reconciliation warning strings
1846
+ */
1847
+ function runConsistencyGate(capabilityClusters, profileMembership, capMap) {
1848
+ const { CLUSTERS: clustersObj } = getClusters();
1849
+ const { resolveProfile, loadSkillsManifest } = getInstallProfiles();
1850
+
1851
+ // ── HARD gate: cluster set comparison ──────────────────────────────────────
1852
+ for (const capId of Object.keys(capabilityClusters)) {
1853
+ // S2b: inline literal guard (CodeQL barrier)
1854
+ if (capId === '__proto__' || capId === 'constructor' || capId === 'prototype') continue;
1855
+ // Only check if a CLUSTERS entry with the same name exists
1856
+ if (!Object.prototype.hasOwnProperty.call(clustersObj, capId)) continue;
1857
+ const derivedSet = new Set(capabilityClusters[capId]);
1858
+ const handAuthored = clustersObj[capId];
1859
+ const handAuthoredSet = new Set(handAuthored);
1860
+ // Compare sets (order-insensitive)
1861
+ let mismatch = derivedSet.size !== handAuthoredSet.size;
1862
+ if (!mismatch) {
1863
+ for (const s of derivedSet) {
1864
+ if (!handAuthoredSet.has(s)) { mismatch = true; break; }
1865
+ }
1866
+ }
1867
+ if (mismatch) {
1868
+ throw new Error(
1869
+ 'capability-cluster consistency gate FAILED for capId "' + capId + '":\n' +
1870
+ ' derived set: [' + [...derivedSet].sort().join(', ') + ']\n' +
1871
+ ' hand-authored set: [' + [...handAuthoredSet].sort().join(', ') + ']\n' +
1872
+ 'The capability\'s skills array must match the hand-authored CLUSTERS["' + capId + '"] at cutover.',
1873
+ );
1874
+ }
1875
+ }
1876
+
1877
+ // ── SOFT gate: profile reconciliation warnings ─────────────────────────────
1878
+
1879
+ // FIX 1: load the REAL skills manifest once (same path as bin/install.js uses),
1880
+ // so resolveProfile expands requires:-closure and the effective set is accurate.
1881
+ // D-12 flat-hyphen: commands live flat at commands/pp-*.md (no gsd/ subdir); a
1882
+ // stale commands/gsd path yields an EMPTY manifest, making every profile's
1883
+ // effective set empty and firing false-positive reconciliation warnings.
1884
+ const commandsDir = path.join(ROOT, 'commands');
1885
+ const skillsManifest = loadSkillsManifest(commandsDir);
1886
+
1887
+ // FIX 1: resolve each profile's effective set once and cache — don't reload per-capability.
1888
+ const profileEffectiveSetCache = Object.create(null);
1889
+ function getEffectiveSet(profileName) {
1890
+ if (profileName in profileEffectiveSetCache) return profileEffectiveSetCache[profileName];
1891
+ const resolved = resolveProfile({ modes: [profileName], manifest: skillsManifest });
1892
+ const effectiveSet = resolved.skills === '*' ? null : resolved.skills;
1893
+ profileEffectiveSetCache[profileName] = effectiveSet;
1894
+ return effectiveSet;
1895
+ }
1896
+
1897
+ const warnings = [];
1898
+
1899
+ // FIX 3: iterate capabilityClusters (same set as profileMembership after FIX 3 scoping).
1900
+ for (const capId of Object.keys(capabilityClusters)) {
1901
+ // S2b: inline literal guard (CodeQL barrier)
1902
+ if (capId === '__proto__' || capId === 'constructor' || capId === 'prototype') continue;
1903
+ const membership = profileMembership[capId];
1904
+ if (!membership) continue; // no profile membership (e.g. cap has skills but invalid tier)
1905
+ const cap = capMap.get(capId);
1906
+ if (!cap || !Array.isArray(cap.skills)) continue;
1907
+
1908
+ // Collect the non-full profiles for this capability
1909
+ const nonFullProfiles = membership.profiles.filter((p) => p !== 'full');
1910
+
1911
+ // FIX 4: one warning per (capability, skill) gap — list all missing profiles together
1912
+ for (const skill of cap.skills) {
1913
+ // S2b: inline literal guard (CodeQL barrier)
1914
+ if (skill === '__proto__' || skill === 'constructor' || skill === 'prototype') continue;
1915
+
1916
+ const missingProfiles = [];
1917
+ for (const profileName of nonFullProfiles) {
1918
+ const effectiveSet = getEffectiveSet(profileName);
1919
+ if (effectiveSet === null) continue; // profile resolved to full (unexpected but safe)
1920
+ if (!effectiveSet.has(skill)) {
1921
+ missingProfiles.push(profileName);
1922
+ }
1923
+ }
1924
+
1925
+ if (missingProfiles.length > 0) {
1926
+ warnings.push(
1927
+ '⚠ pending-reconciliation: capability \'' + capId + '\' (tier ' + membership.tier + ')' +
1928
+ ' skill \'' + skill + '\' not yet in hand-authored profile(s): <' + missingProfiles.join(', ') +
1929
+ '>; add at cutover',
1930
+ );
1931
+ }
1932
+ }
1933
+ }
1934
+
1935
+ return warnings;
1936
+ }
1937
+
1938
+ // ─── ADR-857 phase 5e: configFormat ↔ installSurface parity gate ─────────────
1939
+
1940
+ // Map: installSurface → expected configFormat
1941
+ // Derived from the pairing of capability.json descriptors (installSurface)
1942
+ // and capability.json descriptors (configFormat). DEFECT.GENERATIVE-FIX: this map
1943
+ // is the single parity contract between the two generated surfaces.
1944
+ // NOTE: both values come from the descriptor bodies in capMap — no dependency on
1945
+ // runtime-config-adapter-registry.cjs, which now requires capability-registry.cjs
1946
+ // (the file this gen-script produces), and thus must not be required here.
1947
+ const INSTALL_SURFACE_TO_CONFIG_FORMAT = new Map([
1948
+ ['settings-json', 'settings-json'],
1949
+ ['codex-toml', 'toml'],
1950
+ ['copilot-instructions', 'markdown'],
1951
+ ['cline-rules', 'markdown-dir'],
1952
+ ['cursor-hooks-json', 'none'],
1953
+ ['profile-marker-only', 'none'],
1954
+ ]);
1955
+
1956
+ /**
1957
+ * ADR-857 phase 5e: configFormat ↔ installSurface parity gate.
1958
+ *
1959
+ * For each runtime capability that has an installSurface in its descriptor,
1960
+ * assert that its configFormat matches the expected value derived from its
1961
+ * installSurface. Both values are read directly from the capMap descriptor
1962
+ * bodies — no dependency on runtime-config-adapter-registry.cjs.
1963
+ *
1964
+ * HARD gate — throws on mismatch (DEFECT.GENERATIVE-FIX: this invariant is
1965
+ * derived from two parallel generated surfaces and must fail loudly).
1966
+ *
1967
+ * @param {Map<string, object>} capMap Fully-validated capability map.
1968
+ * @returns {void} Throws on mismatch; returns normally on success.
1969
+ */
1970
+ function runConfigFormatParityGate(capMap) {
1971
+ // Read installSurface directly from the descriptor bodies already loaded into
1972
+ // capMap — eliminates the require cycle introduced when adapter-registry was
1973
+ // changed to require capability-registry.cjs (ADR-857 phase 5g drive 2).
1974
+ for (const [capId, cap] of capMap) {
1975
+ if (cap.role !== 'runtime') continue;
1976
+
1977
+ const r = cap.runtime;
1978
+ if (!r || typeof r.configFormat !== 'string') continue; // already validated above
1979
+
1980
+ // Only check runtimes that have an installSurface (i.e. are config-adapter runtimes)
1981
+ if (typeof r.installSurface !== 'string') continue; // grok etc. excluded — no installSurface
1982
+
1983
+ const installSurface = r.installSurface;
1984
+ const expectedConfigFormat = INSTALL_SURFACE_TO_CONFIG_FORMAT.get(installSurface);
1985
+
1986
+ if (expectedConfigFormat === undefined) {
1987
+ // Unknown installSurface — the mapping needs to be updated
1988
+ throw new Error(
1989
+ 'configFormat parity gate: runtime "' + capId + '" has installSurface "' + installSurface +
1990
+ '" which is not in the INSTALL_SURFACE_TO_CONFIG_FORMAT mapping — ' +
1991
+ 'update the mapping in scripts/gen-capability-registry.cjs',
1992
+ );
1993
+ }
1994
+
1995
+ if (r.configFormat !== expectedConfigFormat) {
1996
+ throw new Error(
1997
+ 'configFormat parity gate FAILED for runtime "' + capId + '":\n' +
1998
+ ' installSurface: ' + installSurface + '\n' +
1999
+ ' expected configFormat: ' + expectedConfigFormat + '\n' +
2000
+ ' actual configFormat: ' + r.configFormat + '\n' +
2001
+ 'The capability.json configFormat must match the value derived from installSurface ' +
2002
+ '(src: scripts/gen-capability-registry.cjs INSTALL_SURFACE_TO_CONFIG_FORMAT)',
2003
+ );
2004
+ }
2005
+ }
2006
+ }
2007
+
2008
+ // ─── Gen-time wired guard ─────────────────────────────────────────────────────
2009
+
2010
+ /**
2011
+ * Validate that every hook point declared by a capability has a corresponding
2012
+ * `loop render-hooks <point>` call site in one of the host-loop workflow files.
2013
+ *
2014
+ * Only valid loop points (in VALID_LOOP_POINTS) are checked here. Invalid points
2015
+ * are already caught by validateStep/validateContribution/validateGate — do not
2016
+ * double-report.
2017
+ *
2018
+ * @param {object} cap Validated capability object.
2019
+ * @param {Set<string>} wiredSet Set of points that have call sites in host workflows.
2020
+ * @returns {string[]} Array of error strings; empty means all points are wired.
2021
+ */
2022
+ function validateHooksWired(cap, wiredSet) {
2023
+ const errors = [];
2024
+ const capId = cap.id || '(unknown)';
2025
+
2026
+ function checkPoint(point, groupName, idx) {
2027
+ // Only flag valid points that are unwired — invalid points are schema-validator's job.
2028
+ if (!VALID_LOOP_POINTS.has(point)) return;
2029
+ if (!wiredSet.has(point)) {
2030
+ errors.push(
2031
+ 'capability "' + capId + '" ' + groupName + '[' + idx + '].point "' + point +
2032
+ '" is declared but not wired in any host-loop workflow ' +
2033
+ '(no `loop render-hooks ' + point + '` call site). ' +
2034
+ 'Wire the call site in the host workflow ' +
2035
+ '(see scripts/gen-loop-host-contract.cjs STEP_WORKFLOWS) or remove the hook.',
2036
+ );
2037
+ }
2038
+ }
2039
+
2040
+ for (let i = 0; i < (cap.steps || []).length; i++) {
2041
+ const hook = cap.steps[i];
2042
+ if (hook.point !== undefined) checkPoint(hook.point, 'steps', i);
2043
+ }
2044
+ for (let i = 0; i < (cap.contributions || []).length; i++) {
2045
+ const hook = cap.contributions[i];
2046
+ if (hook.point !== undefined) checkPoint(hook.point, 'contributions', i);
2047
+ }
2048
+ for (let i = 0; i < (cap.gates || []).length; i++) {
2049
+ const hook = cap.gates[i];
2050
+ if (hook.point !== undefined) checkPoint(hook.point, 'gates', i);
2051
+ }
2052
+
2053
+ return errors;
2054
+ }
2055
+
2056
+ // ─── Registry builder ─────────────────────────────────────────────────────────
2057
+
2058
+ /**
2059
+ * Read + validate all capabilities/<id>/capability.json files.
2060
+ * Returns { capMap, errors } where capMap is Map<id, cap>.
2061
+ *
2062
+ * @param {Set<string>} [centralKeys] Keys in central config-schema for collision detection.
2063
+ * If omitted, reads from disk. Pass new Set() to skip central-collision checks
2064
+ * (used during 3a-impl while migration is in-progress).
2065
+ * @param {string} [capabilitiesDir] Override capabilities dir (for testing with fixtures).
2066
+ */
2067
+ function loadAndValidate(centralKeys, capabilitiesDir) {
2068
+ const resolvedCentralKeys = centralKeys !== undefined ? centralKeys : loadCentralConfigKeys();
2069
+ const resolvedCapDir = capabilitiesDir !== undefined ? capabilitiesDir : CAPABILITIES_DIR;
2070
+ const errors = [];
2071
+ const capMap = new Map();
2072
+
2073
+ if (!fs.existsSync(resolvedCapDir)) {
2074
+ return { capMap, errors };
2075
+ }
2076
+
2077
+ // Compute wired points ONCE before iterating capabilities so the filesystem
2078
+ // scan is not repeated per-capability. ROOT is the repo root (defined at top of file).
2079
+ const wiredSet = getWiredLoopPoints(ROOT);
2080
+
2081
+ const folderEntries = fs.readdirSync(resolvedCapDir, { withFileTypes: true })
2082
+ .filter((e) => e.isDirectory())
2083
+ .map((e) => e.name)
2084
+ .sort();
2085
+
2086
+ for (const folderId of folderEntries) {
2087
+ const capPath = path.join(resolvedCapDir, folderId, 'capability.json');
2088
+ if (!fs.existsSync(capPath)) continue;
2089
+
2090
+ let cap;
2091
+ try {
2092
+ cap = JSON.parse(fs.readFileSync(capPath, 'utf8'));
2093
+ } catch (err) {
2094
+ errors.push(folderId + '/capability.json: JSON parse error: ' + String(err.message));
2095
+ continue;
2096
+ }
2097
+
2098
+ const capErrors = validateCapability(cap, folderId);
2099
+ if (capErrors.length > 0) {
2100
+ for (const e of capErrors) errors.push(folderId + '/capability.json: ' + e);
2101
+ continue; // skip cross-validation if basic schema fails
2102
+ }
2103
+
2104
+ const contractErrors = validateAgainstContract(cap, cap.id);
2105
+ if (contractErrors.length > 0) {
2106
+ for (const e of contractErrors) errors.push(folderId + '/capability.json: ' + e);
2107
+ // Fix #6: do NOT add contract-invalid caps to capMap — validateCrossCapability should
2108
+ // only see fully-valid capabilities so its invariants are meaningful.
2109
+ continue;
2110
+ }
2111
+
2112
+ // Gen-time wired guard: reject hooks that declare a valid point with no call site.
2113
+ const wiredErrors = validateHooksWired(cap, wiredSet);
2114
+ if (wiredErrors.length > 0) {
2115
+ for (const e of wiredErrors) errors.push(folderId + '/capability.json: ' + e);
2116
+ continue;
2117
+ }
2118
+
2119
+ const fragmentErrors = materializeHookFragments(cap, path.dirname(capPath));
2120
+ if (fragmentErrors.length > 0) {
2121
+ for (const e of fragmentErrors) errors.push(folderId + '/capability.json: ' + e);
2122
+ continue;
2123
+ }
2124
+
2125
+ capMap.set(cap.id, cap);
2126
+ }
2127
+
2128
+ // Cross-capability invariants — capMap contains only fully-valid capabilities at this point.
2129
+ const crossErrors = validateCrossCapability(capMap, resolvedCentralKeys);
2130
+ errors.push(...crossErrors);
2131
+
2132
+ // C2: Global consumes-satisfiability — runs after capMap is fully built so cross-capability
2133
+ // produces are visible. A capability with consumes errors is kept in capMap (it passed per-cap
2134
+ // validation) but the errors are surfaced so the build fails.
2135
+ const consumesErrors = validateConsumesGlobal(capMap);
2136
+ errors.push(...consumesErrors);
2137
+
2138
+ return { capMap, errors };
2139
+ }
2140
+
2141
+ /**
2142
+ * Build the registry object from a validated capMap.
2143
+ *
2144
+ * @param {Map<string, object>} capMap
2145
+ */
2146
+ function buildRegistry(capMap) {
2147
+ // S2b: Use Object.create(null) for all accumulator maps so prototype-pollution
2148
+ // can't touch Object.prototype even if a reserved name slips through validation.
2149
+ const capabilities = Object.create(null);
2150
+ const bySkill = Object.create(null);
2151
+ const byAgent = Object.create(null);
2152
+ const byLoopPoint = Object.create(null);
2153
+ const configKeys = Object.create(null);
2154
+ const configSchema = Object.create(null);
2155
+ const runtimes = Object.create(null);
2156
+
2157
+ // Initialize byLoopPoint for all valid points
2158
+ for (const point of VALID_LOOP_POINTS) {
2159
+ byLoopPoint[point] = { steps: [], contributions: [], gates: [] };
2160
+ }
2161
+
2162
+ // Phase 1: collect per-point entries grouped by point
2163
+ const pointSteps = new Map(); // point → [{ capId, step }]
2164
+ const pointContribs = new Map(); // point → [{ capId, contrib }]
2165
+ const pointGates = new Map(); // point → [{ capId, gate }]
2166
+
2167
+ for (const point of VALID_LOOP_POINTS) {
2168
+ pointSteps.set(point, []);
2169
+ pointContribs.set(point, []);
2170
+ pointGates.set(point, []);
2171
+ }
2172
+
2173
+ for (const [capId, cap] of capMap) {
2174
+ // S2b: inline literal guard at each write site (CodeQL barrier)
2175
+ if (capId === '__proto__' || capId === 'constructor' || capId === 'prototype') continue;
2176
+ capabilities[capId] = cap;
2177
+
2178
+ if (cap.role === 'feature') {
2179
+ for (const skill of (cap.skills || [])) {
2180
+ // S2b: inline literal guard at each write site (CodeQL barrier)
2181
+ if (skill === '__proto__' || skill === 'constructor' || skill === 'prototype') continue;
2182
+ bySkill[skill] = capId;
2183
+ }
2184
+ for (const agent of (cap.agents || [])) {
2185
+ // S2b: inline literal guard at each write site (CodeQL barrier)
2186
+ if (agent === '__proto__' || agent === 'constructor' || agent === 'prototype') continue;
2187
+ byAgent[agent] = capId;
2188
+ }
2189
+ for (const key of Object.keys(cap.config || {})) {
2190
+ // S2b: inline literal guard at each write site (CodeQL barrier)
2191
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;
2192
+ configKeys[key] = capId;
2193
+
2194
+ // Build configSchema entry — validate the slice first (throw on violation)
2195
+ const slice = (cap.config || {})[key];
2196
+ const sliceErrors = validateConfigSliceEntry(capId, key, slice);
2197
+ if (sliceErrors.length > 0) {
2198
+ throw new Error(
2199
+ 'configSchema validation failed during registry build:\n' +
2200
+ sliceErrors.map((e) => ' ' + e).join('\n'),
2201
+ );
2202
+ }
2203
+ // S2b: inline literal guard for configSchema write site
2204
+ if (key !== '__proto__' && key !== 'constructor' && key !== 'prototype') {
2205
+ configSchema[key] = {
2206
+ owner: capId,
2207
+ type: slice.type,
2208
+ default: slice.default,
2209
+ description: slice.description,
2210
+ };
2211
+ // Preserve values array for enum types if present
2212
+ if (slice.type === 'enum' && Array.isArray(slice.values)) {
2213
+ configSchema[key].values = slice.values;
2214
+ }
2215
+ }
2216
+ }
2217
+
2218
+ for (const step of (cap.steps || [])) {
2219
+ if (VALID_LOOP_POINTS.has(step.point)) {
2220
+ pointSteps.get(step.point).push({ capId, step });
2221
+ }
2222
+ }
2223
+ for (const contrib of (cap.contributions || [])) {
2224
+ if (VALID_LOOP_POINTS.has(contrib.point)) {
2225
+ // Group contributions by into, then cap-id order
2226
+ pointContribs.get(contrib.point).push({ capId, contrib });
2227
+ }
2228
+ }
2229
+ for (const gate of (cap.gates || [])) {
2230
+ if (VALID_LOOP_POINTS.has(gate.point)) {
2231
+ pointGates.get(gate.point).push({ capId, gate });
2232
+ }
2233
+ }
2234
+ } else if (cap.role === 'runtime') {
2235
+ // S2b: inline literal guard at each write site (CodeQL barrier) — capId already guarded above
2236
+ runtimes[capId] = cap;
2237
+ }
2238
+ }
2239
+
2240
+ // Phase 2: materialize ordering
2241
+ for (const point of VALID_LOOP_POINTS) {
2242
+ // Steps: topological sort by produces/consumes, cap-id tiebreak
2243
+ const sortedSteps = topoSortSteps(pointSteps.get(point));
2244
+ byLoopPoint[point].steps = sortedSteps.map((e) => ({
2245
+ capId: e.capId,
2246
+ ...e.step,
2247
+ }));
2248
+
2249
+ // Contributions: topological sort by produces/consumes, cap-id tiebreak
2250
+ const sortedContribs = topoSortContributions(pointContribs.get(point));
2251
+ byLoopPoint[point].contributions = sortedContribs.map((e) => ({
2252
+ capId: e.capId,
2253
+ ...e.contrib,
2254
+ }));
2255
+
2256
+ // Gates: as declared (stable by capId order)
2257
+ const gates = pointGates.get(point);
2258
+ gates.sort((a, b) => a.capId.localeCompare(b.capId));
2259
+ byLoopPoint[point].gates = gates.map((e) => ({
2260
+ capId: e.capId,
2261
+ ...e.gate,
2262
+ }));
2263
+ }
2264
+
2265
+ // ── ADR-959: commandFamilies index ─────────────────────────────────────────
2266
+ // family → { capId, module, router }
2267
+ // Built from all feature capabilities' commands arrays.
2268
+ const commandFamilies = Object.create(null);
2269
+ for (const [capId, cap] of capMap) {
2270
+ // S2b: inline literal guard at each write site (CodeQL barrier)
2271
+ if (capId === '__proto__' || capId === 'constructor' || capId === 'prototype') continue;
2272
+ if (cap.role !== 'feature' || !Array.isArray(cap.commands)) continue;
2273
+ for (const cmd of cap.commands) {
2274
+ if (typeof cmd.family !== 'string' || cmd.family.length === 0) continue;
2275
+ // S2b: inline literal guard at family key write site (CodeQL barrier)
2276
+ if (cmd.family === '__proto__' || cmd.family === 'constructor' || cmd.family === 'prototype') continue;
2277
+ if (typeof cmd.module !== 'string' || cmd.module.length === 0) continue;
2278
+ if (typeof cmd.router !== 'string' || cmd.router.length === 0) continue;
2279
+ commandFamilies[cmd.family] = { capId, module: cmd.module, router: cmd.router };
2280
+ }
2281
+ }
2282
+
2283
+ // ── ADR-857 phase 4a: derived views ────────────────────────────────────────
2284
+ const capabilityClusters = deriveCapabilityClusters(capMap);
2285
+ const profileMembership = deriveProfileMembership(capMap);
2286
+ // runConsistencyGate: hard gate throws on mismatch; returns soft warning strings.
2287
+ // Warnings are returned in the registry object so callers can emit them to stderr
2288
+ // without affecting the serialized file content (determinism gate stays clean).
2289
+ const reconciliationWarnings = runConsistencyGate(capabilityClusters, profileMembership, capMap);
2290
+
2291
+ // ADR-857 phase 5e: configFormat ↔ installSurface parity gate.
2292
+ // HARD gate — throws on mismatch; SOFT skip if adapter module not loadable.
2293
+ runConfigFormatParityGate(capMap);
2294
+
2295
+ return {
2296
+ version: SCHEMA_VERSION,
2297
+ capabilities,
2298
+ bySkill,
2299
+ byAgent,
2300
+ byLoopPoint,
2301
+ configKeys,
2302
+ configSchema,
2303
+ runtimes,
2304
+ commandFamilies,
2305
+ capabilityClusters,
2306
+ profileMembership,
2307
+ // warnings are NOT serialized — returned only for caller consumption via stderr
2308
+ _reconciliationWarnings: reconciliationWarnings,
2309
+ };
2310
+ }
2311
+
2312
+ // ─── Registry serialization ───────────────────────────────────────────────────
2313
+
2314
+ /**
2315
+ * Serialize the registry to a CommonJS module string.
2316
+ *
2317
+ * @param {object} registry The registry object from buildRegistry()
2318
+ * @param {Map<string, object>} capMap Used for requiresClosure()
2319
+ */
2320
+ function serializeRegistry(registry, capMap) {
2321
+ const lines = [];
2322
+
2323
+ lines.push("'use strict';");
2324
+ lines.push('');
2325
+ lines.push('/**');
2326
+ lines.push(' * capability-registry.cjs — generated by scripts/gen-capability-registry.cjs');
2327
+ lines.push(' * DO NOT EDIT BY HAND. Run: node scripts/gen-capability-registry.cjs --write');
2328
+ lines.push(' * ADR-894 §5 — role-partitioned Capability Registry.');
2329
+ lines.push(' */');
2330
+ lines.push('');
2331
+
2332
+ // Serialize each section as a variable to keep the file readable
2333
+ lines.push('const capabilities = ' + JSON.stringify(registry.capabilities, null, 2) + ';');
2334
+ lines.push('');
2335
+ lines.push('const bySkill = ' + JSON.stringify(registry.bySkill, null, 2) + ';');
2336
+ lines.push('');
2337
+ lines.push('const byAgent = ' + JSON.stringify(registry.byAgent, null, 2) + ';');
2338
+ lines.push('');
2339
+ lines.push('const byLoopPoint = ' + JSON.stringify(registry.byLoopPoint, null, 2) + ';');
2340
+ lines.push('');
2341
+ lines.push('const configKeys = ' + JSON.stringify(registry.configKeys, null, 2) + ';');
2342
+ lines.push('');
2343
+ lines.push('const configSchema = ' + JSON.stringify(registry.configSchema, null, 2) + ';');
2344
+ lines.push('');
2345
+ lines.push('const runtimes = ' + JSON.stringify(registry.runtimes, null, 2) + ';');
2346
+ lines.push('');
2347
+
2348
+ // ADR-959: commandFamilies index — sort family keys for determinism.
2349
+ const sortedCommandFamilies = Object.create(null);
2350
+ const commandFamilyKeys = Object.keys(registry.commandFamilies || {}).sort();
2351
+ for (const family of commandFamilyKeys) {
2352
+ // S2b: inline literal guard at write site (CodeQL barrier)
2353
+ if (family === '__proto__' || family === 'constructor' || family === 'prototype') continue;
2354
+ sortedCommandFamilies[family] = registry.commandFamilies[family];
2355
+ }
2356
+ lines.push('const commandFamilies = ' + JSON.stringify(sortedCommandFamilies, null, 2) + ';');
2357
+ lines.push('');
2358
+
2359
+ // ADR-857 phase 4a: derived views — globally sorted capIds for determinism.
2360
+ // FIX 2: collect ALL capIds across both views and sort globally so feature + runtime
2361
+ // capIds interleave correctly when both are present (phase 5 readiness).
2362
+ const allClusterCapIds = new Set(Object.keys(registry.capabilityClusters));
2363
+ const allProfileCapIds = new Set(Object.keys(registry.profileMembership));
2364
+ const allCapIds = new Set([...allClusterCapIds, ...allProfileCapIds]);
2365
+ // FIX 5: inline literal guard at write sites (CodeQL barrier)
2366
+ allCapIds.delete('__proto__');
2367
+ allCapIds.delete('constructor');
2368
+ allCapIds.delete('prototype');
2369
+ const globalSortedCapIds = [...allCapIds].sort();
2370
+
2371
+ const sortedCapabilityClusters = Object.create(null);
2372
+ for (const capId of globalSortedCapIds) {
2373
+ // S2b: inline literal guard at each write site (CodeQL barrier)
2374
+ if (capId === '__proto__' || capId === 'constructor' || capId === 'prototype') continue;
2375
+ if (registry.capabilityClusters[capId] !== undefined) {
2376
+ sortedCapabilityClusters[capId] = registry.capabilityClusters[capId];
2377
+ }
2378
+ }
2379
+ lines.push('const capabilityClusters = ' + JSON.stringify(sortedCapabilityClusters, null, 2) + ';');
2380
+ lines.push('');
2381
+
2382
+ const sortedProfileMembership = Object.create(null);
2383
+ for (const capId of globalSortedCapIds) {
2384
+ // S2b: inline literal guard at each write site (CodeQL barrier)
2385
+ if (capId === '__proto__' || capId === 'constructor' || capId === 'prototype') continue;
2386
+ if (registry.profileMembership[capId] !== undefined) {
2387
+ sortedProfileMembership[capId] = registry.profileMembership[capId];
2388
+ }
2389
+ }
2390
+ lines.push('const profileMembership = ' + JSON.stringify(sortedProfileMembership, null, 2) + ';');
2391
+ lines.push('');
2392
+
2393
+ // Inline the requires graph so requiresClosure() works without re-reading files
2394
+ const requiresGraph = {};
2395
+ for (const [id, cap] of capMap) {
2396
+ requiresGraph[id] = Array.isArray(cap.requires) ? cap.requires : [];
2397
+ }
2398
+ lines.push('const _requiresGraph = ' + JSON.stringify(requiresGraph, null, 2) + ';');
2399
+ lines.push('');
2400
+
2401
+ // requiresClosure function
2402
+ lines.push('function requiresClosure(id) {');
2403
+ lines.push(' const visited = new Set();');
2404
+ lines.push(' const queue = [id];');
2405
+ lines.push(' while (queue.length > 0) {');
2406
+ lines.push(' const current = queue.shift();');
2407
+ lines.push(' const reqs = _requiresGraph[current] || [];');
2408
+ lines.push(' for (const req of reqs) {');
2409
+ lines.push(' if (!visited.has(req)) {');
2410
+ lines.push(' visited.add(req);');
2411
+ lines.push(' queue.push(req);');
2412
+ lines.push(' }');
2413
+ lines.push(' }');
2414
+ lines.push(' }');
2415
+ lines.push(' return visited;');
2416
+ lines.push('}');
2417
+ lines.push('');
2418
+
2419
+ lines.push('module.exports = {');
2420
+ lines.push(" version: '" + registry.version + "',");
2421
+ lines.push(' capabilities,');
2422
+ lines.push(' bySkill,');
2423
+ lines.push(' byAgent,');
2424
+ lines.push(' byLoopPoint,');
2425
+ lines.push(' configKeys,');
2426
+ lines.push(' configSchema,');
2427
+ lines.push(' runtimes,');
2428
+ lines.push(' commandFamilies,');
2429
+ lines.push(' capabilityClusters,');
2430
+ lines.push(' profileMembership,');
2431
+ lines.push(' requiresClosure,');
2432
+ lines.push('};');
2433
+ lines.push('');
2434
+
2435
+ return lines.join('\n');
2436
+ }
2437
+
2438
+ // ─── --check diff helper ──────────────────────────────────────────────────────
2439
+
2440
+ /**
2441
+ * Compare committed registry with live registry (for --check).
2442
+ * Strips the generated comment line for comparison.
2443
+ */
2444
+ function stripGeneratedComment(content) {
2445
+ return content
2446
+ .split('\n')
2447
+ .filter((line) => !line.includes('generated by scripts/gen-capability-registry.cjs'))
2448
+ .join('\n');
2449
+ }
2450
+
2451
+ /**
2452
+ * Normalize line endings to LF.
2453
+ * The generator always writes LF, but Windows git (autocrlf) checks out committed files with
2454
+ * CRLF. The --check comparison must be line-ending-agnostic so it only fails on REAL content
2455
+ * differences, not on checkout-introduced whitespace differences.
2456
+ *
2457
+ * @param {string} content
2458
+ * @returns {string}
2459
+ */
2460
+ function normalizeLineEndings(content) {
2461
+ return content.replace(/\r/g, '');
2462
+ }
2463
+
2464
+ // ─── Main ─────────────────────────────────────────────────────────────────────
2465
+
2466
+ /**
2467
+ * Fix #3: Emit pending-migration WARNINGs for config keys that collide with the central
2468
+ * config-schema. Per ADR-894 staged cutover, a collision during the registry-only phase is
2469
+ * NOT a hard error — the capability pipeline is being established before the atomic cutover
2470
+ * PR for each feature. The registry still generates; the warning tells the maintainer which
2471
+ * keys need to be moved out of the central schema at cutover time.
2472
+ *
2473
+ * A NEW unexpected collision (a key that shouldn't be in both) is also surfaced — the
2474
+ * maintainer sees it in build output rather than it being silently swallowed.
2475
+ *
2476
+ * Reference: ADR-894 §4 "config-key ownership exclusive AND complete — presence in both =
2477
+ * collision = a mid-flight migration; finish the move."
2478
+ *
2479
+ * @param {string[]} crossErrors Errors from validateCrossCapability (may include collision msgs)
2480
+ * @param {Map<string, object>} capMap
2481
+ * @returns {{ hardErrors: string[], pendingMigrationWarnings: string[] }}
2482
+ */
2483
+ function classifyCrossErrors(crossErrors) {
2484
+ const hardErrors = [];
2485
+ const pendingMigrationWarnings = [];
2486
+ const collisionRe = /config key "([^"]+)" is declared in capability "([^"]+)" AND exists in the central config-schema/;
2487
+
2488
+ for (const e of crossErrors) {
2489
+ const m = collisionRe.exec(e);
2490
+ if (m) {
2491
+ // Collision = pending-migration warning, not a hard error during 3a-impl staged cutover
2492
+ pendingMigrationWarnings.push(
2493
+ '⚠ pending-migration: capability \'' + m[2] + '\' declares config key \'' + m[1] +
2494
+ '\' still present in central config-schema; finish the move at cutover',
2495
+ );
2496
+ } else {
2497
+ hardErrors.push(e);
2498
+ }
2499
+ }
2500
+ return { hardErrors, pendingMigrationWarnings };
2501
+ }
2502
+
2503
+ function main() {
2504
+ const flag = process.argv[2];
2505
+
2506
+ if (flag === '--check') {
2507
+ // Fix #3: read the REAL central config keys so collision detection fires and is visible.
2508
+ const centralKeys = loadCentralConfigKeys();
2509
+ const { capMap, errors } = loadAndValidate(centralKeys);
2510
+
2511
+ // Separate pending-migration warnings from hard errors
2512
+ const { hardErrors, pendingMigrationWarnings } = classifyCrossErrors(errors);
2513
+ for (const w of pendingMigrationWarnings) process.stderr.write(w + '\n');
2514
+ if (hardErrors.length > 0) {
2515
+ for (const e of hardErrors) process.stderr.write(' ERROR ' + e + '\n');
2516
+ throw new ExitError(1, 'capability validation failed (' + hardErrors.length + ' error(s))');
2517
+ }
2518
+
2519
+ const registry = buildRegistry(capMap);
2520
+ // ADR-857 phase 4a: emit pending-reconciliation warnings to stderr only
2521
+ // (they do NOT affect the generated file content, so --check stays clean)
2522
+ for (const w of (registry._reconciliationWarnings || [])) process.stderr.write(w + '\n');
2523
+ const live = serializeRegistry(registry, capMap);
2524
+
2525
+ if (!fs.existsSync(REGISTRY_PATH)) {
2526
+ process.stderr.write(
2527
+ 'pp-core/bin/lib/capability-registry.cjs does not exist. Run:\n' +
2528
+ ' node scripts/gen-capability-registry.cjs --write\n',
2529
+ );
2530
+ throw new ExitError(1);
2531
+ }
2532
+
2533
+ const committed = fs.readFileSync(REGISTRY_PATH, 'utf8');
2534
+ if (normalizeLineEndings(stripGeneratedComment(committed)) !== normalizeLineEndings(stripGeneratedComment(live))) {
2535
+ process.stderr.write(
2536
+ 'pp-core/bin/lib/capability-registry.cjs is stale. Run:\n' +
2537
+ ' node scripts/gen-capability-registry.cjs --write\n',
2538
+ );
2539
+ throw new ExitError(1);
2540
+ }
2541
+
2542
+ process.stdout.write('pp-core/bin/lib/capability-registry.cjs is up to date.\n');
2543
+ } else if (flag === '--write') {
2544
+ // Fix #3: read the REAL central config keys so collision detection fires and is visible.
2545
+ const centralKeys = loadCentralConfigKeys();
2546
+ const { capMap, errors } = loadAndValidate(centralKeys);
2547
+
2548
+ // Separate pending-migration warnings from hard errors
2549
+ const { hardErrors, pendingMigrationWarnings } = classifyCrossErrors(errors);
2550
+ for (const w of pendingMigrationWarnings) process.stderr.write(w + '\n');
2551
+ if (hardErrors.length > 0) {
2552
+ for (const e of hardErrors) process.stderr.write(' ERROR ' + e + '\n');
2553
+ throw new ExitError(1, 'capability validation failed — registry not written');
2554
+ }
2555
+
2556
+ const registry = buildRegistry(capMap);
2557
+ // ADR-857 phase 4a: emit pending-reconciliation warnings to stderr only
2558
+ for (const w of (registry._reconciliationWarnings || [])) process.stderr.write(w + '\n');
2559
+ const content = serializeRegistry(registry, capMap);
2560
+ // Fix #5: mkdir-p before writing so --write doesn't ENOENT in a fresh worktree.
2561
+ fs.mkdirSync(path.dirname(REGISTRY_PATH), { recursive: true });
2562
+ fs.writeFileSync(REGISTRY_PATH, content, 'utf8');
2563
+ process.stdout.write('Wrote ' + REGISTRY_PATH + '\n');
2564
+ } else {
2565
+ // Default: print to stdout — use real central keys for visibility
2566
+ const centralKeys = loadCentralConfigKeys();
2567
+ const { capMap, errors } = loadAndValidate(centralKeys);
2568
+
2569
+ const { hardErrors, pendingMigrationWarnings } = classifyCrossErrors(errors);
2570
+ for (const w of pendingMigrationWarnings) process.stderr.write(w + '\n');
2571
+ if (hardErrors.length > 0) {
2572
+ for (const e of hardErrors) process.stderr.write(' ERROR ' + e + '\n');
2573
+ throw new ExitError(1, 'capability validation failed');
2574
+ }
2575
+ const registry = buildRegistry(capMap);
2576
+ // ADR-857 phase 4a: emit pending-reconciliation warnings to stderr only
2577
+ for (const w of (registry._reconciliationWarnings || [])) process.stderr.write(w + '\n');
2578
+ process.stdout.write(serializeRegistry(registry, capMap) + '\n');
2579
+ }
2580
+ }
2581
+
2582
+ // ─── Exports (for tests) ──────────────────────────────────────────────────────
2583
+
2584
+ module.exports = {
2585
+ validateCapability,
2586
+ validateAgainstContract,
2587
+ validateConsumesGlobal,
2588
+ validateCrossCapability,
2589
+ classifyCrossErrors,
2590
+ loadCentralConfigKeys,
2591
+ loadAndValidate,
2592
+ buildRegistry,
2593
+ serializeRegistry,
2594
+ computeRequiresClosure,
2595
+ topoSortSteps,
2596
+ normalizeLineEndings,
2597
+ stripGeneratedComment,
2598
+ validateConfigSliceEntry,
2599
+ VALID_CONFIG_SLICE_TYPES,
2600
+ LOOP_HOST_CONTRACT,
2601
+ VALID_LOOP_POINTS,
2602
+ POINT_ORDER,
2603
+ POINT_TO_CONTRACT,
2604
+ HOST_ARTIFACT_EARLIEST_POINT_IDX,
2605
+ SCHEMA_VERSION,
2606
+ validateHooksWired,
2607
+ // ADR-857 phase 4a: derived views + gates
2608
+ deriveCapabilityClusters,
2609
+ deriveProfileMembership,
2610
+ runConsistencyGate,
2611
+ // ADR-959: command entry validation
2612
+ validateCommandEntry,
2613
+ validateRuntimeCompat,
2614
+ // ADR-1016 phase 5a: runtime body validators + closed-vocab sets
2615
+ validateConfigHome,
2616
+ validateArtifactLayout,
2617
+ validateArtifactKindEntry,
2618
+ VALID_CONFIG_HOME_KINDS,
2619
+ VALID_COMMAND_STYLES,
2620
+ VALID_HOOKS_SURFACES,
2621
+ VALID_HOOK_EVENTS,
2622
+ VALID_SANDBOX_TIERS,
2623
+ VALID_ARTIFACT_KIND_NAMES,
2624
+ VALID_ARTIFACT_NESTINGS,
2625
+ // ADR-857 phase 5e: closed ConverterName enum
2626
+ VALID_CONVERTER_NAMES,
2627
+ // ADR-857 phase 5e: configFormat ↔ installSurface parity gate
2628
+ runConfigFormatParityGate,
2629
+ INSTALL_SURFACE_TO_CONFIG_FORMAT,
2630
+ // ADR-857 phase 5f: cross-field consistency gates
2631
+ INSTALL_SURFACE_TO_ALLOWED_HOOKS_SURFACES,
2632
+ VALID_INSTALL_SURFACES,
2633
+ VALID_EXTENDED_HOOK_EVENTS,
2634
+ VALID_PERMISSION_WRITERS,
2635
+ validateRuntimeBody,
2636
+ // FIX 5 (lazy): PROFILE_RANK and CLUSTERS are loaded on first access via getters
2637
+ // so importing the generator on a fresh/unbuilt worktree doesn't fail at module load.
2638
+ get PROFILE_RANK() { return getInstallProfiles().PROFILE_RANK; },
2639
+ get CLUSTERS() { return getClusters().CLUSTERS; },
2640
+ };
2641
+
2642
+ // ─── CLI entry point ──────────────────────────────────────────────────────────
2643
+
2644
+ if (require.main === module) {
2645
+ runMain(main);
2646
+ }