onto-mcp 0.3.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 (447) hide show
  1. package/.onto/authority/core-lens-registry.yaml +134 -0
  2. package/.onto/authority/core-lexicon.yaml +1562 -0
  3. package/.onto/authority/diagnostic-codes.yaml +94 -0
  4. package/.onto/domains/accounting/competency_qs.md +384 -0
  5. package/.onto/domains/accounting/concepts.md +186 -0
  6. package/.onto/domains/accounting/conciseness_rules.md +160 -0
  7. package/.onto/domains/accounting/dependency_rules.md +239 -0
  8. package/.onto/domains/accounting/domain_scope.md +213 -0
  9. package/.onto/domains/accounting/extension_cases.md +416 -0
  10. package/.onto/domains/accounting/logic_rules.md +226 -0
  11. package/.onto/domains/accounting/structure_spec.md +298 -0
  12. package/.onto/domains/accounting-kr/competency_qs.md +562 -0
  13. package/.onto/domains/accounting-kr/concepts.md +187 -0
  14. package/.onto/domains/accounting-kr/conciseness_rules.md +125 -0
  15. package/.onto/domains/accounting-kr/dependency_rules.md +93 -0
  16. package/.onto/domains/accounting-kr/domain_scope.md +140 -0
  17. package/.onto/domains/accounting-kr/extension_cases.md +343 -0
  18. package/.onto/domains/accounting-kr/logic_rules.md +160 -0
  19. package/.onto/domains/accounting-kr/structure_spec.md +85 -0
  20. package/.onto/domains/business/competency_qs.md +263 -0
  21. package/.onto/domains/business/concepts.md +200 -0
  22. package/.onto/domains/business/conciseness_rules.md +135 -0
  23. package/.onto/domains/business/dependency_rules.md +113 -0
  24. package/.onto/domains/business/domain_scope.md +240 -0
  25. package/.onto/domains/business/extension_cases.md +249 -0
  26. package/.onto/domains/business/logic_rules.md +134 -0
  27. package/.onto/domains/business/structure_spec.md +114 -0
  28. package/.onto/domains/finance/competency_qs.md +362 -0
  29. package/.onto/domains/finance/concepts.md +194 -0
  30. package/.onto/domains/finance/conciseness_rules.md +155 -0
  31. package/.onto/domains/finance/dependency_rules.md +171 -0
  32. package/.onto/domains/finance/domain_scope.md +215 -0
  33. package/.onto/domains/finance/extension_cases.md +350 -0
  34. package/.onto/domains/finance/logic_rules.md +191 -0
  35. package/.onto/domains/finance/structure_spec.md +182 -0
  36. package/.onto/domains/llm-native-development/competency_qs.md +430 -0
  37. package/.onto/domains/llm-native-development/concepts.md +242 -0
  38. package/.onto/domains/llm-native-development/conciseness_rules.md +163 -0
  39. package/.onto/domains/llm-native-development/dependency_rules.md +216 -0
  40. package/.onto/domains/llm-native-development/domain_scope.md +197 -0
  41. package/.onto/domains/llm-native-development/extension_cases.md +474 -0
  42. package/.onto/domains/llm-native-development/logic_rules.md +123 -0
  43. package/.onto/domains/llm-native-development/prompt_interface.md +49 -0
  44. package/.onto/domains/llm-native-development/structure_spec.md +245 -0
  45. package/.onto/domains/market-intelligence/competency_qs.md +274 -0
  46. package/.onto/domains/market-intelligence/concepts.md +233 -0
  47. package/.onto/domains/market-intelligence/conciseness_rules.md +165 -0
  48. package/.onto/domains/market-intelligence/dependency_rules.md +197 -0
  49. package/.onto/domains/market-intelligence/domain_scope.md +231 -0
  50. package/.onto/domains/market-intelligence/extension_cases.md +425 -0
  51. package/.onto/domains/market-intelligence/logic_rules.md +247 -0
  52. package/.onto/domains/market-intelligence/structure_spec.md +209 -0
  53. package/.onto/domains/ontology/competency_qs.md +394 -0
  54. package/.onto/domains/ontology/concepts.md +172 -0
  55. package/.onto/domains/ontology/conciseness_rules.md +134 -0
  56. package/.onto/domains/ontology/dependency_rules.md +125 -0
  57. package/.onto/domains/ontology/domain_scope.md +114 -0
  58. package/.onto/domains/ontology/extension_cases.md +501 -0
  59. package/.onto/domains/ontology/logic_rules.md +114 -0
  60. package/.onto/domains/ontology/problem_framing_profile.md +67 -0
  61. package/.onto/domains/ontology/structure_spec.md +115 -0
  62. package/.onto/domains/palantir-foundry/RESEARCH_NOTES.md +911 -0
  63. package/.onto/domains/palantir-foundry/competency_qs.md +191 -0
  64. package/.onto/domains/palantir-foundry/competitive_comparison.md +329 -0
  65. package/.onto/domains/palantir-foundry/concepts.md +197 -0
  66. package/.onto/domains/palantir-foundry/conciseness_rules.md +245 -0
  67. package/.onto/domains/palantir-foundry/dependency_rules.md +135 -0
  68. package/.onto/domains/palantir-foundry/domain_scope.md +395 -0
  69. package/.onto/domains/palantir-foundry/extension_cases.md +210 -0
  70. package/.onto/domains/palantir-foundry/logic_rules.md +172 -0
  71. package/.onto/domains/palantir-foundry/structure_spec.md +291 -0
  72. package/.onto/domains/software-engineering/competency_qs.md +538 -0
  73. package/.onto/domains/software-engineering/concepts.md +238 -0
  74. package/.onto/domains/software-engineering/conciseness_rules.md +167 -0
  75. package/.onto/domains/software-engineering/dependency_rules.md +216 -0
  76. package/.onto/domains/software-engineering/domain_scope.md +183 -0
  77. package/.onto/domains/software-engineering/extension_cases.md +551 -0
  78. package/.onto/domains/software-engineering/logic_rules.md +240 -0
  79. package/.onto/domains/software-engineering/problem_framing_profile.md +68 -0
  80. package/.onto/domains/software-engineering/structure_spec.md +185 -0
  81. package/.onto/domains/ui-design/competency_qs.md +567 -0
  82. package/.onto/domains/ui-design/concepts.md +194 -0
  83. package/.onto/domains/ui-design/conciseness_rules.md +190 -0
  84. package/.onto/domains/ui-design/dependency_rules.md +323 -0
  85. package/.onto/domains/ui-design/domain_scope.md +340 -0
  86. package/.onto/domains/ui-design/extension_cases.md +563 -0
  87. package/.onto/domains/ui-design/logic_rules.md +349 -0
  88. package/.onto/domains/ui-design/structure_spec.md +252 -0
  89. package/.onto/domains/visual-design/competency_qs.md +472 -0
  90. package/.onto/domains/visual-design/concepts.md +147 -0
  91. package/.onto/domains/visual-design/conciseness_rules.md +186 -0
  92. package/.onto/domains/visual-design/dependency_rules.md +282 -0
  93. package/.onto/domains/visual-design/domain_scope.md +290 -0
  94. package/.onto/domains/visual-design/extension_cases.md +480 -0
  95. package/.onto/domains/visual-design/logic_rules.md +232 -0
  96. package/.onto/domains/visual-design/structure_spec.md +213 -0
  97. package/.onto/principles/llm-native-development-guideline.md +401 -0
  98. package/.onto/principles/llm-runtime-interface-principles.md +665 -0
  99. package/.onto/principles/non-specialist-communication-guideline.md +74 -0
  100. package/.onto/principles/ontology-as-code-guideline.md +243 -0
  101. package/.onto/principles/ontology-as-code-naming-charter.md +130 -0
  102. package/.onto/principles/product-locality-principle.md +129 -0
  103. package/.onto/principles/productization-charter.md +569 -0
  104. package/.onto/processes/evolve/material-kind-adapter-contract.md +113 -0
  105. package/.onto/processes/reconstruct/reconstruct-boundary-contract.md +366 -0
  106. package/.onto/processes/reconstruct/source-profile-contract.md +107 -0
  107. package/.onto/processes/reconstruct/source-profiles/code.md +72 -0
  108. package/.onto/processes/reconstruct/source-profiles/database.md +74 -0
  109. package/.onto/processes/reconstruct/source-profiles/document.md +71 -0
  110. package/.onto/processes/reconstruct/source-profiles/spreadsheet.md +79 -0
  111. package/.onto/processes/review/binding-contract.md +270 -0
  112. package/.onto/processes/review/execution-preparation-artifacts.md +281 -0
  113. package/.onto/processes/review/interpretation-contract.md +245 -0
  114. package/.onto/processes/review/issue-stance-deliberation-contract.md +761 -0
  115. package/.onto/processes/review/lens-prompt-contract.md +402 -0
  116. package/.onto/processes/review/lens-registry.md +127 -0
  117. package/.onto/processes/review/pre-dispatch-contracts.md +428 -0
  118. package/.onto/processes/review/productized-live-path.md +398 -0
  119. package/.onto/processes/review/prompt-execution-runner-contract.md +187 -0
  120. package/.onto/processes/review/record-contract.md +427 -0
  121. package/.onto/processes/review/record-field-mapping.md +337 -0
  122. package/.onto/processes/review/review-context-manifest-contract.md +356 -0
  123. package/.onto/processes/review/review-execution-ux-contract.md +809 -0
  124. package/.onto/processes/review/review-target-profile-contract.md +259 -0
  125. package/.onto/processes/review/shared-phenomenon-contract.md +129 -0
  126. package/.onto/processes/review/synthesize-prompt-contract.md +343 -0
  127. package/.onto/processes/shared/target-material-kind-contract.md +198 -0
  128. package/.onto/roles/axiology.md +81 -0
  129. package/.onto/roles/conciseness.md +36 -0
  130. package/.onto/roles/coverage.md +34 -0
  131. package/.onto/roles/dependency.md +37 -0
  132. package/.onto/roles/evolution.md +35 -0
  133. package/.onto/roles/logic.md +104 -0
  134. package/.onto/roles/pragmatics.md +32 -0
  135. package/.onto/roles/semantics.md +36 -0
  136. package/.onto/roles/structure.md +33 -0
  137. package/.onto/roles/synthesize.md +92 -0
  138. package/AGENTS.md +240 -0
  139. package/CLAUDE.md +39 -0
  140. package/README.md +287 -0
  141. package/bin/onto +92 -0
  142. package/dist/cli.js +101 -0
  143. package/dist/core-api/reconstruct-api.js +222 -0
  144. package/dist/core-api/review-api.js +1271 -0
  145. package/dist/core-runtime/cli/assemble-review-record.js +431 -0
  146. package/dist/core-runtime/cli/bootstrap-review-binding.js +186 -0
  147. package/dist/core-runtime/cli/codex-nested-dispatch.js +226 -0
  148. package/dist/core-runtime/cli/codex-nested-dispatch.test.js +390 -0
  149. package/dist/core-runtime/cli/codex-nested-teamlead-executor.js +464 -0
  150. package/dist/core-runtime/cli/codex-nested-teamlead-executor.test.js +335 -0
  151. package/dist/core-runtime/cli/codex-review-unit-executor.js +228 -0
  152. package/dist/core-runtime/cli/complete-review-session.js +64 -0
  153. package/dist/core-runtime/cli/complexity-assessment.js +153 -0
  154. package/dist/core-runtime/cli/coordinator-helpers.js +583 -0
  155. package/dist/core-runtime/cli/coordinator-state-machine-deliberation.test.js +167 -0
  156. package/dist/core-runtime/cli/coordinator-state-machine.js +794 -0
  157. package/dist/core-runtime/cli/e2e-codex-multi-agent-fixes.test.js +615 -0
  158. package/dist/core-runtime/cli/e2e-start-review-session.test.js +312 -0
  159. package/dist/core-runtime/cli/health.js +44 -0
  160. package/dist/core-runtime/cli/inline-http-review-unit-executor.js +656 -0
  161. package/dist/core-runtime/cli/inline-http-review-unit-executor.test.js +567 -0
  162. package/dist/core-runtime/cli/materialize-review-execution-preparation.js +104 -0
  163. package/dist/core-runtime/cli/materialize-review-prompt-packets.js +952 -0
  164. package/dist/core-runtime/cli/migrate-session-roots.js +118 -0
  165. package/dist/core-runtime/cli/mock-review-unit-executor.js +285 -0
  166. package/dist/core-runtime/cli/onto-tools.js +369 -0
  167. package/dist/core-runtime/cli/prepare-review-session.js +272 -0
  168. package/dist/core-runtime/cli/render-review-final-output.js +350 -0
  169. package/dist/core-runtime/cli/repo-layout-migration-replace.smoke.test.js +106 -0
  170. package/dist/core-runtime/cli/review-invoke-auto-resolution.test.js +268 -0
  171. package/dist/core-runtime/cli/review-invoke-coordinator-topology.test.js +136 -0
  172. package/dist/core-runtime/cli/review-invoke-resolver-caching.test.js +201 -0
  173. package/dist/core-runtime/cli/review-invoke-topology-dispatch.test.js +192 -0
  174. package/dist/core-runtime/cli/review-invoke.js +2030 -0
  175. package/dist/core-runtime/cli/run-review-prompt-execution.js +2152 -0
  176. package/dist/core-runtime/cli/session-root-guard.js +168 -0
  177. package/dist/core-runtime/cli/spawn-watcher.js +173 -0
  178. package/dist/core-runtime/cli/spawn-watcher.test.js +457 -0
  179. package/dist/core-runtime/cli/start-review-session.js +68 -0
  180. package/dist/core-runtime/cli/strip-wrapping-code-fence.js +56 -0
  181. package/dist/core-runtime/cli/strip-wrapping-code-fence.test.js +79 -0
  182. package/dist/core-runtime/cli/teamcreate-lens-deliberation-executor.js +412 -0
  183. package/dist/core-runtime/cli/teamcreate-lens-deliberation-executor.test.js +351 -0
  184. package/dist/core-runtime/cli/topology-executor-mapping.js +139 -0
  185. package/dist/core-runtime/cli/topology-executor-mapping.test.js +173 -0
  186. package/dist/core-runtime/cli/write-review-interpretation.js +81 -0
  187. package/dist/core-runtime/config/onto-config-cli.js +278 -0
  188. package/dist/core-runtime/config/onto-config-key-path.js +288 -0
  189. package/dist/core-runtime/config/onto-config-key-path.test.js +195 -0
  190. package/dist/core-runtime/config/onto-config-preview.js +108 -0
  191. package/dist/core-runtime/config/onto-config-preview.test.js +132 -0
  192. package/dist/core-runtime/discovery/config-chain.js +118 -0
  193. package/dist/core-runtime/discovery/config-chain.test.js +103 -0
  194. package/dist/core-runtime/discovery/config-profile.js +199 -0
  195. package/dist/core-runtime/discovery/config-profile.test.js +233 -0
  196. package/dist/core-runtime/discovery/host-detection.js +33 -0
  197. package/dist/core-runtime/discovery/host-detection.test.js +186 -0
  198. package/dist/core-runtime/discovery/installation-paths.js +21 -0
  199. package/dist/core-runtime/discovery/installation-paths.test.js +65 -0
  200. package/dist/core-runtime/discovery/lens-registry.js +60 -0
  201. package/dist/core-runtime/discovery/lens-registry.test.js +81 -0
  202. package/dist/core-runtime/discovery/onto-home.js +71 -0
  203. package/dist/core-runtime/discovery/path-normalization.js +28 -0
  204. package/dist/core-runtime/discovery/path-normalization.test.js +22 -0
  205. package/dist/core-runtime/discovery/plugin-path.js +72 -0
  206. package/dist/core-runtime/discovery/plugin-path.test.js +95 -0
  207. package/dist/core-runtime/discovery/project-root.js +47 -0
  208. package/dist/core-runtime/discovery/settings-chain.js +353 -0
  209. package/dist/core-runtime/discovery/walk-up.js +17 -0
  210. package/dist/core-runtime/evolve/adapters/code-product/compile/compile-defense.js +344 -0
  211. package/dist/core-runtime/evolve/adapters/code-product/compile/compile-defense.test.js +915 -0
  212. package/dist/core-runtime/evolve/adapters/code-product/compile/compile.js +564 -0
  213. package/dist/core-runtime/evolve/adapters/code-product/compile/compile.test.js +708 -0
  214. package/dist/core-runtime/evolve/adapters/code-product/parsers/brief-parser.js +165 -0
  215. package/dist/core-runtime/evolve/adapters/code-product/parsers/brief-parser.test.js +227 -0
  216. package/dist/core-runtime/evolve/adapters/code-product/validators/validate.js +59 -0
  217. package/dist/core-runtime/evolve/adapters/code-product/validators/validate.test.js +205 -0
  218. package/dist/core-runtime/evolve/adapters/methodology/adapter.js +16 -0
  219. package/dist/core-runtime/evolve/adapters/methodology/adapter.test.js +9 -0
  220. package/dist/core-runtime/evolve/adapters/methodology/perspectives/authority-consistency.js +298 -0
  221. package/dist/core-runtime/evolve/adapters/methodology/perspectives/authority-consistency.test.js +70 -0
  222. package/dist/core-runtime/evolve/adapters/methodology/scope-types/process.js +46 -0
  223. package/dist/core-runtime/evolve/adapters/methodology/scope-types/process.test.js +73 -0
  224. package/dist/core-runtime/evolve/adapters/registry.js +47 -0
  225. package/dist/core-runtime/evolve/adapters/registry.test.js +67 -0
  226. package/dist/core-runtime/evolve/cli.js +256 -0
  227. package/dist/core-runtime/evolve/commands/align.js +194 -0
  228. package/dist/core-runtime/evolve/commands/align.test.js +82 -0
  229. package/dist/core-runtime/evolve/commands/apply.js +161 -0
  230. package/dist/core-runtime/evolve/commands/apply.test.js +138 -0
  231. package/dist/core-runtime/evolve/commands/close.js +39 -0
  232. package/dist/core-runtime/evolve/commands/close.test.js +99 -0
  233. package/dist/core-runtime/evolve/commands/defer.js +40 -0
  234. package/dist/core-runtime/evolve/commands/defer.test.js +134 -0
  235. package/dist/core-runtime/evolve/commands/draft.js +323 -0
  236. package/dist/core-runtime/evolve/commands/draft.test.js +178 -0
  237. package/dist/core-runtime/evolve/commands/e2e-evolve-full-cycle.test.js +208 -0
  238. package/dist/core-runtime/evolve/commands/error-messages.js +125 -0
  239. package/dist/core-runtime/evolve/commands/error-messages.test.js +167 -0
  240. package/dist/core-runtime/evolve/commands/propose-align.js +222 -0
  241. package/dist/core-runtime/evolve/commands/propose-align.test.js +136 -0
  242. package/dist/core-runtime/evolve/commands/reconstruct.js +330 -0
  243. package/dist/core-runtime/evolve/commands/reconstruct.test.js +278 -0
  244. package/dist/core-runtime/evolve/commands/shared.js +22 -0
  245. package/dist/core-runtime/evolve/commands/stale-check.js +103 -0
  246. package/dist/core-runtime/evolve/commands/stale-check.test.js +84 -0
  247. package/dist/core-runtime/evolve/commands/start.js +887 -0
  248. package/dist/core-runtime/evolve/commands/start.test.js +396 -0
  249. package/dist/core-runtime/evolve/config/project-config.js +99 -0
  250. package/dist/core-runtime/evolve/config/project-config.test.js +170 -0
  251. package/dist/core-runtime/evolve/renderers/align-packet.js +280 -0
  252. package/dist/core-runtime/evolve/renderers/align-packet.test.js +332 -0
  253. package/dist/core-runtime/evolve/renderers/draft-packet.js +303 -0
  254. package/dist/core-runtime/evolve/renderers/draft-packet.test.js +377 -0
  255. package/dist/core-runtime/evolve/renderers/format.js +5 -0
  256. package/dist/core-runtime/evolve/renderers/scope-md.js +237 -0
  257. package/dist/core-runtime/evolve/renderers/scope-md.test.js +306 -0
  258. package/dist/core-runtime/govern/cli.js +369 -0
  259. package/dist/core-runtime/govern/cli.test.js +314 -0
  260. package/dist/core-runtime/govern/drift-engine.js +103 -0
  261. package/dist/core-runtime/govern/drift-engine.test.js +319 -0
  262. package/dist/core-runtime/govern/promote-principle.js +206 -0
  263. package/dist/core-runtime/govern/promote-principle.test.js +368 -0
  264. package/dist/core-runtime/govern/queue.js +81 -0
  265. package/dist/core-runtime/govern/types.js +16 -0
  266. package/dist/core-runtime/install/cli.js +530 -0
  267. package/dist/core-runtime/install/detect.js +128 -0
  268. package/dist/core-runtime/install/detect.test.js +155 -0
  269. package/dist/core-runtime/install/gitignore-update.js +74 -0
  270. package/dist/core-runtime/install/gitignore-update.test.js +64 -0
  271. package/dist/core-runtime/install/install-integration.test.js +373 -0
  272. package/dist/core-runtime/install/prompts.js +389 -0
  273. package/dist/core-runtime/install/prompts.test.js +293 -0
  274. package/dist/core-runtime/install/types.js +26 -0
  275. package/dist/core-runtime/install/validation.js +295 -0
  276. package/dist/core-runtime/install/validation.test.js +313 -0
  277. package/dist/core-runtime/install/writer.js +254 -0
  278. package/dist/core-runtime/install/writer.test.js +218 -0
  279. package/dist/core-runtime/learning/extractor.js +461 -0
  280. package/dist/core-runtime/learning/feedback.js +179 -0
  281. package/dist/core-runtime/learning/health-report.js +165 -0
  282. package/dist/core-runtime/learning/health-report.test.js +169 -0
  283. package/dist/core-runtime/learning/loader.js +388 -0
  284. package/dist/core-runtime/learning/loader.test.js +102 -0
  285. package/dist/core-runtime/learning/promote/apply-state.js +240 -0
  286. package/dist/core-runtime/learning/promote/audit-obligation.js +195 -0
  287. package/dist/core-runtime/learning/promote/collector.js +432 -0
  288. package/dist/core-runtime/learning/promote/degraded-state.js +125 -0
  289. package/dist/core-runtime/learning/promote/domain-doc-proposer.js +166 -0
  290. package/dist/core-runtime/learning/promote/e2e-promote.test.js +6385 -0
  291. package/dist/core-runtime/learning/promote/health-snapshot.js +150 -0
  292. package/dist/core-runtime/learning/promote/insight-reclassifier.js +544 -0
  293. package/dist/core-runtime/learning/promote/judgment-auditor.js +517 -0
  294. package/dist/core-runtime/learning/promote/panel-reviewer.js +1158 -0
  295. package/dist/core-runtime/learning/promote/promote-executor.js +1675 -0
  296. package/dist/core-runtime/learning/promote/promoter.js +307 -0
  297. package/dist/core-runtime/learning/promote/retirement.js +122 -0
  298. package/dist/core-runtime/learning/promote/types.js +23 -0
  299. package/dist/core-runtime/learning/prompt-sections.js +51 -0
  300. package/dist/core-runtime/learning/shared/artifact-registry-init.js +45 -0
  301. package/dist/core-runtime/learning/shared/artifact-registry.js +254 -0
  302. package/dist/core-runtime/learning/shared/audit-obligation-kernel.js +73 -0
  303. package/dist/core-runtime/learning/shared/audit-state.js +99 -0
  304. package/dist/core-runtime/learning/shared/duplicate-check.js +28 -0
  305. package/dist/core-runtime/learning/shared/llm-caller.js +831 -0
  306. package/dist/core-runtime/learning/shared/llm-caller.test.js +601 -0
  307. package/dist/core-runtime/learning/shared/llm-tool-loop.js +393 -0
  308. package/dist/core-runtime/learning/shared/mode.js +25 -0
  309. package/dist/core-runtime/learning/shared/paths.js +84 -0
  310. package/dist/core-runtime/learning/shared/paths.test.js +79 -0
  311. package/dist/core-runtime/learning/shared/patterns.js +37 -0
  312. package/dist/core-runtime/learning/shared/recoverability.js +355 -0
  313. package/dist/core-runtime/learning/shared/recovery-context.js +374 -0
  314. package/dist/core-runtime/learning/shared/scope.js +1 -0
  315. package/dist/core-runtime/learning/shared/semantic-classifier.js +94 -0
  316. package/dist/core-runtime/learning/shared/specs/apply-execution-state-spec.js +42 -0
  317. package/dist/core-runtime/learning/shared/specs/audit-state-spec.js +37 -0
  318. package/dist/core-runtime/learning/shared/specs/backup-metadata-spec.js +39 -0
  319. package/dist/core-runtime/learning/shared/specs/emergency-log-spec.js +41 -0
  320. package/dist/core-runtime/learning/shared/specs/layout-version-spec.js +38 -0
  321. package/dist/core-runtime/learning/shared/specs/promote-decisions-spec.js +43 -0
  322. package/dist/core-runtime/learning/shared/specs/promote-report-spec.js +113 -0
  323. package/dist/core-runtime/learning/shared/specs/prune-log-spec.js +36 -0
  324. package/dist/core-runtime/learning/shared/specs/recovery-resolution-spec.js +48 -0
  325. package/dist/core-runtime/learning/shared/specs/restore-manifest-spec.js +43 -0
  326. package/dist/core-runtime/learning/shared/specs/spec-helpers.js +64 -0
  327. package/dist/core-runtime/learning/usage-tracker.js +190 -0
  328. package/dist/core-runtime/learning/usage-tracker.test.js +176 -0
  329. package/dist/core-runtime/llm/llm-caller.js +649 -0
  330. package/dist/core-runtime/llm/llm-tool-loop.js +401 -0
  331. package/dist/core-runtime/llm/model-switcher.js +62 -0
  332. package/dist/core-runtime/logger.js +22 -0
  333. package/dist/core-runtime/onboard/detect-review-axes.js +122 -0
  334. package/dist/core-runtime/onboard/detect-review-axes.test.js +127 -0
  335. package/dist/core-runtime/onboard/write-review-block.js +188 -0
  336. package/dist/core-runtime/onboard/write-review-block.test.js +240 -0
  337. package/dist/core-runtime/readers/brownfield-builder.js +150 -0
  338. package/dist/core-runtime/readers/brownfield-builder.test.js +136 -0
  339. package/dist/core-runtime/readers/code-chunk-collector.js +53 -0
  340. package/dist/core-runtime/readers/code-chunk-collector.test.js +136 -0
  341. package/dist/core-runtime/readers/file-utils.js +240 -0
  342. package/dist/core-runtime/readers/file-utils.test.js +146 -0
  343. package/dist/core-runtime/readers/lexicon-citation-check.js +93 -0
  344. package/dist/core-runtime/readers/lexicon-citation-check.test.js +77 -0
  345. package/dist/core-runtime/readers/mcp-figma.js +30 -0
  346. package/dist/core-runtime/readers/mcp-figma.test.js +82 -0
  347. package/dist/core-runtime/readers/mcp-generic.js +31 -0
  348. package/dist/core-runtime/readers/mcp-generic.test.js +76 -0
  349. package/dist/core-runtime/readers/ontology-index.js +148 -0
  350. package/dist/core-runtime/readers/ontology-index.test.js +245 -0
  351. package/dist/core-runtime/readers/ontology-query.js +168 -0
  352. package/dist/core-runtime/readers/ontology-query.test.js +311 -0
  353. package/dist/core-runtime/readers/ontology-resolve.js +48 -0
  354. package/dist/core-runtime/readers/ontology-resolve.test.js +48 -0
  355. package/dist/core-runtime/readers/patterns/index.js +7 -0
  356. package/dist/core-runtime/readers/review-log.js +213 -0
  357. package/dist/core-runtime/readers/review-log.test.js +313 -0
  358. package/dist/core-runtime/readers/scan-local.js +102 -0
  359. package/dist/core-runtime/readers/scan-local.test.js +102 -0
  360. package/dist/core-runtime/readers/scan-tarball.js +121 -0
  361. package/dist/core-runtime/readers/scan-tarball.test.js +283 -0
  362. package/dist/core-runtime/readers/scan-vault.js +34 -0
  363. package/dist/core-runtime/readers/scan-vault.test.js +81 -0
  364. package/dist/core-runtime/readers/types.js +42 -0
  365. package/dist/core-runtime/readers/types.test.js +94 -0
  366. package/dist/core-runtime/readers/viewpoint-collectors.js +229 -0
  367. package/dist/core-runtime/reconstruct/artifact-types.js +1 -0
  368. package/dist/core-runtime/reconstruct/directive-validation.js +123 -0
  369. package/dist/core-runtime/reconstruct/materialize-preparation.js +251 -0
  370. package/dist/core-runtime/reconstruct/record.js +198 -0
  371. package/dist/core-runtime/reconstruct/run.js +578 -0
  372. package/dist/core-runtime/reconstruct/seed-candidate-validation.js +356 -0
  373. package/dist/core-runtime/reconstruct/source-observations.js +62 -0
  374. package/dist/core-runtime/reconstruct/source-profiles.js +73 -0
  375. package/dist/core-runtime/release-channel/release-channel.js +90 -0
  376. package/dist/core-runtime/review/artifact-types.js +13 -0
  377. package/dist/core-runtime/review/citation-audit.js +204 -0
  378. package/dist/core-runtime/review/citation-audit.test.js +165 -0
  379. package/dist/core-runtime/review/controlled-lens-deliberation.js +125 -0
  380. package/dist/core-runtime/review/execution-plan-resolver.js +247 -0
  381. package/dist/core-runtime/review/execution-plan-resolver.test.js +243 -0
  382. package/dist/core-runtime/review/execution-topology-resolver-axis-first.test.js +246 -0
  383. package/dist/core-runtime/review/execution-topology-resolver.js +401 -0
  384. package/dist/core-runtime/review/execution-topology-resolver.test.js +315 -0
  385. package/dist/core-runtime/review/failure-records.js +57 -0
  386. package/dist/core-runtime/review/inline-context-embedder.js +141 -0
  387. package/dist/core-runtime/review/inline-context-embedder.test.js +154 -0
  388. package/dist/core-runtime/review/issue-artifact-runtime.js +859 -0
  389. package/dist/core-runtime/review/legacy-mode-policy.js +88 -0
  390. package/dist/core-runtime/review/lens-completion-policy.js +17 -0
  391. package/dist/core-runtime/review/materializers-effort-persist.test.js +79 -0
  392. package/dist/core-runtime/review/materializers.js +963 -0
  393. package/dist/core-runtime/review/ontology-path-classifier.js +179 -0
  394. package/dist/core-runtime/review/ontology-path-classifier.test.js +216 -0
  395. package/dist/core-runtime/review/packet-boundary-policy.js +215 -0
  396. package/dist/core-runtime/review/packet-boundary-policy.test.js +107 -0
  397. package/dist/core-runtime/review/participating-lens-paths.js +61 -0
  398. package/dist/core-runtime/review/participating-lens-paths.test.js +73 -0
  399. package/dist/core-runtime/review/review-artifact-utils.js +287 -0
  400. package/dist/core-runtime/review/review-config-legacy-translate.js +244 -0
  401. package/dist/core-runtime/review/review-config-legacy-translate.test.js +161 -0
  402. package/dist/core-runtime/review/review-config-validator.js +289 -0
  403. package/dist/core-runtime/review/review-config-validator.test.js +236 -0
  404. package/dist/core-runtime/review/review-execution-profile.js +193 -0
  405. package/dist/core-runtime/review/review-execution-route.js +52 -0
  406. package/dist/core-runtime/review/review-progress-contract.js +123 -0
  407. package/dist/core-runtime/review/review-record-validation.js +251 -0
  408. package/dist/core-runtime/review/review-result-classification.js +379 -0
  409. package/dist/core-runtime/review/review-state-machine.js +39 -0
  410. package/dist/core-runtime/review/route-visibility.js +125 -0
  411. package/dist/core-runtime/review/shape-pipeline-audit.test.js +311 -0
  412. package/dist/core-runtime/review/shape-to-topology-id.js +117 -0
  413. package/dist/core-runtime/review/shape-to-topology-id.test.js +132 -0
  414. package/dist/core-runtime/review/topology-shape-derivation.js +155 -0
  415. package/dist/core-runtime/review/topology-shape-derivation.test.js +195 -0
  416. package/dist/core-runtime/scope-runtime/constants.js +12 -0
  417. package/dist/core-runtime/scope-runtime/constraint-pool.js +166 -0
  418. package/dist/core-runtime/scope-runtime/constraint-pool.test.js +674 -0
  419. package/dist/core-runtime/scope-runtime/domain-validation-log.js +135 -0
  420. package/dist/core-runtime/scope-runtime/domain-validation-log.test.js +156 -0
  421. package/dist/core-runtime/scope-runtime/eval-persistence.js +65 -0
  422. package/dist/core-runtime/scope-runtime/eval-persistence.test.js +84 -0
  423. package/dist/core-runtime/scope-runtime/event-pipeline.js +64 -0
  424. package/dist/core-runtime/scope-runtime/event-pipeline.test.js +450 -0
  425. package/dist/core-runtime/scope-runtime/event-store.js +39 -0
  426. package/dist/core-runtime/scope-runtime/event-store.test.js +95 -0
  427. package/dist/core-runtime/scope-runtime/gate-guard.js +348 -0
  428. package/dist/core-runtime/scope-runtime/gate-guard.test.js +1047 -0
  429. package/dist/core-runtime/scope-runtime/hash.js +4 -0
  430. package/dist/core-runtime/scope-runtime/hash.test.js +33 -0
  431. package/dist/core-runtime/scope-runtime/id.js +4 -0
  432. package/dist/core-runtime/scope-runtime/id.test.js +17 -0
  433. package/dist/core-runtime/scope-runtime/reducer.js +297 -0
  434. package/dist/core-runtime/scope-runtime/reducer.test.js +759 -0
  435. package/dist/core-runtime/scope-runtime/scope-manager.js +161 -0
  436. package/dist/core-runtime/scope-runtime/state-machine.js +309 -0
  437. package/dist/core-runtime/scope-runtime/state-machine.test.js +704 -0
  438. package/dist/core-runtime/scope-runtime/types.js +116 -0
  439. package/dist/core-runtime/scope-runtime/types.test.js +69 -0
  440. package/dist/core-runtime/target-material-kind.js +256 -0
  441. package/dist/core-runtime/translate/render-for-user.js +169 -0
  442. package/dist/core-runtime/translate/render-for-user.test.js +122 -0
  443. package/dist/mcp/server.js +1011 -0
  444. package/dist/mcp/tool-schemas.js +93 -0
  445. package/dist/providers/capability-contract.js +1 -0
  446. package/package.json +68 -0
  447. package/settings.example.json +33 -0
