@warlock.js/ai 5.1.0 → 5.2.2

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 (251) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/README.md +4 -0
  3. package/cjs/index.cjs +1 -1
  4. package/cjs/index.cjs.map +1 -1
  5. package/cjs/{magic-string.es-BoSa5xIt.cjs → magic-string.es-BQeqHJ-a.cjs} +22 -17
  6. package/cjs/magic-string.es-BQeqHJ-a.cjs.map +1 -0
  7. package/cjs/matcher-logic-07fFOz7r.cjs.map +1 -1
  8. package/cjs/{matchers-DnV47KR_.cjs → matchers-CINm4ojZ.cjs} +27 -27
  9. package/cjs/matchers-CINm4ojZ.cjs.map +1 -0
  10. package/esm/agent/agent-input-builder.mjs.map +1 -1
  11. package/esm/agent/agent-stream.d.mts.map +1 -1
  12. package/esm/agent/agent-stream.mjs.map +1 -1
  13. package/esm/agent/agent.d.mts.map +1 -1
  14. package/esm/agent/agent.mjs.map +1 -1
  15. package/esm/agent/json-stream-guard.mjs.map +1 -1
  16. package/esm/agent/signature.mjs.map +1 -1
  17. package/esm/agent/snapshot.mjs.map +1 -1
  18. package/esm/agent/spawn-sub-agent.d.mts.map +1 -1
  19. package/esm/batch/batch.d.mts.map +1 -1
  20. package/esm/batch/batch.mjs.map +1 -1
  21. package/esm/checkpoint/memory.d.mts.map +1 -1
  22. package/esm/checkpoint/pg.mjs.map +1 -1
  23. package/esm/checkpoint/redis.mjs.map +1 -1
  24. package/esm/config.d.mts.map +1 -1
  25. package/esm/eval/dataset.d.mts.map +1 -1
  26. package/esm/eval/dataset.mjs.map +1 -1
  27. package/esm/eval/eval-runner.d.mts.map +1 -1
  28. package/esm/eval/eval-runner.mjs.map +1 -1
  29. package/esm/eval/judge-scorer.d.mts.map +1 -1
  30. package/esm/eval/regression.d.mts.map +1 -1
  31. package/esm/eval/regression.mjs.map +1 -1
  32. package/esm/eval/report-json.d.mts.map +1 -1
  33. package/esm/eval/report-junit.mjs.map +1 -1
  34. package/esm/eval/scorers.d.mts.map +1 -1
  35. package/esm/eval/scorers.mjs.map +1 -1
  36. package/esm/guard/detectors/injection.mjs.map +1 -1
  37. package/esm/guard/detectors/moderation.mjs.map +1 -1
  38. package/esm/guard/detectors/pii.mjs.map +1 -1
  39. package/esm/guard/detectors/topic.mjs.map +1 -1
  40. package/esm/human/human-approval.mjs.map +1 -1
  41. package/esm/human/resume.d.mts.map +1 -1
  42. package/esm/human/stores/memory.d.mts.map +1 -1
  43. package/esm/human/stores/pg.mjs.map +1 -1
  44. package/esm/human/stores/redis.mjs.map +1 -1
  45. package/esm/image/image.mjs.map +1 -1
  46. package/esm/memory/derive-id.mjs.map +1 -1
  47. package/esm/memory/episodic-memory.mjs.map +1 -1
  48. package/esm/memory/memory.mjs.map +1 -1
  49. package/esm/memory/procedural-memory.mjs.map +1 -1
  50. package/esm/memory/semantic-memory.mjs.map +1 -1
  51. package/esm/memory/working-memory.mjs.map +1 -1
  52. package/esm/middleware/builtins/budget.mjs.map +1 -1
  53. package/esm/middleware/builtins/semantic-cache.mjs.map +1 -1
  54. package/esm/middleware/helpers/compose.d.mts.map +1 -1
  55. package/esm/middleware/helpers/for-tool.mjs.map +1 -1
  56. package/esm/middleware/pipeline.d.mts.map +1 -1
  57. package/esm/middleware/utils/extract-user-text.mjs.map +1 -1
  58. package/esm/middleware/utils/namespaced-state.d.mts.map +1 -1
  59. package/esm/mock/mock-agent.d.mts.map +1 -1
  60. package/esm/mock/mock-agent.mjs.map +1 -1
  61. package/esm/mock/mock-model.d.mts.map +1 -1
  62. package/esm/mock/mock-model.mjs.map +1 -1
  63. package/esm/mock/mock-router.d.mts.map +1 -1
  64. package/esm/model/fallback-model.mjs.map +1 -1
  65. package/esm/node_modules/{@jridgewell → .pnpm/@jridgewell_sourcemap-codec@1.6.0/node_modules/@jridgewell}/sourcemap-codec/dist/sourcemap-codec.mjs +19 -14
  66. package/esm/node_modules/.pnpm/@jridgewell_sourcemap-codec@1.6.0/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map +1 -0
  67. package/esm/node_modules/{@vitest → .pnpm/@vitest_expect@4.1.10/node_modules/@vitest}/expect/dist/index.mjs +8 -8
  68. package/esm/node_modules/.pnpm/@vitest_expect@4.1.10/node_modules/@vitest/expect/dist/index.mjs.map +1 -0
  69. package/esm/node_modules/{@vitest → .pnpm/@vitest_pretty-format@4.1.10/node_modules/@vitest}/pretty-format/dist/index.mjs +4 -4
  70. package/esm/node_modules/.pnpm/@vitest_pretty-format@4.1.10/node_modules/@vitest/pretty-format/dist/index.mjs.map +1 -0
  71. package/esm/node_modules/{@vitest → .pnpm/@vitest_runner@4.1.10/node_modules/@vitest}/runner/dist/chunk-artifact.mjs +5 -5
  72. package/esm/node_modules/.pnpm/@vitest_runner@4.1.10/node_modules/@vitest/runner/dist/chunk-artifact.mjs.map +1 -0
  73. package/esm/node_modules/{@vitest → .pnpm/@vitest_snapshot@4.1.10/node_modules/@vitest}/snapshot/dist/index.mjs +7 -7
  74. package/esm/node_modules/.pnpm/@vitest_snapshot@4.1.10/node_modules/@vitest/snapshot/dist/index.mjs.map +1 -0
  75. package/esm/node_modules/{@vitest → .pnpm/@vitest_spy@4.1.10/node_modules/@vitest}/spy/dist/index.mjs +1 -1
  76. package/esm/node_modules/.pnpm/@vitest_spy@4.1.10/node_modules/@vitest/spy/dist/index.mjs.map +1 -0
  77. package/esm/node_modules/{@vitest → .pnpm/@vitest_utils@4.1.10/node_modules/@vitest}/utils/dist/chunk-pathe.M-eThtNZ.mjs +1 -1
  78. package/esm/node_modules/.pnpm/@vitest_utils@4.1.10/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.mjs.map +1 -0
  79. package/esm/node_modules/{@vitest → .pnpm/@vitest_utils@4.1.10/node_modules/@vitest}/utils/dist/diff.mjs +4 -4
  80. package/esm/node_modules/.pnpm/@vitest_utils@4.1.10/node_modules/@vitest/utils/dist/diff.mjs.map +1 -0
  81. package/esm/node_modules/{@vitest → .pnpm/@vitest_utils@4.1.10/node_modules/@vitest}/utils/dist/display.mjs +3 -3
  82. package/esm/node_modules/.pnpm/@vitest_utils@4.1.10/node_modules/@vitest/utils/dist/display.mjs.map +1 -0
  83. package/esm/node_modules/{@vitest → .pnpm/@vitest_utils@4.1.10/node_modules/@vitest}/utils/dist/error.mjs +2 -2
  84. package/esm/node_modules/.pnpm/@vitest_utils@4.1.10/node_modules/@vitest/utils/dist/error.mjs.map +1 -0
  85. package/esm/node_modules/{@vitest → .pnpm/@vitest_utils@4.1.10/node_modules/@vitest}/utils/dist/helpers.mjs +1 -1
  86. package/esm/node_modules/.pnpm/@vitest_utils@4.1.10/node_modules/@vitest/utils/dist/helpers.mjs.map +1 -0
  87. package/esm/node_modules/{@vitest → .pnpm/@vitest_utils@4.1.10/node_modules/@vitest}/utils/dist/offset.mjs +1 -1
  88. package/esm/node_modules/.pnpm/@vitest_utils@4.1.10/node_modules/@vitest/utils/dist/offset.mjs.map +1 -0
  89. package/esm/node_modules/{@vitest → .pnpm/@vitest_utils@4.1.10/node_modules/@vitest}/utils/dist/serialize.mjs +1 -1
  90. package/esm/node_modules/.pnpm/@vitest_utils@4.1.10/node_modules/@vitest/utils/dist/serialize.mjs.map +1 -0
  91. package/esm/node_modules/{@vitest → .pnpm/@vitest_utils@4.1.10/node_modules/@vitest}/utils/dist/source-map.mjs +1 -1
  92. package/esm/node_modules/.pnpm/@vitest_utils@4.1.10/node_modules/@vitest/utils/dist/source-map.mjs.map +1 -0
  93. package/esm/node_modules/{@vitest → .pnpm/@vitest_utils@4.1.10/node_modules/@vitest}/utils/dist/timers.mjs +1 -1
  94. package/esm/node_modules/.pnpm/@vitest_utils@4.1.10/node_modules/@vitest/utils/dist/timers.mjs.map +1 -0
  95. package/esm/node_modules/{chai → .pnpm/chai@6.2.2/node_modules/chai}/index.mjs +1 -1
  96. package/esm/node_modules/.pnpm/chai@6.2.2/node_modules/chai/index.mjs.map +1 -0
  97. package/esm/node_modules/{magic-string → .pnpm/magic-string@0.30.21/node_modules/magic-string}/dist/magic-string.es.mjs +3 -3
  98. package/esm/node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/dist/magic-string.es.mjs.map +1 -0
  99. package/esm/node_modules/{tinyrainbow → .pnpm/tinyrainbow@3.1.1/node_modules/tinyrainbow}/dist/index.mjs +1 -1
  100. package/esm/node_modules/.pnpm/tinyrainbow@3.1.1/node_modules/tinyrainbow/dist/index.mjs.map +1 -0
  101. package/esm/node_modules/{vitest → .pnpm/vitest@4.1.10_@opentelemetr_3b60e89b8b51a25e87011ae54ec49250/node_modules/vitest}/dist/chunks/_commonjsHelpers.D26ty3Ew.mjs +1 -1
  102. package/esm/node_modules/.pnpm/vitest@4.1.10_@opentelemetr_3b60e89b8b51a25e87011ae54ec49250/node_modules/vitest/dist/chunks/_commonjsHelpers.D26ty3Ew.mjs.map +1 -0
  103. package/esm/node_modules/{vitest → .pnpm/vitest@4.1.10_@opentelemetr_3b60e89b8b51a25e87011ae54ec49250/node_modules/vitest}/dist/chunks/rpc.MzXet3jl.mjs +1 -1
  104. package/esm/node_modules/.pnpm/vitest@4.1.10_@opentelemetr_3b60e89b8b51a25e87011ae54ec49250/node_modules/vitest/dist/chunks/rpc.MzXet3jl.mjs.map +1 -0
  105. package/esm/node_modules/{vitest → .pnpm/vitest@4.1.10_@opentelemetr_3b60e89b8b51a25e87011ae54ec49250/node_modules/vitest}/dist/chunks/test.DNmyFkvJ.mjs +11 -11
  106. package/esm/node_modules/.pnpm/vitest@4.1.10_@opentelemetr_3b60e89b8b51a25e87011ae54ec49250/node_modules/vitest/dist/chunks/test.DNmyFkvJ.mjs.map +1 -0
  107. package/esm/node_modules/{vitest → .pnpm/vitest@4.1.10_@opentelemetr_3b60e89b8b51a25e87011ae54ec49250/node_modules/vitest}/dist/chunks/utils.BX5Fg8C4.mjs +2 -2
  108. package/esm/node_modules/.pnpm/vitest@4.1.10_@opentelemetr_3b60e89b8b51a25e87011ae54ec49250/node_modules/vitest/dist/chunks/utils.BX5Fg8C4.mjs.map +1 -0
  109. package/esm/object-stream/parse-partial-json.mjs.map +1 -1
  110. package/esm/object-stream/stream-object.d.mts.map +1 -1
  111. package/esm/object-stream/stream-object.mjs.map +1 -1
  112. package/esm/observe/observer-registry.d.mts.map +1 -1
  113. package/esm/orchestrator/as-tool.d.mts.map +1 -1
  114. package/esm/orchestrator/checkpoint.mjs.map +1 -1
  115. package/esm/orchestrator/compaction.mjs.map +1 -1
  116. package/esm/orchestrator/emitter.d.mts.map +1 -1
  117. package/esm/orchestrator/emitter.mjs.map +1 -1
  118. package/esm/orchestrator/execution.d.mts.map +1 -1
  119. package/esm/orchestrator/execution.mjs.map +1 -1
  120. package/esm/orchestrator/memory.mjs.map +1 -1
  121. package/esm/orchestrator/orchestrator-stream.d.mts.map +1 -1
  122. package/esm/orchestrator/orchestrator-stream.mjs.map +1 -1
  123. package/esm/orchestrator/orchestrator.d.mts.map +1 -1
  124. package/esm/orchestrator/orchestrator.mjs.map +1 -1
  125. package/esm/orchestrator/session-lock.d.mts.map +1 -1
  126. package/esm/orchestrator/signature.mjs.map +1 -1
  127. package/esm/planner/dag-scheduler.mjs.map +1 -1
  128. package/esm/planner/plan-prompt.mjs.map +1 -1
  129. package/esm/planner/planner-run.mjs.map +1 -1
  130. package/esm/planner/planner.d.mts.map +1 -1
  131. package/esm/planner/planner.mjs.map +1 -1
  132. package/esm/planner/signature.mjs.map +1 -1
  133. package/esm/planner/snapshot.mjs.map +1 -1
  134. package/esm/prompt/prompt-langfuse-sync.mjs.map +1 -1
  135. package/esm/prompt/prompt-validate.mjs.map +1 -1
  136. package/esm/prompt/prompt.mjs.map +1 -1
  137. package/esm/prompts/prompts-manager.d.mts.map +1 -1
  138. package/esm/prompts/prompts-manager.mjs.map +1 -1
  139. package/esm/prompts/prompts-validate.mjs.map +1 -1
  140. package/esm/rag/chunk/chunk.mjs.map +1 -1
  141. package/esm/rag/chunk/markdown.mjs.map +1 -1
  142. package/esm/rag/chunk/sentence.mjs.map +1 -1
  143. package/esm/rag/hybrid/bm25.mjs.map +1 -1
  144. package/esm/rag/hybrid/hybrid-rank.mjs.map +1 -1
  145. package/esm/rag/hybrid/rrf.mjs.map +1 -1
  146. package/esm/rag/loaders/load-html.mjs.map +1 -1
  147. package/esm/rag/loaders/load-pdf.d.mts.map +1 -1
  148. package/esm/rag/loaders/load-pdf.mjs.map +1 -1
  149. package/esm/rag/loaders/load-text.mjs.map +1 -1
  150. package/esm/rag/rerank/keyword-reranker.mjs.map +1 -1
  151. package/esm/rag/rerank/llm-reranker.mjs.map +1 -1
  152. package/esm/rag/retrieve.mjs.map +1 -1
  153. package/esm/rag/store/cache-vector-store.mjs.map +1 -1
  154. package/esm/rag/store/pg-vector-store.mjs.map +1 -1
  155. package/esm/rag/transforms/multi-query.mjs.map +1 -1
  156. package/esm/security/outbound-policy.mjs.map +1 -1
  157. package/esm/security/private-ip.mjs.map +1 -1
  158. package/esm/security/redact.d.mts.map +1 -1
  159. package/esm/security/redact.mjs.map +1 -1
  160. package/esm/serve/serve.d.mts.map +1 -1
  161. package/esm/serve/serve.mjs.map +1 -1
  162. package/esm/serve/stream-to-sse.d.mts.map +1 -1
  163. package/esm/skills/catalog.mjs.map +1 -1
  164. package/esm/skills/skills.mjs.map +1 -1
  165. package/esm/skills/sources/directory-source.mjs.map +1 -1
  166. package/esm/skills/sources/parse-frontmatter.mjs.map +1 -1
  167. package/esm/skills/sources/url-source.mjs.map +1 -1
  168. package/esm/skills/store/mock-skills-store.mjs.map +1 -1
  169. package/esm/skills/store/procedural-skill-store.mjs.map +1 -1
  170. package/esm/snapshot/memory.d.mts.map +1 -1
  171. package/esm/snapshot/pg.mjs.map +1 -1
  172. package/esm/speech/speech.mjs.map +1 -1
  173. package/esm/supervisor/as-tool.d.mts.map +1 -1
  174. package/esm/supervisor/cancellation.mjs.map +1 -1
  175. package/esm/supervisor/emitter.d.mts.map +1 -1
  176. package/esm/supervisor/emitter.mjs.map +1 -1
  177. package/esm/supervisor/entries.mjs.map +1 -1
  178. package/esm/supervisor/execution.d.mts.map +1 -1
  179. package/esm/supervisor/execution.mjs.map +1 -1
  180. package/esm/supervisor/fan-out.mjs.map +1 -1
  181. package/esm/supervisor/router-factory.mjs.map +1 -1
  182. package/esm/supervisor/router-prompt.mjs.map +1 -1
  183. package/esm/supervisor/signature.mjs.map +1 -1
  184. package/esm/supervisor/snapshot.mjs.map +1 -1
  185. package/esm/supervisor/supervisor-stream.d.mts.map +1 -1
  186. package/esm/supervisor/supervisor-stream.mjs.map +1 -1
  187. package/esm/supervisor/supervisor.d.mts.map +1 -1
  188. package/esm/supervisor/supervisor.mjs.map +1 -1
  189. package/esm/system-prompt/refined-system-prompt.d.mts.map +1 -1
  190. package/esm/system-prompt/refined-system-prompt.mjs.map +1 -1
  191. package/esm/system-prompt/system-prompt.d.mts.map +1 -1
  192. package/esm/system-prompt/system-prompt.mjs.map +1 -1
  193. package/esm/team/team.d.mts.map +1 -1
  194. package/esm/testing/matcher-logic.mjs.map +1 -1
  195. package/esm/testing/matchers.mjs +1 -1
  196. package/esm/testing/register-lazy.d.mts.map +1 -1
  197. package/esm/tool/executable-as-tool.d.mts.map +1 -1
  198. package/esm/tool/tool.d.mts.map +1 -1
  199. package/esm/tool/tool.mjs.map +1 -1
  200. package/esm/transcribe/audio-input.mjs.map +1 -1
  201. package/esm/transcribe/transcribe.mjs.map +1 -1
  202. package/esm/utils/extract-json-payload.mjs.map +1 -1
  203. package/esm/utils/generate-run-id.mjs.map +1 -1
  204. package/esm/utils/prepare-attachment-part.mjs.map +1 -1
  205. package/esm/utils/run-context.d.mts.map +1 -1
  206. package/esm/utils/safe-json-parse.d.mts.map +1 -1
  207. package/esm/vcr/cassette-io.mjs.map +1 -1
  208. package/esm/vcr/hash-request.mjs.map +1 -1
  209. package/esm/vcr/vcr.mjs.map +1 -1
  210. package/esm/workflow/cancellation.mjs.map +1 -1
  211. package/esm/workflow/emitter.mjs.map +1 -1
  212. package/esm/workflow/engine.mjs.map +1 -1
  213. package/esm/workflow/retry.mjs.map +1 -1
  214. package/esm/workflow/router.mjs.map +1 -1
  215. package/esm/workflow/signature.d.mts.map +1 -1
  216. package/esm/workflow/signature.mjs.map +1 -1
  217. package/esm/workflow/snapshot.mjs.map +1 -1
  218. package/esm/workflow/step-runner.mjs.map +1 -1
  219. package/esm/workflow/step.d.mts.map +1 -1
  220. package/esm/workflow/step.mjs.map +1 -1
  221. package/esm/workflow/workflow.d.mts.map +1 -1
  222. package/esm/workflow/workflow.mjs.map +1 -1
  223. package/llms-full.txt +2 -0
  224. package/package.json +7 -4
  225. package/skills/ai-basics/SKILL.md +2 -0
  226. package/cjs/magic-string.es-BoSa5xIt.cjs.map +0 -1
  227. package/cjs/matchers-DnV47KR_.cjs.map +0 -1
  228. package/esm/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map +0 -1
  229. package/esm/node_modules/@vitest/expect/dist/index.mjs.map +0 -1
  230. package/esm/node_modules/@vitest/pretty-format/dist/index.mjs.map +0 -1
  231. package/esm/node_modules/@vitest/runner/dist/chunk-artifact.mjs.map +0 -1
  232. package/esm/node_modules/@vitest/snapshot/dist/index.mjs.map +0 -1
  233. package/esm/node_modules/@vitest/spy/dist/index.mjs.map +0 -1
  234. package/esm/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.mjs.map +0 -1
  235. package/esm/node_modules/@vitest/utils/dist/diff.mjs.map +0 -1
  236. package/esm/node_modules/@vitest/utils/dist/display.mjs.map +0 -1
  237. package/esm/node_modules/@vitest/utils/dist/error.mjs.map +0 -1
  238. package/esm/node_modules/@vitest/utils/dist/helpers.mjs.map +0 -1
  239. package/esm/node_modules/@vitest/utils/dist/offset.mjs.map +0 -1
  240. package/esm/node_modules/@vitest/utils/dist/serialize.mjs.map +0 -1
  241. package/esm/node_modules/@vitest/utils/dist/source-map.mjs.map +0 -1
  242. package/esm/node_modules/@vitest/utils/dist/timers.mjs.map +0 -1
  243. package/esm/node_modules/chai/index.mjs.map +0 -1
  244. package/esm/node_modules/magic-string/dist/magic-string.es.mjs.map +0 -1
  245. package/esm/node_modules/tinyrainbow/dist/index.mjs.map +0 -1
  246. package/esm/node_modules/vitest/dist/chunks/_commonjsHelpers.D26ty3Ew.mjs.map +0 -1
  247. package/esm/node_modules/vitest/dist/chunks/rpc.MzXet3jl.mjs.map +0 -1
  248. package/esm/node_modules/vitest/dist/chunks/test.DNmyFkvJ.mjs.map +0 -1
  249. package/esm/node_modules/vitest/dist/chunks/utils.BX5Fg8C4.mjs.map +0 -1
  250. /package/esm/node_modules/{@vitest → .pnpm/@vitest_runner@4.1.10/node_modules/@vitest}/runner/dist/index.mjs +0 -0
  251. /package/esm/node_modules/{@vitest → .pnpm/@vitest_runner@4.1.10/node_modules/@vitest}/runner/dist/utils.mjs +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"prompt-validate.mjs","names":[],"sources":["../../../../../../../ai/src/prompt/prompt-validate.ts"],"sourcesContent":["import type { AgentContract } from \"../contracts/agent/agent.contract\";\nimport type { ModelContract } from \"../contracts/model.contract\";\nimport { judge } from \"../eval/judge-scorer\";\nimport type { PromptValidationNote, PromptValidationReport } from \"./prompt.type\";\n\n/**\n * Placeholder matcher — kept in lock-step with the matcher\n * `renderPlaceholders` uses (`src/system-prompt/render-placeholders.ts`) so the\n * lint sees the same `{{key}}` / `{{a.b}}` / `{{key|default}}` set the renderer\n * substitutes. Global so every occurrence is collected.\n */\nconst PLACEHOLDER_PATTERN = /\\{\\{\\s*([^{}]+?)\\s*\\}\\}/g;\n\n/** Lower bound below which a prompt is suspiciously terse. */\nconst MIN_REASONABLE_LENGTH = 12;\n\n/** Upper bound above which a prompt is likely bloated / unfocused. */\nconst MAX_REASONABLE_LENGTH = 8000;\n\n/**\n * Severity rank for most-severe-first ordering. Higher sorts earlier.\n */\nconst SEVERITY_RANK: Record<PromptValidationNote[\"severity\"], number> = {\n error: 2,\n warn: 1,\n info: 0,\n};\n\n/**\n * The fixed rubric the LLM-as-judge grades a prompt body against. Surfaced\n * here (not inline) so the static-lint pass and the judge pass document the\n * same quality dimensions.\n */\nexport const PROMPT_JUDGE_RUBRIC = [\n \"Grade this SYSTEM PROMPT on a 0..1 scale for overall quality:\",\n \"- Clarity: is the intent unambiguous and easy to follow?\",\n \"- Role definition: does it clearly state who/what the assistant is?\",\n \"- Output-format specificity: does it say how the answer should be shaped?\",\n \"- No conflicting instructions: are any directives contradictory?\",\n \"Score 1.0 only when all four hold; deduct for each weakness and explain why.\",\n].join(\"\\n\");\n\n/**\n * Heuristic role-line detector — a prompt that never says \"you are …\" /\n * \"act as …\" / \"your role is …\" typically lacks a persona. Case-insensitive.\n */\nconst ROLE_HINT_PATTERN = /\\b(you are|act as|your role is|you're a|you will act)\\b/i;\n\n/**\n * Run the cheap, model-free static lint over a prompt body. Flags:\n * - length out of the reasonable band (too terse / too bloated),\n * - any `{{placeholder}}` that survives (undeclared / unresolved at lint time),\n * - a missing role line.\n *\n * Pure and synchronous — used standalone (no judge model) and merged with the\n * judge findings when a model is available.\n *\n * @param text - The prompt body to lint.\n */\nexport function staticLint(text: string): PromptValidationNote[] {\n const notes: PromptValidationNote[] = [];\n const trimmed = text.trim();\n\n if (trimmed.length < MIN_REASONABLE_LENGTH) {\n notes.push({\n severity: \"warn\",\n message: `Prompt is very short (${trimmed.length} chars) — it may be too vague to steer the model.`,\n suggestion: \"Add an explicit role and at least one concrete instruction.\",\n });\n }\n\n if (trimmed.length > MAX_REASONABLE_LENGTH) {\n notes.push({\n severity: \"warn\",\n message: `Prompt is very long (${trimmed.length} chars) — long prompts dilute focus and inflate cost.`,\n suggestion: \"Split into a tighter persona plus a few focused instructions.\",\n });\n }\n\n const placeholders = collectPlaceholders(text);\n\n for (const placeholder of placeholders) {\n notes.push({\n severity: \"info\",\n message: `Unresolved placeholder \"{{${placeholder}}}\" — confirm it is supplied at resolve time or give it a default (\"{{${placeholder}|...}}\").`,\n });\n }\n\n if (!ROLE_HINT_PATTERN.test(trimmed)) {\n notes.push({\n severity: \"warn\",\n message: \"No role line found — the prompt never states who the assistant is.\",\n suggestion: 'Open with a role, e.g. \"You are a senior support engineer for …\".',\n });\n }\n\n return notes;\n}\n\n/**\n * Collect every distinct placeholder PATH (the part before any `|default`)\n * from a template, in first-seen order. Matches `renderPlaceholders`' own\n * parsing so the lint never disagrees with the renderer.\n */\nfunction collectPlaceholders(template: string): string[] {\n const found: string[] = [];\n const seen = new Set<string>();\n\n for (const match of template.matchAll(PLACEHOLDER_PATTERN)) {\n const path = match[1].split(\"|\")[0].trim();\n\n if (path.length > 0 && !seen.has(path)) {\n seen.add(path);\n found.push(path);\n }\n }\n\n return found;\n}\n\n/**\n * Stable, most-severe-first ordering: `error` before `warn` before `info`,\n * preserving original order within a severity. Returns a fresh array.\n */\nexport function sortNotesBySeverity(\n notes: PromptValidationNote[],\n): PromptValidationNote[] {\n return notes\n .map((note, index) => ({ note, index }))\n .sort((a, b) => {\n const rankDiff = SEVERITY_RANK[b.note.severity] - SEVERITY_RANK[a.note.severity];\n\n return rankDiff !== 0 ? rankDiff : a.index - b.index;\n })\n .map(entry => entry.note);\n}\n\n/**\n * Score the static-lint findings alone, on a `0..1` scale. Starts at `1.0`\n * and deducts per finding by severity, clamped at `0`. Used as the report\n * score when no judge model is available.\n */\nexport function staticScore(notes: PromptValidationNote[]): number {\n let score = 1;\n\n for (const note of notes) {\n if (note.severity === \"error\") {\n score -= 0.4;\n } else if (note.severity === \"warn\") {\n score -= 0.2;\n } else {\n score -= 0.05;\n }\n }\n\n return Math.max(0, Number(score.toFixed(4)));\n}\n\n/**\n * Run the LLM-as-judge pass over `text` using a judge agent built from\n * `model`, REUSING the eval `judge` scorer so there is no second judging\n * path. Returns the judge `score` (`0..1`) and a single derived note carrying\n * its reason (when present). The judge prompt is the prompt-quality rubric;\n * the \"answer to grade\" is the prompt body itself.\n *\n * @param text - The prompt body under evaluation.\n * @param model - The model that powers the judge agent.\n * @param buildJudgeAgent - Factory that wraps a model into a name-bearing judge agent.\n */\nexport async function judgePrompt(\n text: string,\n model: ModelContract,\n buildJudgeAgent: (model: ModelContract) => AgentContract<unknown>,\n): Promise<{ score: number; notes: PromptValidationNote[] }> {\n const judgeAgent = buildJudgeAgent(model);\n const scorer = judge({ agent: judgeAgent, rubric: PROMPT_JUDGE_RUBRIC });\n\n const score = await scorer({\n // The judge scorer only reads `case.input` / `case.expected` / `text` /\n // `output` from the context. We feed the rubric question via `input` and\n // the prompt body as the answer to grade via `text`.\n case: { name: \"prompt-quality\", input: \"Grade the system prompt below.\" },\n text,\n // `result` is unused by the judge scorer's prompt builder; a minimal\n // stand-in keeps the structural contract satisfied without a real run.\n result: { text } as never,\n output: undefined,\n });\n\n const notes: PromptValidationNote[] = [];\n\n if (score.reason) {\n notes.push({\n severity: score.passed ? \"info\" : \"warn\",\n message: `LLM-as-judge: ${score.reason}`,\n });\n }\n\n return { score: score.score, notes };\n}\n\n/**\n * Assemble the final {@link PromptValidationReport} from the static-lint\n * findings and (optionally) the judge findings. Notes are merged and sorted\n * most-severe-first. The score is the static score alone when no judge ran,\n * else the mean of the static score and the judge score.\n */\nexport function buildValidationReport(\n staticNotes: PromptValidationNote[],\n judgeResult?: { score: number; notes: PromptValidationNote[] },\n): PromptValidationReport {\n const allNotes = judgeResult\n ? [...staticNotes, ...judgeResult.notes]\n : staticNotes;\n\n const lintScore = staticScore(staticNotes);\n\n const score = judgeResult\n ? Number(((lintScore + judgeResult.score) / 2).toFixed(4))\n : lintScore;\n\n return {\n score,\n notes: sortNotesBySeverity(allNotes),\n };\n}\n"],"mappings":";;;;;;;;;AAWA,MAAM,sBAAsB;;AAG5B,MAAM,wBAAwB;;AAG9B,MAAM,wBAAwB;;;;AAK9B,MAAM,gBAAkE;CACtE,OAAO;CACP,MAAM;CACN,MAAM;AACR;;;;;;AAOA,MAAa,sBAAsB;CACjC;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;;;;;AAMX,MAA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;AAOA,SAAgB,YAAY,OAAuC;CACjE,IAAI,QAAQ;CAEZ,KAAK,MAAM,QAAQ,OACjB,IAAI,KAAK,aAAa,SACpB,SAAS;MACJ,IAAI,KAAK,aAAa,QAC3B,SAAS;MAET,SAAS;CAIb,OAAO,KAAK,IAAI,GAAG,OAAO,MAAM,QAAQ,CAAC,CAAC,CAAC;AAC7C;;;;;;;;;;;;AAaA,eAAsB,YACpB,MACA,OACA,iBAC2D;CAI3D,MAAM,QAAQ,MAFC,MAAM;EAAE,OADJ,gBAAgB,KACI;EAAG,QAAQ;CAAoB,CAE7C,CAAC,CAAC;EAIzB,MAAM;GAAE,MAAM;GAAkB,OAAO;EAAiC;EACxE;EAGA,QAAQ,EAAE,KAAK;EACf,QAAQ;CACV,CAAC;CAED,MAAM,QAAgC,CAAC;CAEvC,IAAI,MAAM,QACR,MAAM,KAAK;EACT,UAAU,MAAM,SAAS,SAAS;EAClC,SAAS,iBAAiB,MAAM;CAClC,CAAC;CAGH,OAAO;EAAE,OAAO,MAAM;EAAO;CAAM;AACrC;;;;;;;AAQA,SAAgB,sBACd,aACA,aACwB;CACxB,MAAM,WAAW,cACb,CAAC,GAAG,aAAa,GAAG,YAAY,KAAK,IACrC;CAEJ,MAAM,YAAY,YAAY,WAAW;CAMzC,OAAO;EACL,OALY,cACV,SAAS,YAAY,YAAY,SAAS,EAAC,CAAE,QAAQ,CAAC,CAAC,IACvD;EAIF,OAAO,oBAAoB,QAAQ;CACrC;AACF"}
