@caupulican/pi-adaptative 0.80.85 → 0.80.88

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 (340) hide show
  1. package/CHANGELOG.md +160 -1
  2. package/dist/core/agent-session.d.ts +394 -1
  3. package/dist/core/agent-session.d.ts.map +1 -1
  4. package/dist/core/agent-session.js +1862 -46
  5. package/dist/core/agent-session.js.map +1 -1
  6. package/dist/core/autonomy/approval-gate.d.ts +4 -0
  7. package/dist/core/autonomy/approval-gate.d.ts.map +1 -0
  8. package/dist/core/autonomy/approval-gate.js +27 -0
  9. package/dist/core/autonomy/approval-gate.js.map +1 -0
  10. package/dist/core/autonomy/bounded-completion.d.ts +27 -0
  11. package/dist/core/autonomy/bounded-completion.d.ts.map +1 -0
  12. package/dist/core/autonomy/bounded-completion.js +44 -0
  13. package/dist/core/autonomy/bounded-completion.js.map +1 -0
  14. package/dist/core/autonomy/contracts.d.ts +129 -0
  15. package/dist/core/autonomy/contracts.d.ts.map +1 -0
  16. package/dist/core/autonomy/contracts.js +2 -0
  17. package/dist/core/autonomy/contracts.js.map +1 -0
  18. package/dist/core/autonomy/gates.d.ts +15 -0
  19. package/dist/core/autonomy/gates.d.ts.map +1 -0
  20. package/dist/core/autonomy/gates.js +205 -0
  21. package/dist/core/autonomy/gates.js.map +1 -0
  22. package/dist/core/autonomy/lane-tracker.d.ts +48 -0
  23. package/dist/core/autonomy/lane-tracker.d.ts.map +1 -0
  24. package/dist/core/autonomy/lane-tracker.js +125 -0
  25. package/dist/core/autonomy/lane-tracker.js.map +1 -0
  26. package/dist/core/autonomy/path-scope.d.ts +9 -0
  27. package/dist/core/autonomy/path-scope.d.ts.map +1 -0
  28. package/dist/core/autonomy/path-scope.js +122 -0
  29. package/dist/core/autonomy/path-scope.js.map +1 -0
  30. package/dist/core/autonomy/risk-assessment.d.ts +3 -0
  31. package/dist/core/autonomy/risk-assessment.d.ts.map +1 -0
  32. package/dist/core/autonomy/risk-assessment.js +122 -0
  33. package/dist/core/autonomy/risk-assessment.js.map +1 -0
  34. package/dist/core/autonomy/session-lane-record.d.ts +10 -0
  35. package/dist/core/autonomy/session-lane-record.d.ts.map +1 -0
  36. package/dist/core/autonomy/session-lane-record.js +36 -0
  37. package/dist/core/autonomy/session-lane-record.js.map +1 -0
  38. package/dist/core/autonomy/status.d.ts +40 -0
  39. package/dist/core/autonomy/status.d.ts.map +1 -0
  40. package/dist/core/autonomy/status.js +107 -0
  41. package/dist/core/autonomy/status.js.map +1 -0
  42. package/dist/core/autonomy/subagent-prompt.d.ts +21 -0
  43. package/dist/core/autonomy/subagent-prompt.d.ts.map +1 -0
  44. package/dist/core/autonomy/subagent-prompt.js +28 -0
  45. package/dist/core/autonomy/subagent-prompt.js.map +1 -0
  46. package/dist/core/autonomy/telemetry-events.d.ts +18 -0
  47. package/dist/core/autonomy/telemetry-events.d.ts.map +1 -0
  48. package/dist/core/autonomy/telemetry-events.js +60 -0
  49. package/dist/core/autonomy/telemetry-events.js.map +1 -0
  50. package/dist/core/context/artifact-retrieval.d.ts +49 -0
  51. package/dist/core/context/artifact-retrieval.d.ts.map +1 -0
  52. package/dist/core/context/artifact-retrieval.js +49 -0
  53. package/dist/core/context/artifact-retrieval.js.map +1 -0
  54. package/dist/core/context/context-artifacts.d.ts +94 -0
  55. package/dist/core/context/context-artifacts.d.ts.map +1 -0
  56. package/dist/core/context/context-artifacts.js +307 -0
  57. package/dist/core/context/context-artifacts.js.map +1 -0
  58. package/dist/core/context/context-audit.d.ts +66 -0
  59. package/dist/core/context/context-audit.d.ts.map +1 -0
  60. package/dist/core/context/context-audit.js +173 -0
  61. package/dist/core/context/context-audit.js.map +1 -0
  62. package/dist/core/context/context-item.d.ts +117 -0
  63. package/dist/core/context/context-item.d.ts.map +1 -0
  64. package/dist/core/context/context-item.js +36 -0
  65. package/dist/core/context/context-item.js.map +1 -0
  66. package/dist/core/context/context-prompt-enforcement.d.ts +73 -0
  67. package/dist/core/context/context-prompt-enforcement.d.ts.map +1 -0
  68. package/dist/core/context/context-prompt-enforcement.js +153 -0
  69. package/dist/core/context/context-prompt-enforcement.js.map +1 -0
  70. package/dist/core/context/context-prompt-policy.d.ts +90 -0
  71. package/dist/core/context/context-prompt-policy.d.ts.map +1 -0
  72. package/dist/core/context/context-prompt-policy.js +73 -0
  73. package/dist/core/context/context-prompt-policy.js.map +1 -0
  74. package/dist/core/context/context-retention.d.ts +36 -0
  75. package/dist/core/context/context-retention.d.ts.map +1 -0
  76. package/dist/core/context/context-retention.js +108 -0
  77. package/dist/core/context/context-retention.js.map +1 -0
  78. package/dist/core/context/context-store.d.ts +37 -0
  79. package/dist/core/context/context-store.d.ts.map +1 -0
  80. package/dist/core/context/context-store.js +45 -0
  81. package/dist/core/context/context-store.js.map +1 -0
  82. package/dist/core/context/memory-diagnostics.d.ts +50 -0
  83. package/dist/core/context/memory-diagnostics.d.ts.map +1 -0
  84. package/dist/core/context/memory-diagnostics.js +43 -0
  85. package/dist/core/context/memory-diagnostics.js.map +1 -0
  86. package/dist/core/context/memory-index-store.d.ts +28 -0
  87. package/dist/core/context/memory-index-store.d.ts.map +1 -0
  88. package/dist/core/context/memory-index-store.js +38 -0
  89. package/dist/core/context/memory-index-store.js.map +1 -0
  90. package/dist/core/context/memory-prompt-block.d.ts +34 -0
  91. package/dist/core/context/memory-prompt-block.d.ts.map +1 -0
  92. package/dist/core/context/memory-prompt-block.js +58 -0
  93. package/dist/core/context/memory-prompt-block.js.map +1 -0
  94. package/dist/core/context/memory-provider-contract.d.ts +114 -0
  95. package/dist/core/context/memory-provider-contract.d.ts.map +1 -0
  96. package/dist/core/context/memory-provider-contract.js +121 -0
  97. package/dist/core/context/memory-provider-contract.js.map +1 -0
  98. package/dist/core/context/memory-retrieval.d.ts +27 -0
  99. package/dist/core/context/memory-retrieval.d.ts.map +1 -0
  100. package/dist/core/context/memory-retrieval.js +91 -0
  101. package/dist/core/context/memory-retrieval.js.map +1 -0
  102. package/dist/core/context/okf-memory-provider.d.ts +26 -0
  103. package/dist/core/context/okf-memory-provider.d.ts.map +1 -0
  104. package/dist/core/context/okf-memory-provider.js +154 -0
  105. package/dist/core/context/okf-memory-provider.js.map +1 -0
  106. package/dist/core/context/okf-memory.d.ts +42 -0
  107. package/dist/core/context/okf-memory.d.ts.map +1 -0
  108. package/dist/core/context/okf-memory.js +175 -0
  109. package/dist/core/context/okf-memory.js.map +1 -0
  110. package/dist/core/context/policy-engine.d.ts +66 -0
  111. package/dist/core/context/policy-engine.d.ts.map +1 -0
  112. package/dist/core/context/policy-engine.js +171 -0
  113. package/dist/core/context/policy-engine.js.map +1 -0
  114. package/dist/core/context/policy-types.d.ts +102 -0
  115. package/dist/core/context/policy-types.d.ts.map +1 -0
  116. package/dist/core/context/policy-types.js +7 -0
  117. package/dist/core/context/policy-types.js.map +1 -0
  118. package/dist/core/context/sqlite-runtime-index.d.ts +19 -0
  119. package/dist/core/context/sqlite-runtime-index.d.ts.map +1 -0
  120. package/dist/core/context/sqlite-runtime-index.js +344 -0
  121. package/dist/core/context/sqlite-runtime-index.js.map +1 -0
  122. package/dist/core/context/storage-authority.d.ts +20 -0
  123. package/dist/core/context/storage-authority.d.ts.map +1 -0
  124. package/dist/core/context/storage-authority.js +51 -0
  125. package/dist/core/context/storage-authority.js.map +1 -0
  126. package/dist/core/context/tool-output-packer.d.ts +75 -0
  127. package/dist/core/context/tool-output-packer.d.ts.map +1 -0
  128. package/dist/core/context/tool-output-packer.js +77 -0
  129. package/dist/core/context/tool-output-packer.js.map +1 -0
  130. package/dist/core/cost/session-usage.d.ts +20 -0
  131. package/dist/core/cost/session-usage.d.ts.map +1 -0
  132. package/dist/core/cost/session-usage.js +164 -0
  133. package/dist/core/cost/session-usage.js.map +1 -0
  134. package/dist/core/delegation/session-worker-result.d.ts +10 -0
  135. package/dist/core/delegation/session-worker-result.d.ts.map +1 -0
  136. package/dist/core/delegation/session-worker-result.js +36 -0
  137. package/dist/core/delegation/session-worker-result.js.map +1 -0
  138. package/dist/core/delegation/worker-result.d.ts +9 -0
  139. package/dist/core/delegation/worker-result.d.ts.map +1 -0
  140. package/dist/core/delegation/worker-result.js +152 -0
  141. package/dist/core/delegation/worker-result.js.map +1 -0
  142. package/dist/core/delegation/worker-runner.d.ts +58 -0
  143. package/dist/core/delegation/worker-runner.d.ts.map +1 -0
  144. package/dist/core/delegation/worker-runner.js +188 -0
  145. package/dist/core/delegation/worker-runner.js.map +1 -0
  146. package/dist/core/extensions/builtin.d.ts +5 -1
  147. package/dist/core/extensions/builtin.d.ts.map +1 -1
  148. package/dist/core/extensions/builtin.js +23 -1
  149. package/dist/core/extensions/builtin.js.map +1 -1
  150. package/dist/core/footer-data-provider.d.ts +5 -1
  151. package/dist/core/footer-data-provider.d.ts.map +1 -1
  152. package/dist/core/footer-data-provider.js +13 -0
  153. package/dist/core/footer-data-provider.js.map +1 -1
  154. package/dist/core/goals/goal-continuation-controller.d.ts +22 -0
  155. package/dist/core/goals/goal-continuation-controller.d.ts.map +1 -0
  156. package/dist/core/goals/goal-continuation-controller.js +88 -0
  157. package/dist/core/goals/goal-continuation-controller.js.map +1 -0
  158. package/dist/core/goals/goal-continuation-defaults.d.ts +10 -0
  159. package/dist/core/goals/goal-continuation-defaults.d.ts.map +1 -0
  160. package/dist/core/goals/goal-continuation-defaults.js +10 -0
  161. package/dist/core/goals/goal-continuation-defaults.js.map +1 -0
  162. package/dist/core/goals/goal-continuation-prompt.d.ts +18 -0
  163. package/dist/core/goals/goal-continuation-prompt.d.ts.map +1 -0
  164. package/dist/core/goals/goal-continuation-prompt.js +141 -0
  165. package/dist/core/goals/goal-continuation-prompt.js.map +1 -0
  166. package/dist/core/goals/goal-runtime-snapshot.d.ts +19 -0
  167. package/dist/core/goals/goal-runtime-snapshot.d.ts.map +1 -0
  168. package/dist/core/goals/goal-runtime-snapshot.js +23 -0
  169. package/dist/core/goals/goal-runtime-snapshot.js.map +1 -0
  170. package/dist/core/goals/goal-state.d.ts +87 -0
  171. package/dist/core/goals/goal-state.d.ts.map +1 -0
  172. package/dist/core/goals/goal-state.js +259 -0
  173. package/dist/core/goals/goal-state.js.map +1 -0
  174. package/dist/core/goals/goal-tool-core.d.ts +66 -0
  175. package/dist/core/goals/goal-tool-core.d.ts.map +1 -0
  176. package/dist/core/goals/goal-tool-core.js +146 -0
  177. package/dist/core/goals/goal-tool-core.js.map +1 -0
  178. package/dist/core/goals/session-goal-state.d.ts +10 -0
  179. package/dist/core/goals/session-goal-state.d.ts.map +1 -0
  180. package/dist/core/goals/session-goal-state.js +35 -0
  181. package/dist/core/goals/session-goal-state.js.map +1 -0
  182. package/dist/core/learning/learning-audit.d.ts +45 -0
  183. package/dist/core/learning/learning-audit.d.ts.map +1 -0
  184. package/dist/core/learning/learning-audit.js +139 -0
  185. package/dist/core/learning/learning-audit.js.map +1 -0
  186. package/dist/core/learning/learning-gate.d.ts +29 -0
  187. package/dist/core/learning/learning-gate.d.ts.map +1 -0
  188. package/dist/core/learning/learning-gate.js +150 -0
  189. package/dist/core/learning/learning-gate.js.map +1 -0
  190. package/dist/core/learning/session-learning-decision.d.ts +10 -0
  191. package/dist/core/learning/session-learning-decision.d.ts.map +1 -0
  192. package/dist/core/learning/session-learning-decision.js +36 -0
  193. package/dist/core/learning/session-learning-decision.js.map +1 -0
  194. package/dist/core/model-capability.d.ts +41 -0
  195. package/dist/core/model-capability.d.ts.map +1 -0
  196. package/dist/core/model-capability.js +101 -0
  197. package/dist/core/model-capability.js.map +1 -0
  198. package/dist/core/model-router/config-diagnostics.d.ts.map +1 -1
  199. package/dist/core/model-router/config-diagnostics.js +1 -0
  200. package/dist/core/model-router/config-diagnostics.js.map +1 -1
  201. package/dist/core/model-router/intent-classifier.d.ts +2 -0
  202. package/dist/core/model-router/intent-classifier.d.ts.map +1 -1
  203. package/dist/core/model-router/intent-classifier.js +154 -9
  204. package/dist/core/model-router/intent-classifier.js.map +1 -1
  205. package/dist/core/model-router/route-judge.d.ts +54 -0
  206. package/dist/core/model-router/route-judge.d.ts.map +1 -0
  207. package/dist/core/model-router/route-judge.js +128 -0
  208. package/dist/core/model-router/route-judge.js.map +1 -0
  209. package/dist/core/model-router/status.d.ts +4 -1
  210. package/dist/core/model-router/status.d.ts.map +1 -1
  211. package/dist/core/model-router/status.js +30 -6
  212. package/dist/core/model-router/status.js.map +1 -1
  213. package/dist/core/model-router/tool-escalation.d.ts +4 -6
  214. package/dist/core/model-router/tool-escalation.d.ts.map +1 -1
  215. package/dist/core/model-router/tool-escalation.js +1 -1
  216. package/dist/core/model-router/tool-escalation.js.map +1 -1
  217. package/dist/core/models/fitness-store.d.ts +40 -0
  218. package/dist/core/models/fitness-store.d.ts.map +1 -0
  219. package/dist/core/models/fitness-store.js +61 -0
  220. package/dist/core/models/fitness-store.js.map +1 -0
  221. package/dist/core/profile-registry.d.ts.map +1 -1
  222. package/dist/core/profile-registry.js +1 -1
  223. package/dist/core/profile-registry.js.map +1 -1
  224. package/dist/core/prompt-templates.d.ts +2 -0
  225. package/dist/core/prompt-templates.d.ts.map +1 -1
  226. package/dist/core/prompt-templates.js +12 -4
  227. package/dist/core/prompt-templates.js.map +1 -1
  228. package/dist/core/research/automata-provider.d.ts +5 -0
  229. package/dist/core/research/automata-provider.d.ts.map +1 -0
  230. package/dist/core/research/automata-provider.js +15 -0
  231. package/dist/core/research/automata-provider.js.map +1 -0
  232. package/dist/core/research/evidence-bundle.d.ts +10 -0
  233. package/dist/core/research/evidence-bundle.d.ts.map +1 -0
  234. package/dist/core/research/evidence-bundle.js +116 -0
  235. package/dist/core/research/evidence-bundle.js.map +1 -0
  236. package/dist/core/research/model-fitness.d.ts +79 -0
  237. package/dist/core/research/model-fitness.d.ts.map +1 -0
  238. package/dist/core/research/model-fitness.js +257 -0
  239. package/dist/core/research/model-fitness.js.map +1 -0
  240. package/dist/core/research/research-gate.d.ts +11 -0
  241. package/dist/core/research/research-gate.d.ts.map +1 -0
  242. package/dist/core/research/research-gate.js +82 -0
  243. package/dist/core/research/research-gate.js.map +1 -0
  244. package/dist/core/research/research-runner.d.ts +59 -0
  245. package/dist/core/research/research-runner.d.ts.map +1 -0
  246. package/dist/core/research/research-runner.js +155 -0
  247. package/dist/core/research/research-runner.js.map +1 -0
  248. package/dist/core/research/session-evidence-bundle.d.ts +11 -0
  249. package/dist/core/research/session-evidence-bundle.d.ts.map +1 -0
  250. package/dist/core/research/session-evidence-bundle.js +55 -0
  251. package/dist/core/research/session-evidence-bundle.js.map +1 -0
  252. package/dist/core/resource-loader.d.ts.map +1 -1
  253. package/dist/core/resource-loader.js +7 -1
  254. package/dist/core/resource-loader.js.map +1 -1
  255. package/dist/core/settings-manager.d.ts +147 -4
  256. package/dist/core/settings-manager.d.ts.map +1 -1
  257. package/dist/core/settings-manager.js +285 -9
  258. package/dist/core/settings-manager.js.map +1 -1
  259. package/dist/core/skills.d.ts +4 -0
  260. package/dist/core/skills.d.ts.map +1 -1
  261. package/dist/core/skills.js +18 -6
  262. package/dist/core/skills.js.map +1 -1
  263. package/dist/core/slash-commands.d.ts.map +1 -1
  264. package/dist/core/slash-commands.js +4 -0
  265. package/dist/core/slash-commands.js.map +1 -1
  266. package/dist/core/toolkit/script-registry.d.ts +34 -0
  267. package/dist/core/toolkit/script-registry.d.ts.map +1 -0
  268. package/dist/core/toolkit/script-registry.js +71 -0
  269. package/dist/core/toolkit/script-registry.js.map +1 -0
  270. package/dist/core/toolkit/script-runner.d.ts +28 -0
  271. package/dist/core/toolkit/script-runner.d.ts.map +1 -0
  272. package/dist/core/toolkit/script-runner.js +48 -0
  273. package/dist/core/toolkit/script-runner.js.map +1 -0
  274. package/dist/core/tools/artifact-retrieve.d.ts +23 -0
  275. package/dist/core/tools/artifact-retrieve.d.ts.map +1 -0
  276. package/dist/core/tools/artifact-retrieve.js +110 -0
  277. package/dist/core/tools/artifact-retrieve.js.map +1 -0
  278. package/dist/core/tools/delegate.d.ts +32 -0
  279. package/dist/core/tools/delegate.d.ts.map +1 -0
  280. package/dist/core/tools/delegate.js +60 -0
  281. package/dist/core/tools/delegate.js.map +1 -0
  282. package/dist/core/tools/fff-search-backend.d.ts +103 -0
  283. package/dist/core/tools/fff-search-backend.d.ts.map +1 -0
  284. package/dist/core/tools/fff-search-backend.js +151 -0
  285. package/dist/core/tools/fff-search-backend.js.map +1 -0
  286. package/dist/core/tools/find.d.ts +21 -1
  287. package/dist/core/tools/find.d.ts.map +1 -1
  288. package/dist/core/tools/find.js +183 -10
  289. package/dist/core/tools/find.js.map +1 -1
  290. package/dist/core/tools/goal.d.ts +35 -0
  291. package/dist/core/tools/goal.d.ts.map +1 -0
  292. package/dist/core/tools/goal.js +122 -0
  293. package/dist/core/tools/goal.js.map +1 -0
  294. package/dist/core/tools/grep.d.ts +21 -1
  295. package/dist/core/tools/grep.d.ts.map +1 -1
  296. package/dist/core/tools/grep.js +272 -27
  297. package/dist/core/tools/grep.js.map +1 -1
  298. package/dist/core/tools/index.d.ts +4 -1
  299. package/dist/core/tools/index.d.ts.map +1 -1
  300. package/dist/core/tools/index.js +9 -0
  301. package/dist/core/tools/index.js.map +1 -1
  302. package/dist/core/tools/model-fitness.d.ts +30 -0
  303. package/dist/core/tools/model-fitness.d.ts.map +1 -0
  304. package/dist/core/tools/model-fitness.js +38 -0
  305. package/dist/core/tools/model-fitness.js.map +1 -0
  306. package/dist/core/tools/run-toolkit-script.d.ts +24 -0
  307. package/dist/core/tools/run-toolkit-script.d.ts.map +1 -0
  308. package/dist/core/tools/run-toolkit-script.js +103 -0
  309. package/dist/core/tools/run-toolkit-script.js.map +1 -0
  310. package/dist/core/tools/search-router.d.ts +75 -0
  311. package/dist/core/tools/search-router.d.ts.map +1 -0
  312. package/dist/core/tools/search-router.js +85 -0
  313. package/dist/core/tools/search-router.js.map +1 -0
  314. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  315. package/dist/modes/interactive/components/footer.js +18 -16
  316. package/dist/modes/interactive/components/footer.js.map +1 -1
  317. package/dist/modes/interactive/components/settings-selector.d.ts +13 -1
  318. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  319. package/dist/modes/interactive/components/settings-selector.js +471 -11
  320. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  321. package/dist/modes/interactive/interactive-mode.d.ts +4 -0
  322. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  323. package/dist/modes/interactive/interactive-mode.js +220 -39
  324. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  325. package/dist/modes/print-mode.d.ts.map +1 -1
  326. package/dist/modes/print-mode.js +3 -0
  327. package/dist/modes/print-mode.js.map +1 -1
  328. package/dist/utils/tools-manager.d.ts +2 -0
  329. package/dist/utils/tools-manager.d.ts.map +1 -1
  330. package/dist/utils/tools-manager.js +154 -2
  331. package/dist/utils/tools-manager.js.map +1 -1
  332. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  333. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  334. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  335. package/examples/extensions/sandbox/package-lock.json +2 -2
  336. package/examples/extensions/sandbox/package.json +1 -1
  337. package/examples/extensions/with-deps/package-lock.json +2 -2
  338. package/examples/extensions/with-deps/package.json +1 -1
  339. package/npm-shrinkwrap.json +368 -12
  340. package/package.json +5 -4