@@ -0,0 +1,963 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { normalizeLlmModelSwitcher, } from "../llm/model-switcher.js";
5
+ import { assertNoUnsupportedConfigFiles, defaultReviewExecution, projectSettingsPath, } from "../discovery/settings-chain.js";
6
+ import { ensureDirectory, fileExists, isoNow, normalizeDomainValue, renderReviewTargetMaterializedInput, renderTargetSnapshot, writeYamlDocument, } from "./review-artifact-utils.js";
7
+ import { ISSUE_ARTIFACT_IDS, issueArtifactConsumerId, issueArtifactSpec, } from "./issue-artifact-runtime.js";
8
+ import { detectTargetMaterialKind, reviewMaterialSupportStatus, } from "../target-material-kind.js";
9
+ /**
10
+ * Load {projectRoot}/.onto/settings.json into the narrow subset used by
11
+ * the canonical LLM switcher. Missing file → {}.
12
+ *
13
+ * Inline-http executor 의 loadOntoConfig 와 동일 패턴. 본 bootstrap 은 CLI
14
+ * override 를 받지 않으므로 config 단독으로 plan-time 값 도출.
15
+ */
16
+ async function loadOntoConfigForPlan(projectRoot) {
17
+ await assertNoUnsupportedConfigFiles(projectRoot);
18
+ const configPath = projectSettingsPath(projectRoot);
19
+ if (!(await fileExists(configPath)))
20
+ return {};
21
+ const parsed = JSON.parse(await fs.readFile(configPath, "utf8"));
22
+ if (parsed && typeof parsed === "object") {
23
+ return parsed;
24
+ }
25
+ return {};
26
+ }
27
+ /**
28
+ * OntoConfig subset → ResolvedLlmPlan.
29
+ * Returns undefined if no fields are populated (avoid empty record noise).
30
+ */
31
+ function derivePlanTimeLlmResolution(config) {
32
+ const partial = normalizeLlmModelSwitcher(config.llm);
33
+ if (partial === null)
34
+ return undefined;
35
+ const plan = {};
36
+ if (partial.model_id)
37
+ plan.model = partial.model_id;
38
+ if (partial.reasoning_effort)
39
+ plan.reasoning_effort = partial.reasoning_effort;
40
+ if (partial.service_tier)
41
+ plan.service_tier = partial.service_tier;
42
+ if (partial.provider)
43
+ plan.provider = partial.provider;
44
+ return Object.keys(plan).length > 0 ? plan : undefined;
45
+ }
46
+ function resolveReviewExecutionSettingsForArtifacts(config) {
47
+ const defaults = defaultReviewExecution();
48
+ const execution = config.review?.execution;
49
+ if (!execution)
50
+ return defaults;
51
+ return {
52
+ ...defaults,
53
+ ...execution,
54
+ teamlead: {
55
+ ...defaults.teamlead,
56
+ ...execution.teamlead,
57
+ },
58
+ lens: {
59
+ ...defaults.lens,
60
+ ...execution.lens,
61
+ },
62
+ synthesize: {
63
+ ...defaults.synthesize,
64
+ ...execution.synthesize,
65
+ },
66
+ };
67
+ }
68
+ function resolveActorLlmForArtifact(actorLlmRef, inherited) {
69
+ if (actorLlmRef === "inherit")
70
+ return inherited;
71
+ const shouldOverlayInherited = actorLlmRef.auth === undefined && actorLlmRef.provider === undefined;
72
+ return {
73
+ ...(shouldOverlayInherited ? inherited ?? {} : {}),
74
+ ...actorLlmRef,
75
+ };
76
+ }
77
+ function workerExecutorForRealization(executionRealization, hostRuntime) {
78
+ if (hostRuntime === "standalone")
79
+ return "mock";
80
+ if (executionRealization === "direct-call")
81
+ return "direct_call";
82
+ return "codex";
83
+ }
84
+ function defaultAuthForExecutionContext(executionRealization, hostRuntime) {
85
+ if (hostRuntime === "standalone")
86
+ return null;
87
+ if (hostRuntime === "lmstudio")
88
+ return "local";
89
+ if (executionRealization === "direct-call")
90
+ return "api_key";
91
+ return "oauth";
92
+ }
93
+ function credentialRefForSelection(args) {
94
+ if (args.apiKeyEnv)
95
+ return `env:${args.apiKeyEnv}`;
96
+ if (args.auth === "oauth" && args.provider)
97
+ return `host:${args.provider}:oauth`;
98
+ if (args.auth === "local" && args.provider)
99
+ return `local:${args.provider}`;
100
+ return null;
101
+ }
102
+ function buildActorInvocationProfile(args) {
103
+ const resolvedLlm = resolveActorLlmForArtifact(args.actorLlmRef, args.inheritedLlm);
104
+ const normalized = normalizeLlmModelSwitcher(resolvedLlm);
105
+ const effectiveWorkerExecutor = workerExecutorForRealization(args.executionRealization, args.hostRuntime);
106
+ const routeForcesMock = effectiveWorkerExecutor === "mock";
107
+ const directCallWithoutSelection = args.executionRealization === "direct-call" && normalized === null;
108
+ const auth = directCallWithoutSelection || routeForcesMock
109
+ ? null
110
+ : normalized?.auth ??
111
+ defaultAuthForExecutionContext(args.executionRealization, args.hostRuntime);
112
+ const provider = directCallWithoutSelection || routeForcesMock
113
+ ? null
114
+ : normalized?.provider ?? args.hostRuntime;
115
+ const runtimeProvider = routeForcesMock ? "mock" : provider;
116
+ const authMode = routeForcesMock ? null : auth;
117
+ const apiKeyEnv = normalized?.api_key_env ?? resolvedLlm?.api_key_env;
118
+ return {
119
+ actor_profile_id: `actor:${args.actorKind}`,
120
+ actor_kind: args.actorKind,
121
+ seat: args.seat,
122
+ execution_realization: args.executionRealization,
123
+ host_runtime: args.hostRuntime,
124
+ runtime_provider: runtimeProvider,
125
+ auth_mode: authMode,
126
+ model: normalized?.model_id ?? resolvedLlm?.model ?? null,
127
+ effort: normalized?.reasoning_effort ?? resolvedLlm?.effort ?? null,
128
+ service_tier: normalized?.service_tier ?? resolvedLlm?.service_tier ?? null,
129
+ base_url: normalized?.base_url ?? resolvedLlm?.base_url ?? null,
130
+ effective_worker_executor: effectiveWorkerExecutor,
131
+ credential_ref: credentialRefForSelection({
132
+ auth: authMode ?? null,
133
+ provider: runtimeProvider ?? null,
134
+ ...(apiKeyEnv ? { apiKeyEnv } : {}),
135
+ }),
136
+ credential_serialization_policy: "ref_only_no_secret",
137
+ route_unavailable_policy: "fail_before_dispatch",
138
+ capability_requirements: ["review_unit_execution", "artifact_write"],
139
+ source_settings_refs: args.sourceSettingsRefs,
140
+ };
141
+ }
142
+ function consumerIdForLens(lensId) {
143
+ return `lens:${lensId}`;
144
+ }
145
+ function buildActorConsumerBindings(args) {
146
+ return [
147
+ {
148
+ actor_profile_id: "actor:teamlead",
149
+ actor_kind: "teamlead",
150
+ actor_instance_id: "teamlead:main",
151
+ consumer_id: "teamlead",
152
+ consumer_kind: "teamlead",
153
+ lens_id: null,
154
+ applies_to: ["review_coordination"],
155
+ profile_ref: args.actorInvocationProfilesPath,
156
+ context_access_ref: args.reviewContextManifestPath,
157
+ extension_admission_status: "admitted",
158
+ },
159
+ ...args.resolvedLensIds.map((lensId) => ({
160
+ actor_profile_id: "actor:lens",
161
+ actor_kind: "lens",
162
+ actor_instance_id: `lens:${lensId}`,
163
+ consumer_id: consumerIdForLens(lensId),
164
+ consumer_kind: "lens",
165
+ lens_id: lensId,
166
+ applies_to: ["round1:lens"],
167
+ profile_ref: args.actorInvocationProfilesPath,
168
+ context_access_ref: args.reviewContextManifestPath,
169
+ extension_admission_status: "admitted",
170
+ })),
171
+ ...args.resolvedLensIds.map((lensId) => ({
172
+ actor_profile_id: "actor:lens",
173
+ actor_kind: "lens",
174
+ actor_instance_id: `lens:${lensId}`,
175
+ consumer_id: `deliberation:${lensId}`,
176
+ consumer_kind: "deliberation",
177
+ lens_id: lensId,
178
+ applies_to: ["controlled-lens-deliberation:lens-response"],
179
+ profile_ref: args.actorInvocationProfilesPath,
180
+ context_access_ref: args.reviewContextManifestPath,
181
+ extension_admission_status: "admitted",
182
+ })),
183
+ ...ISSUE_ARTIFACT_IDS.map((artifactId) => ({
184
+ actor_profile_id: "actor:teamlead",
185
+ actor_kind: "teamlead",
186
+ actor_instance_id: `issue-artifact:${artifactId}`,
187
+ consumer_id: issueArtifactConsumerId(artifactId),
188
+ consumer_kind: "issue_artifact",
189
+ lens_id: null,
190
+ applies_to: [`issue-artifact:${artifactId}`],
191
+ profile_ref: args.actorInvocationProfilesPath,
192
+ context_access_ref: args.reviewContextManifestPath,
193
+ extension_admission_status: "admitted",
194
+ })),
195
+ {
196
+ actor_profile_id: "actor:teamlead",
197
+ actor_kind: "teamlead",
198
+ actor_instance_id: "controlled-deliberation:teamlead",
199
+ consumer_id: "controlled-deliberation",
200
+ consumer_kind: "controlled-deliberation",
201
+ lens_id: null,
202
+ applies_to: ["controlled-lens-deliberation:teamlead"],
203
+ profile_ref: args.actorInvocationProfilesPath,
204
+ context_access_ref: args.reviewContextManifestPath,
205
+ extension_admission_status: "admitted",
206
+ },
207
+ {
208
+ actor_profile_id: "actor:synthesize",
209
+ actor_kind: "synthesize",
210
+ actor_instance_id: "synthesize:main",
211
+ consumer_id: "synthesize",
212
+ consumer_kind: "synthesize",
213
+ lens_id: null,
214
+ applies_to: ["synthesize"],
215
+ profile_ref: args.actorInvocationProfilesPath,
216
+ context_access_ref: args.reviewContextManifestPath,
217
+ extension_admission_status: "admitted",
218
+ },
219
+ ];
220
+ }
221
+ export function generateReviewSessionId() {
222
+ const now = new Date();
223
+ const year = now.getFullYear();
224
+ const month = String(now.getMonth() + 1).padStart(2, "0");
225
+ const day = String(now.getDate()).padStart(2, "0");
226
+ return `${year}${month}${day}-${crypto.randomBytes(4).toString("hex")}`;
227
+ }
228
+ async function isReservedDiffTargetSessionRoot(args) {
229
+ try {
230
+ const entries = await fs.readdir(args.sessionRoot);
231
+ const diffTargetPath = path.join(args.sessionRoot, "diff-target.patch");
232
+ return (entries.length === 1 &&
233
+ entries[0] === "diff-target.patch" &&
234
+ args.resolvedTargetRefs
235
+ .map((ref) => path.resolve(ref))
236
+ .includes(path.resolve(diffTargetPath)));
237
+ }
238
+ catch {
239
+ return false;
240
+ }
241
+ }
242
+ function resolveBoundaryPolicy(params, projectRoot, allowedOutputRefs) {
243
+ const allowedRoots = params.filesystemAllowedRoots && params.filesystemAllowedRoots.length > 0
244
+ ? params.filesystemAllowedRoots.map((rootPath) => path.resolve(rootPath))
245
+ : [projectRoot];
246
+ return {
247
+ web_research_policy: params.webResearchPolicy ?? "denied",
248
+ repo_exploration_policy: params.repoExplorationPolicy ?? "allowed",
249
+ recursive_reference_expansion_policy: params.recursiveReferenceExpansionPolicy ?? "denied",
250
+ filesystem_scope: {
251
+ allowed_roots: allowedRoots,
252
+ },
253
+ write_policy: {
254
+ source_mutation_policy: "denied",
255
+ allowed_output_refs: allowedOutputRefs,
256
+ },
257
+ provenance_policy: {
258
+ extra_exploration_citation_required: true,
259
+ web_source_citation_required: true,
260
+ },
261
+ };
262
+ }
263
+ function resolveBoundaryPresentation() {
264
+ return {
265
+ role_definition_presentation: "embedded_and_ref",
266
+ primary_target_presentation: "embedded_and_ref",
267
+ required_context_presentation: "ref_only",
268
+ output_seat_presentation: "declared",
269
+ control_policy_presentation: "declared",
270
+ };
271
+ }
272
+ function resolveBoundaryEnforcementProfile() {
273
+ return {
274
+ prompt_boundary_enforcement: "prompt_declared_only",
275
+ filesystem_boundary_enforcement: "prompt_declared_only",
276
+ network_boundary_enforcement: "prompt_declared_only",
277
+ write_boundary_enforcement: "prompt_declared_only",
278
+ };
279
+ }
280
+ function toEffectiveBoundaryDecision(requestedPolicy, guaranteeLevel, note) {
281
+ return {
282
+ requested_policy: requestedPolicy,
283
+ effective_policy: requestedPolicy,
284
+ guarantee_level: guaranteeLevel,
285
+ notes: [note],
286
+ };
287
+ }
288
+ function resolveEffectiveBoundaryState(boundaryPolicy, boundaryEnforcementProfile) {
289
+ return {
290
+ web_research: toEffectiveBoundaryDecision(boundaryPolicy.web_research_policy, boundaryEnforcementProfile.network_boundary_enforcement, "Current execution relies on declared boundary guidance; web access is not environment-enforced yet."),
291
+ repo_exploration: toEffectiveBoundaryDecision(boundaryPolicy.repo_exploration_policy, boundaryEnforcementProfile.filesystem_boundary_enforcement, "Current execution relies on declared boundary guidance for repo exploration scope."),
292
+ recursive_reference_expansion: toEffectiveBoundaryDecision(boundaryPolicy.recursive_reference_expansion_policy, boundaryEnforcementProfile.prompt_boundary_enforcement, "Current execution relies on prompt-declared no-hidden-expansion guidance."),
293
+ source_mutation: toEffectiveBoundaryDecision(boundaryPolicy.write_policy.source_mutation_policy, boundaryEnforcementProfile.write_boundary_enforcement, "Current execution declares output-seat-only writing and source mutation denial in the prompt path."),
294
+ filesystem_scope: {
295
+ requested_allowed_roots: boundaryPolicy.filesystem_scope.allowed_roots,
296
+ effective_allowed_roots: boundaryPolicy.filesystem_scope.allowed_roots,
297
+ guarantee_level: boundaryEnforcementProfile.filesystem_boundary_enforcement,
298
+ notes: [
299
+ "Current execution does not enforce filesystem scope below the host boundary; allowed roots are currently prompt-declared.",
300
+ ],
301
+ },
302
+ };
303
+ }
304
+ export async function writeInvocationInterpretationArtifact(params) {
305
+ await ensureDirectory(params.sessionRoot);
306
+ const interpretationArtifact = {
307
+ entrypoint: params.entrypoint ?? "review",
308
+ target_scope_candidate: {
309
+ kind: params.targetScopeKind,
310
+ primary_ref: params.primaryRef,
311
+ ...(params.memberRefs && params.memberRefs.length > 0
312
+ ? { member_refs: params.memberRefs }
313
+ : {}),
314
+ ...(params.bundleKind ? { bundle_kind: params.bundleKind } : {}),
315
+ },
316
+ intent_summary: params.intentSummary,
317
+ domain_recommendation: params.domainRecommendation ?? "",
318
+ domain_selection_required: params.domainSelectionRequired,
319
+ review_mode_recommendation: params.reviewModeRecommendation,
320
+ lens_selection_plan: {
321
+ always_include: params.alwaysIncludeLensIds ?? [],
322
+ recommended_lenses: params.recommendedLensIds ?? [],
323
+ rationale: params.rationale ?? [],
324
+ },
325
+ ambiguity_notes: params.ambiguityNotes ?? [],
326
+ ...(params.valueAlignmentConfirmed
327
+ ? {
328
+ value_alignment_confirmation: {
329
+ status: "confirmed",
330
+ confirmed_by: "user",
331
+ source_ref: "review invocation flag --confirm-value-alignment",
332
+ confirmed_at: isoNow(),
333
+ },
334
+ }
335
+ : {}),
336
+ };
337
+ const interpretationArtifactPath = path.join(params.sessionRoot, "interpretation.yaml");
338
+ await writeYamlDocument(interpretationArtifactPath, interpretationArtifact);
339
+ return interpretationArtifactPath;
340
+ }
341
+ export async function bootstrapInvocationBindingArtifacts(params) {
342
+ if (params.resolvedTargetRefs.length === 0) {
343
+ throw new Error("resolvedTargetRefs must not be empty.");
344
+ }
345
+ if (params.resolvedLensIds.length === 0) {
346
+ throw new Error("resolvedLensIds must not be empty.");
347
+ }
348
+ const projectRoot = path.resolve(params.projectRoot);
349
+ const sessionId = params.sessionId ?? generateReviewSessionId();
350
+ const sessionRoot = path.join(projectRoot, ".onto", "review", sessionId);
351
+ try {
352
+ await fs.access(sessionRoot);
353
+ if (!(await isReservedDiffTargetSessionRoot({
354
+ sessionRoot,
355
+ resolvedTargetRefs: params.resolvedTargetRefs,
356
+ }))) {
357
+ throw new Error(`Session directory already exists: ${sessionRoot}. Use a different --session-id or remove the existing session.`);
358
+ }
359
+ }
360
+ catch (error) {
361
+ if (error?.code !== "ENOENT") {
362
+ throw error;
363
+ }
364
+ }
365
+ const round1Root = path.join(sessionRoot, "round1");
366
+ const deliberationRootPath = path.join(sessionRoot, "deliberation");
367
+ const deliberationRound1Root = path.join(deliberationRootPath, "round1");
368
+ const executionPreparationRoot = path.join(sessionRoot, "execution-preparation");
369
+ const promptPacketsRoot = path.join(sessionRoot, "prompt-packets");
370
+ const executionPlanPath = path.join(sessionRoot, "execution-plan.yaml");
371
+ const sessionMetadataPath = path.join(sessionRoot, "session-metadata.yaml");
372
+ const bindingOutputPath = path.join(sessionRoot, "binding.yaml");
373
+ const interpretationArtifactPath = path.join(sessionRoot, "interpretation.yaml");
374
+ const targetSnapshotPath = path.join(executionPreparationRoot, "target-snapshot.md");
375
+ const targetSnapshotManifestPath = path.join(executionPreparationRoot, "target-snapshot-manifest.yaml");
376
+ const materializedInputPath = path.join(executionPreparationRoot, "materialized-input.md");
377
+ const contextCandidateAssemblyPath = path.join(executionPreparationRoot, "context-candidate-assembly.yaml");
378
+ const actorInvocationProfilesPath = path.join(executionPreparationRoot, "actor-invocation-profiles.yaml");
379
+ const actorConsumerBindingsPath = path.join(executionPreparationRoot, "actor-consumer-bindings.yaml");
380
+ const domainBindingPath = path.join(executionPreparationRoot, "domain-binding.yaml");
381
+ const reviewValueAlignmentCriteriaPath = path.join(executionPreparationRoot, "review-value-alignment-criteria.yaml");
382
+ const reviewTargetProfilePath = path.join(executionPreparationRoot, "review-target-profile.yaml");
383
+ const reviewContextManifestPath = path.join(executionPreparationRoot, "review-context-manifest.yaml");
384
+ const synthesisOutputPath = path.join(sessionRoot, "synthesis.md");
385
+ const findingLedgerPath = path.join(sessionRoot, "finding-ledger.yaml");
386
+ const findingRelationGraphPath = path.join(sessionRoot, "finding-relation-graph.yaml");
387
+ const issueLedgerPath = path.join(sessionRoot, "issue-ledger.yaml");
388
+ const issueStanceMatrixPath = path.join(sessionRoot, "issue-stance-matrix.yaml");
389
+ const deliberationPlanPath = path.join(sessionRoot, "deliberation-plan.yaml");
390
+ const problemFramingPath = path.join(sessionRoot, "problem-framing.yaml");
391
+ const lensCompletionBarrierPath = path.join(sessionRoot, "lens-completion-barrier.yaml");
392
+ const deliberationOutputPath = path.join(sessionRoot, "deliberation.md");
393
+ const executionResultPath = path.join(sessionRoot, "execution-result.yaml");
394
+ const errorLogPath = path.join(sessionRoot, "error-log.md");
395
+ const reviewRecordPath = path.join(sessionRoot, "review-record.yaml");
396
+ const finalOutputPath = path.join(sessionRoot, "final-output.md");
397
+ const allowedOutputRefs = [
398
+ ...params.resolvedLensIds.map((lensId) => path.join(round1Root, `${lensId}.md`)),
399
+ ...params.resolvedLensIds.map((lensId) => path.join(deliberationRound1Root, `${lensId}-deliberation.md`)),
400
+ findingLedgerPath,
401
+ findingRelationGraphPath,
402
+ issueLedgerPath,
403
+ issueStanceMatrixPath,
404
+ deliberationPlanPath,
405
+ problemFramingPath,
406
+ lensCompletionBarrierPath,
407
+ synthesisOutputPath,
408
+ deliberationOutputPath,
409
+ ];
410
+ await Promise.all([
411
+ ensureDirectory(sessionRoot),
412
+ ensureDirectory(round1Root),
413
+ ensureDirectory(deliberationRound1Root),
414
+ ensureDirectory(executionPreparationRoot),
415
+ ensureDirectory(promptPacketsRoot),
416
+ ]);
417
+ const ontoHome = params.ontoHome
418
+ ? path.resolve(params.ontoHome)
419
+ : path.resolve(projectRoot);
420
+ const ontoConfigSubset = await loadOntoConfigForPlan(projectRoot);
421
+ const ontoConfig = params.ontoConfig ?? ontoConfigSubset;
422
+ const resolvedLlmPlan = derivePlanTimeLlmResolution(ontoConfig);
423
+ const reviewExecutionSettings = resolveReviewExecutionSettingsForArtifacts(ontoConfig);
424
+ const reviewSessionMetadata = {
425
+ session_id: sessionId,
426
+ entrypoint: "review",
427
+ execution_realization: params.executionRealization,
428
+ host_runtime: params.hostRuntime,
429
+ review_mode: params.reviewMode,
430
+ created_at: isoNow(),
431
+ project_root: projectRoot,
432
+ requested_target: params.requestedTarget,
433
+ requested_domain_token: params.requestedDomainToken ?? "",
434
+ onto_home: ontoHome,
435
+ ...(resolvedLlmPlan ? { resolved_llm_plan: resolvedLlmPlan } : {}),
436
+ };
437
+ const boundaryPolicy = resolveBoundaryPolicy(params, projectRoot, allowedOutputRefs);
438
+ const boundaryPresentation = resolveBoundaryPresentation();
439
+ const boundaryEnforcementProfile = resolveBoundaryEnforcementProfile();
440
+ const effectiveBoundaryState = resolveEffectiveBoundaryState(boundaryPolicy, boundaryEnforcementProfile);
441
+ const invocationBindingArtifact = {
442
+ resolved_target_scope: {
443
+ kind: params.targetScopeKind,
444
+ resolved_refs: params.resolvedTargetRefs.map((ref) => path.resolve(ref)),
445
+ ...(params.bundleKind ? { bundle_kind: params.bundleKind } : {}),
446
+ },
447
+ domain_final_selection: {
448
+ recommendation: params.domainRecommendation ?? "",
449
+ final_value: normalizeDomainValue(params.domainFinalValue),
450
+ selection_mode: params.domainSelectionMode,
451
+ },
452
+ resolved_session_domain: normalizeDomainValue(params.domainFinalValue),
453
+ resolved_execution_realization: params.executionRealization,
454
+ resolved_host_runtime: params.hostRuntime,
455
+ resolved_review_mode: params.reviewMode,
456
+ resolved_lens_set: params.resolvedLensIds,
457
+ session_id: sessionId,
458
+ session_root: sessionRoot,
459
+ round1_root: round1Root,
460
+ execution_preparation_root: executionPreparationRoot,
461
+ execution_plan_path: executionPlanPath,
462
+ session_metadata_path: sessionMetadataPath,
463
+ interpretation_artifact_path: interpretationArtifactPath,
464
+ binding_output_path: bindingOutputPath,
465
+ target_snapshot_path: targetSnapshotPath,
466
+ target_snapshot_manifest_path: targetSnapshotManifestPath,
467
+ review_target_profile_path: reviewTargetProfilePath,
468
+ materialized_input_path: materializedInputPath,
469
+ context_candidate_assembly_path: contextCandidateAssemblyPath,
470
+ actor_invocation_profiles_path: actorInvocationProfilesPath,
471
+ actor_consumer_bindings_path: actorConsumerBindingsPath,
472
+ domain_binding_path: domainBindingPath,
473
+ review_value_alignment_criteria_path: reviewValueAlignmentCriteriaPath,
474
+ review_context_manifest_path: reviewContextManifestPath,
475
+ synthesis_output_path: synthesisOutputPath,
476
+ finding_ledger_path: findingLedgerPath,
477
+ finding_relation_graph_path: findingRelationGraphPath,
478
+ issue_ledger_path: issueLedgerPath,
479
+ issue_stance_matrix_path: issueStanceMatrixPath,
480
+ deliberation_plan_path: deliberationPlanPath,
481
+ problem_framing_path: problemFramingPath,
482
+ lens_completion_barrier_path: lensCompletionBarrierPath,
483
+ deliberation_mode: "controlled-lens-deliberation",
484
+ deliberation_root_path: deliberationRootPath,
485
+ deliberation_output_path: deliberationOutputPath,
486
+ execution_result_path: executionResultPath,
487
+ error_log_path: errorLogPath,
488
+ review_record_path: reviewRecordPath,
489
+ final_output_path: finalOutputPath,
490
+ boundary_policy: boundaryPolicy,
491
+ boundary_presentation: boundaryPresentation,
492
+ boundary_enforcement_profile: boundaryEnforcementProfile,
493
+ effective_boundary_state: effectiveBoundaryState,
494
+ binding_notes: params.bindingNotes ?? [],
495
+ };
496
+ const reviewExecutionPlan = {
497
+ session_id: sessionId,
498
+ session_root: sessionRoot,
499
+ execution_realization: params.executionRealization,
500
+ host_runtime: params.hostRuntime,
501
+ review_mode: params.reviewMode,
502
+ interpretation_artifact_path: interpretationArtifactPath,
503
+ binding_output_path: bindingOutputPath,
504
+ session_metadata_path: sessionMetadataPath,
505
+ execution_preparation_root: executionPreparationRoot,
506
+ round1_root: round1Root,
507
+ lens_execution_seats: params.resolvedLensIds.map((lensId) => ({
508
+ lens_id: lensId,
509
+ output_path: path.join(round1Root, `${lensId}.md`),
510
+ })),
511
+ prompt_packets_root: promptPacketsRoot,
512
+ lens_prompt_packet_seats: params.resolvedLensIds.map((lensId) => ({
513
+ lens_id: lensId,
514
+ packet_path: path.join(promptPacketsRoot, `${lensId}.prompt.md`),
515
+ output_path: path.join(round1Root, `${lensId}.md`),
516
+ })),
517
+ issue_artifact_prompt_packet_seats: ISSUE_ARTIFACT_IDS.map((artifactId) => {
518
+ const spec = issueArtifactSpec(artifactId);
519
+ const outputPaths = {
520
+ "finding-ledger": findingLedgerPath,
521
+ "finding-relation-graph": findingRelationGraphPath,
522
+ "issue-ledger": issueLedgerPath,
523
+ "issue-stance-matrix": issueStanceMatrixPath,
524
+ "deliberation-plan": deliberationPlanPath,
525
+ "problem-framing": problemFramingPath,
526
+ };
527
+ return {
528
+ artifact_id: artifactId,
529
+ packet_path: path.join(promptPacketsRoot, spec.prompt_packet_file_name),
530
+ output_path: outputPaths[artifactId],
531
+ };
532
+ }),
533
+ lens_deliberation_prompt_packet_seats: params.resolvedLensIds.map((lensId) => ({
534
+ lens_id: lensId,
535
+ packet_path: path.join(promptPacketsRoot, `${lensId}.deliberation.prompt.md`),
536
+ output_path: path.join(deliberationRound1Root, `${lensId}-deliberation.md`),
537
+ })),
538
+ teamlead_deliberation_prompt_packet_path: path.join(promptPacketsRoot, "teamlead.deliberation.prompt.md"),
539
+ synthesize_prompt_packet_path: path.join(promptPacketsRoot, "synthesize.prompt.md"),
540
+ actor_invocation_profiles_path: actorInvocationProfilesPath,
541
+ actor_consumer_bindings_path: actorConsumerBindingsPath,
542
+ domain_binding_path: domainBindingPath,
543
+ review_target_profile_path: reviewTargetProfilePath,
544
+ review_value_alignment_criteria_path: reviewValueAlignmentCriteriaPath,
545
+ review_context_manifest_path: reviewContextManifestPath,
546
+ synthesis_output_path: synthesisOutputPath,
547
+ finding_ledger_path: findingLedgerPath,
548
+ finding_relation_graph_path: findingRelationGraphPath,
549
+ issue_ledger_path: issueLedgerPath,
550
+ issue_stance_matrix_path: issueStanceMatrixPath,
551
+ deliberation_plan_path: deliberationPlanPath,
552
+ problem_framing_path: problemFramingPath,
553
+ lens_completion_barrier_path: lensCompletionBarrierPath,
554
+ deliberation_mode: "controlled-lens-deliberation",
555
+ deliberation_root_path: deliberationRootPath,
556
+ deliberation_output_path: deliberationOutputPath,
557
+ execution_result_path: executionResultPath,
558
+ error_log_path: errorLogPath,
559
+ final_output_path: finalOutputPath,
560
+ review_record_path: reviewRecordPath,
561
+ boundary_policy: boundaryPolicy,
562
+ boundary_presentation: boundaryPresentation,
563
+ boundary_enforcement_profile: boundaryEnforcementProfile,
564
+ effective_boundary_state: effectiveBoundaryState,
565
+ minimum_participating_lenses: params.resolvedLensIds.length,
566
+ };
567
+ const actorInvocationProfiles = {
568
+ schema_version: "1",
569
+ session_id: sessionId,
570
+ created_at: reviewSessionMetadata.created_at,
571
+ profiles: [
572
+ buildActorInvocationProfile({
573
+ actorKind: "teamlead",
574
+ seat: reviewExecutionSettings.teamlead.seat,
575
+ actorLlmRef: reviewExecutionSettings.teamlead.llm,
576
+ inheritedLlm: ontoConfig.llm,
577
+ executionRealization: params.executionRealization,
578
+ hostRuntime: params.hostRuntime,
579
+ sourceSettingsRefs: ["review.execution.teamlead.llm", "llm"],
580
+ }),
581
+ buildActorInvocationProfile({
582
+ actorKind: "lens",
583
+ seat: reviewExecutionSettings.lens.seat,
584
+ actorLlmRef: reviewExecutionSettings.lens.llm,
585
+ inheritedLlm: ontoConfig.llm,
586
+ executionRealization: params.executionRealization,
587
+ hostRuntime: params.hostRuntime,
588
+ sourceSettingsRefs: ["review.execution.lens.llm", "llm"],
589
+ }),
590
+ buildActorInvocationProfile({
591
+ actorKind: "synthesize",
592
+ seat: reviewExecutionSettings.synthesize.seat,
593
+ actorLlmRef: reviewExecutionSettings.synthesize.llm,
594
+ inheritedLlm: ontoConfig.llm,
595
+ executionRealization: params.executionRealization,
596
+ hostRuntime: params.hostRuntime,
597
+ sourceSettingsRefs: ["review.execution.synthesize.llm", "llm"],
598
+ }),
599
+ ],
600
+ };
601
+ const actorConsumerBindings = {
602
+ schema_version: "1",
603
+ session_id: sessionId,
604
+ created_at: reviewSessionMetadata.created_at,
605
+ bindings: buildActorConsumerBindings({
606
+ sessionId,
607
+ resolvedLensIds: params.resolvedLensIds,
608
+ actorInvocationProfilesPath,
609
+ reviewContextManifestPath,
610
+ }),
611
+ };
612
+ await Promise.all([
613
+ writeYamlDocument(sessionMetadataPath, reviewSessionMetadata),
614
+ writeYamlDocument(bindingOutputPath, invocationBindingArtifact),
615
+ writeYamlDocument(executionPlanPath, reviewExecutionPlan),
616
+ writeYamlDocument(actorInvocationProfilesPath, actorInvocationProfiles),
617
+ writeYamlDocument(actorConsumerBindingsPath, actorConsumerBindings),
618
+ ]);
619
+ return {
620
+ sessionRoot,
621
+ sessionMetadataPath,
622
+ bindingOutputPath,
623
+ };
624
+ }
625
+ const CODE_EXTENSIONS = new Set([
626
+ ".c",
627
+ ".cc",
628
+ ".cpp",
629
+ ".cs",
630
+ ".go",
631
+ ".java",
632
+ ".js",
633
+ ".jsx",
634
+ ".kt",
635
+ ".mjs",
636
+ ".php",
637
+ ".py",
638
+ ".rb",
639
+ ".rs",
640
+ ".sh",
641
+ ".swift",
642
+ ".ts",
643
+ ".tsx",
644
+ ]);
645
+ const CONFIG_EXTENSIONS = new Set([
646
+ ".env",
647
+ ".ini",
648
+ ".json",
649
+ ".lock",
650
+ ".toml",
651
+ ".yaml",
652
+ ".yml",
653
+ ]);
654
+ const DATA_EXTENSIONS = new Set([
655
+ ".csv",
656
+ ".jsonl",
657
+ ".ndjson",
658
+ ".parquet",
659
+ ".tsv",
660
+ ]);
661
+ function uniqueStrings(values) {
662
+ return [...new Set(values)].filter((value) => value.length > 0);
663
+ }
664
+ function uniqueRoles(values) {
665
+ return [...new Set(values)];
666
+ }
667
+ function inferRoleFromRef(ref) {
668
+ const extension = path.extname(ref).toLowerCase();
669
+ if (CODE_EXTENSIONS.has(extension))
670
+ return "computational_artifact";
671
+ if (CONFIG_EXTENSIONS.has(extension))
672
+ return "configuration_artifact";
673
+ if (DATA_EXTENSIONS.has(extension))
674
+ return "data_artifact";
675
+ if (extension === ".xlsx" || extension === ".xlsm")
676
+ return "computational_artifact";
677
+ if (extension === ".md" || extension === ".txt")
678
+ return "knowledge_artifact";
679
+ if (extension === ".patch" || extension === ".diff")
680
+ return "record_artifact";
681
+ if (extension === ".pdf" || extension === ".docx" || extension === ".pptx") {
682
+ return "presentation_artifact";
683
+ }
684
+ return "knowledge_artifact";
685
+ }
686
+ function isGeneratedReviewPacketRef(ref) {
687
+ const normalized = path.resolve(ref);
688
+ return normalized.includes(`${path.sep}.onto${path.sep}review${path.sep}manual-targets${path.sep}`);
689
+ }
690
+ function isRuntimeDiffTargetRef(ref, sessionRoot) {
691
+ const resolvedRef = path.resolve(ref);
692
+ const relativeToSession = path.relative(path.resolve(sessionRoot), resolvedRef);
693
+ return (path.basename(resolvedRef) === "diff-target.patch" &&
694
+ relativeToSession.length > 0 &&
695
+ !relativeToSession.startsWith("..") &&
696
+ !path.isAbsolute(relativeToSession));
697
+ }
698
+ function deriveReviewTargetInputKind(args) {
699
+ if (args.resolvedTargetRefs.some((ref) => isRuntimeDiffTargetRef(ref, args.sessionRoot))) {
700
+ return "git_diff";
701
+ }
702
+ if (args.resolvedTargetRefs.some(isGeneratedReviewPacketRef)) {
703
+ return "generated_packet";
704
+ }
705
+ if (args.scopeKind === "bundle")
706
+ return "explicit_bundle";
707
+ if (args.scopeKind === "directory")
708
+ return "directory";
709
+ return "single_file";
710
+ }
711
+ function deriveArtifactRoles(args) {
712
+ if (args.inputKind === "git_diff") {
713
+ return {
714
+ primary: "computational_artifact",
715
+ secondary: ["record_artifact", "configuration_artifact"],
716
+ confidenceBasis: "runtime diff target implies implementation-change review",
717
+ };
718
+ }
719
+ if (args.inputKind === "generated_packet") {
720
+ return {
721
+ primary: "record_artifact",
722
+ secondary: ["knowledge_artifact"],
723
+ confidenceBasis: "target path is an explicit generated review packet",
724
+ };
725
+ }
726
+ if (args.scopeKind === "directory") {
727
+ return {
728
+ primary: "computational_artifact",
729
+ secondary: ["configuration_artifact", "knowledge_artifact"],
730
+ confidenceBasis: "directory target is treated as a bounded project artifact",
731
+ };
732
+ }
733
+ const primaryRef = args.resolvedTargetRefs[0] ?? "";
734
+ const primary = args.bundleKind?.includes("implementation")
735
+ ? "computational_artifact"
736
+ : inferRoleFromRef(primaryRef);
737
+ const secondary = uniqueRoles(args.resolvedTargetRefs
738
+ .slice(1)
739
+ .map(inferRoleFromRef)
740
+ .filter((role) => role !== primary));
741
+ return {
742
+ primary,
743
+ secondary,
744
+ confidenceBasis: args.scopeKind === "bundle"
745
+ ? "explicit bundle target with primary/supporting refs"
746
+ : "runtime file-extension heuristic",
747
+ };
748
+ }
749
+ function goalsForRole(role) {
750
+ switch (role) {
751
+ case "computational_artifact":
752
+ return ["correctness", "verifiability", "regression_risk", "maintainability"];
753
+ case "configuration_artifact":
754
+ return ["scope_control", "precedence", "invalid_input_behavior"];
755
+ case "data_artifact":
756
+ return ["completeness", "consistency", "lineage"];
757
+ case "record_artifact":
758
+ return ["provenance", "evidence_preservation", "auditability"];
759
+ case "contract_artifact":
760
+ return ["obligations", "exceptions", "failure_conditions"];
761
+ case "decision_artifact":
762
+ return ["judgment_criteria", "tradeoff_clarity", "actionability"];
763
+ case "procedural_artifact":
764
+ return ["reproducibility", "sequence_integrity", "operator_safety"];
765
+ case "creative_artifact":
766
+ return ["coherence", "intended_experience", "continuity"];
767
+ case "presentation_artifact":
768
+ return ["audience_decision_support", "clarity", "traceability"];
769
+ case "knowledge_artifact":
770
+ return ["conceptual_accuracy", "completeness_for_purpose", "internal_consistency"];
771
+ }
772
+ }
773
+ function domainGoalAdditions(domain) {
774
+ switch (normalizeDomainValue(domain)) {
775
+ case "software-engineering":
776
+ return ["runtime_contract", "test_evidence", "error_path_clarity"];
777
+ case "llm-native-development":
778
+ return ["context_isolation", "artifact_truth", "fail_loud_behavior"];
779
+ default:
780
+ return [];
781
+ }
782
+ }
783
+ function deriveClosureLevel(args) {
784
+ if (args.inputKind === "generated_packet")
785
+ return "open_partial";
786
+ if (args.inputKind === "directory" ||
787
+ args.inputKind === "explicit_bundle" ||
788
+ args.inputKind === "git_diff") {
789
+ return "bounded_partial";
790
+ }
791
+ if (args.primaryRole === "configuration_artifact" ||
792
+ args.primaryRole === "contract_artifact" ||
793
+ args.primaryRole === "data_artifact") {
794
+ return "bounded_closed";
795
+ }
796
+ return "bounded_partial";
797
+ }
798
+ function confidenceForInputKind(inputKind) {
799
+ switch (inputKind) {
800
+ case "git_diff":
801
+ return 0.9;
802
+ case "single_file":
803
+ return 0.85;
804
+ case "explicit_bundle":
805
+ return 0.8;
806
+ case "directory":
807
+ return 0.75;
808
+ case "generated_packet":
809
+ return 0.65;
810
+ }
811
+ }
812
+ async function targetRefKind(ref, sessionRoot) {
813
+ if (isRuntimeDiffTargetRef(ref, sessionRoot) || isGeneratedReviewPacketRef(ref)) {
814
+ return { kind: "generated", exists: true };
815
+ }
816
+ try {
817
+ const stat = await fs.stat(ref);
818
+ return {
819
+ kind: stat.isDirectory() ? "directory" : "file",
820
+ exists: true,
821
+ };
822
+ }
823
+ catch {
824
+ return { kind: "file", exists: false };
825
+ }
826
+ }
827
+ async function targetRefSha256(ref, kind, directoryListingOptions) {
828
+ try {
829
+ const content = kind === "directory"
830
+ ? Buffer.from(await renderTargetSnapshot([ref], directoryListingOptions), "utf8")
831
+ : await fs.readFile(ref);
832
+ return crypto.createHash("sha256").update(content).digest("hex");
833
+ }
834
+ catch {
835
+ return null;
836
+ }
837
+ }
838
+ async function buildReviewTargetProfileArtifact(params) {
839
+ const sessionRoot = path.resolve(params.sessionRoot);
840
+ const sessionId = path.basename(sessionRoot);
841
+ const resolvedRefs = params.resolvedTargetRefs.map((ref) => path.resolve(ref));
842
+ const inputKind = deriveReviewTargetInputKind({
843
+ scopeKind: params.scopeKind,
844
+ resolvedTargetRefs: resolvedRefs,
845
+ sessionRoot,
846
+ });
847
+ const roles = deriveArtifactRoles({
848
+ inputKind,
849
+ scopeKind: params.scopeKind,
850
+ resolvedTargetRefs: resolvedRefs,
851
+ ...(params.bundleKind ? { bundleKind: params.bundleKind } : {}),
852
+ });
853
+ const materialDetection = await detectTargetMaterialKind(resolvedRefs);
854
+ const materialSupport = reviewMaterialSupportStatus(materialDetection.target_material_kind);
855
+ const closureLevel = deriveClosureLevel({
856
+ inputKind,
857
+ primaryRole: roles.primary,
858
+ });
859
+ const targetRefs = [];
860
+ for (const [index, ref] of resolvedRefs.entries()) {
861
+ const kind = await targetRefKind(ref, sessionRoot);
862
+ targetRefs.push({
863
+ ref,
864
+ role: index === 0 ? "primary" : "supporting",
865
+ kind: kind.kind,
866
+ exists: kind.exists,
867
+ sha256: kind.exists
868
+ ? await targetRefSha256(ref, kind.kind, params.directoryListingOptions)
869
+ : null,
870
+ });
871
+ }
872
+ return {
873
+ schema_version: "1",
874
+ session_id: sessionId,
875
+ created_at: isoNow(),
876
+ target_scope_kind: params.scopeKind,
877
+ materialized_input_kind: params.materializedKind,
878
+ target_input_kind: inputKind,
879
+ target_material_kind: materialDetection.target_material_kind,
880
+ requested_target: params.requestedTarget ?? null,
881
+ review_intent_summary: params.reviewIntentSummary ?? null,
882
+ artifact_roles: {
883
+ primary: roles.primary,
884
+ secondary: roles.secondary,
885
+ },
886
+ domain: normalizeDomainValue(params.sessionDomain ?? "none"),
887
+ maturity: "review_candidate",
888
+ closure_level: closureLevel,
889
+ review_goal: uniqueStrings([
890
+ ...goalsForRole(roles.primary),
891
+ ...roles.secondary.flatMap(goalsForRole),
892
+ ...domainGoalAdditions(params.sessionDomain ?? "none"),
893
+ ]),
894
+ closure_obligation_policy: [
895
+ "must_close_in_target",
896
+ "must_close_before_next_stage",
897
+ "may_close_during_next_stage",
898
+ "planned_later",
899
+ "out_of_scope",
900
+ ],
901
+ target_refs: targetRefs,
902
+ material_profile: {
903
+ target_material_kind: materialDetection.target_material_kind,
904
+ target_material_kind_candidates: materialDetection.target_material_kind_candidates,
905
+ support_status: materialSupport.status,
906
+ unsupported_reason: materialSupport.reason,
907
+ detection: {
908
+ owner: "runtime_heuristic",
909
+ confidence: materialDetection.confidence,
910
+ confidence_basis: materialDetection.confidence_basis,
911
+ },
912
+ },
913
+ boundary: {
914
+ filesystem_allowed_roots: params.filesystemAllowedRoots && params.filesystemAllowedRoots.length > 0
915
+ ? params.filesystemAllowedRoots.map((rootPath) => path.resolve(rootPath))
916
+ : [],
917
+ source: "binding",
918
+ },
919
+ inference: {
920
+ owner: "runtime_heuristic",
921
+ confidence: confidenceForInputKind(inputKind),
922
+ confidence_basis: roles.confidenceBasis,
923
+ },
924
+ };
925
+ }
926
+ export async function materializeReviewExecutionPreparationArtifacts(params) {
927
+ if (params.resolvedTargetRefs.length === 0) {
928
+ throw new Error("resolvedTargetRefs must not be empty.");
929
+ }
930
+ const sessionRoot = path.resolve(params.sessionRoot);
931
+ const executionPreparationRoot = path.join(sessionRoot, "execution-preparation");
932
+ const targetSnapshotPath = path.join(executionPreparationRoot, "target-snapshot.md");
933
+ const targetSnapshotManifestPath = path.join(executionPreparationRoot, "target-snapshot-manifest.yaml");
934
+ const materializedInputPath = path.join(executionPreparationRoot, "materialized-input.md");
935
+ const reviewTargetProfilePath = path.join(executionPreparationRoot, "review-target-profile.yaml");
936
+ const contextCandidateAssemblyPath = path.join(executionPreparationRoot, "context-candidate-assembly.yaml");
937
+ await ensureDirectory(executionPreparationRoot);
938
+ const materializedRefs = params.materializedRefs && params.materializedRefs.length > 0
939
+ ? params.materializedRefs.map((ref) => path.resolve(ref))
940
+ : params.resolvedTargetRefs.map((ref) => path.resolve(ref));
941
+ const targetSnapshotManifest = {
942
+ review_target_scope_kind: params.scopeKind,
943
+ resolved_target_refs: params.resolvedTargetRefs.map((ref) => path.resolve(ref)),
944
+ review_target_profile_ref: reviewTargetProfilePath,
945
+ captured_at: isoNow(),
946
+ capture_reason: "prompt-backed review execution",
947
+ };
948
+ const reviewTargetProfile = await buildReviewTargetProfileArtifact(params);
949
+ const contextCandidateAssembly = {
950
+ system_purpose_refs: params.systemPurposeRefs ?? [],
951
+ domain_context_refs: params.domainContextRefs ?? [],
952
+ role_definition_refs: params.roleDefinitionRefs ?? [],
953
+ execution_rule_refs: params.executionRuleRefs ?? [],
954
+ };
955
+ await Promise.all([
956
+ fs.writeFile(targetSnapshotPath, await renderTargetSnapshot(params.resolvedTargetRefs.map((ref) => path.resolve(ref)), params.directoryListingOptions), "utf8"),
957
+ writeYamlDocument(targetSnapshotManifestPath, targetSnapshotManifest),
958
+ writeYamlDocument(reviewTargetProfilePath, reviewTargetProfile),
959
+ fs.writeFile(materializedInputPath, await renderReviewTargetMaterializedInput(params.materializedKind, materializedRefs, params.directoryListingOptions), "utf8"),
960
+ writeYamlDocument(contextCandidateAssemblyPath, contextCandidateAssembly),
961
+ ]);
962
+ return executionPreparationRoot;
963
+ }