1
+ {"version":3,"file":"prompt-validate.mjs","names":[],"sources":["../../../../../../../ai/src/prompt/prompt-validate.ts"],"sourcesContent":["import type { AgentContract } from \"../contracts/agent/agent.contract\";\nimport type { ModelContract } from \"../contracts/model.contract\";\nimport { judge } from \"../eval/judge-scorer\";\nimport type { PromptValidationNote, PromptValidationReport } from \"./prompt.type\";\n\n/**\n * Placeholder matcher — kept in lock-step with the matcher\n * `renderPlaceholders` uses (`src/system-prompt/render-placeholders.ts`) so the\n * lint sees the same `{{key}}` / `{{a.b}}` / `{{key|default}}` set the renderer\n * substitutes. Global so every occurrence is collected.\n */\nconst PLACEHOLDER_PATTERN = /\\{\\{\\s*([^{}]+?)\\s*\\}\\}/g;\n\n/** Lower bound below which a prompt is suspiciously terse. */\nconst MIN_REASONABLE_LENGTH = 12;\n\n/** Upper bound above which a prompt is likely bloated / unfocused. */\nconst MAX_REASONABLE_LENGTH = 8000;\n\n/**\n * Severity rank for most-severe-first ordering. Higher sorts earlier.\n */\nconst SEVERITY_RANK: Record<PromptValidationNote[\"severity\"], number> = {\n error: 2,\n warn: 1,\n info: 0,\n};\n\n/**\n * The fixed rubric the LLM-as-judge grades a prompt body against. Surfaced\n * here (not inline) so the static-lint pass and the judge pass document the\n * same quality dimensions.\n */\nexport const PROMPT_JUDGE_RUBRIC = [\n \"Grade this SYSTEM PROMPT on a 0..1 scale for overall quality:\",\n \"- Clarity: is the intent unambiguous and easy to follow?\",\n \"- Role definition: does it clearly state who/what the assistant is?\",\n \"- Output-format specificity: does it say how the answer should be shaped?\",\n \"- No conflicting instructions: are any directives contradictory?\",\n \"Score 1.0 only when all four hold; deduct for each weakness and explain why.\",\n].join(\"\\n\");\n\n/**\n * Heuristic role-line detector — a prompt that never says \"you are …\" /\n * \"act as …\" / \"your role is …\" typically lacks a persona. Case-insensitive.\n */\nconst ROLE_HINT_PATTERN = /\\b(you are|act as|your role is|you're a|you will act)\\b/i;\n\n/**\n * Run the cheap, model-free static lint over a prompt body. Flags:\n * - length out of the reasonable band (too terse / too bloated),\n * - any `{{placeholder}}` that survives (undeclared / unresolved at lint time),\n * - a missing role line.\n *\n * Pure and synchronous — used standalone (no judge model) and merged with the\n * judge findings when a model is available.\n *\n * @param text - The prompt body to lint.\n */\nexport function staticLint(text: string): PromptValidationNote[] {\n const notes: PromptValidationNote[] = [];\n const trimmed = text.trim();\n\n if (trimmed.length < MIN_REASONABLE_LENGTH) {\n notes.push({\n severity: \"warn\",\n message: `Prompt is very short (${trimmed.length} chars) — it may be too vague to steer the model.`,\n suggestion: \"Add an explicit role and at least one concrete instruction.\",\n });\n }\n\n if (trimmed.length > MAX_REASONABLE_LENGTH) {\n notes.push({\n severity: \"warn\",\n message: `Prompt is very long (${trimmed.length} chars) — long prompts dilute focus and inflate cost.`,\n suggestion: \"Split into a tighter persona plus a few focused instructions.\",\n });\n }\n\n const placeholders = collectPlaceholders(text);\n\n for (const placeholder of placeholders) {\n notes.push({\n severity: \"info\",\n message: `Unresolved placeholder \"{{${placeholder}}}\" — confirm it is supplied at resolve time or give it a default (\"{{${placeholder}|...}}\").`,\n });\n }\n\n if (!ROLE_HINT_PATTERN.test(trimmed)) {\n notes.push({\n severity: \"warn\",\n message: \"No role line found — the prompt never states who the assistant is.\",\n suggestion: 'Open with a role, e.g. \"You are a senior support engineer for …\".',\n });\n }\n\n return notes;\n}\n\n/**\n * Collect every distinct placeholder PATH (the part before any `|default`)\n * from a template, in first-seen order. Matches `renderPlaceholders`' own\n * parsing so the lint never disagrees with the renderer.\n */\nfunction collectPlaceholders(template: string): string[] {\n const found: string[] = [];\n const seen = new Set<string>();\n\n for (const match of template.matchAll(PLACEHOLDER_PATTERN)) {\n const path = match[1].split(\"|\")[0].trim();\n\n if (path.length > 0 && !seen.has(path)) {\n seen.add(path);\n found.push(path);\n }\n }\n\n return found;\n}\n\n/**\n * Stable, most-severe-first ordering: `error` before `warn` before `info`,\n * preserving original order within a severity. Returns a fresh array.\n */\nexport function sortNotesBySeverity(\n notes: PromptValidationNote[],\n): PromptValidationNote[] {\n return notes\n .map((note, index) => ({ note, index }))\n .sort((a, b) => {\n const rankDiff = SEVERITY_RANK[b.note.severity] - SEVERITY_RANK[a.note.severity];\n\n return rankDiff !== 0 ? rankDiff : a.index - b.index;\n })\n .map(entry => entry.note);\n}\n\n/**\n * Score the static-lint findings alone, on a `0..1` scale. Starts at `1.0`\n * and deducts per finding by severity, clamped at `0`. Used as the report\n * score when no judge model is available.\n */\nexport function staticScore(notes: PromptValidationNote[]): number {\n let score = 1;\n\n for (const note of notes) {\n if (note.severity === \"error\") {\n score -= 0.4;\n } else if (note.severity === \"warn\") {\n score -= 0.2;\n } else {\n score -= 0.05;\n }\n }\n\n return Math.max(0, Number(score.toFixed(4)));\n}\n\n/**\n * Run the LLM-as-judge pass over `text` using a judge agent built from\n * `model`, REUSING the eval `judge` scorer so there is no second judging\n * path. Returns the judge `score` (`0..1`) and a single derived note carrying\n * its reason (when present). The judge prompt is the prompt-quality rubric;\n * the \"answer to grade\" is the prompt body itself.\n *\n * @param text - The prompt body under evaluation.\n * @param model - The model that powers the judge agent.\n * @param buildJudgeAgent - Factory that wraps a model into a name-bearing judge agent.\n */\nexport async function judgePrompt(\n text: string,\n model: ModelContract,\n buildJudgeAgent: (model: ModelContract) => AgentContract<unknown>,\n): Promise<{ score: number; notes: PromptValidationNote[] }> {\n const judgeAgent = buildJudgeAgent(model);\n const scorer = judge({ agent: judgeAgent, rubric: PROMPT_JUDGE_RUBRIC });\n\n const score = await scorer({\n // The judge scorer only reads `case.input` / `case.expected` / `text` /\n // `output` from the context. We feed the rubric question via `input` and\n // the prompt body as the answer to grade via `text`.\n case: { name: \"prompt-quality\", input: \"Grade the system prompt below.\" },\n text,\n // `result` is unused by the judge scorer's prompt builder; a minimal\n // stand-in keeps the structural contract satisfied without a real run.\n result: { text } as never,\n output: undefined,\n });\n\n const notes: PromptValidationNote[] = [];\n\n if (score.reason) {\n notes.push({\n severity: score.passed ? \"info\" : \"warn\",\n message: `LLM-as-judge: ${score.reason}`,\n });\n }\n\n return { score: score.score, notes };\n}\n\n/**\n * Assemble the final {@link PromptValidationReport} from the static-lint\n * findings and (optionally) the judge findings. Notes are merged and sorted\n * most-severe-first. The score is the static score alone when no judge ran,\n * else the mean of the static score and the judge score.\n */\nexport function buildValidationReport(\n staticNotes: PromptValidationNote[],\n judgeResult?: { score: number; notes: PromptValidationNote[] },\n): PromptValidationReport {\n const allNotes = judgeResult\n ? [...staticNotes, ...judgeResult.notes]\n : staticNotes;\n\n const lintScore = staticScore(staticNotes);\n\n const score = judgeResult\n ? Number(((lintScore + judgeResult.score) / 2).toFixed(4))\n : lintScore;\n\n return {\n score,\n notes: sortNotesBySeverity(allNotes),\n };\n}\n"],"mappings":";;;;;;;;;AAWA,MAAM,sBAAsB;;AAG5B,MAAM,wBAAwB;;AAG9B,MAAM,wBAAwB;;;;AAK9B,MAAM,gBAAkE;CACtE,OAAO;CACP,MAAM;CACN,MAAM;AACR;;;;;;AAOA,MAAa,sBAAsB;CACjC;CACA;CACA;CACA;CACA;CACA;AACF,EAAE,KAAK,IAAI;;;;;AAMX,MAAM,oBAAoB;;;;;;;;;;;;AAa1B,SAAgB,WAAW,MAAsC;CAC/D,MAAM,QAAgC,CAAC;CACvC,MAAM,UAAU,KAAK,KAAK;CAE1B,IAAI,QAAQ,SAAS,uBACnB,MAAM,KAAK;EACT,UAAU;EACV,SAAS,yBAAyB,QAAQ,OAAO;EACjD,YAAY;CACd,CAAC;CAGH,IAAI,QAAQ,SAAS,uBACnB,MAAM,KAAK;EACT,UAAU;EACV,SAAS,wBAAwB,QAAQ,OAAO;EAChD,YAAY;CACd,CAAC;CAGH,MAAM,eAAe,oBAAoB,IAAI;CAE7C,KAAK,MAAM,eAAe,cACxB,MAAM,KAAK;EACT,UAAU;EACV,SAAS,6BAA6B,YAAY,wEAAwE,YAAY;CACxI,CAAC;CAGH,IAAI,CAAC,kBAAkB,KAAK,OAAO,GACjC,MAAM,KAAK;EACT,UAAU;EACV,SAAS;EACT,YAAY;CACd,CAAC;CAGH,OAAO;AACT;;;;;;AAOA,SAAS,oBAAoB,UAA4B;CACvD,MAAM,QAAkB,CAAC;CACzB,MAAM,uBAAO,IAAI,IAAY;CAE7B,KAAK,MAAM,SAAS,SAAS,SAAS,mBAAmB,GAAG;EAC1D,MAAM,OAAO,MAAM,GAAG,MAAM,GAAG,EAAE,GAAG,KAAK;EAEzC,IAAI,KAAK,SAAS,KAAK,CAAC,KAAK,IAAI,IAAI,GAAG;GACtC,KA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AQ;CACrC;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"prompt.mjs","names":["createPromptsManager"],"sources":["../../../../../../../ai/src/prompt/prompt.ts"],"sourcesContent":["import type { SystemPromptContract } from \"../contracts/system-prompt.contract\";\nimport {\n defaultPromptsManager,\n prompts as createPromptsManager,\n} from \"../prompts/prompts-manager\";\nimport type { PromptsManagerContract } from \"../prompts/prompts-manager.contract\";\nimport { Instruction } from \"../system-prompt/instruction\";\nimport { renderPlaceholders } from \"../system-prompt/render-placeholders\";\nimport { SystemPrompt } from \"../system-prompt/system-prompt\";\nimport { PromptNotFoundError, PromptValidationError } from \"./errors\";\nimport {\n syncLangfusePrompts,\n warmLangfuse,\n} from \"./prompt-langfuse-sync\";\nimport {\n buildValidationReport,\n judgePrompt,\n staticLint,\n} from \"./prompt-validate\";\nimport { agent } from \"../agent/agent\";\nimport type { AgentContract } from \"../contracts/agent/agent.contract\";\nimport type { ModelContract } from \"../contracts/model.contract\";\nimport type {\n PromptEntry,\n PromptRegistryContract,\n PromptRegistryOptions,\n PromptResolveOptions,\n PromptValidateOptions,\n PromptValidationReport,\n PromptVersion,\n ResolvedPrompt,\n} from \"./prompt.type\";\n\n/**\n * Build the one-shot judge agent the `validate()` LLM-as-judge pass runs.\n * Name-bearing (the eval `judge` scorer requires a usable agent) and seeded\n * with a strict-JSON instruction so its verdict parses even without an output\n * schema. Kept module-private so the registry's only model dependency is the\n * `agent()` factory.\n */\nfunction buildJudgeAgent(model: ModelContract): AgentContract<unknown> {\n return agent({\n name: \"prompt-quality-judge\",\n model,\n systemPrompt:\n \"You are a strict prompt-quality grader. Respond with JSON only: \" +\n '{ \"score\": <0..1>, \"passed\": <true|false>, \"reason\": \"<short explanation>\" }.',\n });\n}\n\n/**\n * Build the `SystemPromptContract` a single {@link PromptVersion} maps to: its\n * `template` becomes one instruction block, and its `required` keys ride along\n * as `meta.required` so the unified manager (and `validate`) can see them.\n *\n * Deliberately ANONYMOUS (no `meta.name`) so the `SystemPrompt` constructor\n * never auto-registers this version into the process-wide `ai.prompts` default\n * manager — each `prompt()` registry owns its OWN isolated\n * {@link PromptsManagerContract}, the single storage shape behind this facade.\n */\nfunction versionToContract(version: PromptVersion): SystemPromptContract {\n return new SystemPrompt([new Instruction(version.template)], {\n ...(version.required ? { required: version.required } : {}),\n });\n}\n\n/**\n * Legacy `PromptRegistryContract` — now a THIN FACADE over the unified\n * {@link PromptsManagerContract} (`ai.prompts`).\n *\n * **Role.** The store behind `ai.prompt(...)`. Historically it held a private\n * `Map<string, PromptVersion[]>`; it now delegates ALL storage to a private,\n * per-instance {@link PromptsManagerContract}, so there is exactly ONE storage\n * shape across the whole prompt surface: a `SystemPromptContract` keyed by\n * `name@version`. A version's raw `template` string maps to a single\n * instruction block and its `required` keys to `meta.required`.\n *\n * **Responsibility.**\n * - Owns: the legacy method surface (`register` / `add` / `versions` /\n * `resolve` / `validate` / `sync`) and the back-compat behaviors — duplicate\n * version rejection, required-key assertion on `resolve()`, the\n * `{ score, notes }` validation report shape, and the optional Langfuse sync.\n * - Does NOT own: the actual storage (delegated to the internal manager),\n * placeholder rendering (delegated to `renderPlaceholders`), or the unified\n * validation primitives (delegated to `prompt-validate`).\n *\n * Each `prompt(options)` call builds its own isolated manager — so parallel\n * test suites and multi-tenant apps never share mutable global prompt state,\n * exactly as before the unification.\n *\n * Users construct via the `prompt()` factory — `new PromptRegistry()` is not\n * the public API.\n */\nclass PromptRegistry implements PromptRegistryContract {\n /** The single backing store — one isolated unified manager per registry. */\n private readonly manager: PromptsManagerContract;\n\n /** Per-name version metadata mirror, kept so `versions()` returns the rich\n * {@link PromptVersion} shape (template + required + meta) the legacy API\n * promised — the manager itself only stores the flattened contract. */\n private readonly versionMeta = new Map<string, PromptVersion[]>();\n\n public constructor(private readonly options: PromptRegistryOptions = {}) {\n this.manager = createPromptsManager();\n\n for (const entry of options.prompts ?? []) {\n this.register(entry);\n }\n\n if (options.langfuse) {\n warmLangfuse(options.langfuse);\n }\n }\n\n /**\n * Register a whole entry. Merges onto an existing name's history; a\n * duplicate version label throws {@link PromptValidationError}.\n */\n public register(entry: PromptEntry): PromptRegistryContract {\n for (const version of entry.versions) {\n this.add(entry.name, version);\n }\n\n // An entry with an empty version list still creates the name so `has`\n // / `list` reflect it.\n if (!this.versionMeta.has(entry.name)) {\n this.versionMeta.set(entry.name, []);\n }\n\n return this;\n }\n\n /**\n * Add a new version to a name (creating it when absent). A duplicate\n * version label throws {@link PromptValidationError} — never a silent\n * overwrite.\n */\n public add(name: string, version: PromptVersion): PromptRegistryContract {\n const mirror = this.versionMeta.get(name) ?? [];\n\n if (mirror.some(existing => existing.version === version.version)) {\n throw new PromptValidationError(\n `Prompt \"${name}\" already has a version labeled \"${version.version}\".`,\n { context: { name, version: version.version } },\n );\n }\n\n this.manager.register(versionToContract(version), {\n name,\n version: version.version,\n });\n\n this.versionMeta.set(name, [...mirror, version]);\n\n return this;\n }\n\n /** Whether a name is registered. */\n public has(name: string): boolean {\n return this.versionMeta.has(name);\n }\n\n /** Every registered prompt name, in registration order. */\n public list(): string[] {\n return [...this.versionMeta.keys()];\n }\n\n /** Versions registered for a name, latest last. Throws on an unknown name. */\n public versions(name: string): PromptVersion[] {\n const mirror = this.versionMeta.get(name);\n\n if (!mirror) {\n throw new PromptNotFoundError(name);\n }\n\n return [...mirror];\n }\n\n /**\n * Resolve + render. Picks the requested or latest version, validates the\n * version's `required` keys against the merged placeholders, then renders by\n * delegating to the shared `renderPlaceholders` over the contract's text.\n */\n public resolve(name: string, options: PromptResolveOptions = {}): ResolvedPrompt {\n const picked = this.pickVersion(name, options.version);\n const placeholders = options.placeholders ?? {};\n\n this.assertRequired(name, picked, placeholders);\n\n // Render the RAW template (placeholders intact) against the merged values —\n // resolving the contract first would bake inline `{{key|default}}` defaults\n // in and shadow an explicitly-supplied value. The stored block text is the\n // single source of the un-rendered template.\n const contract = this.manager.get(name, picked.version);\n const template = contract.blocks[0]?.text ?? picked.template;\n const text = renderPlaceholders(template, placeholders);\n\n return {\n name,\n version: picked.version,\n text,\n toSystemPrompt: () => new SystemPrompt([new Instruction(text)]),\n };\n }\n\n /**\n * Quality-check a raw prompt body or a registered prompt (by name). Backed by\n * the unified deterministic validate primitives plus the LLM-as-judge pass,\n * but returns the legacy `{ score, notes }` report shape so existing callers\n * keep working.\n *\n * Always runs the static lint; runs the LLM-as-judge pass too when a model is\n * resolvable. Never throws when no judge model is available.\n */\n public async validate(\n textOrName: string,\n options: PromptValidateOptions = {},\n ): Promise<PromptValidationReport> {\n const text = this.resolveValidationText(textOrName, options.version);\n const staticNotes = staticLint(text);\n\n const model = options.model ?? this.options.judgeModel;\n\n if (!model) {\n return buildValidationReport(staticNotes);\n }\n\n const judgeResult = await judgePrompt(text, model, buildJudgeAgent);\n\n return buildValidationReport(staticNotes, judgeResult);\n }\n\n /**\n * Synchronize named prompts with Langfuse-prompts. No-op (resolves) when no\n * `langfuse` option was configured. The resolved (rendered) body + the\n * `name@version` label are what is pushed/pulled.\n */\n public async sync(): Promise<void> {\n if (!this.options.langfuse) {\n return;\n }\n\n await syncLangfusePrompts(\n this.options.langfuse,\n this.list(),\n this.snapshotEntries(),\n entry => this.register(entry),\n );\n }\n\n /**\n * Pick the requested (or latest) {@link PromptVersion} for a name from the\n * mirror, throwing {@link PromptNotFoundError} on an unknown name or version.\n */\n private pickVersion(name: string, version?: string): PromptVersion {\n const mirror = this.versionMeta.get(name);\n\n if (!mirror || mirror.length === 0) {\n throw new PromptNotFoundError(name);\n }\n\n const picked = version\n ? mirror.find(candidate => candidate.version === version)\n : mirror[mirror.length - 1];\n\n if (!picked) {\n throw new PromptNotFoundError(name, {\n context: { name, version },\n });\n }\n\n return picked;\n }\n\n /**\n * Resolve the text `validate()` should grade: a registered name yields its\n * picked version's raw `template`; anything else is treated as the raw body.\n */\n private resolveValidationText(textOrName: string, version?: string): string {\n const mirror = this.versionMeta.get(textOrName);\n\n if (!mirror || mirror.length === 0) {\n return textOrName;\n }\n\n const picked = version\n ? mirror.find(candidate => candidate.version === version)\n : mirror[mirror.length - 1];\n\n return picked ? picked.template : textOrName;\n }\n\n /**\n * Throw {@link PromptValidationError} listing every `required` key absent\n * from the merged placeholders. A no-op when the version declares none.\n */\n private assertRequired(\n name: string,\n version: PromptVersion,\n placeholders: Record<string, unknown>,\n ): void {\n if (!version.required || version.required.length === 0) {\n return;\n }\n\n const missing = version.required.filter(\n key => placeholders[key] === undefined || placeholders[key] === null || placeholders[key] === \"\",\n );\n\n if (missing.length > 0) {\n throw new PromptValidationError(\n `Prompt \"${name}\" version \"${version.version}\" is missing required placeholder${\n missing.length > 1 ? \"s\" : \"\"\n }: ${missing.join(\", \")}.`,\n { context: { name, version: version.version, missing } },\n );\n }\n }\n\n /** Snapshot the catalog as `PromptEntry[]` (for the Langfuse push path). */\n private snapshotEntries(): PromptEntry[] {\n return [...this.versionMeta.entries()].map(([name, versions]) => ({\n name,\n versions: [...versions],\n }));\n }\n}\n\n/**\n * Create a versioned, typed prompt registry — a thin facade over the unified\n * `ai.prompts` manager.\n *\n * **Role.** Public factory for {@link PromptRegistryContract}. Keeps\n * user-facing code free of `new` and consistent with `ai.memory`,\n * `ai.orchestrator`, `ai.batch` (all return instances). Each call returns a\n * fresh, isolated registry backed by its own unified manager, so parallel test\n * suites and multi-tenant apps never share mutable global prompt state.\n *\n * @param options - Seed entries, an optional default judge model, and an\n * optional Langfuse sync.\n *\n * @example\n * const prompts = prompt({\n * prompts: [\n * {\n * name: \"support-agent\",\n * versions: [\n * { version: \"1\", template: \"You are support for {{product}}. Reply in {{language|English}}.\" },\n * { version: \"2\", template: \"You are senior support for {{product}}.\", required: [\"product\"] },\n * ],\n * },\n * ],\n * });\n *\n * const resolved = prompts.resolve(\"support-agent\", { placeholders: { product: \"Warlock\" } });\n * const agent = ai.agent({ model, systemPrompt: resolved.toSystemPrompt() });\n * // resolved.version === \"2\"; a missing `product` would throw PromptValidationError.\n *\n * @example\n * // Resolve a globally-registered prompt by name from `ai.prompts`.\n * ai.systemPrompt(\"You are support.\", { name: \"support\" });\n * const sp = ai.prompt(\"support\"); // → the registered SystemPromptContract\n */\nfunction promptFactory(\n name: string,\n versionOrTag?: string,\n): SystemPromptContract;\nfunction promptFactory(options?: PromptRegistryOptions): PromptRegistryContract;\nfunction promptFactory(\n first?: string | PromptRegistryOptions,\n versionOrTag?: string,\n): SystemPromptContract | PromptRegistryContract {\n // String form: resolve a globally-registered prompt from the process-wide\n // `ai.prompts` manager (the single unified registry). This is the thin\n // facade's read path onto the shared store.\n if (typeof first === \"string\") {\n return defaultPromptsManager().get(first, versionOrTag);\n }\n\n // Options form: build an isolated registry backed by its own unified manager.\n return new PromptRegistry(first);\n}\n\n/**\n * Create a versioned prompt registry, OR resolve a globally-registered prompt\n * by name from `ai.prompts`.\n *\n * - `prompt(options?)` → a fresh, isolated {@link PromptRegistryContract}.\n * - `prompt(name, versionOrTag?)` → the `SystemPromptContract` registered under\n * `name` in the process-wide `ai.prompts` manager (latest version by default,\n * or a specific version / pinned tag).\n */\nexport const prompt: typeof promptFactory = promptFactory;\n"],"mappings":";;;;;;;;;;;;;;;;;AAwCA,SAAS,gBAAgB,OAA8C;CACrE,OAAO,MAAM;EACX,MAAM;EACN;EACA,cACE;CAEJ,CAAC;AACH;;;;;;;;;;;AAYA,SAAS,kBAAkB,SAA8C;CACvE,OAAO,IAAI,aAAa,CAAC,IAAI,YAAY,QAAQ,QAAQ,CAAC,GAAG,EAC3D,GAAI,QAAQ,WAAW,EAAE,UAAU,QAAQ,SAAS,IAAI,CAAC,EAC3D,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,IAAM,iBAAN,MAAuD;CASrD,AAAO,YAAY,AAAiB,UAAiC,CAAC,GAAG;EAArC;qCAFL,IAAI,IAA6B;EAG9D,KAAK,UAAUA,QAAqB;EAEpC,KAAK,MAAM,SAAS,QAAQ,WAAW,CAAC,GACtC,KAAK,SAAS,KAAK;EAGrB,IAAI,QAAQ,UACV,aAAa,QAAQ,QAAQ;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,cACM;EACN,IAAI,CAAC,QAAQ,YAAY,QAAQ,SAAS,WAAW,GACnD;EAGF,MAAM,UAAU,QAAQ,SAAS,QAC/B,QAAO,aAAa,SAAS,UAAa,aAAa,SAAS,QAAQ,aAAa,SAAS,EAChG;EAEA,IAAI,QAAQ,SAAS,GACnB,MAAM,IAAI,sBACR,WAAW,KAAK,aAAa,QAAQ,QAAQ,mCAC3C,QAAQ,SAAS,IAAI,MAAM,GAC5B,IAAI,QAAQ,KAAK,IAAI,EAAE,IACxB,EAAE,SAAS;GAAE;GAAM,SAAS,QAAQ;GAAS;EAAQ,EAAE,CACzD;CAEJ;;CAGA,AAAQ,kBAAiC;EACvC,OAAO,CAAC,GAAG,KAAK,YAAY,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,eAAe;GAChE;GACA,UAAU,CAAC,GAAG,QAAQ;EACxB,EAAE;CACJ;AACF;AA0CA,SAAS,cACP,OACA,cAC+C;CAI/C,IAAI,OAAO,UAAU,UACnB,OAAO,sBAAsB,CAAC,CAAC,IAAI,OAAO,YAAY;CAIxD,OAAO,IAAI,eAAe,KAAK;AACjC;;;;;;;;;;AAWA,MAAa,SAA+B"}
1
+ {"version":3,"file":"prompt.mjs","names":["createPromptsManager"],"sources":["../../../../../../../ai/src/prompt/prompt.ts"],"sourcesContent":["import type { SystemPromptContract } from \"../contracts/system-prompt.contract\";\nimport {\n defaultPromptsManager,\n prompts as createPromptsManager,\n} from \"../prompts/prompts-manager\";\nimport type { PromptsManagerContract } from \"../prompts/prompts-manager.contract\";\nimport { Instruction } from \"../system-prompt/instruction\";\nimport { renderPlaceholders } from \"../system-prompt/render-placeholders\";\nimport { SystemPrompt } from \"../system-prompt/system-prompt\";\nimport { PromptNotFoundError, PromptValidationError } from \"./errors\";\nimport {\n syncLangfusePrompts,\n warmLangfuse,\n} from \"./prompt-langfuse-sync\";\nimport {\n buildValidationReport,\n judgePrompt,\n staticLint,\n} from \"./prompt-validate\";\nimport { agent } from \"../agent/agent\";\nimport type { AgentContract } from \"../contracts/agent/agent.contract\";\nimport type { ModelContract } from \"../contracts/model.contract\";\nimport type {\n PromptEntry,\n PromptRegistryContract,\n PromptRegistryOptions,\n PromptResolveOptions,\n PromptValidateOptions,\n PromptValidationReport,\n PromptVersion,\n ResolvedPrompt,\n} from \"./prompt.type\";\n\n/**\n * Build the one-shot judge agent the `validate()` LLM-as-judge pass runs.\n * Name-bearing (the eval `judge` scorer requires a usable agent) and seeded\n * with a strict-JSON instruction so its verdict parses even without an output\n * schema. Kept module-private so the registry's only model dependency is the\n * `agent()` factory.\n */\nfunction buildJudgeAgent(model: ModelContract): AgentContract<unknown> {\n return agent({\n name: \"prompt-quality-judge\",\n model,\n systemPrompt:\n \"You are a strict prompt-quality grader. Respond with JSON only: \" +\n '{ \"score\": <0..1>, \"passed\": <true|false>, \"reason\": \"<short explanation>\" }.',\n });\n}\n\n/**\n * Build the `SystemPromptContract` a single {@link PromptVersion} maps to: its\n * `template` becomes one instruction block, and its `required` keys ride along\n * as `meta.required` so the unified manager (and `validate`) can see them.\n *\n * Deliberately ANONYMOUS (no `meta.name`) so the `SystemPrompt` constructor\n * never auto-registers this version into the process-wide `ai.prompts` default\n * manager — each `prompt()` registry owns its OWN isolated\n * {@link PromptsManagerContract}, the single storage shape behind this facade.\n */\nfunction versionToContract(version: PromptVersion): SystemPromptContract {\n return new SystemPrompt([new Instruction(version.template)], {\n ...(version.required ? { required: version.required } : {}),\n });\n}\n\n/**\n * Legacy `PromptRegistryContract` — now a THIN FACADE over the unified\n * {@link PromptsManagerContract} (`ai.prompts`).\n *\n * **Role.** The store behind `ai.prompt(...)`. Historically it held a private\n * `Map<string, PromptVersion[]>`; it now delegates ALL storage to a private,\n * per-instance {@link PromptsManagerContract}, so there is exactly ONE storage\n * shape across the whole prompt surface: a `SystemPromptContract` keyed by\n * `name@version`. A version's raw `template` string maps to a single\n * instruction block and its `required` keys to `meta.required`.\n *\n * **Responsibility.**\n * - Owns: the legacy method surface (`register` / `add` / `versions` /\n * `resolve` / `validate` / `sync`) and the back-compat behaviors — duplicate\n * version rejection, required-key assertion on `resolve()`, the\n * `{ score, notes }` validation report shape, and the optional Langfuse sync.\n * - Does NOT own: the actual storage (delegated to the internal manager),\n * placeholder rendering (delegated to `renderPlaceholders`), or the unified\n * validation primitives (delegated to `prompt-validate`).\n *\n * Each `prompt(options)` call builds its own isolated manager — so parallel\n * test suites and multi-tenant apps never share mutable global prompt state,\n * exactly as before the unification.\n *\n * Users construct via the `prompt()` factory — `new PromptRegistry()` is not\n * the public API.\n */\nclass PromptRegistry implements PromptRegistryContract {\n /** The single backing store — one isolated unified manager per registry. */\n private readonly manager: PromptsManagerContract;\n\n /** Per-name version metadata mirror, kept so `versions()` returns the rich\n * {@link PromptVersion} shape (template + required + meta) the legacy API\n * promised — the manager itself only stores the flattened contract. */\n private readonly versionMeta = new Map<string, PromptVersion[]>();\n\n public constructor(private readonly options: PromptRegistryOptions = {}) {\n this.manager = createPromptsManager();\n\n for (const entry of options.prompts ?? []) {\n this.register(entry);\n }\n\n if (options.langfuse) {\n warmLangfuse(options.langfuse);\n }\n }\n\n /**\n * Register a whole entry. Merges onto an existing name's history; a\n * duplicate version label throws {@link PromptValidationError}.\n */\n public register(entry: PromptEntry): PromptRegistryContract {\n for (const version of entry.versions) {\n this.add(entry.name, version);\n }\n\n // An entry with an empty version list still creates the name so `has`\n // / `list` reflect it.\n if (!this.versionMeta.has(entry.name)) {\n this.versionMeta.set(entry.name, []);\n }\n\n return this;\n }\n\n /**\n * Add a new version to a name (creating it when absent). A duplicate\n * version label throws {@link PromptValidationError} — never a silent\n * overwrite.\n */\n public add(name: string, version: PromptVersion): PromptRegistryContract {\n const mirror = this.versionMeta.get(name) ?? [];\n\n if (mirror.some(existing => existing.version === version.version)) {\n throw new PromptValidationError(\n `Prompt \"${name}\" already has a version labeled \"${version.version}\".`,\n { context: { name, version: version.version } },\n );\n }\n\n this.manager.register(versionToContract(version), {\n name,\n version: version.version,\n });\n\n this.versionMeta.set(name, [...mirror, version]);\n\n return this;\n }\n\n /** Whether a name is registered. */\n public has(name: string): boolean {\n return this.versionMeta.has(name);\n }\n\n /** Every registered prompt name, in registration order. */\n public list(): string[] {\n return [...this.versionMeta.keys()];\n }\n\n /** Versions registered for a name, latest last. Throws on an unknown name. */\n public versions(name: string): PromptVersion[] {\n const mirror = this.versionMeta.get(name);\n\n if (!mirror) {\n throw new PromptNotFoundError(name);\n }\n\n return [...mirror];\n }\n\n /**\n * Resolve + render. Picks the requested or latest version, validates the\n * version's `required` keys against the merged placeholders, then renders by\n * delegating to the shared `renderPlaceholders` over the contract's text.\n */\n public resolve(name: string, options: PromptResolveOptions = {}): ResolvedPrompt {\n const picked = this.pickVersion(name, options.version);\n const placeholders = options.placeholders ?? {};\n\n this.assertRequired(name, picked, placeholders);\n\n // Render the RAW template (placeholders intact) against the merged values —\n // resolving the contract first would bake inline `{{key|default}}` defaults\n // in and shadow an explicitly-supplied value. The stored block text is the\n // single source of the un-rendered template.\n const contract = this.manager.get(name, picked.version);\n const template = contract.blocks[0]?.text ?? picked.template;\n const text = renderPlaceholders(template, placeholders);\n\n return {\n name,\n version: picked.version,\n text,\n toSystemPrompt: () => new SystemPrompt([new Instruction(text)]),\n };\n }\n\n /**\n * Quality-check a raw prompt body or a registered prompt (by name). Backed by\n * the unified deterministic validate primitives plus the LLM-as-judge pass,\n * but returns the legacy `{ score, notes }` report shape so existing callers\n * keep working.\n *\n * Always runs the static lint; runs the LLM-as-judge pass too when a model is\n * resolvable. Never throws when no judge model is available.\n */\n public async validate(\n textOrName: string,\n options: PromptValidateOptions = {},\n ): Promise<PromptValidationReport> {\n const text = this.resolveValidationText(textOrName, options.version);\n const staticNotes = staticLint(text);\n\n const model = options.model ?? this.options.judgeModel;\n\n if (!model) {\n return buildValidationReport(staticNotes);\n }\n\n const judgeResult = await judgePrompt(text, model, buildJudgeAgent);\n\n return buildValidationReport(staticNotes, judgeResult);\n }\n\n /**\n * Synchronize named prompts with Langfuse-prompts. No-op (resolves) when no\n * `langfuse` option was configured. The resolved (rendered) body + the\n * `name@version` label are what is pushed/pulled.\n */\n public async sync(): Promise<void> {\n if (!this.options.langfuse) {\n return;\n }\n\n await syncLangfusePrompts(\n this.options.langfuse,\n this.list(),\n this.snapshotEntries(),\n entry => this.register(entry),\n );\n }\n\n /**\n * Pick the requested (or latest) {@link PromptVersion} for a name from the\n * mirror, throwing {@link PromptNotFoundError} on an unknown name or version.\n */\n private pickVersion(name: string, version?: string): PromptVersion {\n const mirror = this.versionMeta.get(name);\n\n if (!mirror || mirror.length === 0) {\n throw new PromptNotFoundError(name);\n }\n\n const picked = version\n ? mirror.find(candidate => candidate.version === version)\n : mirror[mirror.length - 1];\n\n if (!picked) {\n throw new PromptNotFoundError(name, {\n context: { name, version },\n });\n }\n\n return picked;\n }\n\n /**\n * Resolve the text `validate()` should grade: a registered name yields its\n * picked version's raw `template`; anything else is treated as the raw body.\n */\n private resolveValidationText(textOrName: string, version?: string): string {\n const mirror = this.versionMeta.get(textOrName);\n\n if (!mirror || mirror.length === 0) {\n return textOrName;\n }\n\n const picked = version\n ? mirror.find(candidate => candidate.version === version)\n : mirror[mirror.length - 1];\n\n return picked ? picked.template : textOrName;\n }\n\n /**\n * Throw {@link PromptValidationError} listing every `required` key absent\n * from the merged placeholders. A no-op when the version declares none.\n */\n private assertRequired(\n name: string,\n version: PromptVersion,\n placeholders: Record<string, unknown>,\n ): void {\n if (!version.required || version.required.length === 0) {\n return;\n }\n\n const missing = version.required.filter(\n key => placeholders[key] === undefined || placeholders[key] === null || placeholders[key] === \"\",\n );\n\n if (missing.length > 0) {\n throw new PromptValidationError(\n `Prompt \"${name}\" version \"${version.version}\" is missing required placeholder${\n missing.length > 1 ? \"s\" : \"\"\n }: ${missing.join(\", \")}.`,\n { context: { name, version: version.version, missing } },\n );\n }\n }\n\n /** Snapshot the catalog as `PromptEntry[]` (for the Langfuse push path). */\n private snapshotEntries(): PromptEntry[] {\n return [...this.versionMeta.entries()].map(([name, versions]) => ({\n name,\n versions: [...versions],\n }));\n }\n}\n\n/**\n * Create a versioned, typed prompt registry — a thin facade over the unified\n * `ai.prompts` manager.\n *\n * **Role.** Public factory for {@link PromptRegistryContract}. Keeps\n * user-facing code free of `new` and consistent with `ai.memory`,\n * `ai.orchestrator`, `ai.batch` (all return instances). Each call returns a\n * fresh, isolated registry backed by its own unified manager, so parallel test\n * suites and multi-tenant apps never share mutable global prompt state.\n *\n * @param options - Seed entries, an optional default judge model, and an\n * optional Langfuse sync.\n *\n * @example\n * const prompts = prompt({\n * prompts: [\n * {\n * name: \"support-agent\",\n * versions: [\n * { version: \"1\", template: \"You are support for {{product}}. Reply in {{language|English}}.\" },\n * { version: \"2\", template: \"You are senior support for {{product}}.\", required: [\"product\"] },\n * ],\n * },\n * ],\n * });\n *\n * const resolved = prompts.resolve(\"support-agent\", { placeholders: { product: \"Warlock\" } });\n * const agent = ai.agent({ model, systemPrompt: resolved.toSystemPrompt() });\n * // resolved.version === \"2\"; a missing `product` would throw PromptValidationError.\n *\n * @example\n * // Resolve a globally-registered prompt by name from `ai.prompts`.\n * ai.systemPrompt(\"You are support.\", { name: \"support\" });\n * const sp = ai.prompt(\"support\"); // → the registered SystemPromptContract\n */\nfunction promptFactory(\n name: string,\n versionOrTag?: string,\n): SystemPromptContract;\nfunction promptFactory(options?: PromptRegistryOptions): PromptRegistryContract;\nfunction promptFactory(\n first?: string | PromptRegistryOptions,\n versionOrTag?: string,\n): SystemPromptContract | PromptRegistryContract {\n // String form: resolve a globally-registered prompt from the process-wide\n // `ai.prompts` manager (the single unified registry). This is the thin\n // facade's read path onto the shared store.\n if (typeof first === \"string\") {\n return defaultPromptsManager().get(first, versionOrTag);\n }\n\n // Options form: build an isolated registry backed by its own unified manager.\n return new PromptRegistry(first);\n}\n\n/**\n * Create a versioned prompt registry, OR resolve a globally-registered prompt\n * by name from `ai.prompts`.\n *\n * - `prompt(options?)` → a fresh, isolated {@link PromptRegistryContract}.\n * - `prompt(name, versionOrTag?)` → the `SystemPromptContract` registered under\n * `name` in the process-wide `ai.prompts` manager (latest version by default,\n * or a specific version / pinned tag).\n */\nexport const prompt: typeof promptFactory = promptFactory;\n"],"mappings":";;;;;;;;;;;;;;;;;AAwCA,SAAS,gBAAgB,OAA8C;CACrE,OAAO,MAAM;EACX,MAAM;EACN;EACA,cACE;CAEJ,CAAC;AACH;;;;;;;;;;;AAYA,SAAS,kBAAkB,SAA8C;CACvE,OAAO,IAAI,aAAa,CAAC,IAAI,YAAY,QAAQ,QAAQ,CAAC,GAAG,EAC3D,GAAI,QAAQ,WAAW,EAAE,UAAU,QAAQ,SAAS,IAAI,CAAC,EAC3D,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,IAAM,iBAAN,MAAuD;CASrD,AAAO,YAAY,AAAiB,UAAiC,CAAC,GAAG;EAArC;qCAFL,IAAI,IAA6B;EAG9D,KAAK,UAAUA,QAAqB;EAEpC,KAAK,MAAM,SAAS,QAAQ,WAAW,CAAC,GACtC,KAAK,SAAS,KAAK;EAGrB,IAAI,QAAQ,UACV,aAAa,QAAQ,QAAQ;CAEjC;;;;;CAMA,AAAO,SAAS,OAA4C;EAC1D,KAAK,MAAM,WAAW,MAAM,UAC1B,KAAK,IAAI,MAAM,MAAM,OAAO;EAK9B,IAAI,CAAC,KAAK,YAAY,IAAI,MAAM,IAAI,GAClC,KAAK,YAAY,IAAI,MAAM,MAAM,CAAC,CAAC;EAGrC,OAAO;CACT;;;;;;CAOA,AAAO,IAAI,MAAc,SAAgD;EACvE,MAAM,SAAS,KAAK,YAAY,IAAI,IAAI,KAAK,CAAC;EAE9C,IAAI,OAAO,MAAK,aAAY,SAAS,YAAY,QAAQ,OAAO,GAC9D,MAAM,IAAI,sBACR,WAAW,KAAK,mCAAmC,QAAQ,QAAQ,KACnE,EAAE,SAAS;GAAE;GAAM,SAAS,QAAQ;EAAQ,EAAE,CAChD;EAGF,KAAK,QAAQ,SAAS,kBAAkB,OAA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CACJ;AACF;AA0CA,SAAS,cACP,OACA,cAC+C;CAI/C,IAAI,OAAO,UAAU,UACnB,OAAO,sBAAsB,EAAE,IAAI,OAAO,YAAY;CAIxD,OAAO,IAAI,eAAe,KAAK;AACjC;;;;;;;;;;AAWA,MAAa,SAA+B"}
@@ -1 +1 @@
1
- {"version":3,"file":"prompts-manager.d.mts","names":[],"sources":["../../../../../../../ai/src/prompts/prompts-manager.ts"],"mappings":";;;;;;AAsCA;;iBAAgB,SAAA,CAAU,IAAA,UAAc,OAAe;;AAAA;AA2nBvD;;;;;;;;AAAgF;AAehF;;;;AAA+D;;;;;;;;iBAf/C,OAAA,CAAQ,OAAA,GAAU,qBAAA,GAAwB,sBAAsB;;iBAehE,qBAAA,IAAyB,sBAAsB"}
1
+ {"version":3,"file":"prompts-manager.d.mts","names":[],"sources":["../../../../../../../ai/src/prompts/prompts-manager.ts"],"mappings":";;;;;;AAsCA;;iBAAgB,SAAA,CAAU,IAAA,UAAc,OAAe;;AAAA;AA2nBvD;;;;;;;;AAAgF;AAehF;;;;AAA+D;;;;;;;;iBAf/C,OAAA,CAAQ,OAAA,GAAU,qBAAA,GAAwB,sBAAsB;;iBAehE,qBAAA,CAAA,GAAyB,sBAAsB"}
@@ -1 +1 @@
1
- {"version":3,"file":"prompts-manager.mjs","names":[],"sources":["../../../../../../../ai/src/prompts/prompts-manager.ts"],"sourcesContent":["import type { Placeholders } from \"../contracts/placeholders.type\";\nimport type {\n SystemPromptBlockContract,\n SystemPromptContract,\n SystemPromptMeta,\n} from \"../contracts/system-prompt.contract\";\nimport { InvalidRequestError } from \"../errors\";\nimport { Instruction } from \"../system-prompt/instruction\";\nimport { Persona } from \"../system-prompt/persona\";\nimport { SystemPrompt } from \"../system-prompt/system-prompt\";\nimport type {\n PromptsManagerContract,\n PromptsManagerEntry,\n PromptsManagerRegisterOptions,\n} from \"./prompts-manager.contract\";\nimport type {\n ExportedPromptVersion,\n ExportedRegistry,\n PromptDiff,\n PromptDiffBlock,\n PromptJudgeCacheLike,\n PromptsManagerOptions,\n PromptTemplateVersion,\n PromptValidateTarget,\n PromptValidationResult,\n PromptsValidateOptions,\n} from \"./prompts-manager.type\";\nimport {\n describeContractTarget,\n findMissingPlaceholders,\n findUnreferencedRequired,\n judgePromptBodyCached,\n} from \"./prompts-validate\";\n\n/**\n * Build the `name@version` registry key. Centralized so the duplicate check,\n * `get`, and `composedFrom` provenance all agree on one label shape.\n */\nexport function promptKey(name: string, version: string): string {\n return `${name}@${version}`;\n}\n\n/**\n * Serialize a prompt's observable content — its ordered blocks (discriminator\n * + raw template text) — into a stable signature. Two prompts with the same\n * blocks in the same order share a signature, which is how `register()` tells\n * an idempotent re-registration from a genuine clash. Meta is intentionally\n * excluded: provenance / description should not defeat idempotency.\n */\nfunction contentSignature(contract: SystemPromptContract): string {\n return JSON.stringify(\n contract.blocks.map(block => [block.type, block.text]),\n );\n}\n\n/**\n * Reconstruct a block from its `{ type, text }` snapshot — `persona` blocks\n * become a `Persona`, everything else an `Instruction`. The inverse of the\n * flattening `export()` performs, so an imported registry resolves identically.\n */\nfunction blockFromSnapshot(block: PromptDiffBlock): SystemPromptBlockContract {\n return block.type === \"persona\"\n ? new Persona(block.text)\n : new Instruction(block.text);\n}\n\n/**\n * Narrow a {@link PromptTemplateVersion} body to its ordered block list: a raw\n * string becomes one instruction block; an explicit block list is used verbatim.\n */\nfunction blocksFromTemplate(\n template: string | readonly SystemPromptBlockContract[],\n): SystemPromptBlockContract[] {\n if (typeof template === \"string\") {\n return [new Instruction(template)];\n }\n\n return [...template];\n}\n\n/**\n * Concrete `PromptsManagerContract` — a single registry of named, versioned\n * `SystemPromptContract` builders keyed by `name@version`.\n *\n * **Role.** The store behind `ai.prompts`. It holds one flat\n * `Map<string, PromptsManagerEntry>` keyed by `name@version`, plus a monotonic\n * counter that stamps each entry's `addedAt` so \"latest\" is deterministic\n * (highest `addedAt` for a name) without ever reading the wall clock.\n *\n * **Responsibility.**\n * - Owns: the registry map, the `addedAt` counter, the duplicate /\n * idempotency rule, default version derivation, latest selection, the\n * per-version tag pins, and the validate / diff / export / import surface.\n * - Does NOT own: prompt rendering (delegated to the contract's `resolve()`),\n * block composition, or the LLM-judge mechanics (delegated to the eval\n * `judge` scorer via `prompts-validate`).\n *\n * Users construct via the `prompts()` factory — `new PromptsManager()` is not\n * the public API.\n */\nclass PromptsManager implements PromptsManagerContract {\n /** Flat registry keyed by `name@version`. */\n private readonly entries = new Map<string, PromptsManagerEntry>();\n\n /** First-seen order of names, for a stable `list()`. */\n private readonly names: string[] = [];\n\n /** Per-name tag pins: `name` → (`tag` → `version`). */\n private readonly pins = new Map<string, Map<string, string>>();\n\n /** Optional process-level judge-verdict memo (absent ⇒ judge always runs live). */\n private readonly judgeCache?: PromptJudgeCacheLike;\n\n /** Monotonic insertion counter — the deterministic stand-in for a timestamp. */\n private counter = 0;\n\n public constructor(options: PromptsManagerOptions = {}) {\n this.judgeCache = options.judgeCache;\n }\n\n public register(\n contract: SystemPromptContract,\n options: PromptsManagerRegisterOptions = {},\n ): PromptsManagerContract {\n const meta = contract.meta();\n // An explicit override (from define() / import()) wins over the contract's\n // own meta — it lets those bulk paths register an anonymous contract under\n // a name without the SystemPrompt constructor's default-manager auto-reg.\n const name = options.name ?? meta?.name;\n\n if (!name) {\n throw new InvalidRequestError(\n \"Cannot register a prompt without a name — set meta.name via \" +\n \"systemPrompt(input, { name }) or .meta({ name }).\",\n { context: { meta } },\n );\n }\n\n const version =\n options.version ?? meta?.version ?? this.nextVersion(name);\n const key = promptKey(name, version);\n const existing = this.entries.get(key);\n\n if (existing) {\n // Idempotent re-registration: identical content under the same\n // name@version is a no-op, not an error. Anything else is a clash.\n if (contentSignature(existing.contract) === contentSignature(contract)) {\n return this;\n }\n\n throw new InvalidRequestError(\n `A different prompt is already registered as \"${key}\".`,\n { context: { name, version } },\n );\n }\n\n if (!this.names.includes(name)) {\n this.names.push(name);\n }\n\n this.entries.set(key, {\n name,\n version,\n addedAt: this.counter++,\n contract,\n ...(options.tags ? { tags: options.tags } : {}),\n });\n\n return this;\n }\n\n public create(\n input?: string | ReadonlyArray<SystemPromptBlockContract>,\n meta?: SystemPromptMeta,\n ): SystemPromptContract {\n // Mirror `systemPromptFactory` exactly (no import — `system-prompt.ts`\n // already depends on this module, so importing its factory back here would\n // close an import cycle). A name in `meta` auto-registers into the\n // process-wide default manager via the SystemPrompt constructor.\n if (input === undefined) {\n return new SystemPrompt([], meta);\n }\n\n if (typeof input === \"string\") {\n return new SystemPrompt([new Instruction(input)], meta);\n }\n\n return new SystemPrompt([...input], meta);\n }\n\n public get(name: string, versionOrTag?: string): SystemPromptContract {\n return this.requireEntry(name, versionOrTag).contract;\n }\n\n public has(name: string, versionOrTag?: string): boolean {\n const { baseName, selector } = this.parseSelector(name, versionOrTag);\n\n if (selector !== undefined) {\n return this.resolveSelector(baseName, selector) !== undefined;\n }\n\n return this.latestEntry(baseName) !== undefined;\n }\n\n public list(): string[] {\n return [...this.names];\n }\n\n public versions(name: string): string[] {\n return [...this.entries.values()]\n .filter(entry => entry.name === name)\n .sort((a, b) => a.addedAt - b.addedAt)\n .map(entry => entry.version);\n }\n\n public resolve(\n name: string,\n versionOrTag?: string,\n placeholders?: Placeholders,\n ): string {\n return this.requireEntry(name, versionOrTag).contract.resolve(placeholders);\n }\n\n public define(\n name: string,\n versions: readonly PromptTemplateVersion[],\n ): PromptsManagerContract {\n for (const entry of versions) {\n const blocks = blocksFromTemplate(entry.template);\n // Anonymous contract (no name in meta ⇒ no SystemPrompt constructor\n // auto-registration into the default manager); the name/version are\n // supplied explicitly so define() targets only THIS manager.\n const contract = new SystemPrompt(blocks);\n\n this.register(contract, { name, version: entry.version });\n }\n\n return this;\n }\n\n public tag(\n name: string,\n tag: string,\n version: string,\n ): PromptsManagerContract {\n // Validate the target exists before pinning — a tag to a missing version is\n // an authoring mistake, not a silent dangling pin.\n if (!this.entries.has(promptKey(name, version))) {\n throw new InvalidRequestError(\n `Cannot tag \"${tag}\" — no prompt registered as \"${promptKey(\n name,\n version,\n )}\".`,\n { context: { name, tag, version } },\n );\n }\n\n const nameTags = this.pins.get(name) ?? new Map<string, string>();\n nameTags.set(tag, version);\n this.pins.set(name, nameTags);\n\n return this;\n }\n\n public async validate(\n target: PromptValidateTarget,\n options: PromptsValidateOptions = {},\n ): Promise<PromptValidationResult> {\n const { text, required } = this.describeTarget(target);\n\n const provided = new Set(Object.keys(options.placeholders ?? {}));\n const declared = new Set<string>([\n ...required,\n ...(options.declare ?? []),\n ]);\n\n const missing = findMissingPlaceholders(text, provided, declared);\n\n // A declared-required key that the body never references is itself a\n // defect — surface it as an issue (it does not affect `missing` / `ok`,\n // which track unresolved placeholders).\n const unreferenced = findUnreferencedRequired(text, required);\n\n const ok = missing.length === 0;\n\n if (!options.judge) {\n if (unreferenced.length === 0) {\n return { ok, missing };\n }\n\n return {\n ok,\n missing,\n issues: unreferenced.map(\n key => `Required key \"${key}\" is never referenced in the prompt.`,\n ),\n };\n }\n\n // Per-call cache override wins over the manager-level memo. `criteria`\n // (when set) replaces the built-in rubric the judge grades against.\n const cache = options.judgeCache ?? this.judgeCache;\n const judgeOutcome = await judgePromptBodyCached(\n text,\n options.judge,\n cache,\n options.criteria,\n );\n\n const issues = [\n ...unreferenced.map(\n key => `Required key \"${key}\" is never referenced in the prompt.`,\n ),\n ...judgeOutcome.issues,\n ];\n\n return {\n ok,\n missing,\n ...(judgeOutcome.score !== undefined ? { score: judgeOutcome.score } : {}),\n issues,\n };\n }\n\n public diff(name: string, from: string, to: string): PromptDiff {\n const fromBlocks = this.snapshotBlocks(this.requireExact(name, from));\n const toBlocks = this.snapshotBlocks(this.requireExact(name, to));\n\n const added: PromptDiffBlock[] = [];\n const removed: PromptDiffBlock[] = [];\n const changed: { from: PromptDiffBlock; to: PromptDiffBlock }[] = [];\n\n const max = Math.max(fromBlocks.length, toBlocks.length);\n\n for (let index = 0; index < max; index++) {\n const left = fromBlocks[index];\n const right = toBlocks[index];\n\n if (left && !right) {\n removed.push(left);\n continue;\n }\n\n if (!left && right) {\n added.push(right);\n continue;\n }\n\n if (left && right && (left.type !== right.type || left.text !== right.text)) {\n changed.push({ from: left, to: right });\n }\n }\n\n return {\n name,\n from,\n to,\n added,\n removed,\n changed,\n identical:\n added.length === 0 && removed.length === 0 && changed.length === 0,\n };\n }\n\n public export(): ExportedRegistry {\n return {\n prompts: this.names.map(name => ({\n name,\n versions: this.versions(name).map(version =>\n this.exportVersion(name, version),\n ),\n })),\n };\n }\n\n public import(snapshot: ExportedRegistry): PromptsManagerContract {\n for (const exported of snapshot.prompts) {\n for (const version of exported.versions) {\n const blocks = version.blocks.map(blockFromSnapshot);\n // Anonymous (no `name` in meta) so the SystemPrompt constructor does\n // not auto-register into the default manager; description / required\n // ride along for round-trip fidelity. Name/version are explicit so the\n // import lands only on THIS manager.\n const contract = new SystemPrompt(blocks, {\n ...(version.description ? { description: version.description } : {}),\n ...(version.required ? { required: version.required } : {}),\n });\n\n this.register(contract, {\n name: exported.name,\n version: version.version,\n });\n\n for (const tag of version.tags ?? []) {\n this.tag(exported.name, tag, version.version);\n }\n }\n }\n\n return this;\n }\n\n /**\n * Flatten a registered version into its portable `{ version, blocks, tags?,\n * description?, required? }` snapshot for `export()`.\n */\n private exportVersion(name: string, version: string): ExportedPromptVersion {\n const entry = this.requireExact(name, version);\n const meta = entry.contract.meta();\n const tags = this.tagsForVersion(name, version);\n\n return {\n version,\n blocks: this.snapshotBlocks(entry),\n ...(tags.length > 0 ? { tags } : {}),\n ...(meta?.description ? { description: meta.description } : {}),\n ...(meta?.required ? { required: [...meta.required] } : {}),\n };\n }\n\n /** Every tag currently pinned to a specific `name@version`, in pin order. */\n private tagsForVersion(name: string, version: string): string[] {\n const nameTags = this.pins.get(name);\n\n if (!nameTags) {\n return [];\n }\n\n const tags: string[] = [];\n\n for (const [tag, pinnedVersion] of nameTags) {\n if (pinnedVersion === version) {\n tags.push(tag);\n }\n }\n\n return tags;\n }\n\n /** Flatten an entry's blocks to `{ type, text }` snapshots. */\n private snapshotBlocks(entry: PromptsManagerEntry): PromptDiffBlock[] {\n return entry.contract.blocks.map(block => ({\n type: block.type,\n text: block.text,\n }));\n }\n\n /**\n * Resolve the body + declared-required keys for any `validate` target: a\n * registered name (or `name@selector`), a `SystemPromptContract` instance, or\n * a raw string.\n */\n private describeTarget(target: PromptValidateTarget): {\n text: string;\n required: readonly string[];\n } {\n if (typeof target === \"string\") {\n // An inline `name@selector` (or a bare registered name) resolves through\n // the registry; anything else is a raw prompt body validated verbatim.\n const { baseName, selector } = this.parseSelector(target, undefined);\n const entry = selector\n ? this.resolveSelector(baseName, selector)\n : this.latestEntry(baseName);\n\n if (entry) {\n return describeContractTarget(entry.contract);\n }\n\n return { text: target, required: [] };\n }\n\n if (isSystemPromptContract(target)) {\n return describeContractTarget(target);\n }\n\n if (isBlock(target)) {\n return { text: target.text, required: [] };\n }\n\n throw new InvalidRequestError(\n \"validate() target must be a registered name, a SystemPromptContract, \" +\n \"a prompt block, or a raw string.\",\n { context: { target } },\n );\n }\n\n /**\n * The next integer version label for a name — `\"1\"` for the first, then the\n * count of existing versions plus one. String-typed to match the free-form\n * `version` label shape.\n */\n private nextVersion(name: string): string {\n const count = [...this.entries.values()].filter(\n entry => entry.name === name,\n ).length;\n\n return String(count + 1);\n }\n\n /** Pick the highest-`addedAt` entry for a name, or `undefined` when absent. */\n private latestEntry(name: string): PromptsManagerEntry | undefined {\n let latest: PromptsManagerEntry | undefined;\n\n for (const entry of this.entries.values()) {\n if (entry.name !== name) {\n continue;\n }\n\n if (!latest || entry.addedAt > latest.addedAt) {\n latest = entry;\n }\n }\n\n return latest;\n }\n\n /**\n * Split a name argument into its base name + optional selector. The selector\n * comes from the explicit second argument when present, else from an inline\n * `name@selector` in the first argument. A bare name yields no selector.\n */\n private parseSelector(\n name: string,\n versionOrTag: string | undefined,\n ): { baseName: string; selector: string | undefined } {\n if (versionOrTag !== undefined) {\n return { baseName: name, selector: versionOrTag };\n }\n\n const at = name.indexOf(\"@\");\n\n if (at > 0) {\n return { baseName: name.slice(0, at), selector: name.slice(at + 1) };\n }\n\n return { baseName: name, selector: undefined };\n }\n\n /**\n * Resolve a selector (a version label OR a pinned tag) to a concrete entry.\n * Version labels win over tags when both could match — the explicit label is\n * the more specific intent. Returns `undefined` when neither resolves.\n */\n private resolveSelector(\n name: string,\n selector: string,\n ): PromptsManagerEntry | undefined {\n const byVersion = this.entries.get(promptKey(name, selector));\n\n if (byVersion) {\n return byVersion;\n }\n\n const pinnedVersion = this.pins.get(name)?.get(selector);\n\n if (pinnedVersion !== undefined) {\n return this.entries.get(promptKey(name, pinnedVersion));\n }\n\n return undefined;\n }\n\n /**\n * Resolve an entry by name (+ optional version / tag / inline selector),\n * throwing {@link InvalidRequestError} when the name or the requested\n * selector is unknown. The single lookup path `get` / `resolve` share.\n */\n private requireEntry(\n name: string,\n versionOrTag?: string,\n ): PromptsManagerEntry {\n const { baseName, selector } = this.parseSelector(name, versionOrTag);\n\n if (selector !== undefined) {\n const entry = this.resolveSelector(baseName, selector);\n\n if (!entry) {\n throw new InvalidRequestError(\n `No prompt registered as \"${baseName}\" with version/tag \"${selector}\".`,\n { context: { name: baseName, selector } },\n );\n }\n\n return entry;\n }\n\n const latest = this.latestEntry(baseName);\n\n if (!latest) {\n throw new InvalidRequestError(\n `No prompt registered under name \"${baseName}\".`,\n { context: { name: baseName } },\n );\n }\n\n return latest;\n }\n\n /**\n * Resolve a name + EXACT version label to its entry (no tag fallback), for\n * `diff` / `export` where a concrete version is always required. Throws\n * {@link InvalidRequestError} on a miss.\n */\n private requireExact(name: string, version: string): PromptsManagerEntry {\n const entry = this.entries.get(promptKey(name, version));\n\n if (!entry) {\n throw new InvalidRequestError(\n `No prompt registered as \"${promptKey(name, version)}\".`,\n { context: { name, version } },\n );\n }\n\n return entry;\n }\n}\n\n/**\n * Narrow an arbitrary value to a `SystemPromptContract` — true when it exposes\n * the builder surface (`blocks` array + a callable `resolve`) AND a callable\n * `meta`. Robust across duplicate package copies (no `instanceof`).\n */\nfunction isSystemPromptContract(\n value: unknown,\n): value is SystemPromptContract {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Array.isArray((value as { blocks?: unknown }).blocks) &&\n typeof (value as { resolve?: unknown }).resolve === \"function\" &&\n typeof (value as { meta?: unknown }).meta === \"function\"\n );\n}\n\n/**\n * Narrow an arbitrary value to a single `SystemPromptBlockContract` — true when\n * it carries a string `type` + `text` and a callable `resolve` but is NOT a\n * full prompt (no `blocks` array). Lets `validate` accept a lone block.\n */\nfunction isBlock(value: unknown): value is SystemPromptBlockContract {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { type?: unknown }).type === \"string\" &&\n typeof (value as { text?: unknown }).text === \"string\" &&\n typeof (value as { resolve?: unknown }).resolve === \"function\"\n );\n}\n\n/**\n * Create a new, isolated prompts manager.\n *\n * **Role.** Public factory for {@link PromptsManagerContract} — keeps\n * user-facing code free of `new` and consistent with the other `ai.*`\n * factories. Each call returns a fresh registry, so parallel test suites and\n * multi-tenant apps never share mutable global prompt state.\n *\n * The process-wide instance that named `systemPrompt(...)` builders\n * auto-register into is `ai.prompts` (see {@link defaultPromptsManager}).\n *\n * @param options - Optional wiring, notably a `judgeCache` that memoizes\n * LLM-judge verdicts (absent ⇒ every judge pass runs live).\n *\n * @example\n * const registry = prompts();\n * registry.register(systemPrompt(\"You are support.\", { name: \"support\" }));\n * registry.resolve(\"support\"); // \"You are support.\"\n *\n * @example\n * // Memoize judge verdicts across validations.\n * const registry = prompts({ judgeCache: new MemoryCacheDriver() });\n */\nexport function prompts(options?: PromptsManagerOptions): PromptsManagerContract {\n return new PromptsManager(options);\n}\n\n/**\n * The process-wide default manager that named prompts auto-register into.\n *\n * Held as a module-level singleton (lazily created on first access) so\n * `system-prompt.ts` can register a named builder without importing the\n * `PromptsManager` class — keeping the auto-registration seam free of a\n * runtime import cycle.\n */\nlet defaultManager: PromptsManagerContract | undefined;\n\n/** Accessor for the process-wide default {@link PromptsManagerContract}. */\nexport function defaultPromptsManager(): PromptsManagerContract {\n if (!defaultManager) {\n defaultManager = new PromptsManager();\n }\n\n return defaultManager;\n}\n"],"mappings":";;;;;;;;;;;;AAsCA,SAAgB,UAAU,MAAc,SAAyB;CAC/D,OAAO,GAAG,KAAK,GAAG;AACpB;;;;;;;;AASA,SAAS,iBAAiB,UAAwC;CAChE,OAAO,KAAK,UACV,SAAS,OAAO,KAAI,UAAS,CAAC,MAAM,MAAM,MAAM,IAAI,CAAC,CACvD;AACF;;;;;;AAOA,SAAS,kBAAkB,OAAmD;CAC5E,OAAO,MAAM,SAAS,YAClB,IAAI,QAAQ,MAAM,IAAI,IACtB,IAAI,YAAY,MAAM,IAAI;AAChC;;;;;AAMA,SAAS,mBACP,UAC6B;CAC7B,IAAI,OAAO,aAAa,UACtB,OAAO,CAAC,IAAI,YAAY,QAAQ,CAAC;CAGnC,OAAO,CAAC,GAAG,QAAQ;AACrB;;;;;;;;;;;;;;;;;;;;;AAsBA,IAAM,iBAAN,MAAuD;CAgBrD,AAAO,YAAY,UAAiC,CAAC,GAAG;iCAd7B,IAAI,IAAiC;eAG7B,CAAC;8BAGZ,IAAI,IAAiC;iBAM3C;EAGhB,KAAK,aAAa,QAAQ;CAC5B;CAEA,AAAO,SACL,UACA,UAAyC,CAAC,GAClB;EACxB,MAAM,OAAO,SAAS,KAAK;EAI3B,MAAM,OAAO,QAAQ,QAAQ,MAAM;EAEnC,IAAI,CAAC,MACH,MAAM,IAAI,oBACR,iHAEA,EAAE,SAAS,EAAE,KAAK,EAAE,CACtB;EAGF,MAAM,UACJ,QAAQ,WAAW,MAAM,WAAW,KAAK,YAAY,IAAI;EAC3D,MAAM,MAAM,UAAU,MAAM,OAAO;EACnC,MAAM,WAAW,KAAK,QAAQ,IAAI,GAAG;EAErC,IAAI,UAAU;GAGZ,IAAI,iBAAiB,SAAS,QAAQ,MAAM,iBAAiB,QAAQ,GACnE,OAAO;GAGT,MAAM,IAAI,oBACR,gDAAgD,IAAI,KACpD,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,CAAC,gBACH,iBAAiB,IAAI,eAAe;CAGtC,OAAO;AACT"}
1
+ {"version":3,"file":"prompts-manager.mjs","names":[],"sources":["../../../../../../../ai/src/prompts/prompts-manager.ts"],"sourcesContent":["import type { Placeholders } from \"../contracts/placeholders.type\";\nimport type {\n SystemPromptBlockContract,\n SystemPromptContract,\n SystemPromptMeta,\n} from \"../contracts/system-prompt.contract\";\nimport { InvalidRequestError } from \"../errors\";\nimport { Instruction } from \"../system-prompt/instruction\";\nimport { Persona } from \"../system-prompt/persona\";\nimport { SystemPrompt } from \"../system-prompt/system-prompt\";\nimport type {\n PromptsManagerContract,\n PromptsManagerEntry,\n PromptsManagerRegisterOptions,\n} from \"./prompts-manager.contract\";\nimport type {\n ExportedPromptVersion,\n ExportedRegistry,\n PromptDiff,\n PromptDiffBlock,\n PromptJudgeCacheLike,\n PromptsManagerOptions,\n PromptTemplateVersion,\n PromptValidateTarget,\n PromptValidationResult,\n PromptsValidateOptions,\n} from \"./prompts-manager.type\";\nimport {\n describeContractTarget,\n findMissingPlaceholders,\n findUnreferencedRequired,\n judgePromptBodyCached,\n} from \"./prompts-validate\";\n\n/**\n * Build the `name@version` registry key. Centralized so the duplicate check,\n * `get`, and `composedFrom` provenance all agree on one label shape.\n */\nexport function promptKey(name: string, version: string): string {\n return `${name}@${version}`;\n}\n\n/**\n * Serialize a prompt's observable content — its ordered blocks (discriminator\n * + raw template text) — into a stable signature. Two prompts with the same\n * blocks in the same order share a signature, which is how `register()` tells\n * an idempotent re-registration from a genuine clash. Meta is intentionally\n * excluded: provenance / description should not defeat idempotency.\n */\nfunction contentSignature(contract: SystemPromptContract): string {\n return JSON.stringify(\n contract.blocks.map(block => [block.type, block.text]),\n );\n}\n\n/**\n * Reconstruct a block from its `{ type, text }` snapshot — `persona` blocks\n * become a `Persona`, everything else an `Instruction`. The inverse of the\n * flattening `export()` performs, so an imported registry resolves identically.\n */\nfunction blockFromSnapshot(block: PromptDiffBlock): SystemPromptBlockContract {\n return block.type === \"persona\"\n ? new Persona(block.text)\n : new Instruction(block.text);\n}\n\n/**\n * Narrow a {@link PromptTemplateVersion} body to its ordered block list: a raw\n * string becomes one instruction block; an explicit block list is used verbatim.\n */\nfunction blocksFromTemplate(\n template: string | readonly SystemPromptBlockContract[],\n): SystemPromptBlockContract[] {\n if (typeof template === \"string\") {\n return [new Instruction(template)];\n }\n\n return [...template];\n}\n\n/**\n * Concrete `PromptsManagerContract` — a single registry of named, versioned\n * `SystemPromptContract` builders keyed by `name@version`.\n *\n * **Role.** The store behind `ai.prompts`. It holds one flat\n * `Map<string, PromptsManagerEntry>` keyed by `name@version`, plus a monotonic\n * counter that stamps each entry's `addedAt` so \"latest\" is deterministic\n * (highest `addedAt` for a name) without ever reading the wall clock.\n *\n * **Responsibility.**\n * - Owns: the registry map, the `addedAt` counter, the duplicate /\n * idempotency rule, default version derivation, latest selection, the\n * per-version tag pins, and the validate / diff / export / import surface.\n * - Does NOT own: prompt rendering (delegated to the contract's `resolve()`),\n * block composition, or the LLM-judge mechanics (delegated to the eval\n * `judge` scorer via `prompts-validate`).\n *\n * Users construct via the `prompts()` factory — `new PromptsManager()` is not\n * the public API.\n */\nclass PromptsManager implements PromptsManagerContract {\n /** Flat registry keyed by `name@version`. */\n private readonly entries = new Map<string, PromptsManagerEntry>();\n\n /** First-seen order of names, for a stable `list()`. */\n private readonly names: string[] = [];\n\n /** Per-name tag pins: `name` → (`tag` → `version`). */\n private readonly pins = new Map<string, Map<string, string>>();\n\n /** Optional process-level judge-verdict memo (absent ⇒ judge always runs live). */\n private readonly judgeCache?: PromptJudgeCacheLike;\n\n /** Monotonic insertion counter — the deterministic stand-in for a timestamp. */\n private counter = 0;\n\n public constructor(options: PromptsManagerOptions = {}) {\n this.judgeCache = options.judgeCache;\n }\n\n public register(\n contract: SystemPromptContract,\n options: PromptsManagerRegisterOptions = {},\n ): PromptsManagerContract {\n const meta = contract.meta();\n // An explicit override (from define() / import()) wins over the contract's\n // own meta — it lets those bulk paths register an anonymous contract under\n // a name without the SystemPrompt constructor's default-manager auto-reg.\n const name = options.name ?? meta?.name;\n\n if (!name) {\n throw new InvalidRequestError(\n \"Cannot register a prompt without a name — set meta.name via \" +\n \"systemPrompt(input, { name }) or .meta({ name }).\",\n { context: { meta } },\n );\n }\n\n const version =\n options.version ?? meta?.version ?? this.nextVersion(name);\n const key = promptKey(name, version);\n const existing = this.entries.get(key);\n\n if (existing) {\n // Idempotent re-registration: identical content under the same\n // name@version is a no-op, not an error. Anything else is a clash.\n if (contentSignature(existing.contract) === contentSignature(contract)) {\n return this;\n }\n\n throw new InvalidRequestError(\n `A different prompt is already registered as \"${key}\".`,\n { context: { name, version } },\n );\n }\n\n if (!this.names.includes(name)) {\n this.names.push(name);\n }\n\n this.entries.set(key, {\n name,\n version,\n addedAt: this.counter++,\n contract,\n ...(options.tags ? { tags: options.tags } : {}),\n });\n\n return this;\n }\n\n public create(\n input?: string | ReadonlyArray<SystemPromptBlockContract>,\n meta?: SystemPromptMeta,\n ): SystemPromptContract {\n // Mirror `systemPromptFactory` exactly (no import — `system-prompt.ts`\n // already depends on this module, so importing its factory back here would\n // close an import cycle). A name in `meta` auto-registers into the\n // process-wide default manager via the SystemPrompt constructor.\n if (input === undefined) {\n return new SystemPrompt([], meta);\n }\n\n if (typeof input === \"string\") {\n return new SystemPrompt([new Instruction(input)], meta);\n }\n\n return new SystemPrompt([...input], meta);\n }\n\n public get(name: string, versionOrTag?: string): SystemPromptContract {\n return this.requireEntry(name, versionOrTag).contract;\n }\n\n public has(name: string, versionOrTag?: string): boolean {\n const { baseName, selector } = this.parseSelector(name, versionOrTag);\n\n if (selector !== undefined) {\n return this.resolveSelector(baseName, selector) !== undefined;\n }\n\n return this.latestEntry(baseName) !== undefined;\n }\n\n public list(): string[] {\n return [...this.names];\n }\n\n public versions(name: string): string[] {\n return [...this.entries.values()]\n .filter(entry => entry.name === name)\n .sort((a, b) => a.addedAt - b.addedAt)\n .map(entry => entry.version);\n }\n\n public resolve(\n name: string,\n versionOrTag?: string,\n placeholders?: Placeholders,\n ): string {\n return this.requireEntry(name, versionOrTag).contract.resolve(placeholders);\n }\n\n public define(\n name: string,\n versions: readonly PromptTemplateVersion[],\n ): PromptsManagerContract {\n for (const entry of versions) {\n const blocks = blocksFromTemplate(entry.template);\n // Anonymous contract (no name in meta ⇒ no SystemPrompt constructor\n // auto-registration into the default manager); the name/version are\n // supplied explicitly so define() targets only THIS manager.\n const contract = new SystemPrompt(blocks);\n\n this.register(contract, { name, version: entry.version });\n }\n\n return this;\n }\n\n public tag(\n name: string,\n tag: string,\n version: string,\n ): PromptsManagerContract {\n // Validate the target exists before pinning — a tag to a missing version is\n // an authoring mistake, not a silent dangling pin.\n if (!this.entries.has(promptKey(name, version))) {\n throw new InvalidRequestError(\n `Cannot tag \"${tag}\" — no prompt registered as \"${promptKey(\n name,\n version,\n )}\".`,\n { context: { name, tag, version } },\n );\n }\n\n const nameTags = this.pins.get(name) ?? new Map<string, string>();\n nameTags.set(tag, version);\n this.pins.set(name, nameTags);\n\n return this;\n }\n\n public async validate(\n target: PromptValidateTarget,\n options: PromptsValidateOptions = {},\n ): Promise<PromptValidationResult> {\n const { text, required } = this.describeTarget(target);\n\n const provided = new Set(Object.keys(options.placeholders ?? {}));\n const declared = new Set<string>([\n ...required,\n ...(options.declare ?? []),\n ]);\n\n const missing = findMissingPlaceholders(text, provided, declared);\n\n // A declared-required key that the body never references is itself a\n // defect — surface it as an issue (it does not affect `missing` / `ok`,\n // which track unresolved placeholders).\n const unreferenced = findUnreferencedRequired(text, required);\n\n const ok = missing.length === 0;\n\n if (!options.judge) {\n if (unreferenced.length === 0) {\n return { ok, missing };\n }\n\n return {\n ok,\n missing,\n issues: unreferenced.map(\n key => `Required key \"${key}\" is never referenced in the prompt.`,\n ),\n };\n }\n\n // Per-call cache override wins over the manager-level memo. `criteria`\n // (when set) replaces the built-in rubric the judge grades against.\n const cache = options.judgeCache ?? this.judgeCache;\n const judgeOutcome = await judgePromptBodyCached(\n text,\n options.judge,\n cache,\n options.criteria,\n );\n\n const issues = [\n ...unreferenced.map(\n key => `Required key \"${key}\" is never referenced in the prompt.`,\n ),\n ...judgeOutcome.issues,\n ];\n\n return {\n ok,\n missing,\n ...(judgeOutcome.score !== undefined ? { score: judgeOutcome.score } : {}),\n issues,\n };\n }\n\n public diff(name: string, from: string, to: string): PromptDiff {\n const fromBlocks = this.snapshotBlocks(this.requireExact(name, from));\n const toBlocks = this.snapshotBlocks(this.requireExact(name, to));\n\n const added: PromptDiffBlock[] = [];\n const removed: PromptDiffBlock[] = [];\n const changed: { from: PromptDiffBlock; to: PromptDiffBlock }[] = [];\n\n const max = Math.max(fromBlocks.length, toBlocks.length);\n\n for (let index = 0; index < max; index++) {\n const left = fromBlocks[index];\n const right = toBlocks[index];\n\n if (left && !right) {\n removed.push(left);\n continue;\n }\n\n if (!left && right) {\n added.push(right);\n continue;\n }\n\n if (left && right && (left.type !== right.type || left.text !== right.text)) {\n changed.push({ from: left, to: right });\n }\n }\n\n return {\n name,\n from,\n to,\n added,\n removed,\n changed,\n identical:\n added.length === 0 && removed.length === 0 && changed.length === 0,\n };\n }\n\n public export(): ExportedRegistry {\n return {\n prompts: this.names.map(name => ({\n name,\n versions: this.versions(name).map(version =>\n this.exportVersion(name, version),\n ),\n })),\n };\n }\n\n public import(snapshot: ExportedRegistry): PromptsManagerContract {\n for (const exported of snapshot.prompts) {\n for (const version of exported.versions) {\n const blocks = version.blocks.map(blockFromSnapshot);\n // Anonymous (no `name` in meta) so the SystemPrompt constructor does\n // not auto-register into the default manager; description / required\n // ride along for round-trip fidelity. Name/version are explicit so the\n // import lands only on THIS manager.\n const contract = new SystemPrompt(blocks, {\n ...(version.description ? { description: version.description } : {}),\n ...(version.required ? { required: version.required } : {}),\n });\n\n this.register(contract, {\n name: exported.name,\n version: version.version,\n });\n\n for (const tag of version.tags ?? []) {\n this.tag(exported.name, tag, version.version);\n }\n }\n }\n\n return this;\n }\n\n /**\n * Flatten a registered version into its portable `{ version, blocks, tags?,\n * description?, required? }` snapshot for `export()`.\n */\n private exportVersion(name: string, version: string): ExportedPromptVersion {\n const entry = this.requireExact(name, version);\n const meta = entry.contract.meta();\n const tags = this.tagsForVersion(name, version);\n\n return {\n version,\n blocks: this.snapshotBlocks(entry),\n ...(tags.length > 0 ? { tags } : {}),\n ...(meta?.description ? { description: meta.description } : {}),\n ...(meta?.required ? { required: [...meta.required] } : {}),\n };\n }\n\n /** Every tag currently pinned to a specific `name@version`, in pin order. */\n private tagsForVersion(name: string, version: string): string[] {\n const nameTags = this.pins.get(name);\n\n if (!nameTags) {\n return [];\n }\n\n const tags: string[] = [];\n\n for (const [tag, pinnedVersion] of nameTags) {\n if (pinnedVersion === version) {\n tags.push(tag);\n }\n }\n\n return tags;\n }\n\n /** Flatten an entry's blocks to `{ type, text }` snapshots. */\n private snapshotBlocks(entry: PromptsManagerEntry): PromptDiffBlock[] {\n return entry.contract.blocks.map(block => ({\n type: block.type,\n text: block.text,\n }));\n }\n\n /**\n * Resolve the body + declared-required keys for any `validate` target: a\n * registered name (or `name@selector`), a `SystemPromptContract` instance, or\n * a raw string.\n */\n private describeTarget(target: PromptValidateTarget): {\n text: string;\n required: readonly string[];\n } {\n if (typeof target === \"string\") {\n // An inline `name@selector` (or a bare registered name) resolves through\n // the registry; anything else is a raw prompt body validated verbatim.\n const { baseName, selector } = this.parseSelector(target, undefined);\n const entry = selector\n ? this.resolveSelector(baseName, selector)\n : this.latestEntry(baseName);\n\n if (entry) {\n return describeContractTarget(entry.contract);\n }\n\n return { text: target, required: [] };\n }\n\n if (isSystemPromptContract(target)) {\n return describeContractTarget(target);\n }\n\n if (isBlock(target)) {\n return { text: target.text, required: [] };\n }\n\n throw new InvalidRequestError(\n \"validate() target must be a registered name, a SystemPromptContract, \" +\n \"a prompt block, or a raw string.\",\n { context: { target } },\n );\n }\n\n /**\n * The next integer version label for a name — `\"1\"` for the first, then the\n * count of existing versions plus one. String-typed to match the free-form\n * `version` label shape.\n */\n private nextVersion(name: string): string {\n const count = [...this.entries.values()].filter(\n entry => entry.name === name,\n ).length;\n\n return String(count + 1);\n }\n\n /** Pick the highest-`addedAt` entry for a name, or `undefined` when absent. */\n private latestEntry(name: string): PromptsManagerEntry | undefined {\n let latest: PromptsManagerEntry | undefined;\n\n for (const entry of this.entries.values()) {\n if (entry.name !== name) {\n continue;\n }\n\n if (!latest || entry.addedAt > latest.addedAt) {\n latest = entry;\n }\n }\n\n return latest;\n }\n\n /**\n * Split a name argument into its base name + optional selector. The selector\n * comes from the explicit second argument when present, else from an inline\n * `name@selector` in the first argument. A bare name yields no selector.\n */\n private parseSelector(\n name: string,\n versionOrTag: string | undefined,\n ): { baseName: string; selector: string | undefined } {\n if (versionOrTag !== undefined) {\n return { baseName: name, selector: versionOrTag };\n }\n\n const at = name.indexOf(\"@\");\n\n if (at > 0) {\n return { baseName: name.slice(0, at), selector: name.slice(at + 1) };\n }\n\n return { baseName: name, selector: undefined };\n }\n\n /**\n * Resolve a selector (a version label OR a pinned tag) to a concrete entry.\n * Version labels win over tags when both could match — the explicit label is\n * the more specific intent. Returns `undefined` when neither resolves.\n */\n private resolveSelector(\n name: string,\n selector: string,\n ): PromptsManagerEntry | undefined {\n const byVersion = this.entries.get(promptKey(name, selector));\n\n if (byVersion) {\n return byVersion;\n }\n\n const pinnedVersion = this.pins.get(name)?.get(selector);\n\n if (pinnedVersion !== undefined) {\n return this.entries.get(promptKey(name, pinnedVersion));\n }\n\n return undefined;\n }\n\n /**\n * Resolve an entry by name (+ optional version / tag / inline selector),\n * throwing {@link InvalidRequestError} when the name or the requested\n * selector is unknown. The single lookup path `get` / `resolve` share.\n */\n private requireEntry(\n name: string,\n versionOrTag?: string,\n ): PromptsManagerEntry {\n const { baseName, selector } = this.parseSelector(name, versionOrTag);\n\n if (selector !== undefined) {\n const entry = this.resolveSelector(baseName, selector);\n\n if (!entry) {\n throw new InvalidRequestError(\n `No prompt registered as \"${baseName}\" with version/tag \"${selector}\".`,\n { context: { name: baseName, selector } },\n );\n }\n\n return entry;\n }\n\n const latest = this.latestEntry(baseName);\n\n if (!latest) {\n throw new InvalidRequestError(\n `No prompt registered under name \"${baseName}\".`,\n { context: { name: baseName } },\n );\n }\n\n return latest;\n }\n\n /**\n * Resolve a name + EXACT version label to its entry (no tag fallback), for\n * `diff` / `export` where a concrete version is always required. Throws\n * {@link InvalidRequestError} on a miss.\n */\n private requireExact(name: string, version: string): PromptsManagerEntry {\n const entry = this.entries.get(promptKey(name, version));\n\n if (!entry) {\n throw new InvalidRequestError(\n `No prompt registered as \"${promptKey(name, version)}\".`,\n { context: { name, version } },\n );\n }\n\n return entry;\n }\n}\n\n/**\n * Narrow an arbitrary value to a `SystemPromptContract` — true when it exposes\n * the builder surface (`blocks` array + a callable `resolve`) AND a callable\n * `meta`. Robust across duplicate package copies (no `instanceof`).\n */\nfunction isSystemPromptContract(\n value: unknown,\n): value is SystemPromptContract {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Array.isArray((value as { blocks?: unknown }).blocks) &&\n typeof (value as { resolve?: unknown }).resolve === \"function\" &&\n typeof (value as { meta?: unknown }).meta === \"function\"\n );\n}\n\n/**\n * Narrow an arbitrary value to a single `SystemPromptBlockContract` — true when\n * it carries a string `type` + `text` and a callable `resolve` but is NOT a\n * full prompt (no `blocks` array). Lets `validate` accept a lone block.\n */\nfunction isBlock(value: unknown): value is SystemPromptBlockContract {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { type?: unknown }).type === \"string\" &&\n typeof (value as { text?: unknown }).text === \"string\" &&\n typeof (value as { resolve?: unknown }).resolve === \"function\"\n );\n}\n\n/**\n * Create a new, isolated prompts manager.\n *\n * **Role.** Public factory for {@link PromptsManagerContract} — keeps\n * user-facing code free of `new` and consistent with the other `ai.*`\n * factories. Each call returns a fresh registry, so parallel test suites and\n * multi-tenant apps never share mutable global prompt state.\n *\n * The process-wide instance that named `systemPrompt(...)` builders\n * auto-register into is `ai.prompts` (see {@link defaultPromptsManager}).\n *\n * @param options - Optional wiring, notably a `judgeCache` that memoizes\n * LLM-judge verdicts (absent ⇒ every judge pass runs live).\n *\n * @example\n * const registry = prompts();\n * registry.register(systemPrompt(\"You are support.\", { name: \"support\" }));\n * registry.resolve(\"support\"); // \"You are support.\"\n *\n * @example\n * // Memoize judge verdicts across validations.\n * const registry = prompts({ judgeCache: new MemoryCacheDriver() });\n */\nexport function prompts(options?: PromptsManagerOptions): PromptsManagerContract {\n return new PromptsManager(options);\n}\n\n/**\n * The process-wide default manager that named prompts auto-register into.\n *\n * Held as a module-level singleton (lazily created on first access) so\n * `system-prompt.ts` can register a named builder without importing the\n * `PromptsManager` class — keeping the auto-registration seam free of a\n * runtime import cycle.\n */\nlet defaultManager: PromptsManagerContract | undefined;\n\n/** Accessor for the process-wide default {@link PromptsManagerContract}. */\nexport function defaultPromptsManager(): PromptsManagerContract {\n if (!defaultManager) {\n defaultManager = new PromptsManager();\n }\n\n return defaultManager;\n}\n"],"mappings":";;;;;;;;;;;;AAsCA,SAAgB,UAAU,MAAc,SAAyB;CAC/D,OAAO,GAAG,KAAK,GAAG;AACpB;;;;;;;;AASA,SAAS,iBAAiB,UAAwC;CAChE,OAAO,KAAK,UACV,SAAS,OAAO,KAAI,UAAS,CAAC,MAAM,MAAM,MAAM,IAAI,CAAC,CACvD;AACF;;;;;;AAOA,SAAS,kBAAkB,OAAmD;CAC5E,OAAO,MAAM,SAAS,YAClB,IAAI,QAAQ,MAAM,IAAI,IACtB,IAAI,YAAY,MAAM,IAAI;AAChC;;;;;AAMA,SAAS,mBACP,UAC6B;CAC7B,IAAI,OAAO,aAAa,UACtB,OAAO,CAAC,IAAI,YAAY,QAAQ,CAAC;CAGnC,OAAO,CAAC,GAAG,QAAQ;AACrB;;;;;;;;;;;;;;;;;;;;;AAsBA,IAAM,iBAAN,MAAuD;CAgBrD,AAAO,YAAY,UAAiC,CAAC,GAAG;iCAd7B,IAAI,IAAiC;eAG7B,CAAC;8BAGZ,IAAI,IAAiC;iBA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OA,SAAS,uBACP,OAC+B;CAC/B,OACE,OAAO,UAAU,YACjB,UAAU,QACV,MAAM,QAAS,MAA+B,MAAM,KACpD,OAAQ,MAAgC,YAAY,cACpD,OAAQ,MAA6B,SAAS;AAElD;;;;;;AAOA,SAAS,QAAQ,OAAoD;CACnE,OACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAA6B,SAAS,YAC9C,OAAQ,MAA6B,SAAS,YAC9C,OAAQ,MAAgC,YAAY;AAExD;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,QAAQ,SAAyD;CAC/E,OAAO,IAAI,eAAe,OAAO;AACnC;;;;;;;;;AAUA,IAAI;;AAGJ,SAAgB,wBAAgD;CAC9D,IAAI,CAAC,gBACH,iBAAiB,IAAI,eAAe;CAGtC,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"prompts-validate.mjs","names":[],"sources":["../../../../../../../ai/src/prompts/prompts-validate.ts"],"sourcesContent":["import { agent } from \"../agent/agent\";\nimport type { AgentContract } from \"../contracts/agent/agent.contract\";\nimport type { ModelContract } from \"../contracts/model.contract\";\nimport type { SystemPromptContract } from \"../contracts/system-prompt.contract\";\nimport { judge } from \"../eval/judge-scorer\";\nimport { PROMPT_JUDGE_RUBRIC } from \"../prompt/prompt-validate\";\nimport type { PromptJudgeCacheLike } from \"./prompts-manager.type\";\n\n/**\n * Placeholder matcher — kept in lock-step with the matcher\n * `renderPlaceholders` (`src/system-prompt/render-placeholders.ts`) and the\n * legacy `prompt-validate` lint both use, so the deterministic validator sees\n * the exact same `{{key}}` / `{{a.b}}` / `{{key|default}}` set the renderer\n * substitutes. Global so every occurrence is collected.\n */\nconst PLACEHOLDER_PATTERN = /\\{\\{\\s*([^{}]+?)\\s*\\}\\}/g;\n\n/**\n * One parsed placeholder occurrence — the key path (the part before any\n * `|default`) and whether the occurrence carried an inline default.\n */\ntype ParsedPlaceholder = {\n /** The dot-path key, e.g. `language` or `user.name`. */\n readonly path: string;\n /** Whether THIS occurrence declared an inline `{{key|default}}` fallback. */\n readonly hasDefault: boolean;\n};\n\n/**\n * Collect every distinct placeholder occurrence from a template, in first-seen\n * order. A key is considered to \"have a default\" only when EVERY occurrence of\n * it carries one — a single bare `{{key}}` means the renderer can leave it\n * unresolved, so the key is still required.\n */\nfunction collectPlaceholders(template: string): ParsedPlaceholder[] {\n const byPath = new Map<string, boolean>();\n const order: string[] = [];\n\n for (const match of template.matchAll(PLACEHOLDER_PATTERN)) {\n const [rawPath, rawDefault] = match[1].split(\"|\");\n const path = rawPath.trim();\n\n if (path.length === 0) {\n continue;\n }\n\n const hasDefault = rawDefault !== undefined;\n\n if (!byPath.has(path)) {\n byPath.set(path, hasDefault);\n order.push(path);\n } else {\n // A key only counts as defaulted when ALL of its occurrences default.\n byPath.set(path, (byPath.get(path) ?? false) && hasDefault);\n }\n }\n\n return order.map(path => ({ path, hasDefault: byPath.get(path) ?? false }));\n}\n\n/**\n * Run the deterministic (model-free) half of validation over a resolved prompt\n * body. Reports every `{{key}}` placeholder that has NO inline default and is\n * neither supplied in `provided` nor declared in `declared` (the prompt's\n * `meta.required` plus any caller-declared keys).\n *\n * Pure and synchronous — the only required half of `validate`; the LLM-judge\n * half is optional and layered on top.\n *\n * @param text - The resolved prompt body (placeholders may still be present).\n * @param provided - Placeholder keys the caller has supplied a value for.\n * @param declared - Placeholder keys declared as known/required (e.g. `meta.required`).\n */\nexport function findMissingPlaceholders(\n text: string,\n provided: ReadonlySet<string>,\n declared: ReadonlySet<string>,\n): string[] {\n const missing: string[] = [];\n\n for (const { path, hasDefault } of collectPlaceholders(text)) {\n if (hasDefault) {\n continue;\n }\n\n if (provided.has(path) || declared.has(path)) {\n continue;\n }\n\n missing.push(path);\n }\n\n return missing;\n}\n\n/**\n * A `meta.required` key absent from the template entirely — declared as\n * required but never referenced — is itself a defect worth surfacing. Returns\n * the declared keys that appear nowhere in the body.\n */\nexport function findUnreferencedRequired(\n text: string,\n required: readonly string[],\n): string[] {\n const present = new Set(collectPlaceholders(text).map(p => p.path));\n\n return required.filter(key => !present.has(key));\n}\n\n/**\n * Build the one-shot judge agent the optional LLM-as-judge pass runs. Mirrors\n * the legacy `prompt.ts` judge agent (strict-JSON instruction so the verdict\n * parses even without an output schema), so the two validate paths share one\n * judging contract.\n */\nfunction buildJudgeAgent(model: ModelContract): AgentContract<unknown> {\n return agent({\n name: \"prompt-quality-judge\",\n model,\n systemPrompt:\n \"You are a strict prompt-quality grader. Respond with JSON only: \" +\n '{ \"score\": <0..1>, \"passed\": <true|false>, \"reason\": \"<short explanation>\" }.',\n });\n}\n\n/**\n * Turn caller-supplied `criteria` into the judge rubric that replaces the\n * built-in {@link PROMPT_JUDGE_RUBRIC}. A single string is used verbatim;\n * a list is joined into a numbered rule set the judge must check ALL of.\n * Returns `undefined` for an empty/blank input, so the caller falls back\n * to the default rubric.\n *\n * @example\n * formatCriteria([\"Addresses the user by {{name}}\", \"Under 200 words\"]);\n * // → \"Grade the system prompt against ALL of these criteria …\\n1. …\\n2. …\"\n */\nexport function formatCriteria(\n criteria: string | readonly string[] | undefined,\n): string | undefined {\n if (criteria === undefined) {\n return undefined;\n }\n\n if (typeof criteria === \"string\") {\n const trimmed = criteria.trim();\n\n return trimmed.length > 0 ? trimmed : undefined;\n }\n\n const rules = criteria.map(rule => rule.trim()).filter(rule => rule.length > 0);\n\n if (rules.length === 0) {\n return undefined;\n }\n\n return (\n \"Grade the system prompt against ALL of the following criteria — it passes only if it satisfies every one:\\n\" +\n rules.map((rule, index) => `${index + 1}. ${rule}`).join(\"\\n\")\n );\n}\n\n/** Outcome of the optional LLM-as-judge pass over a resolved prompt body. */\nexport type JudgeOutcome = {\n /**\n * The judge score in `[0, 1]`, or `undefined` when the judge degraded\n * (errored, returned no parseable verdict, or threw) — never a misleading\n * `0` masquerading as a real verdict.\n */\n readonly score?: number;\n /** Human-readable issues raised by the judge (its reason, or a degrade note). */\n readonly issues: string[];\n};\n\n/**\n * Run the optional LLM-as-judge pass over a resolved prompt body, REUSING the\n * eval `judge` scorer (the same path `prompt().validate` uses) so there is no\n * second judging implementation.\n *\n * **Nova-safe by contract.** The judge NEVER throws here: the eval scorer\n * already degrades a broken judge to `score: 0` with a failure reason, and any\n * exception that still escapes (model wiring, agent construction) is caught.\n * Both degrade paths surface `score: undefined` plus an issue note — so a flaky\n * judge can never fail an otherwise-valid prompt.\n *\n * @param text - The resolved prompt body under evaluation.\n * @param model - The model that powers the judge agent.\n * @param criteria - Optional caller rules that REPLACE the built-in rubric\n * ({@link formatCriteria}). Omitted ⇒ the default prompt-quality rubric.\n */\nexport async function judgePromptBody(\n text: string,\n model: ModelContract,\n criteria?: string | readonly string[],\n): Promise<JudgeOutcome> {\n try {\n const judgeAgent = buildJudgeAgent(model);\n const scorer = judge({\n agent: judgeAgent,\n rubric: formatCriteria(criteria) ?? PROMPT_JUDGE_RUBRIC,\n });\n\n const verdict = await scorer({\n case: { name: \"prompt-quality\", input: \"Grade the system prompt below.\" },\n text,\n // `result` is unused by the judge scorer's prompt builder; a minimal\n // stand-in keeps the structural contract satisfied without a real run.\n result: { text } as never,\n output: undefined,\n });\n\n // The eval scorer signals a degraded judge with score 0 + a diagnostic\n // reason (\"judge failed: …\" / \"judge returned no parseable verdict\"). Treat\n // that as \"no usable score\" rather than a real 0 verdict.\n const degraded =\n verdict.score === 0 &&\n typeof verdict.reason === \"string\" &&\n /^judge (failed|returned no parseable)/.test(verdict.reason);\n\n if (degraded) {\n return {\n issues: [`LLM-judge unavailable: ${verdict.reason}`],\n };\n }\n\n return {\n score: verdict.score,\n issues: verdict.reason ? [verdict.reason] : [],\n };\n } catch (error) {\n // Last-resort guard: never let a judge failure throw out of validate().\n const message = error instanceof Error ? error.message : String(error);\n\n return {\n issues: [`LLM-judge unavailable: ${message}`],\n };\n }\n}\n\n/**\n * Non-cryptographic 53-bit string hash (cyrb53) — deterministic across runs\n * and platforms, with no `node:crypto` dependency (keeps the validate path\n * usable in any runtime). Mirrors the VCR request hash; collision-resistant\n * enough for a per-prompt judge-verdict keyspace. Returned as base-36.\n */\nfunction hashString(input: string): string {\n let h1 = 0xdeadbeef;\n let h2 = 0x41c6ce57;\n\n for (let i = 0; i < input.length; i++) {\n const ch = input.charCodeAt(i);\n\n h1 = Math.imul(h1 ^ ch, 2654435761);\n h2 = Math.imul(h2 ^ ch, 1597334677);\n }\n\n h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507);\n h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909);\n h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507);\n h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909);\n\n const combined = 4294967296 * (2097151 & h2) + (h1 >>> 0);\n\n return combined.toString(36);\n}\n\n/**\n * Build the judge-verdict cache key for a resolved prompt body + judge model\n * + the effective rubric. Combines the model's `provider:name` identity with a\n * content hash of the rubric-plus-body, so the same prompt graded by the same\n * judge against the same rules hits the cache — while a change to the prompt,\n * the model, OR the `criteria` misses it (different rules ⇒ different verdict).\n */\nexport function judgeCacheKey(\n text: string,\n model: ModelContract,\n criteria?: string | readonly string[],\n): string {\n const rubric = formatCriteria(criteria) ?? PROMPT_JUDGE_RUBRIC;\n\n return `prompts.judge.${model.provider}:${model.name}.${hashString(`${rubric}\u0000${text}`)}`;\n}\n\n/**\n * Run the judge pass with an OPTIONAL memo cache in front. On a hit, the stored\n * {@link JudgeOutcome} is returned without a model call; on a miss, the live\n * judge runs and a USABLE verdict (one carrying a `score`) is written back.\n * Degraded outcomes (no score) are NOT cached — a transient judge failure must\n * never poison the memo. A `null`/absent cache degrades to a direct judge call.\n *\n * Cache I/O is itself fault-tolerant: a `get`/`set` that rejects is swallowed\n * so a flaky cache can never break (or fail) validation.\n *\n * @param text - The resolved prompt body under evaluation.\n * @param model - The judge model.\n * @param cache - Optional verdict memo (any `CacheDriver`-like get/set surface).\n * @param criteria - Optional caller rules that REPLACE the built-in rubric; also\n * folded into the cache key so a re-validation with different rules re-runs.\n */\nexport async function judgePromptBodyCached(\n text: string,\n model: ModelContract,\n cache?: PromptJudgeCacheLike,\n criteria?: string | readonly string[],\n): Promise<JudgeOutcome> {\n if (!cache) {\n return judgePromptBody(text, model, criteria);\n }\n\n const key = judgeCacheKey(text, model, criteria);\n\n const cached = await readJudgeCache(cache, key);\n\n if (cached) {\n return cached;\n }\n\n const outcome = await judgePromptBody(text, model, criteria);\n\n // Only memoize a usable verdict — never a degraded (scoreless) one.\n if (outcome.score !== undefined) {\n await writeJudgeCache(cache, key, outcome);\n }\n\n return outcome;\n}\n\n/** Read a cached verdict, swallowing any cache fault (treated as a miss). */\nasync function readJudgeCache(\n cache: PromptJudgeCacheLike,\n key: string,\n): Promise<JudgeOutcome | undefined> {\n try {\n const value = await cache.get<JudgeOutcome>(key);\n\n return value ?? undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Write a verdict, swallowing any cache fault (best-effort memo). */\nasync function writeJudgeCache(\n cache: PromptJudgeCacheLike,\n key: string,\n outcome: JudgeOutcome,\n): Promise<void> {\n try {\n await cache.set(key, outcome);\n } catch {\n // Best-effort — a failed memo write never affects the validation result.\n }\n}\n\n/**\n * Resolve the body + declared-required keys for a validation target that is a\n * `SystemPromptContract` (named or anonymous). The declared set is the\n * prompt's `meta.required` (when present).\n */\nexport function describeContractTarget(contract: SystemPromptContract): {\n text: string;\n required: readonly string[];\n} {\n const meta = contract.meta();\n\n return {\n text: contract.resolve(),\n required: meta?.required ?? [],\n };\n}\n"],"mappings":";;;;;;;;;;;;AAeA,MAAM,sBAAsB;;;;;;;AAmB5B,SAAS,oBAAoB,UAAuC;CAClE,MAAM,yBAAS,IAAI,IAAqB;CACxC,MAAM,QAAkB,CAAC;CAEzB,KAAK,MAAM,SAAS,SAAS,SAAS,mBAAmB,GAAG;EAC1D,MAAM,CAAC,SAAS,cAAc,MAAM,EAAE,CAAC,MAAM,GAAG;EAChD,MAAM,OAAO,QAAQ,KAAK;EAE1B,IAAI,KAAK,WAAW,GAClB;EAGF,MAAM,aAAa,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,MAAM,SAAS,GAAG,MAAM,KAAK,GAAG,WAAW,GAAG,OAAO,GAAG,MAAM;AACxF;;;;;;;;;;;;;;;;;AAkBA,eAAsB,sBACpB,MACA,OACA,OACA,UACuB;CACvB,IAAI,CAAC,OACH,OAAO,gBAAgB,MAAM,OAAO,QAAQ;CAG9C,MAAM,MAAM,cAAc,MAAM,OAAO,QAAQ;CAE/C,MAAM,SAAS,MAAM,eAAe,OAAO,GAAG;CAE9C,IAAI,QACF,OAAO;CAGT,MAAM,UAAU,MAAM,gBAAgB,MAAM,OAAO,QAAQ;CAG3D,IAAI,QAAQ,UAAU,QACpB,MAAM,gBAAgB,OAAO,KAAK,OAAO;CAG3C,OAAO;AACT;;AAGA,eAAe,eACb,OACA,KACmC;CACnC,IAAI;EAGF,OAAO,MAFa,MAAM,IAAkB,GAAG,KAE/B;CAClB,QAAQ;EACN;CACF;AACF;;AAGA,eAAe,gBACb,OACA,KACA,SACe;CACf,IAAI;EACF,MAAM,MAAM,IAAI,KAAK,OAAO;CAC9B,QAAQ,CAER;AACF;;;;;;AAOA,SAAgB,uBAAuB,UAGrC;CACA,MAAM,OAAO,SAAS,KAAK;CAE3B,OAAO;EACL,MAAM,SAAS,QAAQ;EACvB,UAAU,MAAM,YAAY,CAAC;CAC/B;AACF"}
1
+ {"version":3,"file":"prompts-validate.mjs","names":[],"sources":["../../../../../../../ai/src/prompts/prompts-validate.ts"],"sourcesContent":["import { agent } from \"../agent/agent\";\nimport type { AgentContract } from \"../contracts/agent/agent.contract\";\nimport type { ModelContract } from \"../contracts/model.contract\";\nimport type { SystemPromptContract } from \"../contracts/system-prompt.contract\";\nimport { judge } from \"../eval/judge-scorer\";\nimport { PROMPT_JUDGE_RUBRIC } from \"../prompt/prompt-validate\";\nimport type { PromptJudgeCacheLike } from \"./prompts-manager.type\";\n\n/**\n * Placeholder matcher — kept in lock-step with the matcher\n * `renderPlaceholders` (`src/system-prompt/render-placeholders.ts`) and the\n * legacy `prompt-validate` lint both use, so the deterministic validator sees\n * the exact same `{{key}}` / `{{a.b}}` / `{{key|default}}` set the renderer\n * substitutes. Global so every occurrence is collected.\n */\nconst PLACEHOLDER_PATTERN = /\\{\\{\\s*([^{}]+?)\\s*\\}\\}/g;\n\n/**\n * One parsed placeholder occurrence — the key path (the part before any\n * `|default`) and whether the occurrence carried an inline default.\n */\ntype ParsedPlaceholder = {\n /** The dot-path key, e.g. `language` or `user.name`. */\n readonly path: string;\n /** Whether THIS occurrence declared an inline `{{key|default}}` fallback. */\n readonly hasDefault: boolean;\n};\n\n/**\n * Collect every distinct placeholder occurrence from a template, in first-seen\n * order. A key is considered to \"have a default\" only when EVERY occurrence of\n * it carries one — a single bare `{{key}}` means the renderer can leave it\n * unresolved, so the key is still required.\n */\nfunction collectPlaceholders(template: string): ParsedPlaceholder[] {\n const byPath = new Map<string, boolean>();\n const order: string[] = [];\n\n for (const match of template.matchAll(PLACEHOLDER_PATTERN)) {\n const [rawPath, rawDefault] = match[1].split(\"|\");\n const path = rawPath.trim();\n\n if (path.length === 0) {\n continue;\n }\n\n const hasDefault = rawDefault !== undefined;\n\n if (!byPath.has(path)) {\n byPath.set(path, hasDefault);\n order.push(path);\n } else {\n // A key only counts as defaulted when ALL of its occurrences default.\n byPath.set(path, (byPath.get(path) ?? false) && hasDefault);\n }\n }\n\n return order.map(path => ({ path, hasDefault: byPath.get(path) ?? false }));\n}\n\n/**\n * Run the deterministic (model-free) half of validation over a resolved prompt\n * body. Reports every `{{key}}` placeholder that has NO inline default and is\n * neither supplied in `provided` nor declared in `declared` (the prompt's\n * `meta.required` plus any caller-declared keys).\n *\n * Pure and synchronous — the only required half of `validate`; the LLM-judge\n * half is optional and layered on top.\n *\n * @param text - The resolved prompt body (placeholders may still be present).\n * @param provided - Placeholder keys the caller has supplied a value for.\n * @param declared - Placeholder keys declared as known/required (e.g. `meta.required`).\n */\nexport function findMissingPlaceholders(\n text: string,\n provided: ReadonlySet<string>,\n declared: ReadonlySet<string>,\n): string[] {\n const missing: string[] = [];\n\n for (const { path, hasDefault } of collectPlaceholders(text)) {\n if (hasDefault) {\n continue;\n }\n\n if (provided.has(path) || declared.has(path)) {\n continue;\n }\n\n missing.push(path);\n }\n\n return missing;\n}\n\n/**\n * A `meta.required` key absent from the template entirely — declared as\n * required but never referenced — is itself a defect worth surfacing. Returns\n * the declared keys that appear nowhere in the body.\n */\nexport function findUnreferencedRequired(\n text: string,\n required: readonly string[],\n): string[] {\n const present = new Set(collectPlaceholders(text).map(p => p.path));\n\n return required.filter(key => !present.has(key));\n}\n\n/**\n * Build the one-shot judge agent the optional LLM-as-judge pass runs. Mirrors\n * the legacy `prompt.ts` judge agent (strict-JSON instruction so the verdict\n * parses even without an output schema), so the two validate paths share one\n * judging contract.\n */\nfunction buildJudgeAgent(model: ModelContract): AgentContract<unknown> {\n return agent({\n name: \"prompt-quality-judge\",\n model,\n systemPrompt:\n \"You are a strict prompt-quality grader. Respond with JSON only: \" +\n '{ \"score\": <0..1>, \"passed\": <true|false>, \"reason\": \"<short explanation>\" }.',\n });\n}\n\n/**\n * Turn caller-supplied `criteria` into the judge rubric that replaces the\n * built-in {@link PROMPT_JUDGE_RUBRIC}. A single string is used verbatim;\n * a list is joined into a numbered rule set the judge must check ALL of.\n * Returns `undefined` for an empty/blank input, so the caller falls back\n * to the default rubric.\n *\n * @example\n * formatCriteria([\"Addresses the user by {{name}}\", \"Under 200 words\"]);\n * // → \"Grade the system prompt against ALL of these criteria …\\n1. …\\n2. …\"\n */\nexport function formatCriteria(\n criteria: string | readonly string[] | undefined,\n): string | undefined {\n if (criteria === undefined) {\n return undefined;\n }\n\n if (typeof criteria === \"string\") {\n const trimmed = criteria.trim();\n\n return trimmed.length > 0 ? trimmed : undefined;\n }\n\n const rules = criteria.map(rule => rule.trim()).filter(rule => rule.length > 0);\n\n if (rules.length === 0) {\n return undefined;\n }\n\n return (\n \"Grade the system prompt against ALL of the following criteria — it passes only if it satisfies every one:\\n\" +\n rules.map((rule, index) => `${index + 1}. ${rule}`).join(\"\\n\")\n );\n}\n\n/** Outcome of the optional LLM-as-judge pass over a resolved prompt body. */\nexport type JudgeOutcome = {\n /**\n * The judge score in `[0, 1]`, or `undefined` when the judge degraded\n * (errored, returned no parseable verdict, or threw) — never a misleading\n * `0` masquerading as a real verdict.\n */\n readonly score?: number;\n /** Human-readable issues raised by the judge (its reason, or a degrade note). */\n readonly issues: string[];\n};\n\n/**\n * Run the optional LLM-as-judge pass over a resolved prompt body, REUSING the\n * eval `judge` scorer (the same path `prompt().validate` uses) so there is no\n * second judging implementation.\n *\n * **Nova-safe by contract.** The judge NEVER throws here: the eval scorer\n * already degrades a broken judge to `score: 0` with a failure reason, and any\n * exception that still escapes (model wiring, agent construction) is caught.\n * Both degrade paths surface `score: undefined` plus an issue note — so a flaky\n * judge can never fail an otherwise-valid prompt.\n *\n * @param text - The resolved prompt body under evaluation.\n * @param model - The model that powers the judge agent.\n * @param criteria - Optional caller rules that REPLACE the built-in rubric\n * ({@link formatCriteria}). Omitted ⇒ the default prompt-quality rubric.\n */\nexport async function judgePromptBody(\n text: string,\n model: ModelContract,\n criteria?: string | readonly string[],\n): Promise<JudgeOutcome> {\n try {\n const judgeAgent = buildJudgeAgent(model);\n const scorer = judge({\n agent: judgeAgent,\n rubric: formatCriteria(criteria) ?? PROMPT_JUDGE_RUBRIC,\n });\n\n const verdict = await scorer({\n case: { name: \"prompt-quality\", input: \"Grade the system prompt below.\" },\n text,\n // `result` is unused by the judge scorer's prompt builder; a minimal\n // stand-in keeps the structural contract satisfied without a real run.\n result: { text } as never,\n output: undefined,\n });\n\n // The eval scorer signals a degraded judge with score 0 + a diagnostic\n // reason (\"judge failed: …\" / \"judge returned no parseable verdict\"). Treat\n // that as \"no usable score\" rather than a real 0 verdict.\n const degraded =\n verdict.score === 0 &&\n typeof verdict.reason === \"string\" &&\n /^judge (failed|returned no parseable)/.test(verdict.reason);\n\n if (degraded) {\n return {\n issues: [`LLM-judge unavailable: ${verdict.reason}`],\n };\n }\n\n return {\n score: verdict.score,\n issues: verdict.reason ? [verdict.reason] : [],\n };\n } catch (error) {\n // Last-resort guard: never let a judge failure throw out of validate().\n const message = error instanceof Error ? error.message : String(error);\n\n return {\n issues: [`LLM-judge unavailable: ${message}`],\n };\n }\n}\n\n/**\n * Non-cryptographic 53-bit string hash (cyrb53) — deterministic across runs\n * and platforms, with no `node:crypto` dependency (keeps the validate path\n * usable in any runtime). Mirrors the VCR request hash; collision-resistant\n * enough for a per-prompt judge-verdict keyspace. Returned as base-36.\n */\nfunction hashString(input: string): string {\n let h1 = 0xdeadbeef;\n let h2 = 0x41c6ce57;\n\n for (let i = 0; i < input.length; i++) {\n const ch = input.charCodeAt(i);\n\n h1 = Math.imul(h1 ^ ch, 2654435761);\n h2 = Math.imul(h2 ^ ch, 1597334677);\n }\n\n h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507);\n h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909);\n h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507);\n h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909);\n\n const combined = 4294967296 * (2097151 & h2) + (h1 >>> 0);\n\n return combined.toString(36);\n}\n\n/**\n * Build the judge-verdict cache key for a resolved prompt body + judge model\n * + the effective rubric. Combines the model's `provider:name` identity with a\n * content hash of the rubric-plus-body, so the same prompt graded by the same\n * judge against the same rules hits the cache — while a change to the prompt,\n * the model, OR the `criteria` misses it (different rules ⇒ different verdict).\n */\nexport function judgeCacheKey(\n text: string,\n model: ModelContract,\n criteria?: string | readonly string[],\n): string {\n const rubric = formatCriteria(criteria) ?? PROMPT_JUDGE_RUBRIC;\n\n return `prompts.judge.${model.provider}:${model.name}.${hashString(`${rubric}\u0000${text}`)}`;\n}\n\n/**\n * Run the judge pass with an OPTIONAL memo cache in front. On a hit, the stored\n * {@link JudgeOutcome} is returned without a model call; on a miss, the live\n * judge runs and a USABLE verdict (one carrying a `score`) is written back.\n * Degraded outcomes (no score) are NOT cached — a transient judge failure must\n * never poison the memo. A `null`/absent cache degrades to a direct judge call.\n *\n * Cache I/O is itself fault-tolerant: a `get`/`set` that rejects is swallowed\n * so a flaky cache can never break (or fail) validation.\n *\n * @param text - The resolved prompt body under evaluation.\n * @param model - The judge model.\n * @param cache - Optional verdict memo (any `CacheDriver`-like get/set surface).\n * @param criteria - Optional caller rules that REPLACE the built-in rubric; also\n * folded into the cache key so a re-validation with different rules re-runs.\n */\nexport async function judgePromptBodyCached(\n text: string,\n model: ModelContract,\n cache?: PromptJudgeCacheLike,\n criteria?: string | readonly string[],\n): Promise<JudgeOutcome> {\n if (!cache) {\n return judgePromptBody(text, model, criteria);\n }\n\n const key = judgeCacheKey(text, model, criteria);\n\n const cached = await readJudgeCache(cache, key);\n\n if (cached) {\n return cached;\n }\n\n const outcome = await judgePromptBody(text, model, criteria);\n\n // Only memoize a usable verdict — never a degraded (scoreless) one.\n if (outcome.score !== undefined) {\n await writeJudgeCache(cache, key, outcome);\n }\n\n return outcome;\n}\n\n/** Read a cached verdict, swallowing any cache fault (treated as a miss). */\nasync function readJudgeCache(\n cache: PromptJudgeCacheLike,\n key: string,\n): Promise<JudgeOutcome | undefined> {\n try {\n const value = await cache.get<JudgeOutcome>(key);\n\n return value ?? undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Write a verdict, swallowing any cache fault (best-effort memo). */\nasync function writeJudgeCache(\n cache: PromptJudgeCacheLike,\n key: string,\n outcome: JudgeOutcome,\n): Promise<void> {\n try {\n await cache.set(key, outcome);\n } catch {\n // Best-effort — a failed memo write never affects the validation result.\n }\n}\n\n/**\n * Resolve the body + declared-required keys for a validation target that is a\n * `SystemPromptContract` (named or anonymous). The declared set is the\n * prompt's `meta.required` (when present).\n */\nexport function describeContractTarget(contract: SystemPromptContract): {\n text: string;\n required: readonly string[];\n} {\n const meta = contract.meta();\n\n return {\n text: contract.resolve(),\n required: meta?.required ?? [],\n };\n}\n"],"mappings":";;;;;;;;;;;;AAeA,MAAM,sBAAsB;;;;;;;AA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K,KAAK,KAAM,OAAO,IAAK,UAAU;CAC3C,MAAM,KAAK,KAAK,KAAM,OAAO,IAAK,UAAU;CAI5C,QAFiB,cAAc,UAAU,OAAO,OAAO,IAEvC,SAAS,EAAE;AAC7B;;;;;;;;AASA,SAAgB,cACd,MACA,OACA,UACQ;CACR,MAAM,SAAS,eAAe,QAAQ,KAAK;CAE3C,OAAO,iBAAiB,MAAM,SAAS,GAAG,MAAM,KAAK,GAAG,WAAW,GAAG,OAAO,GAAG,MAAM;AACxF;;;;;;;;;;;;;;;;;AAkBA,eAAsB,sBACpB,MACA,OACA,OACA,UACuB;CACvB,IAAI,CAAC,OACH,OAAO,gBAAgB,MAAM,OAAO,QAAQ;CAG9C,MAAM,MAAM,cAAc,MAAM,OAAO,QAAQ;CAE/C,MAAM,SAAS,MAAM,eAAe,OAAO,GAAG;CAE9C,IAAI,QACF,OAAO;CAGT,MAAM,UAAU,MAAM,gBAAgB,MAAM,OAAO,QAAQ;CAG3D,IAAI,QAAQ,UAAU,QACpB,MAAM,gBAAgB,OAAO,KAAK,OAAO;CAG3C,OAAO;AACT;;AAGA,eAAe,eACb,OACA,KACmC;CACnC,IAAI;EAGF,OAAO,MAFa,MAAM,IAAkB,GAAG,KAE/B;CAClB,QAAQ;EACN;CACF;AACF;;AAGA,eAAe,gBACb,OACA,KACA,SACe;CACf,IAAI;EACF,MAAM,MAAM,IAAI,KAAK,OAAO;CAC9B,QAAQ,CAER;AACF;;;;;;AAOA,SAAgB,uBAAuB,UAGrC;CACA,MAAM,OAAO,SAAS,KAAK;CAE3B,OAAO;EACL,MAAM,SAAS,QAAQ;EACvB,UAAU,MAAM,YAAY,CAAC;CAC/B;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"chunk.mjs","names":[],"sources":["../../../../../../../../ai/src/rag/chunk/chunk.ts"],"sourcesContent":["import type { Chunk, ChunkOptions } from \"../contracts/chunk-options.type\";\nimport { fixedChunk } from \"./fixed\";\nimport { markdownChunk } from \"./markdown\";\nimport { DEFAULT_SEPARATORS, recursiveChunk } from \"./recursive\";\nimport { sentenceChunk } from \"./sentence\";\n\n/** Default target chunk size in characters. */\nexport const DEFAULT_CHUNK_SIZE = 1000;\n\n/** Default character overlap carried between adjacent chunks. */\nexport const DEFAULT_CHUNK_OVERLAP = 200;\n\n/**\n * Split `text` into citation-bearing {@link Chunk}s according to\n * {@link ChunkOptions}, dispatching on `options.type`:\n *\n * - `\"recursive\"` (default) — separator-aware greedy packing.\n * - `\"markdown\"` — heading/section-aware, then recursive within sections.\n * - `\"sentence\"` — packs whole sentences.\n * - `\"fixed\"` — back-to-back character windows.\n *\n * All strategies are character-based (tokenizer-free) and record the exact\n * `[start, end)` span of every chunk in the original text. Empty or\n * whitespace-only input yields `[]`.\n *\n * @example\n * const chunks = chunk(markdownDoc, { type: \"markdown\", size: 800, overlap: 120 });\n * for (const c of chunks) console.log(c.index, c.span, c.text);\n */\nexport function chunk(text: string, options: ChunkOptions = {}): Chunk[] {\n const type = options.type ?? \"recursive\";\n const size = options.size ?? DEFAULT_CHUNK_SIZE;\n const overlap = options.overlap ?? DEFAULT_CHUNK_OVERLAP;\n const separators = options.separators ?? DEFAULT_SEPARATORS;\n\n // Empty or whitespace-only input yields no chunks — index() then writes\n // nothing and never embeds an empty batch.\n if (text.trim().length === 0) {\n return [];\n }\n\n switch (type) {\n case \"markdown\":\n return markdownChunk(text, size, overlap, separators);\n\n case \"sentence\":\n return sentenceChunk(text, size, overlap);\n\n case \"fixed\":\n return fixedChunk(text, size, overlap);\n\n case \"recursive\":\n default:\n return recursiveChunk(text, size, overlap, separators);\n }\n}\n"],"mappings":";;;;;;;AAOA,MAAa,qBAAqB;;AAGlC,MAAa,wBAAwB;;;;;;;;;;;;;;;;;;AAmBrC,SAAgB,MAAM,MAAc,UAAwB,CAAC,GAAY;CACvE,MAAM,OAAO,QAAQ,QAAQ;CAC7B,MAAM,OAAO,QAAQ;CACrB,MAAM,UAAU,QAAQ;CACxB,MAAM,aAAa,QAAQ,cAAc;CAIzC,IAAI,KAAK,KAAK,CAAC,CAAC,WAAW,GACzB,OAAO,CAAC;CAGV,QAAQ,MAAR;EACE,KAAK,YACH,OAAO,cAAc,MAAM,MAAM,SAAS,UAAU;EAEtD,KAAK,YACH,OAAO,cAAc,MAAM,MAAM,OAAO;EAE1C,KAAK,SACH,OAAO,WAAW,MAAM,MAAM,OAAO;EAGvC,SACE,OAAO,eAAe,MAAM,MAAM,SAAS,UAAU;CACzD;AACF"}
1
+ {"version":3,"file":"chunk.mjs","names":[],"sources":["../../../../../../../../ai/src/rag/chunk/chunk.ts"],"sourcesContent":["import type { Chunk, ChunkOptions } from \"../contracts/chunk-options.type\";\nimport { fixedChunk } from \"./fixed\";\nimport { markdownChunk } from \"./markdown\";\nimport { DEFAULT_SEPARATORS, recursiveChunk } from \"./recursive\";\nimport { sentenceChunk } from \"./sentence\";\n\n/** Default target chunk size in characters. */\nexport const DEFAULT_CHUNK_SIZE = 1000;\n\n/** Default character overlap carried between adjacent chunks. */\nexport const DEFAULT_CHUNK_OVERLAP = 200;\n\n/**\n * Split `text` into citation-bearing {@link Chunk}s according to\n * {@link ChunkOptions}, dispatching on `options.type`:\n *\n * - `\"recursive\"` (default) — separator-aware greedy packing.\n * - `\"markdown\"` — heading/section-aware, then recursive within sections.\n * - `\"sentence\"` — packs whole sentences.\n * - `\"fixed\"` — back-to-back character windows.\n *\n * All strategies are character-based (tokenizer-free) and record the exact\n * `[start, end)` span of every chunk in the original text. Empty or\n * whitespace-only input yields `[]`.\n *\n * @example\n * const chunks = chunk(markdownDoc, { type: \"markdown\", size: 800, overlap: 120 });\n * for (const c of chunks) console.log(c.index, c.span, c.text);\n */\nexport function chunk(text: string, options: ChunkOptions = {}): Chunk[] {\n const type = options.type ?? \"recursive\";\n const size = options.size ?? DEFAULT_CHUNK_SIZE;\n const overlap = options.overlap ?? DEFAULT_CHUNK_OVERLAP;\n const separators = options.separators ?? DEFAULT_SEPARATORS;\n\n // Empty or whitespace-only input yields no chunks — index() then writes\n // nothing and never embeds an empty batch.\n if (text.trim().length === 0) {\n return [];\n }\n\n switch (type) {\n case \"markdown\":\n return markdownChunk(text, size, overlap, separators);\n\n case \"sentence\":\n return sentenceChunk(text, size, overlap);\n\n case \"fixed\":\n return fixedChunk(text, size, overlap);\n\n case \"recursive\":\n default:\n return recursiveChunk(text, size, overlap, separators);\n }\n}\n"],"mappings":";;;;;;;AAOA,MAAa,qBAAqB;;AAGlC,MAAa,wBAAwB;;;;;;;;;;;;;;;;;;AAmBrC,SAAgB,MAAM,MAAc,UAAwB,CAAC,GAAY;CACvE,MAAM,OAAO,QAAQ,QAAQ;CAC7B,MAAM,OAAO,QAAQ;CACrB,MAAM,UAAU,QAAQ;CACxB,MAAM,aAAa,QAAQ,cAAc;CAIzC,IAAI,KAAK,KAAK,EAAE,WAAW,GACzB,OAAO,CAAC;CAGV,QAAQ,MAAR;EACE,KAAK,YACH,OAAO,cAAc,MAAM,MAAM,SAAS,UAAU;EAEtD,KAAK,YACH,OAAO,cAAc,MAAM,MAAM,OAAO;EAE1C,KAAK,SACH,OAAO,WAAW,MAAM,MAAM,OAAO;EAGvC,SACE,OAAO,eAAe,MAAM,MAAM,SAAS,UAAU;CACzD;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"markdown.mjs","names":[],"sources":["../../../../../../../../ai/src/rag/chunk/markdown.ts"],"sourcesContent":["import type { Chunk } from \"../contracts/chunk-options.type\";\nimport { DEFAULT_SEPARATORS, recursiveChunk } from \"./recursive\";\n\n/** Matches an ATX Markdown heading line (`#` … `######`) at line start. */\nconst HEADING_LINE = /^#{1,6}[ \\t].*$/gm;\n\n/**\n * Markdown heading/section-aware splitter.\n *\n * Splits the document on ATX heading boundaries (`#`…`######`) first so a\n * section's heading stays glued to its body, then applies the recursive\n * character splitter WITHIN each section so any section larger than `size`\n * is broken down further. Sections at or under `size` are emitted whole.\n * Spans are exact relative to the original document.\n */\nexport function markdownChunk(\n text: string,\n size: number,\n overlap: number,\n separators: string[] = DEFAULT_SEPARATORS,\n): Chunk[] {\n if (text.length === 0) {\n return [];\n }\n\n const sections = splitSections(text);\n const chunks: Chunk[] = [];\n let index = 0;\n\n for (const section of sections) {\n const body = text.slice(section.start, section.end);\n\n if (body.trim().length === 0) {\n continue;\n }\n\n if (body.length <= size) {\n chunks.push({\n text: body,\n index,\n span: [section.start, section.end],\n });\n index += 1;\n\n continue;\n }\n\n // Recurse within the section, then shift the relative spans to\n // absolute document offsets and renumber sequentially.\n const inner = recursiveChunk(body, size, overlap, separators);\n\n for (const piece of inner) {\n chunks.push({\n text: piece.text,\n index,\n span: [section.start + piece.span[0], section.start + piece.span[1]],\n });\n index += 1;\n }\n }\n\n return chunks;\n}\n\n/** A section's absolute `[start, end)` span (heading line + body until next heading). */\ntype SectionSpan = {\n start: number;\n end: number;\n};\n\n/**\n * Carve the document into sections, each beginning at a heading line and\n * running until the next heading (the preamble before the first heading is\n * its own section). Spans cover the whole document with no gaps.\n */\nfunction splitSections(text: string): SectionSpan[] {\n const starts: number[] = [];\n let match: RegExpExecArray | null;\n\n HEADING_LINE.lastIndex = 0;\n\n while ((match = HEADING_LINE.exec(text)) !== null) {\n starts.push(match.index);\n }\n\n // No headings at all — the whole document is one section.\n if (starts.length === 0) {\n return [{ start: 0, end: text.length }];\n }\n\n const sections: SectionSpan[] = [];\n\n // Preamble before the first heading, if any.\n if (starts[0] > 0) {\n sections.push({ start: 0, end: starts[0] });\n }\n\n starts.forEach((start, position) => {\n const end = position + 1 < starts.length ? starts[position + 1] : text.length;\n\n sections.push({ start, end });\n });\n\n return sections;\n}\n"],"mappings":";;;;AAIA,MAAM,eAAe;;;;;;;;;;AAWrB,SAAgB,cACd,MACA,MACA,SACA,aAAuB,oBACd;CACT,IAAI,KAAK,WAAW,GAClB,OAAO,CAAC;CAGV,MAAM,WAAW,cAAc,IAAI;CACnC,MAAM,SAAkB,CAAC;CACzB,IAAI,QAAQ;CAEZ,KAAK,MAAM,WAAW,UAAU;EAC9B,MAAM,OAAO,KAAK,MAAM,QAAQ,OAAO,QAAQ,GAAG;EAElD,IAAI,KAAK,KAAK,CAAC,CAAC,WAAW,GACzB;EAGF,IAAI,KAAK,UAAU,MAAM;GACvB,OAAO,KAAK;IACV,MAAM;IACN;IACA,MAAM,CAAC,QAAQ,OAAO,QAAQ,GAAG;GACnC,CAAC;GACD,SAAS;GAET;EACF;EAIA,MAAM,QAAQ,eAAe,MAAM,MAAM,SAAS,UAAU;EAE5D,KAAK,MAAM,SAAS,OAAO;GACzB,OAAO,KAAK;IACV,MAAM,MAAM;IACZ;IACA,MAAM,CAAC,QAAQ,QAAQ,MAAM,KAAK,IAAI,QAAQ,QAAQ,MAAM,KAAK,EAAE;GACrE,CAAC;GACD,SAAS;EACX;CACF;CAEA,OAAO;AACT;;;;;;AAaA,SAAS,cAAc,MAA6B;CAClD,MAAM,SAAmB,CAAC;CAC1B,IAAI;CAEJ,aAAa,YAAY;CAEzB,QAAQ,QAAQ,aAAa,KAAK,IAAI,OAAO,MAC3C,OAAO,KAAK,MAAM,KAAK;CAIzB,IAAI,OAAO,WAAW,GACpB,OAAO,CAAC;EAAE,OAAO;EAAG,KAAK,KAAK;CAAO,CAAC;CAGxC,MAAM,WAA0B,CAAC;CAGjC,IAAI,OAAO,KAAK,GACd,SAAS,KAAK;EAAE,OAAO;EAAG,KAAK,OAAO;CAAG,CAAC;CAG5C,OAAO,SAAS,OAAO,aAAa;EAClC,MAAM,MAAM,WAAW,IAAI,OAAO,SAAS,OAAO,WAAW,KAAK,KAAK;EAEvE,SAAS,KAAK;GAAE;GAAO;EAAI,CAAC;CAC9B,CAAC;CAED,OAAO;AACT"}
1
+ {"version":3,"file":"markdown.mjs","names":[],"sources":["../../../../../../../../ai/src/rag/chunk/markdown.ts"],"sourcesContent":["import type { Chunk } from \"../contracts/chunk-options.type\";\nimport { DEFAULT_SEPARATORS, recursiveChunk } from \"./recursive\";\n\n/** Matches an ATX Markdown heading line (`#` … `######`) at line start. */\nconst HEADING_LINE = /^#{1,6}[ \\t].*$/gm;\n\n/**\n * Markdown heading/section-aware splitter.\n *\n * Splits the document on ATX heading boundaries (`#`…`######`) first so a\n * section's heading stays glued to its body, then applies the recursive\n * character splitter WITHIN each section so any section larger than `size`\n * is broken down further. Sections at or under `size` are emitted whole.\n * Spans are exact relative to the original document.\n */\nexport function markdownChunk(\n text: string,\n size: number,\n overlap: number,\n separators: string[] = DEFAULT_SEPARATORS,\n): Chunk[] {\n if (text.length === 0) {\n return [];\n }\n\n const sections = splitSections(text);\n const chunks: Chunk[] = [];\n let index = 0;\n\n for (const section of sections) {\n const body = text.slice(section.start, section.end);\n\n if (body.trim().length === 0) {\n continue;\n }\n\n if (body.length <= size) {\n chunks.push({\n text: body,\n index,\n span: [section.start, section.end],\n });\n index += 1;\n\n continue;\n }\n\n // Recurse within the section, then shift the relative spans to\n // absolute document offsets and renumber sequentially.\n const inner = recursiveChunk(body, size, overlap, separators);\n\n for (const piece of inner) {\n chunks.push({\n text: piece.text,\n index,\n span: [section.start + piece.span[0], section.start + piece.span[1]],\n });\n index += 1;\n }\n }\n\n return chunks;\n}\n\n/** A section's absolute `[start, end)` span (heading line + body until next heading). */\ntype SectionSpan = {\n start: number;\n end: number;\n};\n\n/**\n * Carve the document into sections, each beginning at a heading line and\n * running until the next heading (the preamble before the first heading is\n * its own section). Spans cover the whole document with no gaps.\n */\nfunction splitSections(text: string): SectionSpan[] {\n const starts: number[] = [];\n let match: RegExpExecArray | null;\n\n HEADING_LINE.lastIndex = 0;\n\n while ((match = HEADING_LINE.exec(text)) !== null) {\n starts.push(match.index);\n }\n\n // No headings at all — the whole document is one section.\n if (starts.length === 0) {\n return [{ start: 0, end: text.length }];\n }\n\n const sections: SectionSpan[] = [];\n\n // Preamble before the first heading, if any.\n if (starts[0] > 0) {\n sections.push({ start: 0, end: starts[0] });\n }\n\n starts.forEach((start, position) => {\n const end = position + 1 < starts.length ? starts[position + 1] : text.length;\n\n sections.push({ start, end });\n });\n\n return sections;\n}\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CAC9B,CAAC;CAED,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"sentence.mjs","names":[],"sources":["../../../../../../../../ai/src/rag/chunk/sentence.ts"],"sourcesContent":["import type { Chunk } from \"../contracts/chunk-options.type\";\n\n/** Matches a sentence terminator (`.`, `!`, `?`) followed by whitespace. */\nconst SENTENCE_BOUNDARY = /([.!?])\\s+/g;\n\n/**\n * Sentence-aware character splitter.\n *\n * Splits the text on sentence terminators (`. `, `! `, `? `), keeping the\n * terminator attached, then greedily packs whole sentences into chunks up\n * to `size` characters, carrying `overlap` characters forward between\n * adjacent chunks. A single sentence longer than `size` becomes its own\n * (oversize) chunk rather than being cut mid-sentence. Spans are exact.\n */\nexport function sentenceChunk(text: string, size: number, overlap: number): Chunk[] {\n if (text.trim().length === 0) {\n return [];\n }\n\n const sentences = splitSentences(text);\n const chunks: Chunk[] = [];\n\n let bufferStart = -1;\n let bufferEnd = -1;\n let index = 0;\n\n const flush = (): void => {\n if (bufferStart === -1) {\n return;\n }\n\n chunks.push({\n text: text.slice(bufferStart, bufferEnd),\n index,\n span: [bufferStart, bufferEnd],\n });\n index += 1;\n };\n\n for (const sentence of sentences) {\n if (bufferStart === -1) {\n bufferStart = sentence.start;\n bufferEnd = sentence.end;\n\n continue;\n }\n\n if (sentence.end - bufferStart <= size) {\n bufferEnd = sentence.end;\n\n continue;\n }\n\n flush();\n\n const overlapStart =\n overlap > 0 ? Math.max(bufferStart, sentence.start - overlap) : sentence.start;\n\n bufferStart = overlapStart;\n bufferEnd = sentence.end;\n }\n\n flush();\n\n return chunks;\n}\n\n/** A sentence with its absolute `[start, end)` span in the original text. */\ntype SentenceSpan = {\n start: number;\n end: number;\n};\n\n/**\n * Split `text` into sentence spans on terminator + whitespace, keeping the\n * terminator with its sentence and absorbing the trailing whitespace into\n * the boundary so reconstructing the spans loses no characters.\n */\nfunction splitSentences(text: string): SentenceSpan[] {\n const spans: SentenceSpan[] = [];\n let start = 0;\n let match: RegExpExecArray | null;\n\n SENTENCE_BOUNDARY.lastIndex = 0;\n\n while ((match = SENTENCE_BOUNDARY.exec(text)) !== null) {\n const end = match.index + match[0].length;\n\n spans.push({ start, end });\n start = end;\n }\n\n if (start < text.length) {\n spans.push({ start, end: text.length });\n }\n\n return spans;\n}\n"],"mappings":";;AAGA,MAAM,oBAAoB;;;;;;;;;;AAW1B,SAAgB,cAAc,MAAc,MAAc,SAA0B;CAClF,IAAI,KAAK,KAAK,CAAC,CAAC,WAAW,GACzB,OAAO,CAAC;CAGV,MAAM,YAAY,eAAe,IAAI;CACrC,MAAM,SAAkB,CAAC;CAEzB,IAAI,cAAc;CAClB,IAAI,YAAY;CAChB,IAAI,QAAQ;CAEZ,MAAM,cAAoB;EACxB,IAAI,gBAAgB,IAClB;EAGF,OAAO,KAAK;GACV,MAAM,KAAK,MAAM,aAAa,SAAS;GACvC;GACA,MAAM,CAAC,aAAa,SAAS;EAC/B,CAAC;EACD,SAAS;CACX;CAEA,KAAK,MAAM,YAAY,WAAW;EAChC,IAAI,gBAAgB,IAAI;GACtB,cAAc,SAAS;GACvB,YAAY,SAAS;GAErB;EACF;EAEA,IAAI,SAAS,MAAM,eAAe,MAAM;GACtC,YAAY,SAAS;GAErB;EACF;EAEA,MAAM;EAKN,cAFE,UAAU,IAAI,KAAK,IAAI,aAAa,SAAS,QAAQ,OAAO,IAAI,SAAS;EAG3E,YAAY,SAAS;CACvB;CAEA,MAAM;CAEN,OAAO;AACT;;;;;;AAaA,SAAS,eAAe,MAA8B;CACpD,MAAM,QAAwB,CAAC;CAC/B,IAAI,QAAQ;CACZ,IAAI;CAEJ,kBAAkB,YAAY;CAE9B,QAAQ,QAAQ,kBAAkB,KAAK,IAAI,OAAO,MAAM;EACtD,MAAM,MAAM,MAAM,QAAQ,MAAM,EAAE,CAAC;EAEnC,MAAM,KAAK;GAAE;GAAO;EAAI,CAAC;EACzB,QAAQ;CACV;CAEA,IAAI,QAAQ,KAAK,QACf,MAAM,KAAK;EAAE;EAAO,KAAK,KAAK;CAAO,CAAC;CAGxC,OAAO;AACT"}
1
+ {"version":3,"file":"sentence.mjs","names":[],"sources":["../../../../../../../../ai/src/rag/chunk/sentence.ts"],"sourcesContent":["import type { Chunk } from \"../contracts/chunk-options.type\";\n\n/** Matches a sentence terminator (`.`, `!`, `?`) followed by whitespace. */\nconst SENTENCE_BOUNDARY = /([.!?])\\s+/g;\n\n/**\n * Sentence-aware character splitter.\n *\n * Splits the text on sentence terminators (`. `, `! `, `? `), keeping the\n * terminator attached, then greedily packs whole sentences into chunks up\n * to `size` characters, carrying `overlap` characters forward between\n * adjacent chunks. A single sentence longer than `size` becomes its own\n * (oversize) chunk rather than being cut mid-sentence. Spans are exact.\n */\nexport function sentenceChunk(text: string, size: number, overlap: number): Chunk[] {\n if (text.trim().length === 0) {\n return [];\n }\n\n const sentences = splitSentences(text);\n const chunks: Chunk[] = [];\n\n let bufferStart = -1;\n let bufferEnd = -1;\n let index = 0;\n\n const flush = (): void => {\n if (bufferStart === -1) {\n return;\n }\n\n chunks.push({\n text: text.slice(bufferStart, bufferEnd),\n index,\n span: [bufferStart, bufferEnd],\n });\n index += 1;\n };\n\n for (const sentence of sentences) {\n if (bufferStart === -1) {\n bufferStart = sentence.start;\n bufferEnd = sentence.end;\n\n continue;\n }\n\n if (sentence.end - bufferStart <= size) {\n bufferEnd = sentence.end;\n\n continue;\n }\n\n flush();\n\n const overlapStart =\n overlap > 0 ? Math.max(bufferStart, sentence.start - overlap) : sentence.start;\n\n bufferStart = overlapStart;\n bufferEnd = sentence.end;\n }\n\n flush();\n\n return chunks;\n}\n\n/** A sentence with its absolute `[start, end)` span in the original text. */\ntype SentenceSpan = {\n start: number;\n end: number;\n};\n\n/**\n * Split `text` into sentence spans on terminator + whitespace, keeping the\n * terminator with its sentence and absorbing the trailing whitespace into\n * the boundary so reconstructing the spans loses no characters.\n */\nfunction splitSentences(text: string): SentenceSpan[] {\n const spans: SentenceSpan[] = [];\n let start = 0;\n let match: RegExpExecArray | null;\n\n SENTENCE_BOUNDARY.lastIndex = 0;\n\n while ((match = SENTENCE_BOUNDARY.exec(text)) !== null) {\n const end = match.index + match[0].length;\n\n spans.push({ start, end });\n start = end;\n }\n\n if (start < text.length) {\n spans.push({ start, end: text.length });\n }\n\n return spans;\n}\n"],"mappings":";;AAGA,MAAM,oBAAoB;;;;;;;;;;AAW1B,SAAgB,cAAc,MAAc,MAAc,SAA0B;CAClF,IAAI,KAAK,KAAK,EAAE,WAAW,GACzB,OAAO,CAAC;CAGV,MAAM,YAAY,eAAe,IAAI;CACrC,MAAM,SAAkB,CAAC;CAEzB,IAAI,cAAc;CAClB,IAAI,YAAY;CAChB,IAAI,QAAQ;CAEZ,MAAM,cAAoB;EACxB,IAAI,gBAAgB,IAClB;EAGF,OAAO,KAAK;GACV,MAAM,KAAK,MAAM,aAAa,SAAS;GACvC;GACA,MAAM,CAAC,aAAa,SAAS;EAC/B,CAAC;EACD,SAAS;CACX;CAEA,KAAK,MAAM,YAAY,WAAW;EAChC,IAAI,gBAAgB,IAAI;GACtB,cAAc,SAAS;GACvB,YAAY,SAAS;GAErB;EACF;EAEA,IAAI,SAAS,MAAM,eAAe,MAAM;GACtC,YAAY,SAAS;GAErB;EACF;EAEA,MAAM;EAKN,cAFE,UAAU,IAAI,KAAK,IAAI,aAAa,SAAS,QAAQ,OAAO,IAAI,SAAS;EAG3E,YAAY,SAAS;CACvB;CAEA,MAAM;CAEN,OAAO;AACT;;;;;;AAaA,SAAS,eAAe,MAA8B;CACpD,MAAM,QAAwB,CAAC;CAC/B,IAAI,QAAQ;CACZ,IAAI;CAEJ,kBAAkB,YAAY;CAE9B,QAAQ,QAAQ,kBAAkB,KAAK,IAAI,OAAO,MAAM;EACtD,MAAM,MAAM,MAAM,QAAQ,MAAM,GAAG;EAEnC,MAAM,KAAK;GAAE;GAAO;EAAI,CAAC;EACzB,QAAQ;CACV;CAEA,IAAI,QAAQ,KAAK,QACf,MAAM,KAAK;EAAE;EAAO,KAAK,KAAK;CAAO,CAAC;CAGxC,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"bm25.mjs","names":[],"sources":["../../../../../../../../ai/src/rag/hybrid/bm25.ts"],"sourcesContent":["import type { RankedItem } from \"./rrf\";\n\n/** A document to score lexically. */\nexport type LexicalDoc = { id: string; text: string };\n\nconst BM25_K1 = 1.5;\nconst BM25_B = 0.75;\n\n/** Lowercase + split on non-word characters; drop empties. */\nfunction tokenize(text: string): string[] {\n return text\n .toLowerCase()\n .split(/[^a-z0-9]+/i)\n .filter(Boolean);\n}\n\n/**\n * Rank `docs` against `query` with BM25 (A4) — the lexical half of hybrid\n * retrieval. Scores keyword overlap with TF saturation (`k1`) and length\n * normalization (`b`) over the candidate set, so an exact-term match\n * surfaces even when dense embeddings miss it. Returns docs sorted by\n * score (highest first); zero-score docs are dropped.\n *\n * Operates over the supplied candidate set (typically the dense retriever's\n * over-fetch), so it needs no global corpus index — ideal for fusing with\n * a vector ranking via {@link reciprocalRankFusion}.\n */\nexport function bm25Rank(query: string, docs: ReadonlyArray<LexicalDoc>): RankedItem[] {\n const queryTerms = [...new Set(tokenize(query))];\n if (queryTerms.length === 0 || docs.length === 0) return [];\n\n const tokenized = docs.map(doc => ({ id: doc.id, terms: tokenize(doc.text) }));\n const avgLen =\n tokenized.reduce((sum, d) => sum + d.terms.length, 0) / tokenized.length || 1;\n\n // Document frequency per query term, across the candidate set.\n const df = new Map<string, number>();\n for (const term of queryTerms) {\n df.set(\n term,\n tokenized.filter(d => d.terms.includes(term)).length,\n );\n }\n\n const n = tokenized.length;\n\n const scored = tokenized.map(doc => {\n const len = doc.terms.length || 1;\n let score = 0;\n\n for (const term of queryTerms) {\n const tf = doc.terms.filter(t => t === term).length;\n if (tf === 0) continue;\n\n const docFreq = df.get(term) ?? 0;\n // BM25 idf (with the +1 to keep it non-negative).\n const idf = Math.log(1 + (n - docFreq + 0.5) / (docFreq + 0.5));\n const numerator = tf * (BM25_K1 + 1);\n const denominator = tf + BM25_K1 * (1 - BM25_B + BM25_B * (len / avgLen));\n score += idf * (numerator / denominator);\n }\n\n return { id: doc.id, score };\n });\n\n return scored.filter(item => item.score > 0).sort((a, b) => b.score - a.score);\n}\n"],"mappings":";AAKA,MAAM,UAAU;AAChB,MAAM,SAAS;;AAGf,SAAS,SAAS,MAAwB;CACxC,OAAO,KACJ,YAAY,CAAC,CACb,MAAM,aAAa,CAAC,CACpB,OAAO,OAAO;AACnB;;;;;;;;;;;;AAaA,SAAgB,SAAS,OAAe,MAA+C;CACrF,MAAM,aAAa,CAAC,GAAG,IAAI,IAAI,SAAS,KAAK,CAAC,CAAC;CAC/C,IAAI,WAAW,WAAW,KAAK,KAAK,WAAW,GAAG,OAAO,CAAC;CAE1D,MAAM,YAAY,KAAK,KAAI,SAAQ;EAAE,IAAI,IAAI;EAAI,OAAO,SAAS,IAAI,IAAI;CAAE,EAAE;CAC7E,MAAM,SACJ,UAAU,QAAQ,KAAK,MAAM,MAAM,EAAE,MAAM,QAAQ,CAAC,IAAI,UAAU,UAAU;CAG9E,MAAM,qBAAK,IAAI,IAAoB;CACnC,KAAK,MAAM,QAAQ,YACjB,GAAG,IACD,MACA,UAAU,QAAO,MAAK,EAAE,MAAM,SAAS,IAAI,CAAC,CAAC,CAAC,MAChD;CAGF,MAAM,IAAI,UAAU;CAqBpB,OAnBe,UAAU,KAAI,QAAO;EAClC,MAAM,MAAM,IAAI,MAAM,UAAU;EAChC,IAAI,QAAQ;EAEZ,KAAK,MAAM,QAAQ,YAAY;GAC7B,MAAM,KAAK,IAAI,MAAM,QAAO,MAAK,MAAM,IAAI,CAAC,CAAC;GAC7C,IAAI,OAAO,GAAG;GAEd,MAAM,UAAU,GAAG,IAAI,IAAI,KAAK;GAEhC,MAAM,MAAM,KAAK,IAAI,KAAK,IAAI,UAAU,OAAQ,UAAU,GAAI;GAC9D,MAAM,YAAY,KAAM;GACxB,MAAM,cAAc,KAAK,WAAW,IAAI,SAAS,UAAU,MAAM;GACjE,SAAS,OAAO,YAAY;EAC9B;EAEA,OAAO;GAAE,IAAI,IAAI;GAAI;EAAM;CAC7B,CAEY,CAAC,CAAC,QAAO,SAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,GAAG,MAAM,EAAE,QAAQ,EAAE,KAAK;AAC/E"}
1
+ {"version":3,"file":"bm25.mjs","names":[],"sources":["../../../../../../../../ai/src/rag/hybrid/bm25.ts"],"sourcesContent":["import type { RankedItem } from \"./rrf\";\n\n/** A document to score lexically. */\nexport type LexicalDoc = { id: string; text: string };\n\nconst BM25_K1 = 1.5;\nconst BM25_B = 0.75;\n\n/** Lowercase + split on non-word characters; drop empties. */\nfunction tokenize(text: string): string[] {\n return text\n .toLowerCase()\n .split(/[^a-z0-9]+/i)\n .filter(Boolean);\n}\n\n/**\n * Rank `docs` against `query` with BM25 (A4) — the lexical half of hybrid\n * retrieval. Scores keyword overlap with TF saturation (`k1`) and length\n * normalization (`b`) over the candidate set, so an exact-term match\n * surfaces even when dense embeddings miss it. Returns docs sorted by\n * score (highest first); zero-score docs are dropped.\n *\n * Operates over the supplied candidate set (typically the dense retriever's\n * over-fetch), so it needs no global corpus index — ideal for fusing with\n * a vector ranking via {@link reciprocalRankFusion}.\n */\nexport function bm25Rank(query: string, docs: ReadonlyArray<LexicalDoc>): RankedItem[] {\n const queryTerms = [...new Set(tokenize(query))];\n if (queryTerms.length === 0 || docs.length === 0) return [];\n\n const tokenized = docs.map(doc => ({ id: doc.id, terms: tokenize(doc.text) }));\n const avgLen =\n tokenized.reduce((sum, d) => sum + d.terms.length, 0) / tokenized.length || 1;\n\n // Document frequency per query term, across the candidate set.\n const df = new Map<string, number>();\n for (const term of queryTerms) {\n df.set(\n term,\n tokenized.filter(d => d.terms.includes(term)).length,\n );\n }\n\n const n = tokenized.length;\n\n const scored = tokenized.map(doc => {\n const len = doc.terms.length || 1;\n let score = 0;\n\n for (const term of queryTerms) {\n const tf = doc.terms.filter(t => t === term).length;\n if (tf === 0) continue;\n\n const docFreq = df.get(term) ?? 0;\n // BM25 idf (with the +1 to keep it non-negative).\n const idf = Math.log(1 + (n - docFreq + 0.5) / (docFreq + 0.5));\n const numerator = tf * (BM25_K1 + 1);\n const denominator = tf + BM25_K1 * (1 - BM25_B + BM25_B * (len / avgLen));\n score += idf * (numerator / denominator);\n }\n\n return { id: doc.id, score };\n });\n\n return scored.filter(item => item.score > 0).sort((a, b) => b.score - a.score);\n}\n"],"mappings":";AAKA,MAAM,UAAU;AAChB,MAAM,SAAS;;AAGf,SAAS,SAAS,MAAwB;CACxC,OAAO,KACJ,YAAY,EACZ,MAAM,aAAa,EACnB,OAAO,OAAO;AACnB;;;;;;;;;;;;AAaA,SAAgB,SAAS,OAAe,MAA+C;CACrF,MAAM,aAAa,CAAC,GAAG,IAAI,IAAI,SAAS,KAAK,CAAC,CAAC;CAC/C,IAAI,WAAW,WAAW,KAAK,KAAK,WAAW,GAAG,OAAO,CAAC;CAE1D,MAAM,YAAY,KAAK,KAAI,SAAQ;EAAE,IAAI,IAAI;EAAI,OAAO,SAAS,IAAI,IAAI;CAAE,EAAE;CAC7E,MAAM,SACJ,UAAU,QAAQ,KAAK,MAAM,MAAM,EAAE,MAAM,QAAQ,CAAC,IAAI,UAAU,UAAU;CAG9E,MAAM,qBAAK,IAAI,IAAoB;CACnC,KAAK,MAAM,QAAQ,YACjB,GAAG,IACD,MACA,UAAU,QAAO,MAAK,EAAE,MAAM,SAAS,IAAI,CAAC,EAAE,MAChD;CAGF,MAAM,IAAI,UAAU;CAqBpB,OAnBe,UAAU,KAAI,QAAO;EAClC,MAAM,MAAM,IAAI,MAAM,UAAU;EAChC,IAAI,QAAQ;EAEZ,KAAK,MAAM,QAAQ,YAAY;GAC7B,MAAM,KAAK,IAAI,MAAM,QAAO,MAAK,MAAM,IAAI,EAAE;GAC7C,IAAI,OAAO,GAAG;GAEd,MAAM,UAAU,GAAG,IAAI,IAAI,KAAK;GAEhC,MAAM,MAAM,KAAK,IAAI,KAAK,IAAI,UAAU,OAAQ,UAAU,GAAI;GAC9D,MAAM,YAAY,KAAM;GACxB,MAAM,cAAc,KAAK,WAAW,IAAI,SAAS,UAAU,MAAM;GACjE,SAAS,OAAO,YAAY;EAC9B;EAEA,OAAO;GAAE,IAAI,IAAI;GAAI;EAAM;CAC7B,CAEY,EAAE,QAAO,SAAQ,KAAK,QAAQ,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,QAAQ,EAAE,KAAK;AAC/E"}
@@ -1 +1 @@
1
- {"version":3,"file":"hybrid-rank.mjs","names":[],"sources":["../../../../../../../../ai/src/rag/hybrid/hybrid-rank.ts"],"sourcesContent":["import { bm25Rank, type LexicalDoc } from \"./bm25\";\nimport { reciprocalRankFusion, type RankedItem } from \"./rrf\";\n\n/**\n * Hybrid rank (A4) — fuse a dense (vector) ranking with a BM25 lexical\n * ranking over the same candidate set via Reciprocal Rank Fusion. Dense\n * retrieval captures semantic similarity; BM25 captures exact-term\n * matches dense embeddings miss (names, ids, rare tokens). Fusing both\n * beats either alone for keyword-heavy queries.\n *\n * `dense` is the vector retriever's result in rank order; `candidates`\n * supplies the text for the lexical pass (typically the same over-fetched\n * set). Returns the fused ranking, highest score first.\n *\n * @example\n * const fused = hybridRank({\n * query: \"invoice 8842 refund\",\n * dense: vectorHits, // [{ id }, ...] in similarity order\n * candidates: vectorHits.map(h => ({ id: h.id, text: h.text })),\n * });\n */\nexport function hybridRank(params: {\n query: string;\n dense: ReadonlyArray<{ id: string }>;\n candidates: ReadonlyArray<LexicalDoc>;\n k?: number;\n}): RankedItem[] {\n const denseIds = params.dense.map(d => d.id);\n const lexicalIds = bm25Rank(params.query, params.candidates).map(r => r.id);\n\n return reciprocalRankFusion([denseIds, lexicalIds], params.k);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,WAAW,QAKV;CAIf,OAAO,qBAAqB,CAHX,OAAO,MAAM,KAAI,MAAK,EAAE,EAGL,GAFjB,SAAS,OAAO,OAAO,OAAO,UAAU,CAAC,CAAC,KAAI,MAAK,EAAE,EAExB,CAAC,GAAG,OAAO,CAAC;AAC9D"}
1
+ {"version":3,"file":"hybrid-rank.mjs","names":[],"sources":["../../../../../../../../ai/src/rag/hybrid/hybrid-rank.ts"],"sourcesContent":["import { bm25Rank, type LexicalDoc } from \"./bm25\";\nimport { reciprocalRankFusion, type RankedItem } from \"./rrf\";\n\n/**\n * Hybrid rank (A4) — fuse a dense (vector) ranking with a BM25 lexical\n * ranking over the same candidate set via Reciprocal Rank Fusion. Dense\n * retrieval captures semantic similarity; BM25 captures exact-term\n * matches dense embeddings miss (names, ids, rare tokens). Fusing both\n * beats either alone for keyword-heavy queries.\n *\n * `dense` is the vector retriever's result in rank order; `candidates`\n * supplies the text for the lexical pass (typically the same over-fetched\n * set). Returns the fused ranking, highest score first.\n *\n * @example\n * const fused = hybridRank({\n * query: \"invoice 8842 refund\",\n * dense: vectorHits, // [{ id }, ...] in similarity order\n * candidates: vectorHits.map(h => ({ id: h.id, text: h.text })),\n * });\n */\nexport function hybridRank(params: {\n query: string;\n dense: ReadonlyArray<{ id: string }>;\n candidates: ReadonlyArray<LexicalDoc>;\n k?: number;\n}): RankedItem[] {\n const denseIds = params.dense.map(d => d.id);\n const lexicalIds = bm25Rank(params.query, params.candidates).map(r => r.id);\n\n return reciprocalRankFusion([denseIds, lexicalIds], params.k);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,WAAW,QAKV;CAIf,OAAO,qBAAqB,CAHX,OAAO,MAAM,KAAI,MAAK,EAAE,EAGL,GAFjB,SAAS,OAAO,OAAO,OAAO,UAAU,EAAE,KAAI,MAAK,EAAE,EAExB,CAAC,GAAG,OAAO,CAAC;AAC9D"}
@@ -1 +1 @@
1
- {"version":3,"file":"rrf.mjs","names":[],"sources":["../../../../../../../../ai/src/rag/hybrid/rrf.ts"],"sourcesContent":["/** One item's id paired with a fused relevance score. */\nexport type RankedItem = { id: string; score: number };\n\n/**\n * Reciprocal Rank Fusion (A4) — combine several independently-ranked\n * lists of ids into one consensus ranking. Each list contributes\n * `1 / (k + rank)` to an id's score (rank is 0-based within that list), so\n * an id near the top of multiple lists rises even if no single list ranks\n * it first. The classic fusion for hybrid (dense + lexical) retrieval\n * because it needs no score calibration between the lists.\n *\n * `k` (default 60, the standard) dampens the contribution of lower ranks.\n * Returns ids sorted by fused score, highest first.\n *\n * @example\n * reciprocalRankFusion([[\"a\", \"b\", \"c\"], [\"b\", \"a\"]]);\n * // → [{ id: \"b\", ... }, { id: \"a\", ... }, { id: \"c\", ... }]\n */\nexport function reciprocalRankFusion(\n rankedLists: ReadonlyArray<ReadonlyArray<string>>,\n k = 60,\n): RankedItem[] {\n const scores = new Map<string, number>();\n\n for (const list of rankedLists) {\n list.forEach((id, rank) => {\n scores.set(id, (scores.get(id) ?? 0) + 1 / (k + rank));\n });\n }\n\n return [...scores.entries()]\n .map(([id, score]) => ({ id, score }))\n .sort((a, b) => b.score - a.score);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkBA,SAAgB,qBACd,aACA,IAAI,IACU;CACd,MAAM,yBAAS,IAAI,IAAoB;CAEvC,KAAK,MAAM,QAAQ,aACjB,KAAK,SAAS,IAAI,SAAS;EACzB,OAAO,IAAI,KAAK,OAAO,IAAI,EAAE,KAAK,KAAK,KAAK,IAAI,KAAK;CACvD,CAAC;CAGH,OAAO,CAAC,GAAG,OAAO,QAAQ,CAAC,CAAC,CACzB,KAAK,CAAC,IAAI,YAAY;EAAE;EAAI;CAAM,EAAE,CAAC,CACrC,MAAM,GAAG,MAAM,EAAE,QAAQ,EAAE,KAAK;AACrC"}
1
+ {"version":3,"file":"rrf.mjs","names":[],"sources":["../../../../../../../../ai/src/rag/hybrid/rrf.ts"],"sourcesContent":["/** One item's id paired with a fused relevance score. */\nexport type RankedItem = { id: string; score: number };\n\n/**\n * Reciprocal Rank Fusion (A4) — combine several independently-ranked\n * lists of ids into one consensus ranking. Each list contributes\n * `1 / (k + rank)` to an id's score (rank is 0-based within that list), so\n * an id near the top of multiple lists rises even if no single list ranks\n * it first. The classic fusion for hybrid (dense + lexical) retrieval\n * because it needs no score calibration between the lists.\n *\n * `k` (default 60, the standard) dampens the contribution of lower ranks.\n * Returns ids sorted by fused score, highest first.\n *\n * @example\n * reciprocalRankFusion([[\"a\", \"b\", \"c\"], [\"b\", \"a\"]]);\n * // → [{ id: \"b\", ... }, { id: \"a\", ... }, { id: \"c\", ... }]\n */\nexport function reciprocalRankFusion(\n rankedLists: ReadonlyArray<ReadonlyArray<string>>,\n k = 60,\n): RankedItem[] {\n const scores = new Map<string, number>();\n\n for (const list of rankedLists) {\n list.forEach((id, rank) => {\n scores.set(id, (scores.get(id) ?? 0) + 1 / (k + rank));\n });\n }\n\n return [...scores.entries()]\n .map(([id, score]) => ({ id, score }))\n .sort((a, b) => b.score - a.score);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkBA,SAAgB,qBACd,aACA,IAAI,IACU;CACd,MAAM,yBAAS,IAAI,IAAoB;CAEvC,KAAK,MAAM,QAAQ,aACjB,KAAK,SAAS,IAAI,SAAS;EACzB,OAAO,IAAI,KAAK,OAAO,IAAI,EAAE,KAAK,KAAK,KAAK,IAAI,KAAK;CACvD,CAAC;CAGH,OAAO,CAAC,GAAG,OAAO,QAAQ,CAAC,EACxB,KAAK,CAAC,IAAI,YAAY;EAAE;EAAI;CAAM,EAAE,EACpC,MAAM,GAAG,MAAM,EAAE,QAAQ,EAAE,KAAK;AACrC"}
@@ -1 +1 @@
1
- {"version":3,"file":"load-html.mjs","names":[],"sources":["../../../../../../../../ai/src/rag/loaders/load-html.ts"],"sourcesContent":["import type { RagDocument } from \"../contracts/rag-document.type\";\nimport type { LoadHtmlOptions, RagLoaderResult } from \"./loader.type\";\n\n/** Default `id` when the caller supplies none. */\nconst DEFAULT_ID = \"document\";\n\n/**\n * Elements whose *content* is not human-readable text and must be removed\n * wholesale (open tag → close tag → everything in between) before tags are\n * stripped. `script` / `style` would otherwise leak code into the chunked\n * text; `noscript` / `template` / `head` / `svg` are non-prose noise.\n */\nconst STRIPPED_ELEMENTS = [\n \"script\",\n \"style\",\n \"noscript\",\n \"template\",\n \"head\",\n \"svg\",\n];\n\n/**\n * Block-level tags that imply a line break in the readable text. Replacing\n * them with `\\n` BEFORE the generic tag strip keeps paragraph / list / table\n * structure (so the recursive splitter still sees `\\n\\n` boundaries) instead\n * of collapsing the whole page onto one line.\n */\nconst BLOCK_TAGS =\n /<\\/?(?:p|div|section|article|header|footer|main|aside|nav|h[1-6]|ul|ol|li|table|tr|td|th|thead|tbody|blockquote|pre|hr|br)\\b[^>]*>/gi;\n\n/** Named HTML entities common in prose. Numeric entities are decoded generically. */\nconst NAMED_ENTITIES: Record<string, string> = {\n amp: \"&\",\n lt: \"<\",\n gt: \">\",\n quot: '\"',\n apos: \"'\",\n nbsp: \" \",\n copy: \"©\",\n reg: \"®\",\n trade: \"™\",\n hellip: \"…\",\n mdash: \"—\",\n ndash: \"–\",\n lsquo: \"‘\",\n rsquo: \"’\",\n ldquo: \"“\",\n rdquo: \"”\",\n laquo: \"«\",\n raquo: \"»\",\n middot: \"·\",\n bull: \"•\",\n};\n\n/**\n * Decode the HTML entities that survive tag stripping: named (`&amp;`),\n * decimal (`&#169;`), and hex (`&#xA9;`). Unknown named entities are left\n * verbatim rather than dropped, so unusual markup never silently loses text.\n */\nfunction decodeEntities(text: string): string {\n return text.replace(/&(#x?[0-9a-f]+|[a-z][a-z0-9]*);/gi, (match, body: string) => {\n if (body[0] === \"#\") {\n const codePoint =\n body[1] === \"x\" || body[1] === \"X\"\n ? Number.parseInt(body.slice(2), 16)\n : Number.parseInt(body.slice(1), 10);\n\n if (Number.isNaN(codePoint) || codePoint < 0 || codePoint > 0x10ffff) {\n return match;\n }\n\n try {\n return String.fromCodePoint(codePoint);\n } catch {\n return match;\n }\n }\n\n const named = NAMED_ENTITIES[body.toLowerCase()];\n\n return named ?? match;\n });\n}\n\n/**\n * Pull the `<title>` text out of the document, decoded and trimmed, or\n * `undefined` when there is none. Read BEFORE `<head>` is stripped.\n */\nfunction extractTitle(html: string): string | undefined {\n const match = /<title[^>]*>([\\s\\S]*?)<\\/title>/i.exec(html);\n\n if (!match) {\n return undefined;\n }\n\n const title = decodeEntities(match[1]).replace(/\\s+/g, \" \").trim();\n\n return title.length > 0 ? title : undefined;\n}\n\n/**\n * Strip HTML markup down to readable plain text — a lightweight,\n * dependency-free pass (no DOM parser): drop comments and non-prose elements\n * (`script` / `style` / `head` / `svg` / …) content-and-all, convert block\n * tags to line breaks to preserve paragraph structure, remove every\n * remaining tag, decode entities, then collapse runs of whitespace while\n * keeping blank-line paragraph separators.\n */\nfunction htmlToText(html: string): string {\n let text = html;\n\n // 1. Comments first — a commented-out `<script>` must not survive.\n text = text.replace(/<!--[\\s\\S]*?-->/g, \" \");\n\n // 2. Non-prose elements, content and all.\n for (const tag of STRIPPED_ELEMENTS) {\n const element = new RegExp(`<${tag}\\\\b[^>]*>[\\\\s\\\\S]*?<\\\\/${tag}>`, \"gi\");\n text = text.replace(element, \" \");\n // Defensively drop a self-closing / unterminated open tag too.\n text = text.replace(new RegExp(`<\\\\/?${tag}\\\\b[^>]*>`, \"gi\"), \" \");\n }\n\n // 3. Block tags → newlines, so paragraph / list structure survives.\n text = text.replace(BLOCK_TAGS, \"\\n\");\n\n // 4. Every remaining tag → gone.\n text = text.replace(/<[^>]+>/g, \"\");\n\n // 5. Entities → characters.\n text = decodeEntities(text);\n\n // 6. Normalize whitespace: trim each line, drop blank runs to a single\n // blank line (a paragraph separator the recursive splitter honors).\n text = text\n .replace(/[^\\S\\n]+/g, \" \")\n .replace(/[ \\t]*\\n[ \\t]*/g, \"\\n\")\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .trim();\n\n return text;\n}\n\n/**\n * Load an HTML string into a single {@link RagDocument} of readable text.\n * Scripts, styles, and other non-prose elements are dropped content-and-all,\n * block tags become line breaks (so paragraph structure survives for the\n * splitter), remaining tags are stripped, and HTML entities are decoded — a\n * lightweight regex pass, no heavy DOM dependency.\n *\n * The document's `metadata.title` is set from the page's `<title>` (unless\n * the caller overrode it), and `metadata.loader` is `\"html\"`. The output is\n * the exact shape `index()` consumes.\n *\n * @example\n * const kb = ai.rag({ embedder, store });\n * await kb.index(loadHtml(rawHtmlString, { id: \"landing-page\" }));\n *\n * @param html - The raw HTML markup.\n * @param options - Shared `id` / `metadata` / `tags` ({@link LoadHtmlOptions}).\n * @returns A {@link RagLoaderResult} (one document) ready for `rag.index()`.\n */\nexport function loadHtml(\n html: string,\n options: LoadHtmlOptions = {},\n): RagLoaderResult {\n const id = options.id ?? DEFAULT_ID;\n const title = extractTitle(html);\n const text = htmlToText(html);\n\n // An all-markup / empty page strips to nothing; emit no document so\n // index() never receives a no-op record (matches loadText's behavior).\n if (text.length === 0) {\n return [];\n }\n\n // Derived keys (source, loader, title) sit UNDER the caller's metadata so\n // an explicit override always wins.\n const doc: RagDocument = {\n id,\n text,\n metadata: {\n source: id,\n loader: \"html\",\n ...(title !== undefined ? { title } : {}),\n ...options.metadata,\n },\n tags: options.tags,\n };\n\n return [doc];\n}\n\n/** Internal — exported for the web loader so it shares the exact strip pass. */\nexport { htmlToText, extractTitle };\n"],"mappings":";;AAIA,MAAM,aAAa;;;;;;;AAQnB,MAAM,oBAAoB;CACxB;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;AAQA,MAAM,aACJ;;AAGF,MAAM,iBAAyC;CAC7C,KAAK;CACL,IAAI;CACJ,IAAI;CACJ,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACN,KAAK;CACL,OAAO;CACP,QAAQ;CACR,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,QAAQ;CACR,MAAM;AACR;;;;;;AAOA,SAAS,eAAe,MAAsB;CAC5C,OAAO,KAAK,QAAQ,sCAAsC,OAAO,SAAiB;EAChF,IAAI,KAAK,OAAO,KAAK;GACnB,MAAM,YACJ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I;CAC/B,MAAM,OAAO,WAAW,IAAI;CAI5B,IAAI,KAAK,WAAW,GAClB,OAAO,CAAC;CAiBV,OAAO,CAAC;EAXN;EACA;EACA,UAAU;GACR,QAAQ;GACR,QAAQ;GACR,GAAI,UAAU,SAAY,EAAE,MAAM,IAAI,CAAC;GACvC,GAAG,QAAQ;EACb;EACA,MAAM,QAAQ;CAGN,CAAC;AACb"}
1
+ {"version":3,"file":"load-html.mjs","names":[],"sources":["../../../../../../../../ai/src/rag/loaders/load-html.ts"],"sourcesContent":["import type { RagDocument } from \"../contracts/rag-document.type\";\nimport type { LoadHtmlOptions, RagLoaderResult } from \"./loader.type\";\n\n/** Default `id` when the caller supplies none. */\nconst DEFAULT_ID = \"document\";\n\n/**\n * Elements whose *content* is not human-readable text and must be removed\n * wholesale (open tag → close tag → everything in between) before tags are\n * stripped. `script` / `style` would otherwise leak code into the chunked\n * text; `noscript` / `template` / `head` / `svg` are non-prose noise.\n */\nconst STRIPPED_ELEMENTS = [\n \"script\",\n \"style\",\n \"noscript\",\n \"template\",\n \"head\",\n \"svg\",\n];\n\n/**\n * Block-level tags that imply a line break in the readable text. Replacing\n * them with `\\n` BEFORE the generic tag strip keeps paragraph / list / table\n * structure (so the recursive splitter still sees `\\n\\n` boundaries) instead\n * of collapsing the whole page onto one line.\n */\nconst BLOCK_TAGS =\n /<\\/?(?:p|div|section|article|header|footer|main|aside|nav|h[1-6]|ul|ol|li|table|tr|td|th|thead|tbody|blockquote|pre|hr|br)\\b[^>]*>/gi;\n\n/** Named HTML entities common in prose. Numeric entities are decoded generically. */\nconst NAMED_ENTITIES: Record<string, string> = {\n amp: \"&\",\n lt: \"<\",\n gt: \">\",\n quot: '\"',\n apos: \"'\",\n nbsp: \" \",\n copy: \"©\",\n reg: \"®\",\n trade: \"™\",\n hellip: \"…\",\n mdash: \"—\",\n ndash: \"–\",\n lsquo: \"‘\",\n rsquo: \"’\",\n ldquo: \"“\",\n rdquo: \"”\",\n laquo: \"«\",\n raquo: \"»\",\n middot: \"·\",\n bull: \"•\",\n};\n\n/**\n * Decode the HTML entities that survive tag stripping: named (`&amp;`),\n * decimal (`&#169;`), and hex (`&#xA9;`). Unknown named entities are left\n * verbatim rather than dropped, so unusual markup never silently loses text.\n */\nfunction decodeEntities(text: string): string {\n return text.replace(/&(#x?[0-9a-f]+|[a-z][a-z0-9]*);/gi, (match, body: string) => {\n if (body[0] === \"#\") {\n const codePoint =\n body[1] === \"x\" || body[1] === \"X\"\n ? Number.parseInt(body.slice(2), 16)\n : Number.parseInt(body.slice(1), 10);\n\n if (Number.isNaN(codePoint) || codePoint < 0 || codePoint > 0x10ffff) {\n return match;\n }\n\n try {\n return String.fromCodePoint(codePoint);\n } catch {\n return match;\n }\n }\n\n const named = NAMED_ENTITIES[body.toLowerCase()];\n\n return named ?? match;\n });\n}\n\n/**\n * Pull the `<title>` text out of the document, decoded and trimmed, or\n * `undefined` when there is none. Read BEFORE `<head>` is stripped.\n */\nfunction extractTitle(html: string): string | undefined {\n const match = /<title[^>]*>([\\s\\S]*?)<\\/title>/i.exec(html);\n\n if (!match) {\n return undefined;\n }\n\n const title = decodeEntities(match[1]).replace(/\\s+/g, \" \").trim();\n\n return title.length > 0 ? title : undefined;\n}\n\n/**\n * Strip HTML markup down to readable plain text — a lightweight,\n * dependency-free pass (no DOM parser): drop comments and non-prose elements\n * (`script` / `style` / `head` / `svg` / …) content-and-all, convert block\n * tags to line breaks to preserve paragraph structure, remove every\n * remaining tag, decode entities, then collapse runs of whitespace while\n * keeping blank-line paragraph separators.\n */\nfunction htmlToText(html: string): string {\n let text = html;\n\n // 1. Comments first — a commented-out `<script>` must not survive.\n text = text.replace(/<!--[\\s\\S]*?-->/g, \" \");\n\n // 2. Non-prose elements, content and all.\n for (const tag of STRIPPED_ELEMENTS) {\n const element = new RegExp(`<${tag}\\\\b[^>]*>[\\\\s\\\\S]*?<\\\\/${tag}>`, \"gi\");\n text = text.replace(element, \" \");\n // Defensively drop a self-closing / unterminated open tag too.\n text = text.replace(new RegExp(`<\\\\/?${tag}\\\\b[^>]*>`, \"gi\"), \" \");\n }\n\n // 3. Block tags → newlines, so paragraph / list structure survives.\n text = text.replace(BLOCK_TAGS, \"\\n\");\n\n // 4. Every remaining tag → gone.\n text = text.replace(/<[^>]+>/g, \"\");\n\n // 5. Entities → characters.\n text = decodeEntities(text);\n\n // 6. Normalize whitespace: trim each line, drop blank runs to a single\n // blank line (a paragraph separator the recursive splitter honors).\n text = text\n .replace(/[^\\S\\n]+/g, \" \")\n .replace(/[ \\t]*\\n[ \\t]*/g, \"\\n\")\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .trim();\n\n return text;\n}\n\n/**\n * Load an HTML string into a single {@link RagDocument} of readable text.\n * Scripts, styles, and other non-prose elements are dropped content-and-all,\n * block tags become line breaks (so paragraph structure survives for the\n * splitter), remaining tags are stripped, and HTML entities are decoded — a\n * lightweight regex pass, no heavy DOM dependency.\n *\n * The document's `metadata.title` is set from the page's `<title>` (unless\n * the caller overrode it), and `metadata.loader` is `\"html\"`. The output is\n * the exact shape `index()` consumes.\n *\n * @example\n * const kb = ai.rag({ embedder, store });\n * await kb.index(loadHtml(rawHtmlString, { id: \"landing-page\" }));\n *\n * @param html - The raw HTML markup.\n * @param options - Shared `id` / `metadata` / `tags` ({@link LoadHtmlOptions}).\n * @returns A {@link RagLoaderResult} (one document) ready for `rag.index()`.\n */\nexport function loadHtml(\n html: string,\n options: LoadHtmlOptions = {},\n): RagLoaderResult {\n const id = options.id ?? DEFAULT_ID;\n const title = extractTitle(html);\n const text = htmlToText(html);\n\n // An all-markup / empty page strips to nothing; emit no document so\n // index() never receives a no-op record (matches loadText's behavior).\n if (text.length === 0) {\n return [];\n }\n\n // Derived keys (source, loader, title) sit UNDER the caller's metadata so\n // an explicit override always wins.\n const doc: RagDocument = {\n id,\n text,\n metadata: {\n source: id,\n loader: \"html\",\n ...(title !== undefined ? { title } : {}),\n ...options.metadata,\n },\n tags: options.tags,\n };\n\n return [doc];\n}\n\n/** Internal — exported for the web loader so it shares the exact strip pass. */\nexport { htmlToText, extractTitle };\n"],"mappings":";;AAIA,MAAM,aAAa;;;;;;;AAQnB,MAAM,oBAAoB;CACxB;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;AAQA,MAAM,aACJ;;AAGF,MAAM,iBAAyC;CAC7C,KAAK;CACL,IAAI;CACJ,IAAI;CACJ,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACN,KAAK;CACL,OAAO;CACP,QAAQ;CACR,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,QAAQ;CACR,MAAM;AACR;;;;;;AAOA,SAAS,eAAe,MAAsB;CAC5C,OAAO,KAAK,QAAQ,sCAAsC,OAAO,SAAiB;EAChF,IAAI,KAAK,OAAO,KAAK;GACnB,MAAM,YACJ,KAAK,OAAO,OAAO,KAAK,OAAO,MAC3B,OAAO,SAAS,KAAK,MAAM,CAAC,GAAG,EAAE,IACjC,OAAO,SAAS,KAAK,MAAM,CAAC,GAAG,EAAE;GAEvC,IAAI,OAAO,MAAM,SAAS,KAAK,YAAY,KAAK,YAAY,SAC1D,OAAO;GAGT,IAAI;IACF,OAAO,OAAO,cAAc,SAAS;GACvC,QAAQ;IACN,OAAO;GACT;EACF;EAIA,OAFc,eAAe,KAAK,YAAY,MAE9B;CAClB,CAAC;AACH;;;;;AAMA,SAAS,aAAa,MAAkC;CACtD,MAAM,QAAQ,mCAAmC,KAAK,IAAI;CAE1D,IAAI,CAAC,OACH;CAGF,MAAM,QAAQ,eAAe,MAAM,EAAE,EAAE,QAAQ,QAAQ,GAAG,EAAE,KAAK;CAEjE,OAAO,MAAM,SAAS,IAAI,QAAQ;AACpC;;;;;;;;;AAUA,SAAS,WAAW,MAAsB;CACxC,IAAI,OAAO;CAGX,OAAO,KAAK,QAAQ,oBAAoB,GAAG;CAG3C,KAAK,MAAM,OAAO,mBAAmB;EACnC,MAAM,UAAU,IAAI,OAAO,IAAI,IAAI,yBAAyB,IAAI,IAAI,IAAI;EACxE,OAAO,KAAK,QAAQ,SAAS,GAAG;EAEhC,OAAO,KAAK,QAAQ,IAAI,OAAO,QAAQ,IAAI,YAAY,IAAI,GAAG,GAAG;CACnE;CAGA,OAAO,KAAK,QAAQ,YAAY,IAAI;CAGpC,OAAO,KAAK,QAAQ,YAAY,EAAE;CAGlC,OAAO,eAAe,IAAI;CAI1B,OAAO,KACJ,QAAQ,aAAa,GAAG,EACxB,QAAQ,mBAAmB,IAAI,EAC/B,QAAQ,WAAW,MAAM,EACzB,KAAK;CAER,OAAO;AACT;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,SACd,MACA,UAA2B,CAAC,GACX;CACjB,MAAM,KAAK,QAAQ,MAAM;CACzB,MAAM,QAAQ,aAAa,IAAI;CAC/B,MAAM,OAAO,WAAW,IAAI;CAI5B,IAAI,KAAK,WAAW,GAClB,OAAO,CAAC;CAiBV,OAAO,CAAC;EAXN;EACA;EACA,UAAU;GACR,QAAQ;GACR,QAAQ;GACR,GAAI,UAAU,SAAY,EAAE,MAAM,IAAI,CAAC;GACvC,GAAG,QAAQ;EACb;EACA,MAAM,QAAQ;CAGN,CAAC;AACb"}
@@ -1 +1 @@
1
- {"version":3,"file":"load-pdf.d.mts","names":[],"sources":["../../../../../../../../ai/src/rag/loaders/load-pdf.ts"],"mappings":";;;;;AA8HA;;;;;;;;;;;;;;;;;;;;AAG0B;;;;;;;;;iBAHJ,OAAA,CACpB,KAAA,EAAO,MAAA,GAAS,WAAA,GAAc,UAAA,EAC9B,OAAA,GAAS,cAAA,GACR,OAAA,CAAQ,eAAA"}
1
+ {"version":3,"file":"load-pdf.d.mts","names":[],"sources":["../../../../../../../../ai/src/rag/loaders/load-pdf.ts"],"mappings":";;;;;AAkIA;;;;;;;;;;;;;;;;;;;;AAG0B;;;;;;;;;iBAHJ,OAAA,CACpB,KAAA,EAAO,MAAA,GAAS,WAAA,GAAc,UAAA,EAC9B,OAAA,GAAS,cAAA,GACR,OAAA,CAAQ,eAAA"}