@@ -0,0 +1,344 @@
1
+ import { mkdirSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+ import { DatabaseSync } from "node:sqlite";
4
+ export const SQLITE_RUNTIME_INDEX_SCHEMA_VERSION = 1;
5
+ export const SQLITE_CONTEXT_INDEX_TABLES = [
6
+ "context_items",
7
+ "artifact_metadata",
8
+ "policy_score_cache",
9
+ "policy_decisions",
10
+ "retrieval_records",
11
+ "memory_index",
12
+ ];
13
+ function prepareDatabasePath(databasePath) {
14
+ if (databasePath === ":memory:")
15
+ return;
16
+ mkdirSync(dirname(databasePath), { recursive: true });
17
+ }
18
+ function openDatabase(options) {
19
+ prepareDatabasePath(options.databasePath);
20
+ const database = new DatabaseSync(options.databasePath, {
21
+ enableForeignKeyConstraints: true,
22
+ timeout: options.busyTimeoutMs ?? 5_000,
23
+ });
24
+ database.exec(`
25
+ PRAGMA foreign_keys = ON;
26
+ PRAGMA busy_timeout = ${options.busyTimeoutMs ?? 5_000};
27
+ PRAGMA journal_mode = WAL;
28
+ `);
29
+ migrateSqliteRuntimeIndex(database);
30
+ return database;
31
+ }
32
+ function currentSchemaVersion(database) {
33
+ const row = database.prepare("PRAGMA user_version").get();
34
+ const value = row?.user_version;
35
+ return typeof value === "number" ? value : 0;
36
+ }
37
+ export function migrateSqliteRuntimeIndex(database) {
38
+ const version = currentSchemaVersion(database);
39
+ if (version > SQLITE_RUNTIME_INDEX_SCHEMA_VERSION) {
40
+ throw new Error(`Unsupported Pi context runtime-index schema version ${version}; current runtime supports ${SQLITE_RUNTIME_INDEX_SCHEMA_VERSION}`);
41
+ }
42
+ try {
43
+ database.exec(`
44
+ BEGIN IMMEDIATE;
45
+
46
+ CREATE TABLE IF NOT EXISTS context_items (
47
+ id TEXT PRIMARY KEY NOT NULL,
48
+ kind TEXT NOT NULL,
49
+ retention_class TEXT NOT NULL,
50
+ source TEXT NOT NULL,
51
+ created_at_turn INTEGER NOT NULL,
52
+ last_used_at_turn INTEGER,
53
+ token_estimate INTEGER NOT NULL,
54
+ byte_estimate INTEGER NOT NULL,
55
+ payload_json TEXT NOT NULL
56
+ ) STRICT;
57
+
58
+ CREATE TABLE IF NOT EXISTS artifact_metadata (
59
+ id TEXT PRIMARY KEY NOT NULL,
60
+ kind TEXT NOT NULL,
61
+ storage_path TEXT,
62
+ session_entry_id TEXT,
63
+ tool_name TEXT,
64
+ command TEXT,
65
+ path TEXT,
66
+ byte_length INTEGER NOT NULL,
67
+ line_count INTEGER,
68
+ created_at_turn INTEGER NOT NULL,
69
+ reproducible INTEGER NOT NULL CHECK (reproducible IN (0, 1)),
70
+ payload_exists INTEGER NOT NULL DEFAULT 1 CHECK (payload_exists IN (0, 1)),
71
+ payload_json TEXT NOT NULL
72
+ ) STRICT;
73
+
74
+ CREATE TABLE IF NOT EXISTS policy_score_cache (
75
+ cache_key TEXT PRIMARY KEY NOT NULL,
76
+ created_at_turn INTEGER NOT NULL,
77
+ payload_json TEXT NOT NULL
78
+ ) STRICT;
79
+
80
+ CREATE TABLE IF NOT EXISTS policy_decisions (
81
+ id TEXT PRIMARY KEY NOT NULL,
82
+ context_item_id TEXT,
83
+ recorded_at_turn INTEGER NOT NULL,
84
+ decision_kind TEXT NOT NULL,
85
+ selected_action TEXT NOT NULL,
86
+ mode TEXT NOT NULL,
87
+ applied INTEGER NOT NULL CHECK (applied IN (0, 1)),
88
+ payload_json TEXT NOT NULL
89
+ ) STRICT;
90
+
91
+ CREATE INDEX IF NOT EXISTS idx_policy_decisions_context_item_id
92
+ ON policy_decisions(context_item_id, recorded_at_turn);
93
+
94
+ CREATE TABLE IF NOT EXISTS retrieval_records (
95
+ id TEXT PRIMARY KEY NOT NULL,
96
+ context_item_id TEXT NOT NULL,
97
+ requested_at_turn INTEGER NOT NULL,
98
+ slice_kind TEXT NOT NULL,
99
+ result_summary TEXT NOT NULL,
100
+ payload_json TEXT NOT NULL
101
+ ) STRICT;
102
+
103
+ CREATE INDEX IF NOT EXISTS idx_retrieval_records_context_item_id
104
+ ON retrieval_records(context_item_id, requested_at_turn);
105
+
106
+ CREATE TABLE IF NOT EXISTS memory_index (
107
+ provider_id TEXT NOT NULL,
108
+ item_id TEXT NOT NULL,
109
+ scope TEXT NOT NULL,
110
+ kind TEXT NOT NULL,
111
+ title TEXT,
112
+ summary TEXT NOT NULL,
113
+ indexed_at_turn INTEGER NOT NULL,
114
+ stale INTEGER NOT NULL CHECK (stale IN (0, 1)),
115
+ payload_json TEXT NOT NULL,
116
+ PRIMARY KEY (provider_id, item_id)
117
+ ) STRICT;
118
+
119
+ CREATE INDEX IF NOT EXISTS idx_memory_index_scope
120
+ ON memory_index(scope, provider_id, item_id);
121
+
122
+ PRAGMA user_version = ${SQLITE_RUNTIME_INDEX_SCHEMA_VERSION};
123
+ COMMIT;
124
+ `);
125
+ }
126
+ catch (error) {
127
+ if (database.isTransaction)
128
+ database.exec("ROLLBACK;");
129
+ throw error;
130
+ }
131
+ }
132
+ function isRecord(value) {
133
+ return typeof value === "object" && value !== null && !Array.isArray(value);
134
+ }
135
+ function parseJsonRecord(json, isValid) {
136
+ try {
137
+ const parsed = JSON.parse(json);
138
+ return isValid(parsed) ? parsed : undefined;
139
+ }
140
+ catch {
141
+ return undefined;
142
+ }
143
+ }
144
+ function textColumn(row, column) {
145
+ const value = row?.[column];
146
+ return typeof value === "string" ? value : undefined;
147
+ }
148
+ function isContextItem(value) {
149
+ if (!isRecord(value))
150
+ return false;
151
+ return (typeof value.id === "string" &&
152
+ typeof value.kind === "string" &&
153
+ typeof value.retentionClass === "string" &&
154
+ typeof value.source === "string" &&
155
+ typeof value.createdAtTurn === "number" &&
156
+ typeof value.tokenEstimate === "number" &&
157
+ typeof value.byteEstimate === "number");
158
+ }
159
+ function isPolicyDecision(value) {
160
+ if (!isRecord(value))
161
+ return false;
162
+ return (typeof value.kind === "string" &&
163
+ typeof value.selectedAction === "string" &&
164
+ typeof value.mode === "string" &&
165
+ typeof value.applied === "boolean" &&
166
+ Array.isArray(value.hardConstraints) &&
167
+ Array.isArray(value.candidates) &&
168
+ Array.isArray(value.selectedReasonCodes) &&
169
+ typeof value.estimatedCostTokens === "number" &&
170
+ typeof value.estimatedSavingsTokens === "number" &&
171
+ typeof value.estimatedReliabilityRisk === "number" &&
172
+ typeof value.cacheImpactTokens === "number" &&
173
+ typeof value.reworkRiskTokens === "number" &&
174
+ Array.isArray(value.artifactRefs) &&
175
+ Array.isArray(value.evidenceRefs));
176
+ }
177
+ function isPolicyDecisionRecord(value) {
178
+ if (!isRecord(value))
179
+ return false;
180
+ return (typeof value.id === "string" &&
181
+ (value.contextItemId === undefined || typeof value.contextItemId === "string") &&
182
+ typeof value.recordedAtTurn === "number" &&
183
+ isPolicyDecision(value.decision));
184
+ }
185
+ function isRetrievalRecord(value) {
186
+ if (!isRecord(value))
187
+ return false;
188
+ return (typeof value.id === "string" &&
189
+ typeof value.contextItemId === "string" &&
190
+ typeof value.requestedAtTurn === "number" &&
191
+ typeof value.sliceKind === "string" &&
192
+ typeof value.resultSummary === "string");
193
+ }
194
+ function isMemoryIndexRecord(value) {
195
+ if (!isRecord(value) || !isRecord(value.ref))
196
+ return false;
197
+ return (typeof value.ref.providerId === "string" &&
198
+ typeof value.ref.itemId === "string" &&
199
+ typeof value.ref.scope === "string" &&
200
+ typeof value.ref.kind === "string" &&
201
+ (value.title === undefined || typeof value.title === "string") &&
202
+ typeof value.summary === "string" &&
203
+ typeof value.indexedAtTurn === "number" &&
204
+ typeof value.stale === "boolean");
205
+ }
206
+ function contextItemFromRow(row) {
207
+ const payload = textColumn(row, "payload_json");
208
+ return payload === undefined ? undefined : parseJsonRecord(payload, isContextItem);
209
+ }
210
+ function policyDecisionRecordFromRow(row) {
211
+ const payload = textColumn(row, "payload_json");
212
+ return payload === undefined ? undefined : parseJsonRecord(payload, isPolicyDecisionRecord);
213
+ }
214
+ function retrievalRecordFromRow(row) {
215
+ const payload = textColumn(row, "payload_json");
216
+ return payload === undefined ? undefined : parseJsonRecord(payload, isRetrievalRecord);
217
+ }
218
+ function memoryIndexRecordFromRow(row) {
219
+ const payload = textColumn(row, "payload_json");
220
+ return payload === undefined ? undefined : parseJsonRecord(payload, isMemoryIndexRecord);
221
+ }
222
+ export function createSqliteContextStore(options) {
223
+ const database = openDatabase(options);
224
+ const upsertItem = database.prepare(`
225
+ INSERT INTO context_items (
226
+ id, kind, retention_class, source, created_at_turn, last_used_at_turn, token_estimate, byte_estimate, payload_json
227
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
228
+ ON CONFLICT(id) DO UPDATE SET
229
+ kind = excluded.kind,
230
+ retention_class = excluded.retention_class,
231
+ source = excluded.source,
232
+ created_at_turn = excluded.created_at_turn,
233
+ last_used_at_turn = excluded.last_used_at_turn,
234
+ token_estimate = excluded.token_estimate,
235
+ byte_estimate = excluded.byte_estimate,
236
+ payload_json = excluded.payload_json
237
+ `);
238
+ const getItem = database.prepare("SELECT payload_json FROM context_items WHERE id = ?");
239
+ const listItems = database.prepare("SELECT payload_json FROM context_items ORDER BY created_at_turn, id");
240
+ const removeItem = database.prepare("DELETE FROM context_items WHERE id = ?");
241
+ const recordPolicyDecision = database.prepare(`
242
+ INSERT INTO policy_decisions (
243
+ id, context_item_id, recorded_at_turn, decision_kind, selected_action, mode, applied, payload_json
244
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
245
+ `);
246
+ const listAllPolicyDecisions = database.prepare("SELECT payload_json FROM policy_decisions ORDER BY recorded_at_turn, id");
247
+ const listPolicyDecisionsByItem = database.prepare("SELECT payload_json FROM policy_decisions WHERE context_item_id = ? ORDER BY recorded_at_turn, id");
248
+ const recordRetrieval = database.prepare(`
249
+ INSERT INTO retrieval_records (
250
+ id, context_item_id, requested_at_turn, slice_kind, result_summary, payload_json
251
+ ) VALUES (?, ?, ?, ?, ?, ?)
252
+ `);
253
+ const listAllRetrievals = database.prepare("SELECT payload_json FROM retrieval_records ORDER BY requested_at_turn, id");
254
+ const listRetrievalsByItem = database.prepare("SELECT payload_json FROM retrieval_records WHERE context_item_id = ? ORDER BY requested_at_turn, id");
255
+ return {
256
+ upsertItem(item) {
257
+ upsertItem.run(item.id, item.kind, item.retentionClass, item.source, item.createdAtTurn, item.lastUsedAtTurn ?? null, item.tokenEstimate, item.byteEstimate, JSON.stringify(item));
258
+ },
259
+ getItem(id) {
260
+ return contextItemFromRow(getItem.get(id));
261
+ },
262
+ listItems() {
263
+ return listItems.all().flatMap((row) => {
264
+ const item = contextItemFromRow(row);
265
+ return item === undefined ? [] : [item];
266
+ });
267
+ },
268
+ removeItem(id) {
269
+ removeItem.run(id);
270
+ },
271
+ recordPolicyDecision(record) {
272
+ recordPolicyDecision.run(record.id, record.contextItemId ?? null, record.recordedAtTurn, record.decision.kind, record.decision.selectedAction, record.decision.mode, record.decision.applied ? 1 : 0, JSON.stringify(record));
273
+ },
274
+ listPolicyDecisions(contextItemId) {
275
+ const rows = contextItemId === undefined ? listAllPolicyDecisions.all() : listPolicyDecisionsByItem.all(contextItemId);
276
+ return rows.flatMap((row) => {
277
+ const record = policyDecisionRecordFromRow(row);
278
+ return record === undefined ? [] : [record];
279
+ });
280
+ },
281
+ recordRetrieval(record) {
282
+ recordRetrieval.run(record.id, record.contextItemId, record.requestedAtTurn, record.sliceKind, record.resultSummary, JSON.stringify(record));
283
+ },
284
+ listRetrievals(contextItemId) {
285
+ const rows = contextItemId === undefined ? listAllRetrievals.all() : listRetrievalsByItem.all(contextItemId);
286
+ return rows.flatMap((row) => {
287
+ const record = retrievalRecordFromRow(row);
288
+ return record === undefined ? [] : [record];
289
+ });
290
+ },
291
+ close() {
292
+ database[Symbol.dispose]();
293
+ },
294
+ };
295
+ }
296
+ export function createSqliteMemoryIndexStore(options) {
297
+ const database = openDatabase(options);
298
+ const upsert = database.prepare(`
299
+ INSERT INTO memory_index (
300
+ provider_id, item_id, scope, kind, title, summary, indexed_at_turn, stale, payload_json
301
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
302
+ ON CONFLICT(provider_id, item_id) DO UPDATE SET
303
+ scope = excluded.scope,
304
+ kind = excluded.kind,
305
+ title = excluded.title,
306
+ summary = excluded.summary,
307
+ indexed_at_turn = excluded.indexed_at_turn,
308
+ stale = excluded.stale,
309
+ payload_json = excluded.payload_json
310
+ `);
311
+ const get = database.prepare("SELECT payload_json FROM memory_index WHERE provider_id = ? AND item_id = ?");
312
+ const listAll = database.prepare("SELECT payload_json FROM memory_index ORDER BY provider_id, item_id");
313
+ const listByScope = database.prepare("SELECT payload_json FROM memory_index WHERE scope = ? ORDER BY provider_id, item_id");
314
+ const markStale = database.prepare("UPDATE memory_index SET stale = 1, payload_json = ? WHERE provider_id = ? AND item_id = ?");
315
+ const remove = database.prepare("DELETE FROM memory_index WHERE provider_id = ? AND item_id = ?");
316
+ return {
317
+ upsert(record) {
318
+ upsert.run(record.ref.providerId, record.ref.itemId, record.ref.scope, record.ref.kind, record.title ?? null, record.summary, record.indexedAtTurn, record.stale ? 1 : 0, JSON.stringify(record));
319
+ },
320
+ get(providerId, itemId) {
321
+ return memoryIndexRecordFromRow(get.get(providerId, itemId));
322
+ },
323
+ list(scope) {
324
+ const rows = scope === undefined ? listAll.all() : listByScope.all(scope);
325
+ return rows.flatMap((row) => {
326
+ const record = memoryIndexRecordFromRow(row);
327
+ return record === undefined ? [] : [record];
328
+ });
329
+ },
330
+ markStale(providerId, itemId) {
331
+ const existing = memoryIndexRecordFromRow(get.get(providerId, itemId));
332
+ if (existing === undefined)
333
+ return;
334
+ markStale.run(JSON.stringify({ ...existing, stale: true }), providerId, itemId);
335
+ },
336
+ remove(providerId, itemId) {
337
+ remove.run(providerId, itemId);
338
+ },
339
+ close() {
340
+ database[Symbol.dispose]();
341
+ },
342
+ };
343
+ }
344
+ //# sourceMappingURL=sqlite-runtime-index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sqlite-runtime-index.js","sourceRoot":"","sources":["../../../src/core/context/sqlite-runtime-index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAM3C,MAAM,CAAC,MAAM,mCAAmC,GAAG,CAAC,CAAC;AAErD,MAAM,CAAC,MAAM,2BAA2B,GAAG;IAC1C,eAAe;IACf,mBAAmB;IACnB,oBAAoB;IACpB,kBAAkB;IAClB,mBAAmB;IACnB,cAAc;CACL,CAAC;AAeX,SAAS,mBAAmB,CAAC,YAAoB,EAAQ;IACxD,IAAI,YAAY,KAAK,UAAU;QAAE,OAAO;IACxC,SAAS,CAAC,OAAO,CAAC,YAAY,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,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AO,wBAAwB,CAAC,GAAG,CAAC,GAAG,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC;QAAA,CAC7D;QAED,IAAI,CAAC,KAAyC,EAAuB;YACpE,MAAM,IAAI,GAAG,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,WAAW,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;YAC1E,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC;gBAC5B,MAAM,MAAM,GAAG,wBAAwB,CAAC,GAAG,CAAC,CAAC;gBAC7C,OAAO,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;YAAA,CAC5C,CAAC,CAAC;QAAA,CACH;QAED,SAAS,CAAC,UAAkB,EAAE,MAAc,EAAQ;YACnD,MAAM,QAAQ,GAAG,wBAAwB,CAAC,GAAG,CAAC,GAAG,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC;YACvE,IAAI,QAAQ,KAAK,SAAS;gBAAE,OAAO;YACnC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,GAAG,QAAQ,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,EAAE,UAAU,EAAE,MAAM,CAAC,CAAC;QAAA,CAChF;QAED,MAAM,CAAC,UAAkB,EAAE,MAAc,EAAQ;YAChD,MAAM,CAAC,GAAG,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC;QAAA,CAC/B;QAED,KAAK,GAAS;YACb,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC;QAAA,CAC3B;KACD,CAAC;AAAA,CACF","sourcesContent":["import { mkdirSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { DatabaseSync } from \"node:sqlite\";\nimport type { ContextItem } from \"./context-item.ts\";\nimport type { ContextStore, PolicyDecisionRecord, RetrievalRecord } from \"./context-store.ts\";\nimport type { MemoryIndexRecord, MemoryIndexStore } from \"./memory-index-store.ts\";\nimport type { PolicyDecision } from \"./policy-types.ts\";\n\nexport const SQLITE_RUNTIME_INDEX_SCHEMA_VERSION = 1;\n\nexport const SQLITE_CONTEXT_INDEX_TABLES = [\n\t\"context_items\",\n\t\"artifact_metadata\",\n\t\"policy_score_cache\",\n\t\"policy_decisions\",\n\t\"retrieval_records\",\n\t\"memory_index\",\n] as const;\n\nexport interface SqliteRuntimeIndexOptions {\n\tdatabasePath: string;\n\tbusyTimeoutMs?: number;\n}\n\nexport interface SqliteContextStore extends ContextStore {\n\tclose(): void;\n}\n\nexport interface SqliteMemoryIndexStore extends MemoryIndexStore {\n\tclose(): void;\n}\n\nfunction prepareDatabasePath(databasePath: string): void {\n\tif (databasePath === \":memory:\") return;\n\tmkdirSync(dirname(databasePath), { recursive: true });\n}\n\nfunction openDatabase(options: SqliteRuntimeIndexOptions): DatabaseSync {\n\tprepareDatabasePath(options.databasePath);\n\tconst database = new DatabaseSync(options.databasePath, {\n\t\tenableForeignKeyConstraints: true,\n\t\ttimeout: options.busyTimeoutMs ?? 5_000,\n\t});\n\tdatabase.exec(`\n\t\tPRAGMA foreign_keys = ON;\n\t\tPRAGMA busy_timeout = ${options.busyTimeoutMs ?? 5_000};\n\t\tPRAGMA journal_mode = WAL;\n\t`);\n\tmigrateSqliteRuntimeIndex(database);\n\treturn database;\n}\n\nfunction currentSchemaVersion(database: DatabaseSync): number {\n\tconst row = database.prepare(\"PRAGMA user_version\").get();\n\tconst value = row?.user_version;\n\treturn typeof value === \"number\" ? value : 0;\n}\n\nexport function migrateSqliteRuntimeIndex(database: DatabaseSync): void {\n\tconst version = currentSchemaVersion(database);\n\tif (version > SQLITE_RUNTIME_INDEX_SCHEMA_VERSION) {\n\t\tthrow new Error(\n\t\t\t`Unsupported Pi context runtime-index schema version ${version}; current runtime supports ${SQLITE_RUNTIME_INDEX_SCHEMA_VERSION}`,\n\t\t);\n\t}\n\n\ttry {\n\t\tdatabase.exec(`\n\t\t\tBEGIN IMMEDIATE;\n\n\t\t\tCREATE TABLE IF NOT EXISTS context_items (\n\t\t\t\tid TEXT PRIMARY KEY NOT NULL,\n\t\t\t\tkind TEXT NOT NULL,\n\t\t\t\tretention_class TEXT NOT NULL,\n\t\t\t\tsource TEXT NOT NULL,\n\t\t\t\tcreated_at_turn INTEGER NOT NULL,\n\t\t\t\tlast_used_at_turn INTEGER,\n\t\t\t\ttoken_estimate INTEGER NOT NULL,\n\t\t\t\tbyte_estimate INTEGER NOT NULL,\n\t\t\t\tpayload_json TEXT NOT NULL\n\t\t\t) STRICT;\n\n\t\t\tCREATE TABLE IF NOT EXISTS artifact_metadata (\n\t\t\t\tid TEXT PRIMARY KEY NOT NULL,\n\t\t\t\tkind TEXT NOT NULL,\n\t\t\t\tstorage_path TEXT,\n\t\t\t\tsession_entry_id TEXT,\n\t\t\t\ttool_name TEXT,\n\t\t\t\tcommand TEXT,\n\t\t\t\tpath TEXT,\n\t\t\t\tbyte_length INTEGER NOT NULL,\n\t\t\t\tline_count INTEGER,\n\t\t\t\tcreated_at_turn INTEGER NOT NULL,\n\t\t\t\treproducible INTEGER NOT NULL CHECK (reproducible IN (0, 1)),\n\t\t\t\tpayload_exists INTEGER NOT NULL DEFAULT 1 CHECK (payload_exists IN (0, 1)),\n\t\t\t\tpayload_json TEXT NOT NULL\n\t\t\t) STRICT;\n\n\t\t\tCREATE TABLE IF NOT EXISTS policy_score_cache (\n\t\t\t\tcache_key TEXT PRIMARY KEY NOT NULL,\n\t\t\t\tcreated_at_turn INTEGER NOT NULL,\n\t\t\t\tpayload_json TEXT NOT NULL\n\t\t\t) STRICT;\n\n\t\t\tCREATE TABLE IF NOT EXISTS policy_decisions (\n\t\t\t\tid TEXT PRIMARY KEY NOT NULL,\n\t\t\t\tcontext_item_id TEXT,\n\t\t\t\trecorded_at_turn INTEGER NOT NULL,\n\t\t\t\tdecision_kind TEXT NOT NULL,\n\t\t\t\tselected_action TEXT NOT NULL,\n\t\t\t\tmode TEXT NOT NULL,\n\t\t\t\tapplied INTEGER NOT NULL CHECK (applied IN (0, 1)),\n\t\t\t\tpayload_json TEXT NOT NULL\n\t\t\t) STRICT;\n\n\t\t\tCREATE INDEX IF NOT EXISTS idx_policy_decisions_context_item_id\n\t\t\t\tON policy_decisions(context_item_id, recorded_at_turn);\n\n\t\t\tCREATE TABLE IF NOT EXISTS retrieval_records (\n\t\t\t\tid TEXT PRIMARY KEY NOT NULL,\n\t\t\t\tcontext_item_id TEXT NOT NULL,\n\t\t\t\trequested_at_turn INTEGER NOT NULL,\n\t\t\t\tslice_kind TEXT NOT NULL,\n\t\t\t\tresult_summary TEXT NOT NULL,\n\t\t\t\tpayload_json TEXT NOT NULL\n\t\t\t) STRICT;\n\n\t\t\tCREATE INDEX IF NOT EXISTS idx_retrieval_records_context_item_id\n\t\t\t\tON retrieval_records(context_item_id, requested_at_turn);\n\n\t\t\tCREATE TABLE IF NOT EXISTS memory_index (\n\t\t\t\tprovider_id TEXT NOT NULL,\n\t\t\t\titem_id TEXT NOT NULL,\n\t\t\t\tscope TEXT NOT NULL,\n\t\t\t\tkind TEXT NOT NULL,\n\t\t\t\ttitle TEXT,\n\t\t\t\tsummary TEXT NOT NULL,\n\t\t\t\tindexed_at_turn INTEGER NOT NULL,\n\t\t\t\tstale INTEGER NOT NULL CHECK (stale IN (0, 1)),\n\t\t\t\tpayload_json TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (provider_id, item_id)\n\t\t\t) STRICT;\n\n\t\t\tCREATE INDEX IF NOT EXISTS idx_memory_index_scope\n\t\t\t\tON memory_index(scope, provider_id, item_id);\n\n\t\t\tPRAGMA user_version = ${SQLITE_RUNTIME_INDEX_SCHEMA_VERSION};\n\t\t\tCOMMIT;\n\t\t`);\n\t} catch (error) {\n\t\tif (database.isTransaction) database.exec(\"ROLLBACK;\");\n\t\tthrow error;\n\t}\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction parseJsonRecord<T>(json: string, isValid: (value: unknown) => value is T): T | undefined {\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(json);\n\t\treturn isValid(parsed) ? parsed : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction textColumn(row: Record<string, unknown> | undefined, column: string): string | undefined {\n\tconst value = row?.[column];\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction isContextItem(value: unknown): value is ContextItem {\n\tif (!isRecord(value)) return false;\n\treturn (\n\t\ttypeof value.id === \"string\" &&\n\t\ttypeof value.kind === \"string\" &&\n\t\ttypeof value.retentionClass === \"string\" &&\n\t\ttypeof value.source === \"string\" &&\n\t\ttypeof value.createdAtTurn === \"number\" &&\n\t\ttypeof value.tokenEstimate === \"number\" &&\n\t\ttypeof value.byteEstimate === \"number\"\n\t);\n}\n\nfunction isPolicyDecision(value: unknown): value is PolicyDecision {\n\tif (!isRecord(value)) return false;\n\treturn (\n\t\ttypeof value.kind === \"string\" &&\n\t\ttypeof value.selectedAction === \"string\" &&\n\t\ttypeof value.mode === \"string\" &&\n\t\ttypeof value.applied === \"boolean\" &&\n\t\tArray.isArray(value.hardConstraints) &&\n\t\tArray.isArray(value.candidates) &&\n\t\tArray.isArray(value.selectedReasonCodes) &&\n\t\ttypeof value.estimatedCostTokens === \"number\" &&\n\t\ttypeof value.estimatedSavingsTokens === \"number\" &&\n\t\ttypeof value.estimatedReliabilityRisk === \"number\" &&\n\t\ttypeof value.cacheImpactTokens === \"number\" &&\n\t\ttypeof value.reworkRiskTokens === \"number\" &&\n\t\tArray.isArray(value.artifactRefs) &&\n\t\tArray.isArray(value.evidenceRefs)\n\t);\n}\n\nfunction isPolicyDecisionRecord(value: unknown): value is PolicyDecisionRecord {\n\tif (!isRecord(value)) return false;\n\treturn (\n\t\ttypeof value.id === \"string\" &&\n\t\t(value.contextItemId === undefined || typeof value.contextItemId === \"string\") &&\n\t\ttypeof value.recordedAtTurn === \"number\" &&\n\t\tisPolicyDecision(value.decision)\n\t);\n}\n\nfunction isRetrievalRecord(value: unknown): value is RetrievalRecord {\n\tif (!isRecord(value)) return false;\n\treturn (\n\t\ttypeof value.id === \"string\" &&\n\t\ttypeof value.contextItemId === \"string\" &&\n\t\ttypeof value.requestedAtTurn === \"number\" &&\n\t\ttypeof value.sliceKind === \"string\" &&\n\t\ttypeof value.resultSummary === \"string\"\n\t);\n}\n\nfunction isMemoryIndexRecord(value: unknown): value is MemoryIndexRecord {\n\tif (!isRecord(value) || !isRecord(value.ref)) return false;\n\treturn (\n\t\ttypeof value.ref.providerId === \"string\" &&\n\t\ttypeof value.ref.itemId === \"string\" &&\n\t\ttypeof value.ref.scope === \"string\" &&\n\t\ttypeof value.ref.kind === \"string\" &&\n\t\t(value.title === undefined || typeof value.title === \"string\") &&\n\t\ttypeof value.summary === \"string\" &&\n\t\ttypeof value.indexedAtTurn === \"number\" &&\n\t\ttypeof value.stale === \"boolean\"\n\t);\n}\n\nfunction contextItemFromRow(row: Record<string, unknown> | undefined): ContextItem | undefined {\n\tconst payload = textColumn(row, \"payload_json\");\n\treturn payload === undefined ? undefined : parseJsonRecord(payload, isContextItem);\n}\n\nfunction policyDecisionRecordFromRow(row: Record<string, unknown> | undefined): PolicyDecisionRecord | undefined {\n\tconst payload = textColumn(row, \"payload_json\");\n\treturn payload === undefined ? undefined : parseJsonRecord(payload, isPolicyDecisionRecord);\n}\n\nfunction retrievalRecordFromRow(row: Record<string, unknown> | undefined): RetrievalRecord | undefined {\n\tconst payload = textColumn(row, \"payload_json\");\n\treturn payload === undefined ? undefined : parseJsonRecord(payload, isRetrievalRecord);\n}\n\nfunction memoryIndexRecordFromRow(row: Record<string, unknown> | undefined): MemoryIndexRecord | undefined {\n\tconst payload = textColumn(row, \"payload_json\");\n\treturn payload === undefined ? undefined : parseJsonRecord(payload, isMemoryIndexRecord);\n}\n\nexport function createSqliteContextStore(options: SqliteRuntimeIndexOptions): SqliteContextStore {\n\tconst database = openDatabase(options);\n\tconst upsertItem = database.prepare(`\n\t\tINSERT INTO context_items (\n\t\t\tid, kind, retention_class, source, created_at_turn, last_used_at_turn, token_estimate, byte_estimate, payload_json\n\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)\n\t\tON CONFLICT(id) DO UPDATE SET\n\t\t\tkind = excluded.kind,\n\t\t\tretention_class = excluded.retention_class,\n\t\t\tsource = excluded.source,\n\t\t\tcreated_at_turn = excluded.created_at_turn,\n\t\t\tlast_used_at_turn = excluded.last_used_at_turn,\n\t\t\ttoken_estimate = excluded.token_estimate,\n\t\t\tbyte_estimate = excluded.byte_estimate,\n\t\t\tpayload_json = excluded.payload_json\n\t`);\n\tconst getItem = database.prepare(\"SELECT payload_json FROM context_items WHERE id = ?\");\n\tconst listItems = database.prepare(\"SELECT payload_json FROM context_items ORDER BY created_at_turn, id\");\n\tconst removeItem = database.prepare(\"DELETE FROM context_items WHERE id = ?\");\n\tconst recordPolicyDecision = database.prepare(`\n\t\tINSERT INTO policy_decisions (\n\t\t\tid, context_item_id, recorded_at_turn, decision_kind, selected_action, mode, applied, payload_json\n\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n\t`);\n\tconst listAllPolicyDecisions = database.prepare(\n\t\t\"SELECT payload_json FROM policy_decisions ORDER BY recorded_at_turn, id\",\n\t);\n\tconst listPolicyDecisionsByItem = database.prepare(\n\t\t\"SELECT payload_json FROM policy_decisions WHERE context_item_id = ? ORDER BY recorded_at_turn, id\",\n\t);\n\tconst recordRetrieval = database.prepare(`\n\t\tINSERT INTO retrieval_records (\n\t\t\tid, context_item_id, requested_at_turn, slice_kind, result_summary, payload_json\n\t\t) VALUES (?, ?, ?, ?, ?, ?)\n\t`);\n\tconst listAllRetrievals = database.prepare(\n\t\t\"SELECT payload_json FROM retrieval_records ORDER BY requested_at_turn, id\",\n\t);\n\tconst listRetrievalsByItem = database.prepare(\n\t\t\"SELECT payload_json FROM retrieval_records WHERE context_item_id = ? ORDER BY requested_at_turn, id\",\n\t);\n\n\treturn {\n\t\tupsertItem(item: ContextItem): void {\n\t\t\tupsertItem.run(\n\t\t\t\titem.id,\n\t\t\t\titem.kind,\n\t\t\t\titem.retentionClass,\n\t\t\t\titem.source,\n\t\t\t\titem.createdAtTurn,\n\t\t\t\titem.lastUsedAtTurn ?? null,\n\t\t\t\titem.tokenEstimate,\n\t\t\t\titem.byteEstimate,\n\t\t\t\tJSON.stringify(item),\n\t\t\t);\n\t\t},\n\n\t\tgetItem(id: string): ContextItem | undefined {\n\t\t\treturn contextItemFromRow(getItem.get(id));\n\t\t},\n\n\t\tlistItems(): ContextItem[] {\n\t\t\treturn listItems.all().flatMap((row) => {\n\t\t\t\tconst item = contextItemFromRow(row);\n\t\t\t\treturn item === undefined ? [] : [item];\n\t\t\t});\n\t\t},\n\n\t\tremoveItem(id: string): void {\n\t\t\tremoveItem.run(id);\n\t\t},\n\n\t\trecordPolicyDecision(record: PolicyDecisionRecord): void {\n\t\t\trecordPolicyDecision.run(\n\t\t\t\trecord.id,\n\t\t\t\trecord.contextItemId ?? null,\n\t\t\t\trecord.recordedAtTurn,\n\t\t\t\trecord.decision.kind,\n\t\t\t\trecord.decision.selectedAction,\n\t\t\t\trecord.decision.mode,\n\t\t\t\trecord.decision.applied ? 1 : 0,\n\t\t\t\tJSON.stringify(record),\n\t\t\t);\n\t\t},\n\n\t\tlistPolicyDecisions(contextItemId?: string): PolicyDecisionRecord[] {\n\t\t\tconst rows =\n\t\t\t\tcontextItemId === undefined ? listAllPolicyDecisions.all() : listPolicyDecisionsByItem.all(contextItemId);\n\t\t\treturn rows.flatMap((row) => {\n\t\t\t\tconst record = policyDecisionRecordFromRow(row);\n\t\t\t\treturn record === undefined ? [] : [record];\n\t\t\t});\n\t\t},\n\n\t\trecordRetrieval(record: RetrievalRecord): void {\n\t\t\trecordRetrieval.run(\n\t\t\t\trecord.id,\n\t\t\t\trecord.contextItemId,\n\t\t\t\trecord.requestedAtTurn,\n\t\t\t\trecord.sliceKind,\n\t\t\t\trecord.resultSummary,\n\t\t\t\tJSON.stringify(record),\n\t\t\t);\n\t\t},\n\n\t\tlistRetrievals(contextItemId?: string): RetrievalRecord[] {\n\t\t\tconst rows = contextItemId === undefined ? listAllRetrievals.all() : listRetrievalsByItem.all(contextItemId);\n\t\t\treturn rows.flatMap((row) => {\n\t\t\t\tconst record = retrievalRecordFromRow(row);\n\t\t\t\treturn record === undefined ? [] : [record];\n\t\t\t});\n\t\t},\n\n\t\tclose(): void {\n\t\t\tdatabase[Symbol.dispose]();\n\t\t},\n\t};\n}\n\nexport function createSqliteMemoryIndexStore(options: SqliteRuntimeIndexOptions): SqliteMemoryIndexStore {\n\tconst database = openDatabase(options);\n\tconst upsert = database.prepare(`\n\t\tINSERT INTO memory_index (\n\t\t\tprovider_id, item_id, scope, kind, title, summary, indexed_at_turn, stale, payload_json\n\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)\n\t\tON CONFLICT(provider_id, item_id) DO UPDATE SET\n\t\t\tscope = excluded.scope,\n\t\t\tkind = excluded.kind,\n\t\t\ttitle = excluded.title,\n\t\t\tsummary = excluded.summary,\n\t\t\tindexed_at_turn = excluded.indexed_at_turn,\n\t\t\tstale = excluded.stale,\n\t\t\tpayload_json = excluded.payload_json\n\t`);\n\tconst get = database.prepare(\"SELECT payload_json FROM memory_index WHERE provider_id = ? AND item_id = ?\");\n\tconst listAll = database.prepare(\"SELECT payload_json FROM memory_index ORDER BY provider_id, item_id\");\n\tconst listByScope = database.prepare(\n\t\t\"SELECT payload_json FROM memory_index WHERE scope = ? ORDER BY provider_id, item_id\",\n\t);\n\tconst markStale = database.prepare(\n\t\t\"UPDATE memory_index SET stale = 1, payload_json = ? WHERE provider_id = ? AND item_id = ?\",\n\t);\n\tconst remove = database.prepare(\"DELETE FROM memory_index WHERE provider_id = ? AND item_id = ?\");\n\n\treturn {\n\t\tupsert(record: MemoryIndexRecord): void {\n\t\t\tupsert.run(\n\t\t\t\trecord.ref.providerId,\n\t\t\t\trecord.ref.itemId,\n\t\t\t\trecord.ref.scope,\n\t\t\t\trecord.ref.kind,\n\t\t\t\trecord.title ?? null,\n\t\t\t\trecord.summary,\n\t\t\t\trecord.indexedAtTurn,\n\t\t\t\trecord.stale ? 1 : 0,\n\t\t\t\tJSON.stringify(record),\n\t\t\t);\n\t\t},\n\n\t\tget(providerId: string, itemId: string): MemoryIndexRecord | undefined {\n\t\t\treturn memoryIndexRecordFromRow(get.get(providerId, itemId));\n\t\t},\n\n\t\tlist(scope?: MemoryIndexRecord[\"ref\"][\"scope\"]): MemoryIndexRecord[] {\n\t\t\tconst rows = scope === undefined ? listAll.all() : listByScope.all(scope);\n\t\t\treturn rows.flatMap((row) => {\n\t\t\t\tconst record = memoryIndexRecordFromRow(row);\n\t\t\t\treturn record === undefined ? [] : [record];\n\t\t\t});\n\t\t},\n\n\t\tmarkStale(providerId: string, itemId: string): void {\n\t\t\tconst existing = memoryIndexRecordFromRow(get.get(providerId, itemId));\n\t\t\tif (existing === undefined) return;\n\t\t\tmarkStale.run(JSON.stringify({ ...existing, stale: true }), providerId, itemId);\n\t\t},\n\n\t\tremove(providerId: string, itemId: string): void {\n\t\t\tremove.run(providerId, itemId);\n\t\t},\n\n\t\tclose(): void {\n\t\t\tdatabase[Symbol.dispose]();\n\t\t},\n\t};\n}\n"]}
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Storage authority/rebuildability metadata for SQLite runtime-index table design (Phase M0/M3).
3
+ *
4
+ * This module records, per runtime-index table, whether its rows are the only copy of
5
+ * something (canonical_local_state), rebuildable from another canonical source
6
+ * (derived_rebuildable), disposable performance data
7
+ * (runtime_cache_disposable), or audit/calibration telemetry whose loss does not affect
8
+ * current task truth (append_only_telemetry). Per memory-architecture.md: cleanup and
9
+ * prompt safety must never depend only on disposable/derived rows.
10
+ */
11
+ export type StorageAuthorityClass = "derived_rebuildable" | "runtime_cache_disposable" | "append_only_telemetry" | "canonical_local_state";
12
+ export interface StorageTableAuthority {
13
+ table: string;
14
+ authorityClass: StorageAuthorityClass;
15
+ /** Canonical sources this table can be rebuilt from, if authorityClass is derived_rebuildable. */
16
+ rebuildableFrom?: string[];
17
+ notes: string;
18
+ }
19
+ export declare const CONTEXT_STORAGE_TABLE_AUTHORITY: readonly StorageTableAuthority[];
20
+ //# sourceMappingURL=storage-authority.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storage-authority.d.ts","sourceRoot":"","sources":["../../../src/core/context/storage-authority.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,MAAM,MAAM,qBAAqB,GAC9B,qBAAqB,GACrB,0BAA0B,GAC1B,uBAAuB,GACvB,uBAAuB,CAAC;AAE3B,MAAM,WAAW,qBAAqB;IACrC,KAAK,EAAE,MAAM,CAAC;IACd,cAAc,EAAE,qBAAqB,CAAC;IACtC,kGAAkG;IAClG,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAC3B,KAAK,EAAE,MAAM,CAAC;CACd;AAED,eAAO,MAAM,+BAA+B,EAAE,SAAS,qBAAqB,EA0C3E,CAAC","sourcesContent":["/**\n * Storage authority/rebuildability metadata for SQLite runtime-index table design (Phase M0/M3).\n *\n * This module records, per runtime-index table, whether its rows are the only copy of\n * something (canonical_local_state), rebuildable from another canonical source\n * (derived_rebuildable), disposable performance data\n * (runtime_cache_disposable), or audit/calibration telemetry whose loss does not affect\n * current task truth (append_only_telemetry). Per memory-architecture.md: cleanup and\n * prompt safety must never depend only on disposable/derived rows.\n */\n\nexport type StorageAuthorityClass =\n\t| \"derived_rebuildable\"\n\t| \"runtime_cache_disposable\"\n\t| \"append_only_telemetry\"\n\t| \"canonical_local_state\";\n\nexport interface StorageTableAuthority {\n\ttable: string;\n\tauthorityClass: StorageAuthorityClass;\n\t/** Canonical sources this table can be rebuilt from, if authorityClass is derived_rebuildable. */\n\trebuildableFrom?: string[];\n\tnotes: string;\n}\n\nexport const CONTEXT_STORAGE_TABLE_AUTHORITY: readonly StorageTableAuthority[] = [\n\t{\n\t\ttable: \"context_items\",\n\t\tauthorityClass: \"derived_rebuildable\",\n\t\trebuildableFrom: [\"transcript\", \"artifacts\"],\n\t\tnotes: \"Working-memory context item metadata; rebuildable from transcript/artifacts if the index is lost.\",\n\t},\n\t{\n\t\ttable: \"artifact_metadata\",\n\t\tauthorityClass: \"canonical_local_state\",\n\t\tnotes:\n\t\t\t\"Artifact id/path/byte-length/reproducibility metadata. The artifact payload file is canonical raw \" +\n\t\t\t\"evidence, but this row is the only index to it; loss here can strand a payload as unreachable, so \" +\n\t\t\t\"treat as canonical_local_state and mirror writes into a durable journal before treating a ref as live.\",\n\t},\n\t{\n\t\ttable: \"policy_score_cache\",\n\t\tauthorityClass: \"runtime_cache_disposable\",\n\t\tnotes:\n\t\t\t\"Cached break-even score computations for context-retention candidates; safe to drop and \" +\n\t\t\t\"recompute on demand, and never consulted for a safety/retention decision by itself.\",\n\t},\n\t{\n\t\ttable: \"policy_decisions\",\n\t\tauthorityClass: \"append_only_telemetry\",\n\t\tnotes: \"Policy decision shadow/enforcement log for calibration and review; loss affects calibration, not current task truth.\",\n\t},\n\t{\n\t\ttable: \"retrieval_records\",\n\t\tauthorityClass: \"append_only_telemetry\",\n\t\tnotes: \"Retrieval/rehydration audit trail; loss affects observability, not current task truth.\",\n\t},\n\t{\n\t\ttable: \"memory_index\",\n\t\tauthorityClass: \"derived_rebuildable\",\n\t\trebuildableFrom: [\"okf_bundle\", \"external_provider\"],\n\t\tnotes:\n\t\t\t\"Index over durable memory sources; rebuildable by re-indexing the OKF bundle/provider content. \" +\n\t\t\t\"Rebuild from an external_provider source is conditional on that provider being enabled, reachable, \" +\n\t\t\t\"and permitted by egress/redaction policy at rebuild time; it is not unconditionally rebuildable \" +\n\t\t\t\"the way the OKF-bundle-backed portion is.\",\n\t},\n];\n"]}
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Storage authority/rebuildability metadata for SQLite runtime-index table design (Phase M0/M3).
3
+ *
4
+ * This module records, per runtime-index table, whether its rows are the only copy of
5
+ * something (canonical_local_state), rebuildable from another canonical source
6
+ * (derived_rebuildable), disposable performance data
7
+ * (runtime_cache_disposable), or audit/calibration telemetry whose loss does not affect
8
+ * current task truth (append_only_telemetry). Per memory-architecture.md: cleanup and
9
+ * prompt safety must never depend only on disposable/derived rows.
10
+ */
11
+ export const CONTEXT_STORAGE_TABLE_AUTHORITY = [
12
+ {
13
+ table: "context_items",
14
+ authorityClass: "derived_rebuildable",
15
+ rebuildableFrom: ["transcript", "artifacts"],
16
+ notes: "Working-memory context item metadata; rebuildable from transcript/artifacts if the index is lost.",
17
+ },
18
+ {
19
+ table: "artifact_metadata",
20
+ authorityClass: "canonical_local_state",
21
+ notes: "Artifact id/path/byte-length/reproducibility metadata. The artifact payload file is canonical raw " +
22
+ "evidence, but this row is the only index to it; loss here can strand a payload as unreachable, so " +
23
+ "treat as canonical_local_state and mirror writes into a durable journal before treating a ref as live.",
24
+ },
25
+ {
26
+ table: "policy_score_cache",
27
+ authorityClass: "runtime_cache_disposable",
28
+ notes: "Cached break-even score computations for context-retention candidates; safe to drop and " +
29
+ "recompute on demand, and never consulted for a safety/retention decision by itself.",
30
+ },
31
+ {
32
+ table: "policy_decisions",
33
+ authorityClass: "append_only_telemetry",
34
+ notes: "Policy decision shadow/enforcement log for calibration and review; loss affects calibration, not current task truth.",
35
+ },
36
+ {
37
+ table: "retrieval_records",
38
+ authorityClass: "append_only_telemetry",
39
+ notes: "Retrieval/rehydration audit trail; loss affects observability, not current task truth.",
40
+ },
41
+ {
42
+ table: "memory_index",
43
+ authorityClass: "derived_rebuildable",
44
+ rebuildableFrom: ["okf_bundle", "external_provider"],
45
+ notes: "Index over durable memory sources; rebuildable by re-indexing the OKF bundle/provider content. " +
46
+ "Rebuild from an external_provider source is conditional on that provider being enabled, reachable, " +
47
+ "and permitted by egress/redaction policy at rebuild time; it is not unconditionally rebuildable " +
48
+ "the way the OKF-bundle-backed portion is.",
49
+ },
50
+ ];
51
+ //# sourceMappingURL=storage-authority.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storage-authority.js","sourceRoot":"","sources":["../../../src/core/context/storage-authority.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAgBH,MAAM,CAAC,MAAM,+BAA+B,GAAqC;IAChF;QACC,KAAK,EAAE,eAAe;QACtB,cAAc,EAAE,qBAAqB;QACrC,eAAe,EAAE,CAAC,YAAY,EAAE,WAAW,CAAC;QAC5C,KAAK,EAAE,mGAAmG;KAC1G;IACD;QACC,KAAK,EAAE,mBAAmB;QAC1B,cAAc,EAAE,uBAAuB;QACvC,KAAK,EACJ,oGAAoG;YACpG,oGAAoG;YACpG,wGAAwG;KACzG;IACD;QACC,KAAK,EAAE,oBAAoB;QAC3B,cAAc,EAAE,0BAA0B;QAC1C,KAAK,EACJ,0FAA0F;YAC1F,qFAAqF;KACtF;IACD;QACC,KAAK,EAAE,kBAAkB;QACzB,cAAc,EAAE,uBAAuB;QACvC,KAAK,EAAE,sHAAsH;KAC7H;IACD;QACC,KAAK,EAAE,mBAAmB;QAC1B,cAAc,EAAE,uBAAuB;QACvC,KAAK,EAAE,wFAAwF;KAC/F;IACD;QACC,KAAK,EAAE,cAAc;QACrB,cAAc,EAAE,qBAAqB;QACrC,eAAe,EAAE,CAAC,YAAY,EAAE,mBAAmB,CAAC;QACpD,KAAK,EACJ,iGAAiG;YACjG,qGAAqG;YACrG,kGAAkG;YAClG,2CAA2C;KAC5C;CACD,CAAC","sourcesContent":["/**\n * Storage authority/rebuildability metadata for SQLite runtime-index table design (Phase M0/M3).\n *\n * This module records, per runtime-index table, whether its rows are the only copy of\n * something (canonical_local_state), rebuildable from another canonical source\n * (derived_rebuildable), disposable performance data\n * (runtime_cache_disposable), or audit/calibration telemetry whose loss does not affect\n * current task truth (append_only_telemetry). Per memory-architecture.md: cleanup and\n * prompt safety must never depend only on disposable/derived rows.\n */\n\nexport type StorageAuthorityClass =\n\t| \"derived_rebuildable\"\n\t| \"runtime_cache_disposable\"\n\t| \"append_only_telemetry\"\n\t| \"canonical_local_state\";\n\nexport interface StorageTableAuthority {\n\ttable: string;\n\tauthorityClass: StorageAuthorityClass;\n\t/** Canonical sources this table can be rebuilt from, if authorityClass is derived_rebuildable. */\n\trebuildableFrom?: string[];\n\tnotes: string;\n}\n\nexport const CONTEXT_STORAGE_TABLE_AUTHORITY: readonly StorageTableAuthority[] = [\n\t{\n\t\ttable: \"context_items\",\n\t\tauthorityClass: \"derived_rebuildable\",\n\t\trebuildableFrom: [\"transcript\", \"artifacts\"],\n\t\tnotes: \"Working-memory context item metadata; rebuildable from transcript/artifacts if the index is lost.\",\n\t},\n\t{\n\t\ttable: \"artifact_metadata\",\n\t\tauthorityClass: \"canonical_local_state\",\n\t\tnotes:\n\t\t\t\"Artifact id/path/byte-length/reproducibility metadata. The artifact payload file is canonical raw \" +\n\t\t\t\"evidence, but this row is the only index to it; loss here can strand a payload as unreachable, so \" +\n\t\t\t\"treat as canonical_local_state and mirror writes into a durable journal before treating a ref as live.\",\n\t},\n\t{\n\t\ttable: \"policy_score_cache\",\n\t\tauthorityClass: \"runtime_cache_disposable\",\n\t\tnotes:\n\t\t\t\"Cached break-even score computations for context-retention candidates; safe to drop and \" +\n\t\t\t\"recompute on demand, and never consulted for a safety/retention decision by itself.\",\n\t},\n\t{\n\t\ttable: \"policy_decisions\",\n\t\tauthorityClass: \"append_only_telemetry\",\n\t\tnotes: \"Policy decision shadow/enforcement log for calibration and review; loss affects calibration, not current task truth.\",\n\t},\n\t{\n\t\ttable: \"retrieval_records\",\n\t\tauthorityClass: \"append_only_telemetry\",\n\t\tnotes: \"Retrieval/rehydration audit trail; loss affects observability, not current task truth.\",\n\t},\n\t{\n\t\ttable: \"memory_index\",\n\t\tauthorityClass: \"derived_rebuildable\",\n\t\trebuildableFrom: [\"okf_bundle\", \"external_provider\"],\n\t\tnotes:\n\t\t\t\"Index over durable memory sources; rebuildable by re-indexing the OKF bundle/provider content. \" +\n\t\t\t\"Rebuild from an external_provider source is conditional on that provider being enabled, reachable, \" +\n\t\t\t\"and permitted by egress/redaction policy at rebuild time; it is not unconditionally rebuildable \" +\n\t\t\t\"the way the OKF-bundle-backed portion is.\",\n\t},\n];\n"]}
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Tool output digesting and packing (Phase 3): "measure -> digest/preview/artifact ->
3
+ * prompt item", per tool-output-artifacts.md's boundary rule. Large raw tool output is
4
+ * captured to an artifact BEFORE truncation, so the artifact holds the exact raw payload;
5
+ * the model only ever sees the bounded preview plus an artifact reference.
6
+ *
7
+ * This module is pure with respect to wiring: it takes an `ArtifactStore` by dependency
8
+ * injection and does not know about sessions, transcripts, or prompt construction. A tool
9
+ * (grep/find) that never passes an `ArtifactStore` gets byte-for-byte its prior behavior --
10
+ * packing is opt-in per call site, not a global switch.
11
+ */
12
+ import { type TruncationOptions, type TruncationResult } from "../tools/truncate.ts";
13
+ import type { ArtifactStore } from "./context-artifacts.ts";
14
+ export interface PackToolOutputRequest {
15
+ toolName: string;
16
+ command?: string;
17
+ path?: string;
18
+ rawContent: string;
19
+ sessionEntryId?: string;
20
+ /**
21
+ * Turn number for artifact capture identity. Real session-turn wiring lands in a later
22
+ * slice; callers that don't track turns yet may pass 0.
23
+ */
24
+ createdAtTurn?: number;
25
+ /** Whether re-running the same tool call would reproduce this content. Default: true. */
26
+ reproducible?: boolean;
27
+ truncation?: TruncationOptions;
28
+ }
29
+ export interface PackedToolOutput {
30
+ /**
31
+ * Bounded preview content -- exactly what `truncateHead` alone would have produced.
32
+ * No footer/notice text is appended here; callers already have their own per-tool
33
+ * footer conventions (grep's vs. find's bracket ordering differ) and own formatting
34
+ * the artifact notice into their own notice list via `formatArtifactNotice`.
35
+ */
36
+ content: string;
37
+ truncation: TruncationResult;
38
+ /** Present only if packing succeeded and the artifact is protected from cleanup. */
39
+ artifactId?: string;
40
+ packed: boolean;
41
+ }
42
+ /** Footer notice text for a packed artifact, for callers to fold into their own notices. */
43
+ export declare function formatArtifactNotice(artifactId: string): string;
44
+ /**
45
+ * Measure `request.rawContent`; if it fits within the caps, return it unchanged (small
46
+ * output stays exactly as readable as before this module existed). If it's oversized and
47
+ * an `ArtifactStore` is provided, capture the exact raw payload as an artifact first, then
48
+ * return the same bounded preview `truncateHead` would have produced anyway.
49
+ *
50
+ * Fails closed: if the artifact write succeeds but registering `holderId` as a reference
51
+ * fails (`addReference` returns false), the artifact is not claimed in the result at all --
52
+ * the caller falls back to the bounded/truncated content exactly as if no store had been
53
+ * provided, since an unprotected artifact could be cleaned up at any time.
54
+ */
55
+ export declare function packToolOutput(request: PackToolOutputRequest, artifactStore: ArtifactStore | undefined, holderId: string): PackedToolOutput;
56
+ export interface BroadQueryTracker {
57
+ /** Record one more broad occurrence of `key`; returns the cumulative count including this one. */
58
+ recordBroadQuery(key: string): number;
59
+ }
60
+ export declare function createInMemoryBroadQueryTracker(): BroadQueryTracker;
61
+ /** Normalize a search-tool call into a stable repetition key: same query, same broadness. */
62
+ export declare function normalizeBroadQueryKey(input: {
63
+ toolName: string;
64
+ pattern?: string;
65
+ path?: string;
66
+ glob?: string;
67
+ }): string;
68
+ /**
69
+ * When a broad-query condition (match/result limit hit, or byte truncation) repeats for
70
+ * the same normalized query, produce a compact "do not repeat" style note. This is only
71
+ * the Phase 3 signal; the durable invalidation ledger (supersession/expiry rules) is
72
+ * Phase 6 per implementation-phases.md.
73
+ */
74
+ export declare function broadQueryInvalidationNote(tracker: BroadQueryTracker | undefined, key: string, humanQueryDescription: string): string | undefined;
75
+ //# sourceMappingURL=tool-output-packer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-output-packer.d.ts","sourceRoot":"","sources":["../../../src/core/context/tool-output-packer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,KAAK,iBAAiB,EAAE,KAAK,gBAAgB,EAAgB,MAAM,sBAAsB,CAAC;AACnG,OAAO,KAAK,EAAE,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AS,EACtC,GAAG,EAAE,MAAM,EACX,qBAAqB,EAAE,MAAM,GAC3B,MAAM,GAAG,SAAS,CAKpB","sourcesContent":["/**\n * Tool output digesting and packing (Phase 3): \"measure -> digest/preview/artifact ->\n * prompt item\", per tool-output-artifacts.md's boundary rule. Large raw tool output is\n * captured to an artifact BEFORE truncation, so the artifact holds the exact raw payload;\n * the model only ever sees the bounded preview plus an artifact reference.\n *\n * This module is pure with respect to wiring: it takes an `ArtifactStore` by dependency\n * injection and does not know about sessions, transcripts, or prompt construction. A tool\n * (grep/find) that never passes an `ArtifactStore` gets byte-for-byte its prior behavior --\n * packing is opt-in per call site, not a global switch.\n */\n\nimport { type TruncationOptions, type TruncationResult, truncateHead } from \"../tools/truncate.ts\";\nimport type { ArtifactStore } from \"./context-artifacts.ts\";\n\nexport interface PackToolOutputRequest {\n\ttoolName: string;\n\tcommand?: string;\n\tpath?: string;\n\trawContent: string;\n\tsessionEntryId?: string;\n\t/**\n\t * Turn number for artifact capture identity. Real session-turn wiring lands in a later\n\t * slice; callers that don't track turns yet may pass 0.\n\t */\n\tcreatedAtTurn?: number;\n\t/** Whether re-running the same tool call would reproduce this content. Default: true. */\n\treproducible?: boolean;\n\ttruncation?: TruncationOptions;\n}\n\nexport interface PackedToolOutput {\n\t/**\n\t * Bounded preview content -- exactly what `truncateHead` alone would have produced.\n\t * No footer/notice text is appended here; callers already have their own per-tool\n\t * footer conventions (grep's vs. find's bracket ordering differ) and own formatting\n\t * the artifact notice into their own notice list via `formatArtifactNotice`.\n\t */\n\tcontent: string;\n\ttruncation: TruncationResult;\n\t/** Present only if packing succeeded and the artifact is protected from cleanup. */\n\tartifactId?: string;\n\tpacked: boolean;\n}\n\n/** Footer notice text for a packed artifact, for callers to fold into their own notices. */\nexport function formatArtifactNotice(artifactId: string): string {\n\treturn `Full output: artifact tool-output:${artifactId}`;\n}\n\n/**\n * Measure `request.rawContent`; if it fits within the caps, return it unchanged (small\n * output stays exactly as readable as before this module existed). If it's oversized and\n * an `ArtifactStore` is provided, capture the exact raw payload as an artifact first, then\n * return the same bounded preview `truncateHead` would have produced anyway.\n *\n * Fails closed: if the artifact write succeeds but registering `holderId` as a reference\n * fails (`addReference` returns false), the artifact is not claimed in the result at all --\n * the caller falls back to the bounded/truncated content exactly as if no store had been\n * provided, since an unprotected artifact could be cleaned up at any time.\n */\nexport function packToolOutput(\n\trequest: PackToolOutputRequest,\n\tartifactStore: ArtifactStore | undefined,\n\tholderId: string,\n): PackedToolOutput {\n\tconst truncation = truncateHead(request.rawContent, request.truncation);\n\n\tif (!truncation.truncated || !artifactStore) {\n\t\treturn { content: truncation.content, truncation, packed: false };\n\t}\n\n\tconst { ref } = artifactStore.write({\n\t\tkind: \"tool_output\",\n\t\tcontent: request.rawContent,\n\t\ttoolName: request.toolName,\n\t\tcommand: request.command,\n\t\tpath: request.path,\n\t\tsessionEntryId: request.sessionEntryId,\n\t\tcreatedAtTurn: request.createdAtTurn ?? 0,\n\t\treproducible: request.reproducible ?? true,\n\t});\n\n\tif (!artifactStore.addReference(ref.id, holderId)) {\n\t\treturn { content: truncation.content, truncation, packed: false };\n\t}\n\n\treturn { content: truncation.content, truncation, artifactId: ref.id, packed: true };\n}\n\nexport interface BroadQueryTracker {\n\t/** Record one more broad occurrence of `key`; returns the cumulative count including this one. */\n\trecordBroadQuery(key: string): number;\n}\n\nexport function createInMemoryBroadQueryTracker(): BroadQueryTracker {\n\tconst counts = new Map<string, number>();\n\treturn {\n\t\trecordBroadQuery(key: string): number {\n\t\t\tconst next = (counts.get(key) ?? 0) + 1;\n\t\t\tcounts.set(key, next);\n\t\t\treturn next;\n\t\t},\n\t};\n}\n\n/** Normalize a search-tool call into a stable repetition key: same query, same broadness. */\nexport function normalizeBroadQueryKey(input: {\n\ttoolName: string;\n\tpattern?: string;\n\tpath?: string;\n\tglob?: string;\n}): string {\n\treturn [input.toolName, input.pattern ?? \"\", input.path ?? \"\", input.glob ?? \"\"].join(\"␟\");\n}\n\nconst REPEATED_BROAD_QUERY_THRESHOLD = 2;\n\n/**\n * When a broad-query condition (match/result limit hit, or byte truncation) repeats for\n * the same normalized query, produce a compact \"do not repeat\" style note. This is only\n * the Phase 3 signal; the durable invalidation ledger (supersession/expiry rules) is\n * Phase 6 per implementation-phases.md.\n */\nexport function broadQueryInvalidationNote(\n\ttracker: BroadQueryTracker | undefined,\n\tkey: string,\n\thumanQueryDescription: string,\n): string | undefined {\n\tif (!tracker) return undefined;\n\tconst count = tracker.recordBroadQuery(key);\n\tif (count < REPEATED_BROAD_QUERY_THRESHOLD) return undefined;\n\treturn `Do not repeat: ${humanQueryDescription} has produced broad/truncated results ${count} times in this session. Narrow the path/glob/pattern.`;\n}\n"]}