@caupulican/pi-adaptative 0.81.39 → 0.81.41

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 (884) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/README.md +2 -0
  3. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.d.ts +2 -0
  4. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.d.ts.map +1 -1
  5. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.js +3 -0
  6. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.js.map +1 -1
  7. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.ts +4 -0
  8. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts +9 -0
  9. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts.map +1 -1
  10. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js +290 -107
  11. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js.map +1 -1
  12. package/dist/bundled-resources/extensions/tmux-agent-manager/index.ts +357 -122
  13. package/dist/bundled-resources/skills/tool-call-repair/references/repair-catalogue.md +2 -2
  14. package/dist/cli/args.d.ts +4 -0
  15. package/dist/cli/args.d.ts.map +1 -1
  16. package/dist/cli/args.js +31 -1
  17. package/dist/cli/args.js.map +1 -1
  18. package/dist/core/agent-directory-layout.d.ts +15 -0
  19. package/dist/core/agent-directory-layout.d.ts.map +1 -0
  20. package/dist/core/agent-directory-layout.js +72 -0
  21. package/dist/core/agent-directory-layout.js.map +1 -0
  22. package/dist/core/agent-paths.d.ts +25 -2
  23. package/dist/core/agent-paths.d.ts.map +1 -1
  24. package/dist/core/agent-paths.js +79 -4
  25. package/dist/core/agent-paths.js.map +1 -1
  26. package/dist/core/agent-session-contracts.d.ts +293 -0
  27. package/dist/core/agent-session-contracts.d.ts.map +1 -0
  28. package/dist/core/agent-session-contracts.js +26 -0
  29. package/dist/core/agent-session-contracts.js.map +1 -0
  30. package/dist/core/agent-session-runtime.d.ts +52 -8
  31. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  32. package/dist/core/agent-session-runtime.js +400 -79
  33. package/dist/core/agent-session-runtime.js.map +1 -1
  34. package/dist/core/agent-session-services.d.ts +1 -0
  35. package/dist/core/agent-session-services.d.ts.map +1 -1
  36. package/dist/core/agent-session-services.js +1 -0
  37. package/dist/core/agent-session-services.js.map +1 -1
  38. package/dist/core/agent-session.d.ts +74 -518
  39. package/dist/core/agent-session.d.ts.map +1 -1
  40. package/dist/core/agent-session.js +370 -1432
  41. package/dist/core/agent-session.js.map +1 -1
  42. package/dist/core/auth-storage.d.ts.map +1 -1
  43. package/dist/core/auth-storage.js +3 -1
  44. package/dist/core/auth-storage.js.map +1 -1
  45. package/dist/core/autonomy/approval-gate.d.ts +3 -2
  46. package/dist/core/autonomy/approval-gate.d.ts.map +1 -1
  47. package/dist/core/autonomy/approval-gate.js +6 -28
  48. package/dist/core/autonomy/approval-gate.js.map +1 -1
  49. package/dist/core/autonomy/bounded-completion.d.ts +1 -1
  50. package/dist/core/autonomy/bounded-completion.d.ts.map +1 -1
  51. package/dist/core/autonomy/bounded-completion.js +1 -1
  52. package/dist/core/autonomy/bounded-completion.js.map +1 -1
  53. package/dist/core/autonomy/contracts.d.ts +20 -12
  54. package/dist/core/autonomy/contracts.d.ts.map +1 -1
  55. package/dist/core/autonomy/contracts.js.map +1 -1
  56. package/dist/core/autonomy/foreground-envelope.d.ts +8 -2
  57. package/dist/core/autonomy/foreground-envelope.d.ts.map +1 -1
  58. package/dist/core/autonomy/foreground-envelope.js +8 -25
  59. package/dist/core/autonomy/foreground-envelope.js.map +1 -1
  60. package/dist/core/autonomy/gates.d.ts.map +1 -1
  61. package/dist/core/autonomy/gates.js +8 -10
  62. package/dist/core/autonomy/gates.js.map +1 -1
  63. package/dist/core/autonomy/lane-private-paths.d.ts +2 -0
  64. package/dist/core/autonomy/lane-private-paths.d.ts.map +1 -0
  65. package/dist/core/autonomy/lane-private-paths.js +16 -0
  66. package/dist/core/autonomy/lane-private-paths.js.map +1 -0
  67. package/dist/core/autonomy/lane-tool-surface.d.ts +10 -0
  68. package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
  69. package/dist/core/autonomy/lane-tool-surface.js +48 -9
  70. package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
  71. package/dist/core/autonomy/lane-tracker.d.ts +14 -0
  72. package/dist/core/autonomy/lane-tracker.d.ts.map +1 -1
  73. package/dist/core/autonomy/lane-tracker.js +38 -0
  74. package/dist/core/autonomy/lane-tracker.js.map +1 -1
  75. package/dist/core/autonomy/risk-assessment.d.ts +1 -2
  76. package/dist/core/autonomy/risk-assessment.d.ts.map +1 -1
  77. package/dist/core/autonomy/risk-assessment.js +1 -123
  78. package/dist/core/autonomy/risk-assessment.js.map +1 -1
  79. package/dist/core/autonomy/session-lane-record.d.ts +4 -4
  80. package/dist/core/autonomy/session-lane-record.d.ts.map +1 -1
  81. package/dist/core/autonomy/session-lane-record.js +16 -29
  82. package/dist/core/autonomy/session-lane-record.js.map +1 -1
  83. package/dist/core/autonomy/telemetry-events.d.ts +1 -1
  84. package/dist/core/autonomy/telemetry-events.d.ts.map +1 -1
  85. package/dist/core/autonomy/telemetry-events.js +1 -1
  86. package/dist/core/autonomy/telemetry-events.js.map +1 -1
  87. package/dist/core/autonomy-telemetry.d.ts +7 -7
  88. package/dist/core/autonomy-telemetry.d.ts.map +1 -1
  89. package/dist/core/autonomy-telemetry.js +9 -9
  90. package/dist/core/autonomy-telemetry.js.map +1 -1
  91. package/dist/core/background-lane-controller.d.ts +56 -236
  92. package/dist/core/background-lane-controller.d.ts.map +1 -1
  93. package/dist/core/background-lane-controller.js +141 -1273
  94. package/dist/core/background-lane-controller.js.map +1 -1
  95. package/dist/core/bedrock-sso-login.d.ts +16 -0
  96. package/dist/core/bedrock-sso-login.d.ts.map +1 -0
  97. package/dist/core/bedrock-sso-login.js +98 -0
  98. package/dist/core/bedrock-sso-login.js.map +1 -0
  99. package/dist/core/capability-contract.d.ts +4 -0
  100. package/dist/core/capability-contract.d.ts.map +1 -0
  101. package/dist/core/capability-contract.js +28 -0
  102. package/dist/core/capability-contract.js.map +1 -0
  103. package/dist/core/compaction-controller.d.ts +90 -0
  104. package/dist/core/compaction-controller.d.ts.map +1 -0
  105. package/dist/core/compaction-controller.js +452 -0
  106. package/dist/core/compaction-controller.js.map +1 -0
  107. package/dist/core/compaction-support.d.ts +13 -17
  108. package/dist/core/compaction-support.d.ts.map +1 -1
  109. package/dist/core/compaction-support.js +3 -3
  110. package/dist/core/compaction-support.js.map +1 -1
  111. package/dist/core/context/context-artifacts.d.ts +6 -2
  112. package/dist/core/context/context-artifacts.d.ts.map +1 -1
  113. package/dist/core/context/context-artifacts.js +34 -2
  114. package/dist/core/context/context-artifacts.js.map +1 -1
  115. package/dist/core/context/context-store-retention.d.ts +8 -2
  116. package/dist/core/context/context-store-retention.d.ts.map +1 -1
  117. package/dist/core/context/context-store-retention.js +158 -35
  118. package/dist/core/context/context-store-retention.js.map +1 -1
  119. package/dist/core/context/okf-memory.d.ts.map +1 -1
  120. package/dist/core/context/okf-memory.js +9 -11
  121. package/dist/core/context/okf-memory.js.map +1 -1
  122. package/dist/core/context/sqlite-runtime-index.d.ts.map +1 -1
  123. package/dist/core/context/sqlite-runtime-index.js +6 -8
  124. package/dist/core/context/sqlite-runtime-index.js.map +1 -1
  125. package/dist/core/context-gc.d.ts +3 -0
  126. package/dist/core/context-gc.d.ts.map +1 -1
  127. package/dist/core/context-gc.js +10 -5
  128. package/dist/core/context-gc.js.map +1 -1
  129. package/dist/core/context-pipeline.d.ts +1 -1
  130. package/dist/core/context-pipeline.d.ts.map +1 -1
  131. package/dist/core/context-pipeline.js +16 -37
  132. package/dist/core/context-pipeline.js.map +1 -1
  133. package/dist/core/cost/cost-summary.d.ts.map +1 -1
  134. package/dist/core/cost/cost-summary.js +5 -3
  135. package/dist/core/cost/cost-summary.js.map +1 -1
  136. package/dist/core/cost/daily-usage.d.ts.map +1 -1
  137. package/dist/core/cost/daily-usage.js +4 -5
  138. package/dist/core/cost/daily-usage.js.map +1 -1
  139. package/dist/core/default-tool-surface.d.ts.map +1 -1
  140. package/dist/core/default-tool-surface.js +2 -0
  141. package/dist/core/default-tool-surface.js.map +1 -1
  142. package/dist/core/delegation/managed-lane-controller.d.ts +34 -0
  143. package/dist/core/delegation/managed-lane-controller.d.ts.map +1 -0
  144. package/dist/core/delegation/managed-lane-controller.js +217 -0
  145. package/dist/core/delegation/managed-lane-controller.js.map +1 -0
  146. package/dist/core/delegation/session-worker-claim.d.ts +44 -0
  147. package/dist/core/delegation/session-worker-claim.d.ts.map +1 -0
  148. package/dist/core/delegation/session-worker-claim.js +98 -0
  149. package/dist/core/delegation/session-worker-claim.js.map +1 -0
  150. package/dist/core/delegation/worker-actions.d.ts +7 -5
  151. package/dist/core/delegation/worker-actions.d.ts.map +1 -1
  152. package/dist/core/delegation/worker-actions.js +20 -4
  153. package/dist/core/delegation/worker-actions.js.map +1 -1
  154. package/dist/core/delegation/{worker-result.d.ts → worker-claim.d.ts} +13 -13
  155. package/dist/core/delegation/worker-claim.d.ts.map +1 -0
  156. package/dist/core/delegation/{worker-result.js → worker-claim.js} +61 -51
  157. package/dist/core/delegation/worker-claim.js.map +1 -0
  158. package/dist/core/delegation/worker-delegation-controller.d.ts +110 -0
  159. package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -0
  160. package/dist/core/delegation/worker-delegation-controller.js +861 -0
  161. package/dist/core/delegation/worker-delegation-controller.js.map +1 -0
  162. package/dist/core/delegation/worker-delegation-request.d.ts +11 -0
  163. package/dist/core/delegation/worker-delegation-request.d.ts.map +1 -0
  164. package/dist/core/delegation/worker-delegation-request.js +2 -0
  165. package/dist/core/delegation/worker-delegation-request.js.map +1 -0
  166. package/dist/core/delegation/worker-dispatch-scheduler.d.ts +40 -0
  167. package/dist/core/delegation/worker-dispatch-scheduler.d.ts.map +1 -0
  168. package/dist/core/delegation/worker-dispatch-scheduler.js +93 -0
  169. package/dist/core/delegation/worker-dispatch-scheduler.js.map +1 -0
  170. package/dist/core/delegation/worker-execution-policy.d.ts +62 -0
  171. package/dist/core/delegation/worker-execution-policy.d.ts.map +1 -0
  172. package/dist/core/delegation/worker-execution-policy.js +160 -0
  173. package/dist/core/delegation/worker-execution-policy.js.map +1 -0
  174. package/dist/core/delegation/worker-lane-projection.d.ts +14 -0
  175. package/dist/core/delegation/worker-lane-projection.d.ts.map +1 -0
  176. package/dist/core/delegation/worker-lane-projection.js +100 -0
  177. package/dist/core/delegation/worker-lane-projection.js.map +1 -0
  178. package/dist/core/delegation/worker-lifecycle.d.ts +97 -0
  179. package/dist/core/delegation/worker-lifecycle.d.ts.map +1 -0
  180. package/dist/core/delegation/worker-lifecycle.js +339 -0
  181. package/dist/core/delegation/worker-lifecycle.js.map +1 -0
  182. package/dist/core/delegation/worker-notification-coordinator.d.ts +36 -0
  183. package/dist/core/delegation/worker-notification-coordinator.d.ts.map +1 -0
  184. package/dist/core/delegation/worker-notification-coordinator.js +90 -0
  185. package/dist/core/delegation/worker-notification-coordinator.js.map +1 -0
  186. package/dist/core/delegation/worker-profile-resolver.d.ts +55 -0
  187. package/dist/core/delegation/worker-profile-resolver.d.ts.map +1 -0
  188. package/dist/core/delegation/worker-profile-resolver.js +113 -0
  189. package/dist/core/delegation/worker-profile-resolver.js.map +1 -0
  190. package/dist/core/delegation/worker-runner.d.ts +25 -14
  191. package/dist/core/delegation/worker-runner.d.ts.map +1 -1
  192. package/dist/core/delegation/worker-runner.js +122 -53
  193. package/dist/core/delegation/worker-runner.js.map +1 -1
  194. package/dist/core/delegation/worker-task-label.d.ts +3 -0
  195. package/dist/core/delegation/worker-task-label.d.ts.map +1 -0
  196. package/dist/core/delegation/worker-task-label.js +11 -0
  197. package/dist/core/delegation/worker-task-label.js.map +1 -0
  198. package/dist/core/doctor.d.ts +8 -0
  199. package/dist/core/doctor.d.ts.map +1 -1
  200. package/dist/core/doctor.js +32 -1
  201. package/dist/core/doctor.js.map +1 -1
  202. package/dist/core/extension-import-authority.d.ts +6 -0
  203. package/dist/core/extension-import-authority.d.ts.map +1 -0
  204. package/dist/core/extension-import-authority.js +10 -0
  205. package/dist/core/extension-import-authority.js.map +1 -0
  206. package/dist/core/extensions/index.d.ts +1 -1
  207. package/dist/core/extensions/index.d.ts.map +1 -1
  208. package/dist/core/extensions/index.js.map +1 -1
  209. package/dist/core/extensions/loader.d.ts +5 -1
  210. package/dist/core/extensions/loader.d.ts.map +1 -1
  211. package/dist/core/extensions/loader.js +52 -18
  212. package/dist/core/extensions/loader.js.map +1 -1
  213. package/dist/core/extensions/runner.d.ts +3 -0
  214. package/dist/core/extensions/runner.d.ts.map +1 -1
  215. package/dist/core/extensions/runner.js +20 -5
  216. package/dist/core/extensions/runner.js.map +1 -1
  217. package/dist/core/extensions/stale-context.d.ts +2 -0
  218. package/dist/core/extensions/stale-context.d.ts.map +1 -0
  219. package/dist/core/extensions/stale-context.js +2 -0
  220. package/dist/core/extensions/stale-context.js.map +1 -0
  221. package/dist/core/extensions/storage.d.ts +8 -0
  222. package/dist/core/extensions/storage.d.ts.map +1 -0
  223. package/dist/core/extensions/storage.js +28 -0
  224. package/dist/core/extensions/storage.js.map +1 -0
  225. package/dist/core/extensions/types.d.ts +78 -21
  226. package/dist/core/extensions/types.d.ts.map +1 -1
  227. package/dist/core/extensions/types.js.map +1 -1
  228. package/dist/core/failure-corpus.d.ts +1 -15
  229. package/dist/core/failure-corpus.d.ts.map +1 -1
  230. package/dist/core/failure-corpus.js +9 -37
  231. package/dist/core/failure-corpus.js.map +1 -1
  232. package/dist/core/foreground-recovery-controller.d.ts +53 -0
  233. package/dist/core/foreground-recovery-controller.d.ts.map +1 -0
  234. package/dist/core/foreground-recovery-controller.js +111 -0
  235. package/dist/core/foreground-recovery-controller.js.map +1 -0
  236. package/dist/core/gateways/channel-provider.d.ts +3 -0
  237. package/dist/core/gateways/channel-provider.d.ts.map +1 -1
  238. package/dist/core/gateways/channel-provider.js +31 -6
  239. package/dist/core/gateways/channel-provider.js.map +1 -1
  240. package/dist/core/goal-loop-controller.d.ts +14 -9
  241. package/dist/core/goal-loop-controller.d.ts.map +1 -1
  242. package/dist/core/goal-loop-controller.js +47 -75
  243. package/dist/core/goal-loop-controller.js.map +1 -1
  244. package/dist/core/goals/compact-goal-context.d.ts +11 -0
  245. package/dist/core/goals/compact-goal-context.d.ts.map +1 -0
  246. package/dist/core/goals/compact-goal-context.js +59 -0
  247. package/dist/core/goals/compact-goal-context.js.map +1 -0
  248. package/dist/core/goals/goal-acceptance.d.ts +11 -0
  249. package/dist/core/goals/goal-acceptance.d.ts.map +1 -0
  250. package/dist/core/goals/goal-acceptance.js +27 -0
  251. package/dist/core/goals/goal-acceptance.js.map +1 -0
  252. package/dist/core/goals/goal-auto-continue-controller.d.ts +28 -0
  253. package/dist/core/goals/goal-auto-continue-controller.d.ts.map +1 -0
  254. package/dist/core/goals/goal-auto-continue-controller.js +90 -0
  255. package/dist/core/goals/goal-auto-continue-controller.js.map +1 -0
  256. package/dist/core/goals/goal-continuation-controller.d.ts +2 -2
  257. package/dist/core/goals/goal-continuation-controller.d.ts.map +1 -1
  258. package/dist/core/goals/goal-continuation-controller.js +52 -11
  259. package/dist/core/goals/goal-continuation-controller.js.map +1 -1
  260. package/dist/core/goals/goal-continuation-defaults.d.ts +4 -29
  261. package/dist/core/goals/goal-continuation-defaults.d.ts.map +1 -1
  262. package/dist/core/goals/goal-continuation-defaults.js +4 -32
  263. package/dist/core/goals/goal-continuation-defaults.js.map +1 -1
  264. package/dist/core/goals/goal-continuation-prompt.d.ts +8 -18
  265. package/dist/core/goals/goal-continuation-prompt.d.ts.map +1 -1
  266. package/dist/core/goals/goal-continuation-prompt.js +9 -179
  267. package/dist/core/goals/goal-continuation-prompt.js.map +1 -1
  268. package/dist/core/goals/goal-lifecycle.d.ts +43 -0
  269. package/dist/core/goals/goal-lifecycle.d.ts.map +1 -0
  270. package/dist/core/goals/goal-lifecycle.js +102 -0
  271. package/dist/core/goals/goal-lifecycle.js.map +1 -0
  272. package/dist/core/goals/goal-record.d.ts +17 -0
  273. package/dist/core/goals/goal-record.d.ts.map +1 -0
  274. package/dist/core/goals/goal-record.js +31 -0
  275. package/dist/core/goals/goal-record.js.map +1 -0
  276. package/dist/core/goals/goal-runtime-snapshot.d.ts +11 -9
  277. package/dist/core/goals/goal-runtime-snapshot.d.ts.map +1 -1
  278. package/dist/core/goals/goal-runtime-snapshot.js +10 -8
  279. package/dist/core/goals/goal-runtime-snapshot.js.map +1 -1
  280. package/dist/core/goals/goal-session-controller.d.ts +42 -0
  281. package/dist/core/goals/goal-session-controller.d.ts.map +1 -0
  282. package/dist/core/goals/goal-session-controller.js +128 -0
  283. package/dist/core/goals/goal-session-controller.js.map +1 -0
  284. package/dist/core/goals/goal-state.d.ts +46 -25
  285. package/dist/core/goals/goal-state.d.ts.map +1 -1
  286. package/dist/core/goals/goal-state.js +91 -24
  287. package/dist/core/goals/goal-state.js.map +1 -1
  288. package/dist/core/goals/goal-tool-core.d.ts +9 -10
  289. package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
  290. package/dist/core/goals/goal-tool-core.js +60 -75
  291. package/dist/core/goals/goal-tool-core.js.map +1 -1
  292. package/dist/core/goals/session-goal-state.d.ts +20 -12
  293. package/dist/core/goals/session-goal-state.d.ts.map +1 -1
  294. package/dist/core/goals/session-goal-state.js +133 -33
  295. package/dist/core/goals/session-goal-state.js.map +1 -1
  296. package/dist/core/human-input-controller.d.ts +47 -0
  297. package/dist/core/human-input-controller.d.ts.map +1 -0
  298. package/dist/core/human-input-controller.js +181 -0
  299. package/dist/core/human-input-controller.js.map +1 -0
  300. package/dist/core/human-input.d.ts +100 -0
  301. package/dist/core/human-input.d.ts.map +1 -0
  302. package/dist/core/human-input.js +362 -0
  303. package/dist/core/human-input.js.map +1 -0
  304. package/dist/core/index.d.ts +9 -1
  305. package/dist/core/index.d.ts.map +1 -1
  306. package/dist/core/index.js +9 -1
  307. package/dist/core/index.js.map +1 -1
  308. package/dist/core/{telemetry.d.ts → install-telemetry.d.ts} +1 -1
  309. package/dist/core/install-telemetry.d.ts.map +1 -0
  310. package/dist/core/{telemetry.js → install-telemetry.js} +1 -1
  311. package/dist/core/install-telemetry.js.map +1 -0
  312. package/dist/core/keybindings.d.ts +17 -1
  313. package/dist/core/keybindings.d.ts.map +1 -1
  314. package/dist/core/keybindings.js +24 -6
  315. package/dist/core/keybindings.js.map +1 -1
  316. package/dist/core/learning/learning-audit.d.ts +2 -4
  317. package/dist/core/learning/learning-audit.d.ts.map +1 -1
  318. package/dist/core/learning/learning-audit.js +9 -29
  319. package/dist/core/learning/learning-audit.js.map +1 -1
  320. package/dist/core/learning/learning-gate.d.ts.map +1 -1
  321. package/dist/core/learning/learning-gate.js +1 -6
  322. package/dist/core/learning/learning-gate.js.map +1 -1
  323. package/dist/core/learning/session-learning-decision.d.ts +2 -4
  324. package/dist/core/learning/session-learning-decision.d.ts.map +1 -1
  325. package/dist/core/learning/session-learning-decision.js +9 -29
  326. package/dist/core/learning/session-learning-decision.js.map +1 -1
  327. package/dist/core/local-runtime-controller.d.ts +1 -1
  328. package/dist/core/local-runtime-controller.d.ts.map +1 -1
  329. package/dist/core/local-runtime-controller.js.map +1 -1
  330. package/dist/core/memory-controller.d.ts.map +1 -1
  331. package/dist/core/memory-controller.js +4 -4
  332. package/dist/core/memory-controller.js.map +1 -1
  333. package/dist/core/model-capability.d.ts +0 -19
  334. package/dist/core/model-capability.d.ts.map +1 -1
  335. package/dist/core/model-capability.js +1 -19
  336. package/dist/core/model-capability.js.map +1 -1
  337. package/dist/core/model-registry.d.ts +6 -1
  338. package/dist/core/model-registry.d.ts.map +1 -1
  339. package/dist/core/model-registry.js +13 -5
  340. package/dist/core/model-registry.js.map +1 -1
  341. package/dist/core/model-resolver.d.ts +17 -2
  342. package/dist/core/model-resolver.d.ts.map +1 -1
  343. package/dist/core/model-resolver.js +38 -25
  344. package/dist/core/model-resolver.js.map +1 -1
  345. package/dist/core/model-router/intent-classifier.d.ts +1 -4
  346. package/dist/core/model-router/intent-classifier.d.ts.map +1 -1
  347. package/dist/core/model-router/intent-classifier.js +1 -156
  348. package/dist/core/model-router/intent-classifier.js.map +1 -1
  349. package/dist/core/model-router-controller.d.ts +1 -1
  350. package/dist/core/model-router-controller.d.ts.map +1 -1
  351. package/dist/core/model-router-controller.js +2 -2
  352. package/dist/core/model-router-controller.js.map +1 -1
  353. package/dist/core/model-selection-controller.d.ts +5 -5
  354. package/dist/core/model-selection-controller.d.ts.map +1 -1
  355. package/dist/core/model-selection-controller.js.map +1 -1
  356. package/dist/core/model-tool-protocol.d.ts +23 -0
  357. package/dist/core/model-tool-protocol.d.ts.map +1 -0
  358. package/dist/core/model-tool-protocol.js +43 -0
  359. package/dist/core/model-tool-protocol.js.map +1 -0
  360. package/dist/core/models/adaptation-store.d.ts +4 -6
  361. package/dist/core/models/adaptation-store.d.ts.map +1 -1
  362. package/dist/core/models/adaptation-store.js +95 -83
  363. package/dist/core/models/adaptation-store.js.map +1 -1
  364. package/dist/core/models/fitness-store.d.ts +2 -12
  365. package/dist/core/models/fitness-store.d.ts.map +1 -1
  366. package/dist/core/models/fitness-store.js +84 -57
  367. package/dist/core/models/fitness-store.js.map +1 -1
  368. package/dist/core/models/host-state-store.d.ts +34 -0
  369. package/dist/core/models/host-state-store.d.ts.map +1 -0
  370. package/dist/core/models/host-state-store.js +86 -0
  371. package/dist/core/models/host-state-store.js.map +1 -0
  372. package/dist/core/orchestration/agent-resume.d.ts +24 -0
  373. package/dist/core/orchestration/agent-resume.d.ts.map +1 -0
  374. package/dist/core/orchestration/agent-resume.js +90 -0
  375. package/dist/core/orchestration/agent-resume.js.map +1 -0
  376. package/dist/core/orchestration/capability-gateway.d.ts +61 -0
  377. package/dist/core/orchestration/capability-gateway.d.ts.map +1 -0
  378. package/dist/core/orchestration/capability-gateway.js +152 -0
  379. package/dist/core/orchestration/capability-gateway.js.map +1 -0
  380. package/dist/core/orchestration/contracts.d.ts +343 -0
  381. package/dist/core/orchestration/contracts.d.ts.map +1 -0
  382. package/dist/core/orchestration/contracts.js +135 -0
  383. package/dist/core/orchestration/contracts.js.map +1 -0
  384. package/dist/core/orchestration/delegation-ledger.d.ts +56 -0
  385. package/dist/core/orchestration/delegation-ledger.d.ts.map +1 -0
  386. package/dist/core/orchestration/delegation-ledger.js +200 -0
  387. package/dist/core/orchestration/delegation-ledger.js.map +1 -0
  388. package/dist/core/orchestration/event-store.d.ts +83 -0
  389. package/dist/core/orchestration/event-store.d.ts.map +1 -0
  390. package/dist/core/orchestration/event-store.js +560 -0
  391. package/dist/core/orchestration/event-store.js.map +1 -0
  392. package/dist/core/orchestration/lane-tool-manifests.d.ts +9 -0
  393. package/dist/core/orchestration/lane-tool-manifests.d.ts.map +1 -0
  394. package/dist/core/orchestration/lane-tool-manifests.js +37 -0
  395. package/dist/core/orchestration/lane-tool-manifests.js.map +1 -0
  396. package/dist/core/orchestration/model-binding.d.ts +15 -0
  397. package/dist/core/orchestration/model-binding.d.ts.map +1 -0
  398. package/dist/core/orchestration/model-binding.js +29 -0
  399. package/dist/core/orchestration/model-binding.js.map +1 -0
  400. package/dist/core/orchestration/policy-compiler.d.ts +49 -0
  401. package/dist/core/orchestration/policy-compiler.d.ts.map +1 -0
  402. package/dist/core/orchestration/policy-compiler.js +191 -0
  403. package/dist/core/orchestration/policy-compiler.js.map +1 -0
  404. package/dist/core/orchestration/policy-gate.d.ts +18 -0
  405. package/dist/core/orchestration/policy-gate.d.ts.map +1 -0
  406. package/dist/core/orchestration/policy-gate.js +24 -0
  407. package/dist/core/orchestration/policy-gate.js.map +1 -0
  408. package/dist/core/orchestration/profile-registry.d.ts +51 -0
  409. package/dist/core/orchestration/profile-registry.d.ts.map +1 -0
  410. package/dist/core/orchestration/profile-registry.js +393 -0
  411. package/dist/core/orchestration/profile-registry.js.map +1 -0
  412. package/dist/core/orchestration/profile-store.d.ts +31 -0
  413. package/dist/core/orchestration/profile-store.d.ts.map +1 -0
  414. package/dist/core/orchestration/profile-store.js +136 -0
  415. package/dist/core/orchestration/profile-store.js.map +1 -0
  416. package/dist/core/orchestration/risk-budget.d.ts +9 -0
  417. package/dist/core/orchestration/risk-budget.d.ts.map +1 -0
  418. package/dist/core/orchestration/risk-budget.js +48 -0
  419. package/dist/core/orchestration/risk-budget.js.map +1 -0
  420. package/dist/core/orchestration/task-runtime.d.ts +168 -0
  421. package/dist/core/orchestration/task-runtime.d.ts.map +1 -0
  422. package/dist/core/orchestration/task-runtime.js +1600 -0
  423. package/dist/core/orchestration/task-runtime.js.map +1 -0
  424. package/dist/core/orchestration/work-state-projection.d.ts +32 -0
  425. package/dist/core/orchestration/work-state-projection.d.ts.map +1 -0
  426. package/dist/core/orchestration/work-state-projection.js +116 -0
  427. package/dist/core/orchestration/work-state-projection.js.map +1 -0
  428. package/dist/core/orchestration/worker-execution-contract.d.ts +21 -0
  429. package/dist/core/orchestration/worker-execution-contract.d.ts.map +1 -0
  430. package/dist/core/orchestration/worker-execution-contract.js +179 -0
  431. package/dist/core/orchestration/worker-execution-contract.js.map +1 -0
  432. package/dist/core/orchestration/worker-result-adapter.d.ts +21 -0
  433. package/dist/core/orchestration/worker-result-adapter.d.ts.map +1 -0
  434. package/dist/core/orchestration/worker-result-adapter.js +109 -0
  435. package/dist/core/orchestration/worker-result-adapter.js.map +1 -0
  436. package/dist/core/package-manager.d.ts.map +1 -1
  437. package/dist/core/package-manager.js +20 -3
  438. package/dist/core/package-manager.js.map +1 -1
  439. package/dist/core/process-identity.d.ts +11 -0
  440. package/dist/core/process-identity.d.ts.map +1 -0
  441. package/dist/core/process-identity.js +26 -0
  442. package/dist/core/process-identity.js.map +1 -0
  443. package/dist/core/process-matrix/codes.d.ts +14 -3
  444. package/dist/core/process-matrix/codes.d.ts.map +1 -1
  445. package/dist/core/process-matrix/codes.js.map +1 -1
  446. package/dist/core/process-matrix/resume-launcher.d.ts +26 -0
  447. package/dist/core/process-matrix/resume-launcher.d.ts.map +1 -0
  448. package/dist/core/process-matrix/resume-launcher.js +62 -0
  449. package/dist/core/process-matrix/resume-launcher.js.map +1 -0
  450. package/dist/core/process-matrix/runtime.d.ts +37 -22
  451. package/dist/core/process-matrix/runtime.d.ts.map +1 -1
  452. package/dist/core/process-matrix/runtime.js +399 -76
  453. package/dist/core/process-matrix/runtime.js.map +1 -1
  454. package/dist/core/process-matrix/store.d.ts +5 -2
  455. package/dist/core/process-matrix/store.d.ts.map +1 -1
  456. package/dist/core/process-matrix/store.js +123 -14
  457. package/dist/core/process-matrix/store.js.map +1 -1
  458. package/dist/core/process-matrix/supervisor.d.ts +10 -7
  459. package/dist/core/process-matrix/supervisor.d.ts.map +1 -1
  460. package/dist/core/process-matrix/supervisor.js +45 -14
  461. package/dist/core/process-matrix/supervisor.js.map +1 -1
  462. package/dist/core/profile-filter-controller.d.ts +8 -1
  463. package/dist/core/profile-filter-controller.d.ts.map +1 -1
  464. package/dist/core/profile-filter-controller.js +23 -5
  465. package/dist/core/profile-filter-controller.js.map +1 -1
  466. package/dist/core/profile-registry.d.ts.map +1 -1
  467. package/dist/core/profile-registry.js +6 -8
  468. package/dist/core/profile-registry.js.map +1 -1
  469. package/dist/core/prompt-templates.d.ts +1 -0
  470. package/dist/core/prompt-templates.d.ts.map +1 -1
  471. package/dist/core/prompt-templates.js +18 -29
  472. package/dist/core/prompt-templates.js.map +1 -1
  473. package/dist/core/reflection-controller.d.ts +5 -5
  474. package/dist/core/reflection-controller.d.ts.map +1 -1
  475. package/dist/core/reflection-controller.js +5 -2
  476. package/dist/core/reflection-controller.js.map +1 -1
  477. package/dist/core/reload-blockers.d.ts.map +1 -1
  478. package/dist/core/reload-blockers.js +6 -8
  479. package/dist/core/reload-blockers.js.map +1 -1
  480. package/dist/core/request-auth.d.ts +7 -0
  481. package/dist/core/request-auth.d.ts.map +1 -0
  482. package/dist/core/request-auth.js +8 -0
  483. package/dist/core/request-auth.js.map +1 -0
  484. package/dist/core/research/evidence-bundle.d.ts.map +1 -1
  485. package/dist/core/research/evidence-bundle.js +1 -6
  486. package/dist/core/research/evidence-bundle.js.map +1 -1
  487. package/dist/core/research/lane-model-resolver.d.ts +33 -0
  488. package/dist/core/research/lane-model-resolver.d.ts.map +1 -0
  489. package/dist/core/research/lane-model-resolver.js +65 -0
  490. package/dist/core/research/lane-model-resolver.js.map +1 -0
  491. package/dist/core/research/model-fitness-controller.d.ts +38 -0
  492. package/dist/core/research/model-fitness-controller.d.ts.map +1 -0
  493. package/dist/core/research/model-fitness-controller.js +106 -0
  494. package/dist/core/research/model-fitness-controller.js.map +1 -0
  495. package/dist/core/research/model-fitness.d.ts +1 -1
  496. package/dist/core/research/model-fitness.d.ts.map +1 -1
  497. package/dist/core/research/model-fitness.js +4 -4
  498. package/dist/core/research/model-fitness.js.map +1 -1
  499. package/dist/core/research/research-gate.d.ts.map +1 -1
  500. package/dist/core/research/research-gate.js +7 -7
  501. package/dist/core/research/research-gate.js.map +1 -1
  502. package/dist/core/research/research-lane-controller.d.ts +62 -0
  503. package/dist/core/research/research-lane-controller.d.ts.map +1 -0
  504. package/dist/core/research/research-lane-controller.js +292 -0
  505. package/dist/core/research/research-lane-controller.js.map +1 -0
  506. package/dist/core/research/session-evidence-bundle.d.ts +2 -4
  507. package/dist/core/research/session-evidence-bundle.d.ts.map +1 -1
  508. package/dist/core/research/session-evidence-bundle.js +10 -46
  509. package/dist/core/research/session-evidence-bundle.js.map +1 -1
  510. package/dist/core/resource-loader.d.ts.map +1 -1
  511. package/dist/core/resource-loader.js +23 -8
  512. package/dist/core/resource-loader.js.map +1 -1
  513. package/dist/core/risk-classifier.d.ts +6 -0
  514. package/dist/core/risk-classifier.d.ts.map +1 -0
  515. package/dist/core/risk-classifier.js +233 -0
  516. package/dist/core/risk-classifier.js.map +1 -0
  517. package/dist/core/runtime-builder.d.ts +41 -23
  518. package/dist/core/runtime-builder.d.ts.map +1 -1
  519. package/dist/core/runtime-builder.js +365 -253
  520. package/dist/core/runtime-builder.js.map +1 -1
  521. package/dist/core/sdk.d.ts +6 -3
  522. package/dist/core/sdk.d.ts.map +1 -1
  523. package/dist/core/sdk.js +68 -25
  524. package/dist/core/sdk.js.map +1 -1
  525. package/dist/core/secrets/credential-exposure-guard.d.ts +9 -0
  526. package/dist/core/secrets/credential-exposure-guard.d.ts.map +1 -0
  527. package/dist/core/secrets/credential-exposure-guard.js +241 -0
  528. package/dist/core/secrets/credential-exposure-guard.js.map +1 -0
  529. package/dist/core/secrets/secret-dotenv.d.ts +27 -0
  530. package/dist/core/secrets/secret-dotenv.d.ts.map +1 -0
  531. package/dist/core/secrets/secret-dotenv.js +183 -0
  532. package/dist/core/secrets/secret-dotenv.js.map +1 -0
  533. package/dist/core/secrets/secret-vault-format.d.ts +112 -0
  534. package/dist/core/secrets/secret-vault-format.d.ts.map +1 -0
  535. package/dist/core/secrets/secret-vault-format.js +397 -0
  536. package/dist/core/secrets/secret-vault-format.js.map +1 -0
  537. package/dist/core/secrets/secret-vault.d.ts +72 -0
  538. package/dist/core/secrets/secret-vault.d.ts.map +1 -0
  539. package/dist/core/secrets/secret-vault.js +671 -0
  540. package/dist/core/secrets/secret-vault.js.map +1 -0
  541. package/dist/core/session-analytics.d.ts +4 -23
  542. package/dist/core/session-analytics.d.ts.map +1 -1
  543. package/dist/core/session-analytics.js +67 -70
  544. package/dist/core/session-analytics.js.map +1 -1
  545. package/dist/core/session-image-store.d.ts +33 -0
  546. package/dist/core/session-image-store.d.ts.map +1 -0
  547. package/dist/core/session-image-store.js +283 -0
  548. package/dist/core/session-image-store.js.map +1 -0
  549. package/dist/core/session-role.d.ts +11 -4
  550. package/dist/core/session-role.d.ts.map +1 -1
  551. package/dist/core/session-role.js +24 -5
  552. package/dist/core/session-role.js.map +1 -1
  553. package/dist/core/session-snapshot.d.ts +34 -0
  554. package/dist/core/session-snapshot.d.ts.map +1 -0
  555. package/dist/core/session-snapshot.js +68 -0
  556. package/dist/core/session-snapshot.js.map +1 -0
  557. package/dist/core/session-supervision-runtime.d.ts +31 -0
  558. package/dist/core/session-supervision-runtime.d.ts.map +1 -0
  559. package/dist/core/session-supervision-runtime.js +97 -0
  560. package/dist/core/session-supervision-runtime.js.map +1 -0
  561. package/dist/core/session-tree-navigator.d.ts +4 -6
  562. package/dist/core/session-tree-navigator.d.ts.map +1 -1
  563. package/dist/core/session-tree-navigator.js +4 -1
  564. package/dist/core/session-tree-navigator.js.map +1 -1
  565. package/dist/core/settings-manager.d.ts +10 -5
  566. package/dist/core/settings-manager.d.ts.map +1 -1
  567. package/dist/core/settings-manager.js +81 -29
  568. package/dist/core/settings-manager.js.map +1 -1
  569. package/dist/core/slash-commands.d.ts.map +1 -1
  570. package/dist/core/slash-commands.js +2 -2
  571. package/dist/core/slash-commands.js.map +1 -1
  572. package/dist/core/tasks/session-task-state.d.ts +2 -4
  573. package/dist/core/tasks/session-task-state.d.ts.map +1 -1
  574. package/dist/core/tasks/session-task-state.js +10 -28
  575. package/dist/core/tasks/session-task-state.js.map +1 -1
  576. package/dist/core/tasks/task-projection.d.ts +20 -0
  577. package/dist/core/tasks/task-projection.d.ts.map +1 -0
  578. package/dist/core/tasks/task-projection.js +47 -0
  579. package/dist/core/tasks/task-projection.js.map +1 -0
  580. package/dist/core/tasks/task-state.d.ts +4 -0
  581. package/dist/core/tasks/task-state.d.ts.map +1 -1
  582. package/dist/core/tasks/task-state.js +28 -11
  583. package/dist/core/tasks/task-state.js.map +1 -1
  584. package/dist/core/tool-capability-policy.d.ts +13 -0
  585. package/dist/core/tool-capability-policy.d.ts.map +1 -0
  586. package/dist/core/tool-capability-policy.js +86 -0
  587. package/dist/core/tool-capability-policy.js.map +1 -0
  588. package/dist/core/tool-gate-controller.d.ts.map +1 -1
  589. package/dist/core/tool-gate-controller.js +8 -2
  590. package/dist/core/tool-gate-controller.js.map +1 -1
  591. package/dist/core/tool-protocol-controller.d.ts +89 -0
  592. package/dist/core/tool-protocol-controller.d.ts.map +1 -0
  593. package/dist/core/tool-protocol-controller.js +512 -0
  594. package/dist/core/tool-protocol-controller.js.map +1 -0
  595. package/dist/core/tool-recovery-log-records.d.ts +2 -3
  596. package/dist/core/tool-recovery-log-records.d.ts.map +1 -1
  597. package/dist/core/tool-recovery-log-records.js +9 -35
  598. package/dist/core/tool-recovery-log-records.js.map +1 -1
  599. package/dist/core/tool-recovery-stats.d.ts +21 -1
  600. package/dist/core/tool-recovery-stats.d.ts.map +1 -1
  601. package/dist/core/tool-recovery-stats.js.map +1 -1
  602. package/dist/core/tool-selection/tool-performance-store.d.ts +3 -7
  603. package/dist/core/tool-selection/tool-performance-store.d.ts.map +1 -1
  604. package/dist/core/tool-selection/tool-performance-store.js +97 -138
  605. package/dist/core/tool-selection/tool-performance-store.js.map +1 -1
  606. package/dist/core/tools/ask-question.d.ts +124 -0
  607. package/dist/core/tools/ask-question.d.ts.map +1 -0
  608. package/dist/core/tools/ask-question.js +693 -0
  609. package/dist/core/tools/ask-question.js.map +1 -0
  610. package/dist/core/tools/bash.d.ts +5 -0
  611. package/dist/core/tools/bash.d.ts.map +1 -1
  612. package/dist/core/tools/bash.js +59 -5
  613. package/dist/core/tools/bash.js.map +1 -1
  614. package/dist/core/tools/delegate-status.d.ts +31 -3
  615. package/dist/core/tools/delegate-status.d.ts.map +1 -1
  616. package/dist/core/tools/delegate-status.js +148 -29
  617. package/dist/core/tools/delegate-status.js.map +1 -1
  618. package/dist/core/tools/delegate.d.ts +15 -13
  619. package/dist/core/tools/delegate.d.ts.map +1 -1
  620. package/dist/core/tools/delegate.js +106 -23
  621. package/dist/core/tools/delegate.js.map +1 -1
  622. package/dist/core/tools/extensionify.d.ts.map +1 -1
  623. package/dist/core/tools/extensionify.js +1 -0
  624. package/dist/core/tools/extensionify.js.map +1 -1
  625. package/dist/core/tools/git-filter.d.ts +1 -8
  626. package/dist/core/tools/git-filter.d.ts.map +1 -1
  627. package/dist/core/tools/git-filter.js +2 -63
  628. package/dist/core/tools/git-filter.js.map +1 -1
  629. package/dist/core/tools/goal.d.ts +10 -8
  630. package/dist/core/tools/goal.d.ts.map +1 -1
  631. package/dist/core/tools/goal.js +106 -28
  632. package/dist/core/tools/goal.js.map +1 -1
  633. package/dist/core/tools/index.d.ts +1 -0
  634. package/dist/core/tools/index.d.ts.map +1 -1
  635. package/dist/core/tools/index.js +1 -0
  636. package/dist/core/tools/index.js.map +1 -1
  637. package/dist/core/tools/model-fitness.d.ts.map +1 -1
  638. package/dist/core/tools/model-fitness.js +2 -2
  639. package/dist/core/tools/model-fitness.js.map +1 -1
  640. package/dist/core/tools/orchestration-panel.d.ts +40 -0
  641. package/dist/core/tools/orchestration-panel.d.ts.map +1 -0
  642. package/dist/core/tools/orchestration-panel.js +124 -0
  643. package/dist/core/tools/orchestration-panel.js.map +1 -0
  644. package/dist/core/tools/output-accumulator.d.ts +11 -0
  645. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  646. package/dist/core/tools/output-accumulator.js +36 -3
  647. package/dist/core/tools/output-accumulator.js.map +1 -1
  648. package/dist/core/tools/python.d.ts +2 -0
  649. package/dist/core/tools/python.d.ts.map +1 -1
  650. package/dist/core/tools/python.js +3 -1
  651. package/dist/core/tools/python.js.map +1 -1
  652. package/dist/core/tools/read.d.ts.map +1 -1
  653. package/dist/core/tools/read.js +1 -1
  654. package/dist/core/tools/read.js.map +1 -1
  655. package/dist/core/tools/run-process.d.ts +26 -0
  656. package/dist/core/tools/run-process.d.ts.map +1 -0
  657. package/dist/core/tools/run-process.js +138 -0
  658. package/dist/core/tools/run-process.js.map +1 -0
  659. package/dist/core/tools/search-command-guard.d.ts +14 -0
  660. package/dist/core/tools/search-command-guard.d.ts.map +1 -0
  661. package/dist/core/tools/search-command-guard.js +333 -0
  662. package/dist/core/tools/search-command-guard.js.map +1 -0
  663. package/dist/core/tools/secret-store.d.ts +38 -0
  664. package/dist/core/tools/secret-store.d.ts.map +1 -0
  665. package/dist/core/tools/secret-store.js +412 -0
  666. package/dist/core/tools/secret-store.js.map +1 -0
  667. package/dist/core/tools/shell-command-parser.d.ts +16 -0
  668. package/dist/core/tools/shell-command-parser.d.ts.map +1 -0
  669. package/dist/core/tools/shell-command-parser.js +113 -0
  670. package/dist/core/tools/shell-command-parser.js.map +1 -0
  671. package/dist/core/tools/task-steps.d.ts +2 -0
  672. package/dist/core/tools/task-steps.d.ts.map +1 -1
  673. package/dist/core/tools/task-steps.js +99 -0
  674. package/dist/core/tools/task-steps.js.map +1 -1
  675. package/dist/core/tools/tmux-dispatch.d.ts +3 -5
  676. package/dist/core/tools/tmux-dispatch.d.ts.map +1 -1
  677. package/dist/core/tools/tmux-dispatch.js +4 -4
  678. package/dist/core/tools/tmux-dispatch.js.map +1 -1
  679. package/dist/core/tools/windows-shell-engine.d.ts.map +1 -1
  680. package/dist/core/tools/windows-shell-engine.js +4 -6
  681. package/dist/core/tools/windows-shell-engine.js.map +1 -1
  682. package/dist/core/util/atomic-file.d.ts +6 -2
  683. package/dist/core/util/atomic-file.d.ts.map +1 -1
  684. package/dist/core/util/atomic-file.js +4 -4
  685. package/dist/core/util/atomic-file.js.map +1 -1
  686. package/dist/core/util/bounded-jsonl.d.ts +10 -0
  687. package/dist/core/util/bounded-jsonl.d.ts.map +1 -0
  688. package/dist/core/util/bounded-jsonl.js +75 -0
  689. package/dist/core/util/bounded-jsonl.js.map +1 -0
  690. package/dist/core/util/value-guards.d.ts +5 -0
  691. package/dist/core/util/value-guards.d.ts.map +1 -0
  692. package/dist/core/util/value-guards.js +12 -0
  693. package/dist/core/util/value-guards.js.map +1 -0
  694. package/dist/core/worktree-sync/store.d.ts +3 -3
  695. package/dist/core/worktree-sync/store.d.ts.map +1 -1
  696. package/dist/core/worktree-sync/store.js +10 -5
  697. package/dist/core/worktree-sync/store.js.map +1 -1
  698. package/dist/index.d.ts +15 -4
  699. package/dist/index.d.ts.map +1 -1
  700. package/dist/index.js +14 -3
  701. package/dist/index.js.map +1 -1
  702. package/dist/main.d.ts.map +1 -1
  703. package/dist/main.js +149 -51
  704. package/dist/main.js.map +1 -1
  705. package/dist/migrations.d.ts +4 -6
  706. package/dist/migrations.d.ts.map +1 -1
  707. package/dist/migrations.js +186 -28
  708. package/dist/migrations.js.map +1 -1
  709. package/dist/modes/interactive/auth-dialogs-controller.d.ts +4 -0
  710. package/dist/modes/interactive/auth-dialogs-controller.d.ts.map +1 -1
  711. package/dist/modes/interactive/auth-dialogs-controller.js +60 -1
  712. package/dist/modes/interactive/auth-dialogs-controller.js.map +1 -1
  713. package/dist/modes/interactive/clipboard-input.d.ts +7 -1
  714. package/dist/modes/interactive/clipboard-input.d.ts.map +1 -1
  715. package/dist/modes/interactive/clipboard-input.js +44 -6
  716. package/dist/modes/interactive/clipboard-input.js.map +1 -1
  717. package/dist/modes/interactive/components/activity-lane.d.ts +55 -0
  718. package/dist/modes/interactive/components/activity-lane.d.ts.map +1 -0
  719. package/dist/modes/interactive/components/activity-lane.js +304 -0
  720. package/dist/modes/interactive/components/activity-lane.js.map +1 -0
  721. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  722. package/dist/modes/interactive/components/assistant-message.js +19 -10
  723. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  724. package/dist/modes/interactive/components/expandable-text.d.ts +12 -0
  725. package/dist/modes/interactive/components/expandable-text.d.ts.map +1 -0
  726. package/dist/modes/interactive/components/expandable-text.js +17 -0
  727. package/dist/modes/interactive/components/expandable-text.js.map +1 -0
  728. package/dist/modes/interactive/components/extension-editor.d.ts +15 -1
  729. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
  730. package/dist/modes/interactive/components/extension-editor.js +30 -21
  731. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  732. package/dist/modes/interactive/components/extension-input.d.ts +1 -0
  733. package/dist/modes/interactive/components/extension-input.d.ts.map +1 -1
  734. package/dist/modes/interactive/components/extension-input.js +6 -1
  735. package/dist/modes/interactive/components/extension-input.js.map +1 -1
  736. package/dist/modes/interactive/components/scoped-models-selector.d.ts +2 -2
  737. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  738. package/dist/modes/interactive/components/scoped-models-selector.js +23 -14
  739. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  740. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  741. package/dist/modes/interactive/components/settings-selector.js +6 -6
  742. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  743. package/dist/modes/interactive/components/tool-execution.d.ts +19 -11
  744. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  745. package/dist/modes/interactive/components/tool-execution.js +53 -20
  746. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  747. package/dist/modes/interactive/components/tool-group.d.ts.map +1 -1
  748. package/dist/modes/interactive/components/tool-group.js +3 -0
  749. package/dist/modes/interactive/components/tool-group.js.map +1 -1
  750. package/dist/modes/interactive/components/usage-action-selector.d.ts +16 -0
  751. package/dist/modes/interactive/components/usage-action-selector.d.ts.map +1 -0
  752. package/dist/modes/interactive/components/usage-action-selector.js +46 -0
  753. package/dist/modes/interactive/components/usage-action-selector.js.map +1 -0
  754. package/dist/modes/interactive/config-backup.d.ts.map +1 -1
  755. package/dist/modes/interactive/config-backup.js +5 -4
  756. package/dist/modes/interactive/config-backup.js.map +1 -1
  757. package/dist/modes/interactive/extension-ui-host.d.ts +14 -0
  758. package/dist/modes/interactive/extension-ui-host.d.ts.map +1 -1
  759. package/dist/modes/interactive/extension-ui-host.js +77 -15
  760. package/dist/modes/interactive/extension-ui-host.js.map +1 -1
  761. package/dist/modes/interactive/external-editor.d.ts +15 -0
  762. package/dist/modes/interactive/external-editor.d.ts.map +1 -1
  763. package/dist/modes/interactive/external-editor.js +27 -19
  764. package/dist/modes/interactive/external-editor.js.map +1 -1
  765. package/dist/modes/interactive/history-reload-math.d.ts +6 -2
  766. package/dist/modes/interactive/history-reload-math.d.ts.map +1 -1
  767. package/dist/modes/interactive/history-reload-math.js +10 -5
  768. package/dist/modes/interactive/history-reload-math.js.map +1 -1
  769. package/dist/modes/interactive/interactive-event-controller.d.ts +74 -0
  770. package/dist/modes/interactive/interactive-event-controller.d.ts.map +1 -0
  771. package/dist/modes/interactive/interactive-event-controller.js +328 -0
  772. package/dist/modes/interactive/interactive-event-controller.js.map +1 -0
  773. package/dist/modes/interactive/interactive-mode.d.ts +22 -24
  774. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  775. package/dist/modes/interactive/interactive-mode.js +245 -595
  776. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  777. package/dist/modes/interactive/key-handlers.d.ts.map +1 -1
  778. package/dist/modes/interactive/key-handlers.js +1 -1
  779. package/dist/modes/interactive/key-handlers.js.map +1 -1
  780. package/dist/modes/interactive/loaded-resources-view.d.ts +20 -0
  781. package/dist/modes/interactive/loaded-resources-view.d.ts.map +1 -0
  782. package/dist/modes/interactive/loaded-resources-view.js +147 -0
  783. package/dist/modes/interactive/loaded-resources-view.js.map +1 -0
  784. package/dist/modes/interactive/profile-menu-controller.d.ts.map +1 -1
  785. package/dist/modes/interactive/profile-menu-controller.js +7 -7
  786. package/dist/modes/interactive/profile-menu-controller.js.map +1 -1
  787. package/dist/modes/interactive/report-commands.d.ts.map +1 -1
  788. package/dist/modes/interactive/report-commands.js +21 -0
  789. package/dist/modes/interactive/report-commands.js.map +1 -1
  790. package/dist/modes/interactive/resource-display.d.ts.map +1 -1
  791. package/dist/modes/interactive/resource-display.js +8 -2
  792. package/dist/modes/interactive/resource-display.js.map +1 -1
  793. package/dist/modes/interactive/resource-shell-commands.d.ts +1 -5
  794. package/dist/modes/interactive/resource-shell-commands.d.ts.map +1 -1
  795. package/dist/modes/interactive/resource-shell-commands.js +0 -5
  796. package/dist/modes/interactive/resource-shell-commands.js.map +1 -1
  797. package/dist/modes/interactive/session-flow-commands.d.ts +27 -8
  798. package/dist/modes/interactive/session-flow-commands.d.ts.map +1 -1
  799. package/dist/modes/interactive/session-flow-commands.js +150 -64
  800. package/dist/modes/interactive/session-flow-commands.js.map +1 -1
  801. package/dist/modes/interactive/session-io-commands.d.ts.map +1 -1
  802. package/dist/modes/interactive/session-io-commands.js +16 -6
  803. package/dist/modes/interactive/session-io-commands.js.map +1 -1
  804. package/dist/modes/interactive/session-replacement-errors.d.ts +7 -0
  805. package/dist/modes/interactive/session-replacement-errors.d.ts.map +1 -0
  806. package/dist/modes/interactive/session-replacement-errors.js +15 -0
  807. package/dist/modes/interactive/session-replacement-errors.js.map +1 -0
  808. package/dist/modes/interactive/startup-checks.d.ts.map +1 -1
  809. package/dist/modes/interactive/startup-checks.js +1 -1
  810. package/dist/modes/interactive/startup-checks.js.map +1 -1
  811. package/dist/modes/interactive/usage-commands.d.ts +34 -0
  812. package/dist/modes/interactive/usage-commands.d.ts.map +1 -0
  813. package/dist/modes/interactive/usage-commands.js +225 -0
  814. package/dist/modes/interactive/usage-commands.js.map +1 -0
  815. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  816. package/dist/modes/rpc/rpc-mode.js +82 -23
  817. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  818. package/dist/modes/rpc/rpc-types.d.ts +15 -0
  819. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  820. package/dist/modes/rpc/rpc-types.js +138 -1
  821. package/dist/modes/rpc/rpc-types.js.map +1 -1
  822. package/dist/utils/clipboard-image.d.ts.map +1 -1
  823. package/dist/utils/clipboard-image.js +2 -13
  824. package/dist/utils/clipboard-image.js.map +1 -1
  825. package/dist/utils/clipboard-native.d.ts +1 -0
  826. package/dist/utils/clipboard-native.d.ts.map +1 -1
  827. package/dist/utils/clipboard-native.js.map +1 -1
  828. package/dist/utils/clipboard.d.ts +1 -0
  829. package/dist/utils/clipboard.d.ts.map +1 -1
  830. package/dist/utils/clipboard.js +52 -1
  831. package/dist/utils/clipboard.js.map +1 -1
  832. package/dist/utils/platform.d.ts +3 -0
  833. package/dist/utils/platform.d.ts.map +1 -0
  834. package/dist/utils/platform.js +8 -0
  835. package/dist/utils/platform.js.map +1 -0
  836. package/dist/utils/shell.d.ts.map +1 -1
  837. package/dist/utils/shell.js +5 -3
  838. package/dist/utils/shell.js.map +1 -1
  839. package/dist/utils/version-check.d.ts.map +1 -1
  840. package/dist/utils/version-check.js +3 -1
  841. package/dist/utils/version-check.js.map +1 -1
  842. package/dist/utils/work-directory.d.ts +11 -0
  843. package/dist/utils/work-directory.d.ts.map +1 -1
  844. package/dist/utils/work-directory.js +30 -9
  845. package/dist/utils/work-directory.js.map +1 -1
  846. package/docs/UI_POLISH_ORCHESTRATION.md +38 -0
  847. package/docs/UI_QUALITY_ORCHESTRATION.md +28 -0
  848. package/docs/docs.json +4 -0
  849. package/docs/extensions.md +62 -2
  850. package/docs/harness-architecture.md +156 -0
  851. package/docs/keybindings.md +11 -1
  852. package/docs/process-matrix.md +59 -26
  853. package/docs/providers.md +9 -1
  854. package/docs/rpc.md +45 -2
  855. package/docs/sessions.md +15 -0
  856. package/docs/settings.md +125 -11
  857. package/docs/task-steps.md +8 -0
  858. package/docs/telemetry.md +19 -0
  859. package/docs/tmux-agent-manager.md +10 -3
  860. package/docs/ui-reference/README.md +9 -0
  861. package/docs/ui-reference/orchestration-after.txt +14 -0
  862. package/docs/ui-reference/orchestration-before.txt +13 -0
  863. package/docs/ui-reference/orchestration-reference.txt +16 -0
  864. package/docs/usage.md +22 -2
  865. package/docs/work-directory.md +19 -8
  866. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  867. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  868. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  869. package/examples/extensions/question.ts +34 -245
  870. package/examples/extensions/questionnaire.ts +41 -407
  871. package/examples/extensions/sandbox/package-lock.json +2 -2
  872. package/examples/extensions/sandbox/package.json +1 -1
  873. package/examples/extensions/with-deps/package-lock.json +2 -2
  874. package/examples/extensions/with-deps/package.json +1 -1
  875. package/npm-shrinkwrap.json +13 -13
  876. package/package.json +4 -4
  877. package/dist/core/delegation/session-worker-result.d.ts +0 -46
  878. package/dist/core/delegation/session-worker-result.d.ts.map +0 -1
  879. package/dist/core/delegation/session-worker-result.js +0 -113
  880. package/dist/core/delegation/session-worker-result.js.map +0 -1
  881. package/dist/core/delegation/worker-result.d.ts.map +0 -1
  882. package/dist/core/delegation/worker-result.js.map +0 -1
  883. package/dist/core/telemetry.d.ts.map +0 -1
  884. package/dist/core/telemetry.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"okf-memory.js","sourceRoot":"","sources":["../../../src/core/context/okf-memory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AACjC,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAU9D,MAAM,CAAC,MAAM,kBAAkB,GAAG,QAAQ,CAAC;AAE3C,MAAM,CAAC,MAAM,gBAAgB,GAAG,gBAAgB,CAAC;AAEjD,MAAM,CAAC,MAAM,YAAY,GAAG;IAC3B,iBAAiB;IACjB,sBAAsB;IACtB,wBAAwB;IACxB,qBAAqB;IACrB,mBAAmB;IACnB,wBAAwB;IACxB,kBAAkB;IAClB,oBAAoB;IACpB,iBAAiB;IACjB,gBAAgB;CACP,CAAC;AAwDX,MAAM,uBAAuB,GAAG,IAAI,GAAG,CAA4B;IAClE,CAAC,iBAAiB,EAAE,iBAAiB,CAAC;IACtC,CAAC,sBAAsB,EAAE,sBAAsB,CAAC;IAChD,CAAC,wBAAwB,EAAE,wBAAwB,CAAC;IACpD,CAAC,qBAAqB,EAAE,MAAM,CAAC;IAC/B,CAAC,mBAAmB,EAAE,mBAAmB,CAAC;IAC1C,CAAC,wBAAwB,EAAE,wBAAwB,CAAC;IACpD,CAAC,kBAAkB,EAAE,WAAW,CAAC;IACjC,CAAC,oBAAoB,EAAE,WAAW,CAAC;IACnC,CAAC,iBAAiB,EAAE,iBAAiB,CAAC;IACtC,CAAC,gBAAgB,EAAE,WAAW,CA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import { parseFrontmatter } from \"../../utils/frontmatter.ts\";\nimport type { MemoryScope } from \"./context-item.ts\";\nimport type {\n\tMemoryEvidenceRef,\n\tMemoryItem,\n\tMemoryItemKind,\n\tMemoryRef,\n\tMemoryWriteRequest,\n} from \"./memory-provider-contract.ts\";\n\nexport const PI_OKF_PROVIDER_ID = \"pi-okf\";\n\nexport const PI_OKF_AUTHORITY = \"durable_memory\";\n\nexport const PI_OKF_TYPES = [\n\t\"Design Decision\",\n\t\"Architecture Concept\",\n\t\"Project Rule Candidate\",\n\t\"Implementation Note\",\n\t\"Debugging Finding\",\n\t\"Invalidated Assumption\",\n\t\"Tooling Playbook\",\n\t\"External Reference\",\n\t\"User Preference\",\n\t\"Capability Doc\",\n] as const;\n\nexport type PiOkfType = (typeof PI_OKF_TYPES)[number];\n\nexport type OkfMemoryDiagnosticCode =\n\t| \"missing_frontmatter\"\n\t| \"invalid_frontmatter\"\n\t| \"invalid_yaml\"\n\t| \"missing_type\"\n\t| \"unknown_type\"\n\t| \"missing_title\"\n\t| \"missing_description\"\n\t| \"missing_pi\"\n\t| \"invalid_scope\"\n\t| \"invalid_authority\"\n\t| \"invalid_evidence_refs\";\n\nexport interface OkfMemoryDiagnostic {\n\tcode: OkfMemoryDiagnosticCode;\n\tmessage: string;\n}\n\nexport interface ParseOkfMemoryOptions {\n\tproviderId?: string;\n\turi?: string;\n\tfallbackId?: string;\n}\n\nexport interface ParsedOkfMemoryDocument {\n\titem?: MemoryItem;\n\tbody: string;\n\tdiagnostics: OkfMemoryDiagnostic[];\n}\n\nexport interface OkfMemoryDocumentInput {\n\ttype: PiOkfType;\n\ttitle: string;\n\tdescription: string;\n\tscope: MemoryScope;\n\tbody: string;\n\ttags?: string[];\n\ttimestamp?: string;\n\tevidenceRefs?: string[];\n}\n\nexport interface OkfProjectRulePromotionRequest {\n\titem: MemoryItem;\n\tapprovalId?: string;\n\ttrustedConfigPath?: string;\n}\n\nexport type OkfProjectRulePromotionRejection =\n\t| \"not_project_rule_candidate\"\n\t| \"missing_explicit_promotion_authority\"\n\t| \"stale_or_conflicting_memory\";\n\nconst OKF_TYPE_TO_MEMORY_KIND = new Map<PiOkfType, MemoryItemKind>([\n\t[\"Design Decision\", \"design_decision\"],\n\t[\"Architecture Concept\", \"architecture_concept\"],\n\t[\"Project Rule Candidate\", \"project_rule_candidate\"],\n\t[\"Implementation Note\", \"fact\"],\n\t[\"Debugging Finding\", \"debugging_finding\"],\n\t[\"Invalidated Assumption\", \"invalidated_assumption\"],\n\t[\"Tooling Playbook\", \"procedure\"],\n\t[\"External Reference\", \"reference\"],\n\t[\"User Preference\", \"user_preference\"],\n\t[\"Capability Doc\", \"reference\"],\n]);\n\nconst VALID_SCOPES: readonly MemoryScope[] = [\"session\", \"project\", \"user\", \"global\"];\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction stringField(record: Record<string, unknown>, key: string): string | undefined {\n\tconst value = record[key];\n\treturn typeof value === \"string\" && value.trim().length > 0 ? value : undefined;\n}\n\nfunction stringArrayField(record: Record<string, unknown>, key: string): string[] | undefined {\n\tconst value = record[key];\n\tif (value === undefined) return undefined;\n\treturn Array.isArray(value) && value.every((entry) => typeof entry === \"string\") ? value : undefined;\n}\n\nfunction memoryItemKindForOkfType(type: string): MemoryItemKind | undefined {\n\treturn OKF_TYPE_TO_MEMORY_KIND.get(type as PiOkfType);\n}\n\nfunction memoryIdForDocument(\n\tproviderId: string,\n\turi: string | undefined,\n\ttitle: string,\n\ttimestamp: string | undefined,\n): string {\n\treturn createHash(\"sha256\")\n\t\t.update([providerId, uri ?? \"\", title, timestamp ?? \"\"].join(\"\\0\"))\n\t\t.digest(\"hex\")\n\t\t.slice(0, 24);\n}\n\nfunction evidenceRefsFromOkf(providerId: string, refs: string[] | undefined): MemoryEvidenceRef[] {\n\treturn (refs ?? []).map((ref) => ({ type: \"external\", id: ref, providerId, description: \"OKF evidence_ref\" }));\n}\n\nfunction buildMemoryRef(\n\tproviderId: string,\n\tid: string,\n\tscope: MemoryScope,\n\tkind: MemoryItemKind,\n\turi?: string,\n): MemoryRef {\n\treturn { providerId, itemId: id, scope, kind, uri };\n}\n\nfunction validScope(value: string | undefined): MemoryScope | undefined {\n\treturn value !== undefined && VALID_SCOPES.includes(value as MemoryScope) ? (value as MemoryScope) : undefined;\n}\n\nexport function parseOkfMemoryDocument(content: string, options: ParseOkfMemoryOptions = {}): ParsedOkfMemoryDocument {\n\tlet frontmatter: Record<string, unknown>;\n\tlet body: string;\n\ttry {\n\t\tconst parsed = parseFrontmatter(content);\n\t\tfrontmatter = parsed.frontmatter;\n\t\tbody = parsed.body;\n\t} catch (error) {\n\t\treturn {\n\t\t\tbody: content,\n\t\t\tdiagnostics: [{ code: \"invalid_yaml\", message: error instanceof Error ? error.message : String(error) }],\n\t\t};\n\t}\n\n\tconst diagnostics: OkfMemoryDiagnostic[] = [];\n\tif (!isRecord(frontmatter) || Object.keys(frontmatter).length === 0) {\n\t\treturn { body, diagnostics: [{ code: \"missing_frontmatter\", message: \"OKF memory requires YAML frontmatter.\" }] };\n\t}\n\n\tconst type = stringField(frontmatter, \"type\");\n\tif (type === undefined) diagnostics.push({ code: \"missing_type\", message: \"OKF memory requires a type.\" });\n\tconst kind = type === undefined ? undefined : memoryItemKindForOkfType(type);\n\tif (type !== undefined && kind === undefined)\n\t\tdiagnostics.push({ code: \"unknown_type\", message: `Unknown Pi OKF type: ${type}` });\n\n\tconst title = stringField(frontmatter, \"title\");\n\tif (title === undefined) diagnostics.push({ code: \"missing_title\", message: \"OKF memory requires a title.\" });\n\tconst description = stringField(frontmatter, \"description\");\n\tif (description === undefined)\n\t\tdiagnostics.push({ code: \"missing_description\", message: \"OKF memory requires a description.\" });\n\n\tconst pi = frontmatter.pi;\n\tif (!isRecord(pi)) diagnostics.push({ code: \"missing_pi\", message: \"OKF memory requires a pi block.\" });\n\tconst scope = isRecord(pi) ? validScope(stringField(pi, \"scope\")) : undefined;\n\tif (isRecord(pi) && scope === undefined)\n\t\tdiagnostics.push({ code: \"invalid_scope\", message: \"pi.scope must be session, project, user, or global.\" });\n\tconst authority = isRecord(pi) ? stringField(pi, \"authority\") : undefined;\n\tif (isRecord(pi) && authority !== PI_OKF_AUTHORITY) {\n\t\tdiagnostics.push({ code: \"invalid_authority\", message: `pi.authority must be ${PI_OKF_AUTHORITY}.` });\n\t}\n\tconst evidenceRefs = isRecord(pi) ? stringArrayField(pi, \"evidence_refs\") : undefined;\n\tif (isRecord(pi) && pi.evidence_refs !== undefined && evidenceRefs === undefined) {\n\t\tdiagnostics.push({ code: \"invalid_evidence_refs\", message: \"pi.evidence_refs must be a string array.\" });\n\t}\n\n\tif (\n\t\tdiagnostics.length > 0 ||\n\t\tkind === undefined ||\n\t\ttitle === undefined ||\n\t\tdescription === undefined ||\n\t\tscope === undefined\n\t) {\n\t\treturn { body, diagnostics };\n\t}\n\n\tconst providerId = options.providerId ?? PI_OKF_PROVIDER_ID;\n\tconst timestamp = stringField(frontmatter, \"timestamp\");\n\tconst id = options.fallbackId ?? memoryIdForDocument(providerId, options.uri, title, timestamp);\n\tconst ref = buildMemoryRef(providerId, id, scope, kind, options.uri);\n\treturn {\n\t\tbody,\n\t\tdiagnostics,\n\t\titem: {\n\t\t\tid,\n\t\t\tproviderId,\n\t\t\tsource: \"pi_native\",\n\t\t\tkind,\n\t\t\tscope,\n\t\t\tdurability: \"durable\",\n\t\t\ttitle,\n\t\t\tsummary: description,\n\t\t\tcontent: body.length > 0 ? body : undefined,\n\t\t\trefs: [ref],\n\t\t\tevidenceRefs: evidenceRefsFromOkf(providerId, evidenceRefs),\n\t\t\ttimestamp,\n\t\t},\n\t};\n}\n\nexport function formatOkfMemoryDocument(input: OkfMemoryDocumentInput): string {\n\tconst frontmatter = {\n\t\ttype: input.type,\n\t\ttitle: input.title,\n\t\tdescription: input.description,\n\t\ttags: input.tags,\n\t\ttimestamp: input.timestamp,\n\t\tpi: {\n\t\t\tscope: input.scope,\n\t\t\tauthority: PI_OKF_AUTHORITY,\n\t\t\tevidence_refs: input.evidenceRefs ?? [],\n\t\t},\n\t};\n\treturn `---\\n${stringify(frontmatter).trim()}\\n---\\n\\n${input.body.trim()}\\n`;\n}\n\nexport function okfMemoryItemToWriteRequest(item: MemoryItem, reason: string): MemoryWriteRequest {\n\treturn {\n\t\tproviderId: item.providerId,\n\t\tscope: item.scope,\n\t\tkind: item.kind,\n\t\ttitle: item.title,\n\t\tsummary: item.summary,\n\t\tcontent: item.content,\n\t\tevidenceRefs: item.evidenceRefs,\n\t\tsensitivity: \"normal\",\n\t\treason,\n\t};\n}\n\nexport function validateOkfProjectRulePromotion(\n\trequest: OkfProjectRulePromotionRequest,\n): OkfProjectRulePromotionRejection[] {\n\tconst rejections: OkfProjectRulePromotionRejection[] = [];\n\tif (request.item.kind !== \"project_rule_candidate\") rejections.push(\"not_project_rule_candidate\");\n\tif (request.approvalId === undefined && request.trustedConfigPath === undefined) {\n\t\trejections.push(\"missing_explicit_promotion_authority\");\n\t}\n\tif (request.item.stale || request.item.conflict !== undefined) rejections.push(\"stale_or_conflicting_memory\");\n\treturn rejections;\n}\n"]}
1
+ {"version":3,"file":"okf-memory.js","sourceRoot":"","sources":["../../../src/core/context/okf-memory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AACjC,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AAUzD,MAAM,CAAC,MAAM,kBAAkB,GAAG,QAAQ,CAAC;AAE3C,MAAM,CAAC,MAAM,gBAAgB,GAAG,gBAAgB,CAAC;AAEjD,MAAM,CAAC,MAAM,YAAY,GAAG;IAC3B,iBAAiB;IACjB,sBAAsB;IACtB,wBAAwB;IACxB,qBAAqB;IACrB,mBAAmB;IACnB,wBAAw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,IAAI,OAAO,CAAC,iBAAiB,KAAK,SAAS,EAAE,CAAC;QACjF,UAAU,CAAC,IAAI,CAAC,sCAAsC,CAAC,CAAC;IACzD,CAAC;IACD,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,QAAQ,KAAK,SAAS;QAAE,UAAU,CAAC,IAAI,CAAC,6BAA6B,CAAC,CAAC;IAC9G,OAAO,UAAU,CAAC;AAAA,CAClB","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { stringify } from \"yaml\";\nimport { parseFrontmatter } from \"../../utils/frontmatter.ts\";\nimport { isRecordObject } from \"../util/value-guards.ts\";\nimport type { MemoryScope } from \"./context-item.ts\";\nimport type {\n\tMemoryEvidenceRef,\n\tMemoryItem,\n\tMemoryItemKind,\n\tMemoryRef,\n\tMemoryWriteRequest,\n} from \"./memory-provider-contract.ts\";\n\nexport const PI_OKF_PROVIDER_ID = \"pi-okf\";\n\nexport const PI_OKF_AUTHORITY = \"durable_memory\";\n\nexport const PI_OKF_TYPES = [\n\t\"Design Decision\",\n\t\"Architecture Concept\",\n\t\"Project Rule Candidate\",\n\t\"Implementation Note\",\n\t\"Debugging Finding\",\n\t\"Invalidated Assumption\",\n\t\"Tooling Playbook\",\n\t\"External Reference\",\n\t\"User Preference\",\n\t\"Capability Doc\",\n] as const;\n\nexport type PiOkfType = (typeof PI_OKF_TYPES)[number];\n\nexport type OkfMemoryDiagnosticCode =\n\t| \"missing_frontmatter\"\n\t| \"invalid_frontmatter\"\n\t| \"invalid_yaml\"\n\t| \"missing_type\"\n\t| \"unknown_type\"\n\t| \"missing_title\"\n\t| \"missing_description\"\n\t| \"missing_pi\"\n\t| \"invalid_scope\"\n\t| \"invalid_authority\"\n\t| \"invalid_evidence_refs\";\n\nexport interface OkfMemoryDiagnostic {\n\tcode: OkfMemoryDiagnosticCode;\n\tmessage: string;\n}\n\nexport interface ParseOkfMemoryOptions {\n\tproviderId?: string;\n\turi?: string;\n\tfallbackId?: string;\n}\n\nexport interface ParsedOkfMemoryDocument {\n\titem?: MemoryItem;\n\tbody: string;\n\tdiagnostics: OkfMemoryDiagnostic[];\n}\n\nexport interface OkfMemoryDocumentInput {\n\ttype: PiOkfType;\n\ttitle: string;\n\tdescription: string;\n\tscope: MemoryScope;\n\tbody: string;\n\ttags?: string[];\n\ttimestamp?: string;\n\tevidenceRefs?: string[];\n}\n\nexport interface OkfProjectRulePromotionRequest {\n\titem: MemoryItem;\n\tapprovalId?: string;\n\ttrustedConfigPath?: string;\n}\n\nexport type OkfProjectRulePromotionRejection =\n\t| \"not_project_rule_candidate\"\n\t| \"missing_explicit_promotion_authority\"\n\t| \"stale_or_conflicting_memory\";\n\nconst OKF_TYPE_TO_MEMORY_KIND = new Map<PiOkfType, MemoryItemKind>([\n\t[\"Design Decision\", \"design_decision\"],\n\t[\"Architecture Concept\", \"architecture_concept\"],\n\t[\"Project Rule Candidate\", \"project_rule_candidate\"],\n\t[\"Implementation Note\", \"fact\"],\n\t[\"Debugging Finding\", \"debugging_finding\"],\n\t[\"Invalidated Assumption\", \"invalidated_assumption\"],\n\t[\"Tooling Playbook\", \"procedure\"],\n\t[\"External Reference\", \"reference\"],\n\t[\"User Preference\", \"user_preference\"],\n\t[\"Capability Doc\", \"reference\"],\n]);\n\nconst VALID_SCOPES: readonly MemoryScope[] = [\"session\", \"project\", \"user\", \"global\"];\n\nfunction stringField(record: Record<string, unknown>, key: string): string | undefined {\n\tconst value = record[key];\n\treturn typeof value === \"string\" && value.trim().length > 0 ? value : undefined;\n}\n\nfunction stringArrayField(record: Record<string, unknown>, key: string): string[] | undefined {\n\tconst value = record[key];\n\tif (value === undefined) return undefined;\n\treturn Array.isArray(value) && value.every((entry) => typeof entry === \"string\") ? value : undefined;\n}\n\nfunction memoryItemKindForOkfType(type: string): MemoryItemKind | undefined {\n\treturn OKF_TYPE_TO_MEMORY_KIND.get(type as PiOkfType);\n}\n\nfunction memoryIdForDocument(\n\tproviderId: string,\n\turi: string | undefined,\n\ttitle: string,\n\ttimestamp: string | undefined,\n): string {\n\treturn createHash(\"sha256\")\n\t\t.update([providerId, uri ?? \"\", title, timestamp ?? \"\"].join(\"\\0\"))\n\t\t.digest(\"hex\")\n\t\t.slice(0, 24);\n}\n\nfunction evidenceRefsFromOkf(providerId: string, refs: string[] | undefined): MemoryEvidenceRef[] {\n\treturn (refs ?? []).map((ref) => ({ type: \"external\", id: ref, providerId, description: \"OKF evidence_ref\" }));\n}\n\nfunction buildMemoryRef(\n\tproviderId: string,\n\tid: string,\n\tscope: MemoryScope,\n\tkind: MemoryItemKind,\n\turi?: string,\n): MemoryRef {\n\treturn { providerId, itemId: id, scope, kind, uri };\n}\n\nfunction validScope(value: string | undefined): MemoryScope | undefined {\n\treturn value !== undefined && VALID_SCOPES.includes(value as MemoryScope) ? (value as MemoryScope) : undefined;\n}\n\nexport function parseOkfMemoryDocument(content: string, options: ParseOkfMemoryOptions = {}): ParsedOkfMemoryDocument {\n\tlet frontmatter: Record<string, unknown>;\n\tlet body: string;\n\ttry {\n\t\tconst parsed = parseFrontmatter(content);\n\t\tfrontmatter = parsed.frontmatter;\n\t\tbody = parsed.body;\n\t} catch (error) {\n\t\treturn {\n\t\t\tbody: content,\n\t\t\tdiagnostics: [{ code: \"invalid_yaml\", message: error instanceof Error ? error.message : String(error) }],\n\t\t};\n\t}\n\n\tconst diagnostics: OkfMemoryDiagnostic[] = [];\n\tif (!isRecordObject(frontmatter) || Object.keys(frontmatter).length === 0) {\n\t\treturn { body, diagnostics: [{ code: \"missing_frontmatter\", message: \"OKF memory requires YAML frontmatter.\" }] };\n\t}\n\n\tconst type = stringField(frontmatter, \"type\");\n\tif (type === undefined) diagnostics.push({ code: \"missing_type\", message: \"OKF memory requires a type.\" });\n\tconst kind = type === undefined ? undefined : memoryItemKindForOkfType(type);\n\tif (type !== undefined && kind === undefined)\n\t\tdiagnostics.push({ code: \"unknown_type\", message: `Unknown Pi OKF type: ${type}` });\n\n\tconst title = stringField(frontmatter, \"title\");\n\tif (title === undefined) diagnostics.push({ code: \"missing_title\", message: \"OKF memory requires a title.\" });\n\tconst description = stringField(frontmatter, \"description\");\n\tif (description === undefined)\n\t\tdiagnostics.push({ code: \"missing_description\", message: \"OKF memory requires a description.\" });\n\n\tconst pi = frontmatter.pi;\n\tif (!isRecordObject(pi)) diagnostics.push({ code: \"missing_pi\", message: \"OKF memory requires a pi block.\" });\n\tconst scope = isRecordObject(pi) ? validScope(stringField(pi, \"scope\")) : undefined;\n\tif (isRecordObject(pi) && scope === undefined)\n\t\tdiagnostics.push({ code: \"invalid_scope\", message: \"pi.scope must be session, project, user, or global.\" });\n\tconst authority = isRecordObject(pi) ? stringField(pi, \"authority\") : undefined;\n\tif (isRecordObject(pi) && authority !== PI_OKF_AUTHORITY) {\n\t\tdiagnostics.push({ code: \"invalid_authority\", message: `pi.authority must be ${PI_OKF_AUTHORITY}.` });\n\t}\n\tconst evidenceRefs = isRecordObject(pi) ? stringArrayField(pi, \"evidence_refs\") : undefined;\n\tif (isRecordObject(pi) && pi.evidence_refs !== undefined && evidenceRefs === undefined) {\n\t\tdiagnostics.push({ code: \"invalid_evidence_refs\", message: \"pi.evidence_refs must be a string array.\" });\n\t}\n\n\tif (\n\t\tdiagnostics.length > 0 ||\n\t\tkind === undefined ||\n\t\ttitle === undefined ||\n\t\tdescription === undefined ||\n\t\tscope === undefined\n\t) {\n\t\treturn { body, diagnostics };\n\t}\n\n\tconst providerId = options.providerId ?? PI_OKF_PROVIDER_ID;\n\tconst timestamp = stringField(frontmatter, \"timestamp\");\n\tconst id = options.fallbackId ?? memoryIdForDocument(providerId, options.uri, title, timestamp);\n\tconst ref = buildMemoryRef(providerId, id, scope, kind, options.uri);\n\treturn {\n\t\tbody,\n\t\tdiagnostics,\n\t\titem: {\n\t\t\tid,\n\t\t\tproviderId,\n\t\t\tsource: \"pi_native\",\n\t\t\tkind,\n\t\t\tscope,\n\t\t\tdurability: \"durable\",\n\t\t\ttitle,\n\t\t\tsummary: description,\n\t\t\tcontent: body.length > 0 ? body : undefined,\n\t\t\trefs: [ref],\n\t\t\tevidenceRefs: evidenceRefsFromOkf(providerId, evidenceRefs),\n\t\t\ttimestamp,\n\t\t},\n\t};\n}\n\nexport function formatOkfMemoryDocument(input: OkfMemoryDocumentInput): string {\n\tconst frontmatter = {\n\t\ttype: input.type,\n\t\ttitle: input.title,\n\t\tdescription: input.description,\n\t\ttags: input.tags,\n\t\ttimestamp: input.timestamp,\n\t\tpi: {\n\t\t\tscope: input.scope,\n\t\t\tauthority: PI_OKF_AUTHORITY,\n\t\t\tevidence_refs: input.evidenceRefs ?? [],\n\t\t},\n\t};\n\treturn `---\\n${stringify(frontmatter).trim()}\\n---\\n\\n${input.body.trim()}\\n`;\n}\n\nexport function okfMemoryItemToWriteRequest(item: MemoryItem, reason: string): MemoryWriteRequest {\n\treturn {\n\t\tproviderId: item.providerId,\n\t\tscope: item.scope,\n\t\tkind: item.kind,\n\t\ttitle: item.title,\n\t\tsummary: item.summary,\n\t\tcontent: item.content,\n\t\tevidenceRefs: item.evidenceRefs,\n\t\tsensitivity: \"normal\",\n\t\treason,\n\t};\n}\n\nexport function validateOkfProjectRulePromotion(\n\trequest: OkfProjectRulePromotionRequest,\n): OkfProjectRulePromotionRejection[] {\n\tconst rejections: OkfProjectRulePromotionRejection[] = [];\n\tif (request.item.kind !== \"project_rule_candidate\") rejections.push(\"not_project_rule_candidate\");\n\tif (request.approvalId === undefined && request.trustedConfigPath === undefined) {\n\t\trejections.push(\"missing_explicit_promotion_authority\");\n\t}\n\tif (request.item.stale || request.item.conflict !== undefined) rejections.push(\"stale_or_conflicting_memory\");\n\treturn rejections;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"sqlite-runtime-index.d.ts","sourceRoot":"","sources":["../../../src/core/context/sqlite-runtime-index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE3C,OAAO,KAAK,EAAE,YAAY,EAAyC,MAAM,oBAAoB,CAAC;AAC9F,OAAO,KAAK,EAAqB,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAGnF,eAAO,MAAM,mCAAmC,IAAI,CAAC;AAErD,eAAO,MAAM,2BAA2B,gIAO9B,CAAC;AAEX,MAAM,WAAW,yBAAyB;IACzC,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,kBAAmB,SAAQ,YAAY;IACvD,KAAK,IAAI,IAAI,CAAC;CACd;AAED,MAAM,WAAW,sBAAuB,SAAQ,gBAAgB;IAC/D,KAAK,IAAI,IAAI,CAAC;CACd;AAiCD,wBAAgB,yBAAyB,CAAC,QAAQ,EAAE,YAAY,GAAG,IAAI,CA+FtE;AA4GD,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,yBAAyB,GAAG,kBAAkB,CAqH/F;AAED,wBAAgB,4BAA4B,CAAC,OAAO,EAAE,yBAAyB,GAAG,sBAAsB,CAkEvG","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\ttry {\n\t\tdatabase.exec(`\n\t\t\tPRAGMA foreign_keys = ON;\n\t\t\tPRAGMA busy_timeout = ${options.busyTimeoutMs ?? 5_000};\n\t\t\tPRAGMA journal_mode = WAL;\n\t\t`);\n\t\tmigrateSqliteRuntimeIndex(database);\n\t\treturn database;\n\t} catch (error) {\n\t\tdatabase[Symbol.dispose]();\n\t\tthrow error;\n\t}\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"]}
1
+ {"version":3,"file":"sqlite-runtime-index.d.ts","sourceRoot":"","sources":["../../../src/core/context/sqlite-runtime-index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAG3C,OAAO,KAAK,EAAE,YAAY,EAAyC,MAAM,oBAAoB,CAAC;AAC9F,OAAO,KAAK,EAAqB,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAGnF,eAAO,MAAM,mCAAmC,IAAI,CAAC;AAErD,eAAO,MAAM,2BAA2B,gIAO9B,CAAC;AAEX,MAAM,WAAW,yBAAyB;IACzC,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,kBAAmB,SAAQ,YAAY;IACvD,KAAK,IAAI,IAAI,CAAC;CACd;AAED,MAAM,WAAW,sBAAuB,SAAQ,gBAAgB;IAC/D,KAAK,IAAI,IAAI,CAAC;CACd;AAiCD,wBAAgB,yBAAyB,CAAC,QAAQ,EAAE,YAAY,GAAG,IAAI,CA+FtE;AAwGD,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,yBAAyB,GAAG,kBAAkB,CAqH/F;AAED,wBAAgB,4BAA4B,CAAC,OAAO,EAAE,yBAAyB,GAAG,sBAAsB,CAkEvG","sourcesContent":["import { mkdirSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { DatabaseSync } from \"node:sqlite\";\nimport { isRecordObject } from \"../util/value-guards.ts\";\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\ttry {\n\t\tdatabase.exec(`\n\t\t\tPRAGMA foreign_keys = ON;\n\t\t\tPRAGMA busy_timeout = ${options.busyTimeoutMs ?? 5_000};\n\t\t\tPRAGMA journal_mode = WAL;\n\t\t`);\n\t\tmigrateSqliteRuntimeIndex(database);\n\t\treturn database;\n\t} catch (error) {\n\t\tdatabase[Symbol.dispose]();\n\t\tthrow error;\n\t}\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 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 (!isRecordObject(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 (!isRecordObject(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 (!isRecordObject(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 (!isRecordObject(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 (!isRecordObject(value) || !isRecordObject(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"]}
@@ -1,6 +1,7 @@
1
1
  import { mkdirSync } from "node:fs";
2
2
  import { dirname } from "node:path";
3
3
  import { DatabaseSync } from "node:sqlite";
4
+ import { isRecordObject } from "../util/value-guards.js";
4
5
  export const SQLITE_RUNTIME_INDEX_SCHEMA_VERSION = 1;
5
6
  export const SQLITE_CONTEXT_INDEX_TABLES = [
6
7
  "context_items",
@@ -135,9 +136,6 @@ export function migrateSqliteRuntimeIndex(database) {
135
136
  throw error;
136
137
  }
137
138
  }
138
- function isRecord(value) {
139
- return typeof value === "object" && value !== null && !Array.isArray(value);
140
- }
141
139
  function parseJsonRecord(json, isValid) {
142
140
  try {
143
141
  const parsed = JSON.parse(json);
@@ -152,7 +150,7 @@ function textColumn(row, column) {
152
150
  return typeof value === "string" ? value : undefined;
153
151
  }
154
152
  function isContextItem(value) {
155
- if (!isRecord(value))
153
+ if (!isRecordObject(value))
156
154
  return false;
157
155
  return (typeof value.id === "string" &&
158
156
  typeof value.kind === "string" &&
@@ -163,7 +161,7 @@ function isContextItem(value) {
163
161
  typeof value.byteEstimate === "number");
164
162
  }
165
163
  function isPolicyDecision(value) {
166
- if (!isRecord(value))
164
+ if (!isRecordObject(value))
167
165
  return false;
168
166
  return (typeof value.kind === "string" &&
169
167
  typeof value.selectedAction === "string" &&
@@ -181,7 +179,7 @@ function isPolicyDecision(value) {
181
179
  Array.isArray(value.evidenceRefs));
182
180
  }
183
181
  function isPolicyDecisionRecord(value) {
184
- if (!isRecord(value))
182
+ if (!isRecordObject(value))
185
183
  return false;
186
184
  return (typeof value.id === "string" &&
187
185
  (value.contextItemId === undefined || typeof value.contextItemId === "string") &&
@@ -189,7 +187,7 @@ function isPolicyDecisionRecord(value) {
189
187
  isPolicyDecision(value.decision));
190
188
  }
191
189
  function isRetrievalRecord(value) {
192
- if (!isRecord(value))
190
+ if (!isRecordObject(value))
193
191
  return false;
194
192
  return (typeof value.id === "string" &&
195
193
  typeof value.contextItemId === "string" &&
@@ -198,7 +196,7 @@ function isRetrievalRecord(value) {
198
196
  typeof value.resultSummary === "string");
199
197
  }
200
198
  function isMemoryIndexRecord(value) {
201
- if (!isRecord(value) || !isRecord(value.ref))
199
+ if (!isRecordObject(value) || !isRecordObject(value.ref))
202
200
  return false;
203
201
  return (typeof value.ref.providerId === "string" &&
204
202
  typeof value.ref.itemId === "string" &&
@@ -1 +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,CAAC;AAAA,CACtD;AAED,SAAS,YAAY,CAAC,OAAkC,EAAgB;IACvE,mBAAmB,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;IAC1C,MAAM,QAAQ,GAAG,IAAI,YAAY,CAAC,OAAO,CAAC,YAAY,EAAE;QACvD,2BAA2B,EAAE,IAAI;QACjC,OAAO,EAAE,OAAO,CAAC,aAAa,IAAI,KAAK;KACvC,CAAC,CAAC;IACH,IAAI,CAAC;QACJ,QAAQ,CAAC,IAAI,CAAC;;2BAEW,OAAO,CAAC,aAAa,IAAI,KAAK;;GAEtD,CAAC,CAAC;QACH,yBAAyB,CAAC,QAAQ,CAAC,CAAC;QACpC,OAAO,QAAQ,CAAC;IACjB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC;QAC3B,MA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BAC7C,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\ttry {\n\t\tdatabase.exec(`\n\t\t\tPRAGMA foreign_keys = ON;\n\t\t\tPRAGMA busy_timeout = ${options.busyTimeoutMs ?? 5_000};\n\t\t\tPRAGMA journal_mode = WAL;\n\t\t`);\n\t\tmigrateSqliteRuntimeIndex(database);\n\t\treturn database;\n\t} catch (error) {\n\t\tdatabase[Symbol.dispose]();\n\t\tthrow error;\n\t}\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"]}
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;AAC3C,OAAO,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AAMzD,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,CAAC;AAAA,CACtD;AAED,SAAS,YAAY,CAA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AC,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 { isRecordObject } from \"../util/value-guards.ts\";\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\ttry {\n\t\tdatabase.exec(`\n\t\t\tPRAGMA foreign_keys = ON;\n\t\t\tPRAGMA busy_timeout = ${options.busyTimeoutMs ?? 5_000};\n\t\t\tPRAGMA journal_mode = WAL;\n\t\t`);\n\t\tmigrateSqliteRuntimeIndex(database);\n\t\treturn database;\n\t} catch (error) {\n\t\tdatabase[Symbol.dispose]();\n\t\tthrow error;\n\t}\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 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 (!isRecordObject(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 (!isRecordObject(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 (!isRecordObject(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 (!isRecordObject(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 (!isRecordObject(value) || !isRecordObject(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"]}
@@ -37,6 +37,8 @@ export interface ContextGcCurationHooks {
37
37
  export interface ContextGcOptions extends NormalizedContextGcSettings {
38
38
  cwd: string;
39
39
  storageDir?: string;
40
+ /** Acquire the leased store only when an eligible payload is actually written. */
41
+ acquireStorageDir?: () => string;
40
42
  writePayloads?: boolean;
41
43
  curation?: ContextGcCurationHooks;
42
44
  }
@@ -74,6 +76,7 @@ export declare function getContextGcSettings(settings?: ContextGcSettings): Norm
74
76
  export declare function applyContextGc(messages: AgentMessage[], rawSettings: ContextGcSettings & {
75
77
  cwd?: string;
76
78
  storageDir?: string;
79
+ acquireStorageDir?: () => string;
77
80
  writePayloads?: boolean;
78
81
  curation?: ContextGcCurationHooks;
79
82
  }): ContextGcResult;
@@ -1 +1 @@
1
- {"version":3,"file":"context-gc.d.ts","sourceRoot":"","sources":["../../src/core/context-gc.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAK9D,MAAM,WAAW,wBAAwB;IACxC,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,0EAA0E;IAC1E,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,yFAAyF;IACzF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,uEAAuE;IACvE,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;CACnB;AAED,MAAM,WAAW,iBAAiB;IACjC,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,oEAAoE;IACpE,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,gFAAgF;IAChF,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,oDAAoD;IACpD,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;IACjB,sFAAsF;IACtF,cAAc,CAAC,EAAE,wBAAwB,CAAC;CAC1C;AAED,MAAM,WAAW,2BAA4B,SAAQ,IAAI,CAAC,QAAQ,CAAC,iBAAiB,CAAC,EAAE,gBAAgB,CAAC;IACvG,cAAc,EAAE,QAAQ,CAAC,wBAAwB,CAAC,CAAC;CACnD;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,sBAAsB;IACtC,aAAa,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,CAAC;IAC1D,QAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,qBAAqB,EAAE,YAAY,EAAE,MAAM,KAAK,IAAI,CAAC;CACzE;AAED,MAAM,WAAW,gBAAiB,SAAQ,2BAA2B;IACpE,GAAG,EAAE,MAAM,CAAC;IACZ,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,aAAa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Ae,CAyHjB","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { isAbsolute, resolve } from \"node:path\";\nimport type { AgentMessage } from \"@caupulican/pi-agent-core\";\nimport { estimateTokens } from \"@caupulican/pi-agent-core/node\";\nimport type { ToolResultMessage } from \"@caupulican/pi-ai\";\nimport { normalizePath } from \"../utils/paths.ts\";\n\nexport interface SemanticMemoryGcSettings {\n\tenabled?: boolean;\n\t/** Number of newest Automata/Mind injected pages to preserve verbatim. */\n\tpreserveRecentPages?: number;\n\t/** Minimum provider-visible text chars before a stale semantic memory page is packed. */\n\tminChars?: number;\n\t/** Markers that identify deterministic Automata/Mind context pages. */\n\tmarkers?: string[];\n}\n\nexport interface ContextGcSettings {\n\tenabled?: boolean;\n\t/** Number of most recent AgentMessage rows to preserve verbatim. */\n\tpreserveRecentMessages?: number;\n\t/** Minimum provider-visible text chars before a stale tool result is packed. */\n\tminToolResultChars?: number;\n\t/** Tool names eligible for stale result packing. */\n\ttools?: string[];\n\t/** Provider-context control for deterministic Automata/Mind semantic memory pages. */\n\tsemanticMemory?: SemanticMemoryGcSettings;\n}\n\nexport interface NormalizedContextGcSettings extends Omit<Required<ContextGcSettings>, \"semanticMemory\"> {\n\tsemanticMemory: Required<SemanticMemoryGcSettings>;\n}\n\n/**\n * Brain-curation hooks (both optional; absent hooks are byte-for-byte today's behavior).\n * `resolveDigest` is a pure lookup keyed by the record's content hash — it must return the digest\n * already fenced in the untrusted-content boundary (e.g. BrainCurator.getDigest), with the fence's\n * nonce fixed once at store time, since GC re-renders the stub from raw messages on every request\n * and renders the returned string VERBATIM. `onPacked` lets the caller enqueue digest work with the\n * exact original text at the moment it is packed.\n */\nexport interface ContextGcCurationHooks {\n\tresolveDigest?: (digestKey: string) => string | undefined;\n\tonPacked?: (record: ContextGcPackedRecord, originalText: string) => void;\n}\n\nexport interface ContextGcOptions extends NormalizedContextGcSettings {\n\tcwd: string;\n\tstorageDir?: string;\n\twritePayloads?: boolean;\n\tcuration?: ContextGcCurationHooks;\n}\n\nexport interface ContextGcPackedRecord {\n\ttoolName: string;\n\ttoolCallId: string;\n\tmessageIndex: number;\n\treason: \"superseded-read\" | \"stale-tool-result\" | \"stale-semantic-memory\";\n\toriginalChars: number;\n\toriginalTokens: number;\n\tpackedTokens: number;\n\tstoragePath?: string;\n\tpath?: string;\n\tcommand?: string;\n\tkey?: string;\n\t/** Brain-curator semantic digest of the packed content (model-generated; advisory only). Arrives\n\t * already fenced in the untrusted-content boundary (see ContextGcCurationHooks.resolveDigest) —\n\t * render verbatim, never re-wrap. */\n\tdigest?: string;\n}\n\nexport interface ContextGcReport {\n\tenabled: boolean;\n\tpackedCount: number;\n\toriginalTokens: number;\n\tpackedTokens: number;\n\tsavedTokens: number;\n\trecords: ContextGcPackedRecord[];\n}\n\nexport interface ContextGcResult {\n\tmessages: AgentMessage[];\n\treport: ContextGcReport;\n}\n\nconst DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS: Required<SemanticMemoryGcSettings> = {\n\tenabled: true,\n\tpreserveRecentPages: 1,\n\tminChars: 900,\n\tmarkers: [\n\t\t// Generic memory-subsystem recall page marker (brand-free). Provider-specific markers are\n\t\t// merged in dynamically at runtime via MemoryManager.getContextMarkers().\n\t\t\"<memory_context\",\n\t\t// Pre-existing provider-specific markers (to be generalized to provider-declared markers).\n\t\t\"<automata_context\",\n\t\t\"<automata_response\",\n\t\t\"<automata_query\",\n\t\t\"<automata_fetch\",\n\t\t\"<memory_lifecycle_audit\",\n\t\t\"<memory_lifecycle_purge\",\n\t\t\"<automata_doctor\",\n\t\t\"<automata_optimizer\",\n\t\t\"<automata_mesh\",\n\t\t// Injected task_steps checklist page (tasks/task-state.ts formatTaskStepsContext), re-derived\n\t\t// fresh every turn from live TaskStepsState -- same GC treatment as a memory recall page (Bug\n\t\t// #7 lineage): pack stale turn-copies down to the most recent one instead of accumulating.\n\t\t\"<task_steps_context\",\n\t],\n};\n\nexport const DEFAULT_CONTEXT_GC_SETTINGS: NormalizedContextGcSettings = {\n\tenabled: true,\n\tpreserveRecentMessages: 8,\n\tminToolResultChars: 1200,\n\ttools: [\n\t\t\"read\",\n\t\t\"bash\",\n\t\t\"python\",\n\t\t\"powershell\",\n\t\t\"rg\",\n\t\t\"grep\",\n\t\t\"find\",\n\t\t\"run_toolkit_script\",\n\t\t\"ls\",\n\t\t\"skill_open\",\n\t\t\"automata_graph_status\",\n\t\t\"automata_graph_search\",\n\t\t\"automata_graph_query\",\n\t\t\"automata_graph_neighbors\",\n\t\t\"automata_graph_path\",\n\t\t\"automata_graph_pointer_pack\",\n\t\t\"learning_query_memory\",\n\t\t\"subagent\",\n\t\t\"delegate\",\n\t\t\"task_steps\",\n\t\t\"task_background\",\n\t\t\"task_goal\",\n\t\t\"run_ledger\",\n\t\t\"context_headroom_retrieve\",\n\t\t\"headroom_retrieve\",\n\t],\n\tsemanticMemory: DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS,\n};\n\ntype ToolCallMeta = {\n\tid: string;\n\tname: string;\n\targs: Record<string, unknown>;\n\tmessageIndex: number;\n};\n\nfunction cap(text: string, limit = 220): string {\n\tconst compact = text.replace(/\\s+/g, \" \").trim();\n\treturn compact.length > limit ? `${compact.slice(0, Math.max(0, limit - 1))}…` : compact;\n}\n\nfunction normalizeSemanticMemoryGcSettings(settings?: SemanticMemoryGcSettings): Required<SemanticMemoryGcSettings> {\n\treturn {\n\t\tenabled: settings?.enabled ?? DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS.enabled,\n\t\tpreserveRecentPages: Math.max(\n\t\t\t0,\n\t\t\tMath.floor(settings?.preserveRecentPages ?? DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS.preserveRecentPages),\n\t\t),\n\t\tminChars: Math.max(0, Math.floor(settings?.minChars ?? DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS.minChars)),\n\t\tmarkers:\n\t\t\tsettings?.markers && settings.markers.length > 0\n\t\t\t\t? settings.markers\n\t\t\t\t: DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS.markers,\n\t};\n}\n\nfunction normalizeContextGcSettings(settings?: ContextGcSettings): NormalizedContextGcSettings {\n\treturn {\n\t\tenabled: settings?.enabled ?? DEFAULT_CONTEXT_GC_SETTINGS.enabled,\n\t\tpreserveRecentMessages: Math.max(\n\t\t\t0,\n\t\t\tMath.floor(settings?.preserveRecentMessages ?? DEFAULT_CONTEXT_GC_SETTINGS.preserveRecentMessages),\n\t\t),\n\t\tminToolResultChars: Math.max(\n\t\t\t0,\n\t\t\tMath.floor(settings?.minToolResultChars ?? DEFAULT_CONTEXT_GC_SETTINGS.minToolResultChars),\n\t\t),\n\t\ttools: settings?.tools && settings.tools.length > 0 ? settings.tools : DEFAULT_CONTEXT_GC_SETTINGS.tools,\n\t\tsemanticMemory: normalizeSemanticMemoryGcSettings(settings?.semanticMemory),\n\t};\n}\n\nexport function getContextGcSettings(settings?: ContextGcSettings): NormalizedContextGcSettings {\n\treturn normalizeContextGcSettings(settings);\n}\n\nfunction textContentParts(content: unknown): string[] | undefined {\n\tif (typeof content === \"string\") return [content];\n\tif (!Array.isArray(content)) return undefined;\n\tconst parts: string[] = [];\n\tfor (const part of content) {\n\t\tif (typeof part !== \"object\" || part === null) return undefined;\n\t\tconst typed = part as { type?: string; text?: string; mimeType?: string };\n\t\tif (typed.type === \"text\" && typeof typed.text === \"string\") parts.push(typed.text);\n\t\telse if (typed.type === \"image\") return undefined;\n\t\telse return undefined;\n\t}\n\treturn parts;\n}\n\nfunction joinTextParts(parts: readonly string[]): string {\n\tif (parts.length === 0) return \"\";\n\tif (parts.length === 1) return parts[0];\n\treturn parts.join(\"\\n\");\n}\n\nfunction contentText(content: unknown): string | undefined {\n\tif (typeof content === \"string\") return content;\n\tconst parts = textContentParts(content);\n\treturn parts ? joinTextParts(parts) : undefined;\n}\n\nfunction toolResultParts(message: ToolResultMessage): string[] {\n\tconst parts: string[] = [];\n\tfor (const part of message.content) {\n\t\tif (part.type === \"text\" && part.text) parts.push(part.text);\n\t\telse if (part.type === \"image\") parts.push(`[image ${part.mimeType}]`);\n\t}\n\treturn parts;\n}\n\nfunction toolResultText(message: ToolResultMessage): string {\n\treturn joinTextParts(toolResultParts(message));\n}\n\nfunction smallStringSlice(value: string, start?: number, end?: number): string {\n\tconst sliced = value.slice(start, end);\n\treturn sliced ? ` ${sliced}`.slice(1) : \"\";\n}\n\nfunction joinedPartsContainMarker(parts: string[], marker: string): boolean {\n\tif (marker.length === 0) return true;\n\tconst tailLength = marker.length - 1;\n\tlet tail = \"\";\n\tlet first = true;\n\tfor (const part of parts) {\n\t\tif (part.includes(marker)) return true;\n\t\tif (!first && `${tail}\\n${smallStringSlice(part, 0, tailLength)}`.includes(marker)) return true;\n\t\tif (tailLength === 0) tail = \"\";\n\t\telse if (part.length >= tailLength) tail = smallStringSlice(part, -tailLength);\n\t\telse tail = `${tail}${first ? \"\" : \"\\n\"}${part}`.slice(-tailLength);\n\t\tfirst = false;\n\t}\n\treturn false;\n}\n\nfunction joinedPartsContainAnyMarker(parts: string[], markers: readonly string[]): boolean {\n\treturn markers.some((marker) => joinedPartsContainMarker(parts, marker));\n}\n\n// Gates which custom-message types are eligible for the semantic-memory packer below. Despite the\n// name, this now also covers the injected task_steps checklist page (customType \"task_steps_context\",\n// see agent-session.ts) -- it is a deterministic, re-derivable-from-live-state context page exactly\n// like a memory recall page, so it gets the same GC treatment. A marker match alone\n// is not enough: semanticMessageHasMarker/agentMessageText only inspect a custom message's text at all\n// once it passes this gate, so a customType that doesn't match here never reaches the marker check.\nfunction isSemanticMemoryCustomMessage(message: AgentMessage): boolean {\n\tif (message.role !== \"custom\") return false;\n\tconst customType = String((message as { customType?: unknown }).customType ?? \"\").toLowerCase();\n\treturn (\n\t\tcustomType.includes(\"automata\") ||\n\t\tcustomType.includes(\"memory\") ||\n\t\tcustomType.includes(\"mind\") ||\n\t\tcustomType.includes(\"task_steps\")\n\t);\n}\n\nfunction agentMessageText(message: AgentMessage): string | undefined {\n\tif (message.role === \"toolResult\") return toolResultText(message);\n\tif (isSemanticMemoryCustomMessage(message)) return contentText((message as { content?: unknown }).content);\n\treturn undefined;\n}\n\nfunction semanticMessageHasMarker(message: AgentMessage, settings: Required<SemanticMemoryGcSettings>): boolean {\n\tif (message.role === \"toolResult\") return joinedPartsContainAnyMarker(toolResultParts(message), settings.markers);\n\tif (isSemanticMemoryCustomMessage(message)) {\n\t\tconst parts = textContentParts((message as { content?: unknown }).content);\n\t\treturn parts ? joinedPartsContainAnyMarker(parts, settings.markers) : false;\n\t}\n\treturn false;\n}\n\ninterface ContextGcPlan {\n\tcalls: Map<string, ToolCallMeta>;\n\tlatestReadByPath: Map<string, string>;\n\tsemanticIndexes: number[];\n}\n\nfunction normalizeToolPath(cwd: string, value: unknown): string | undefined {\n\tif (typeof value !== \"string\" || value.trim() === \"\") return undefined;\n\tconst path = value.trim();\n\treturn normalizePath(isAbsolute(path) ? path : resolve(cwd, path));\n}\n\nfunction collectContextGcPlan(\n\tmessages: AgentMessage[],\n\tcwd: string,\n\tsemanticSettings: Required<SemanticMemoryGcSettings>,\n): ContextGcPlan {\n\tconst calls = new Map<string, ToolCallMeta>();\n\tconst readResultCallIds: string[] = [];\n\tconst semanticIndexes: number[] = [];\n\n\tfor (let messageIndex = 0; messageIndex < messages.length; messageIndex++) {\n\t\tconst message = messages[messageIndex];\n\t\tif (message.role === \"assistant\") {\n\t\t\tfor (const part of message.content) {\n\t\t\t\tif (part.type !== \"toolCall\") continue;\n\t\t\t\tcalls.set(part.id, {\n\t\t\t\t\tid: part.id,\n\t\t\t\t\tname: part.name,\n\t\t\t\t\targs: part.arguments ?? {},\n\t\t\t\t\tmessageIndex,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (message.role === \"toolResult\" && message.toolName === \"read\") {\n\t\t\treadResultCallIds.push(message.toolCallId);\n\t\t}\n\n\t\tif (semanticSettings.enabled && semanticMessageHasMarker(message, semanticSettings)) {\n\t\t\tsemanticIndexes.push(messageIndex);\n\t\t}\n\t}\n\n\tconst latestReadByPath = new Map<string, string>();\n\tfor (const toolCallId of readResultCallIds) {\n\t\tconst call = calls.get(toolCallId);\n\t\tconst path = normalizeToolPath(cwd, call?.args.path);\n\t\tif (path) latestReadByPath.set(path, toolCallId);\n\t}\n\n\treturn { calls, latestReadByPath, semanticIndexes };\n}\n\nfunction storagePathFor(storageDir: string | undefined, key: string): string | undefined {\n\tif (!storageDir || !isAbsolute(storageDir)) return undefined;\n\treturn resolve(storageDir, `${key}.txt`);\n}\n\nfunction maybeStoreOriginal(options: ContextGcOptions, key: string, original: string): string | undefined {\n\tconst path = storagePathFor(options.storageDir, key);\n\tif (!path || !options.writePayloads) return path;\n\ttry {\n\t\tmkdirSync(options.storageDir!, { recursive: true });\n\t\tif (!existsSync(path)) writeFileSync(path, original, \"utf8\");\n\t} catch {\n\t\treturn undefined;\n\t}\n\treturn path;\n}\n\nfunction reasonText(record: ContextGcPackedRecord): string {\n\tif (record.reason === \"superseded-read\") return \"older read snapshot superseded by a later read of the same file\";\n\tif (record.reason === \"stale-semantic-memory\") {\n\t\treturn \"older Automata/Mind semantic context page outside the semantic-memory freshness window\";\n\t}\n\treturn \"stale bulky tool output outside the recent context window\";\n}\n\nfunction buildSummary(record: ContextGcPackedRecord): string {\n\tconst semantic = record.reason === \"stale-semantic-memory\";\n\tconst lines = [\n\t\tsemantic ? \"[Semantic GC packed stale Automata/Mind context page]\" : \"[Context GC packed stale tool result]\",\n\t\tsemantic ? undefined : `tool: ${record.toolName}`,\n\t\trecord.path ? `path: ${record.path}` : undefined,\n\t\trecord.command ? `command: ${cap(record.command)}` : undefined,\n\t\t`reason: ${reasonText(record)}`,\n\t\t`original: ${record.originalChars} chars (~${record.originalTokens} tokens)`,\n\t\t// The digest arrives PRE-FENCED from the curator (brain-curator.ts wraps it once, in the\n\t\t// standard untrusted-content boundary — the same treatment memory recall pages get — at the\n\t\t// moment it is stored, not here). Render it VERBATIM: re-wrapping on every GC render would\n\t\t// regenerate the fence's nonce each time, making the packed stub byte-different on every\n\t\t// provider request and busting prompt caching (BUG E).\n\t\trecord.digest ? `summary (auto-digest, machine paraphrase, not authoritative): ${record.digest}` : undefined,\n\t\trecord.storagePath\n\t\t\t? `exact old provider-visible text stored at: ${record.storagePath}`\n\t\t\t: \"exact old provider-visible text retained in the session log, not inline in provider context\",\n\t\tsemantic\n\t\t\t? \"If this memory context matters, query Automata/Mind again with the same topic/filter or fetch the drawer pointers from the stored page.\"\n\t\t\t: record.path\n\t\t\t\t? \"For current file contents, use the read tool on the path above. For the exact old output, read the stored payload path if present.\"\n\t\t\t\t: \"If this exact old output matters, retrieve/read the stored payload path if present or rerun the tool command.\",\n\t\t\"Do not rely on this summary as the original content.\",\n\t].filter((line): line is string => line !== undefined);\n\treturn lines.join(\"\\n\");\n}\n\nfunction gcDetails(message: { details?: unknown }, record: ContextGcPackedRecord): Record<string, unknown> {\n\treturn {\n\t\t...(typeof message.details === \"object\" && message.details !== null ? message.details : {}),\n\t\tcontextGc: {\n\t\t\tpacked: true,\n\t\t\toriginalChars: record.originalChars,\n\t\t\toriginalTokens: record.originalTokens,\n\t\t\tstoragePath: record.storagePath,\n\t\t\treason: record.reason,\n\t\t},\n\t};\n}\n\nfunction makePackedToolResult(message: ToolResultMessage, record: ContextGcPackedRecord): ToolResultMessage {\n\tconst summary = buildSummary(record);\n\treturn {\n\t\t...message,\n\t\tcontent: [{ type: \"text\", text: summary }],\n\t\tdetails: gcDetails(message, record),\n\t};\n}\n\nfunction makePackedSemanticMemoryMessage(message: AgentMessage, record: ContextGcPackedRecord): AgentMessage {\n\tconst summary = buildSummary(record);\n\treturn {\n\t\t...(message as unknown as Record<string, unknown>),\n\t\tcontent: [{ type: \"text\", text: summary }],\n\t\tdetails: gcDetails(message as { details?: unknown }, record),\n\t} as AgentMessage;\n}\n\nexport function applyContextGc(\n\tmessages: AgentMessage[],\n\trawSettings: ContextGcSettings & {\n\t\tcwd?: string;\n\t\tstorageDir?: string;\n\t\twritePayloads?: boolean;\n\t\tcuration?: ContextGcCurationHooks;\n\t},\n): ContextGcResult {\n\tconst settings = normalizeContextGcSettings(rawSettings);\n\tconst baseReport: ContextGcReport = {\n\t\tenabled: settings.enabled,\n\t\tpackedCount: 0,\n\t\toriginalTokens: 0,\n\t\tpackedTokens: 0,\n\t\tsavedTokens: 0,\n\t\trecords: [],\n\t};\n\tif (!settings.enabled) return { messages, report: baseReport };\n\n\tconst options: ContextGcOptions = {\n\t\t...settings,\n\t\tcwd: rawSettings.cwd ?? process.cwd(),\n\t\tstorageDir: rawSettings.storageDir,\n\t\twritePayloads: rawSettings.writePayloads ?? true,\n\t\tcuration: rawSettings.curation,\n\t};\n\tconst eligibleTools = new Set(options.tools);\n\tconst plan = collectContextGcPlan(messages, options.cwd, options.semanticMemory);\n\tconst recentStart = Math.max(0, messages.length - options.preserveRecentMessages);\n\tconst semanticIndexSet = new Set(plan.semanticIndexes);\n\tconst preservedSemanticIndexes = new Set(\n\t\toptions.semanticMemory.preserveRecentPages > 0\n\t\t\t? plan.semanticIndexes.slice(-options.semanticMemory.preserveRecentPages)\n\t\t\t: [],\n\t);\n\tconst nextMessages = messages.slice();\n\tlet changed = false;\n\n\tfor (let index = 0; index < messages.length; index++) {\n\t\tconst message = messages[index];\n\t\tif (semanticIndexSet.has(index) && !preservedSemanticIndexes.has(index) && index < recentStart) {\n\t\t\tconst originalText = agentMessageText(message);\n\t\t\tif (originalText && originalText.length >= options.semanticMemory.minChars) {\n\t\t\t\tconst originalTokens = estimateTokens(message);\n\t\t\t\tconst key = createHash(\"sha256\")\n\t\t\t\t\t.update(\"semantic-memory\\0\")\n\t\t\t\t\t.update(String(index))\n\t\t\t\t\t.update(\"\\0\")\n\t\t\t\t\t.update(originalText)\n\t\t\t\t\t.digest(\"hex\")\n\t\t\t\t\t.slice(0, 24);\n\t\t\t\tconst storagePath = maybeStoreOriginal(options, key, originalText);\n\t\t\t\tconst record: ContextGcPackedRecord = {\n\t\t\t\t\ttoolName: \"automata-mind\",\n\t\t\t\t\ttoolCallId: `semantic-${index}`,\n\t\t\t\t\tmessageIndex: index,\n\t\t\t\t\treason: \"stale-semantic-memory\",\n\t\t\t\t\toriginalChars: originalText.length,\n\t\t\t\t\toriginalTokens,\n\t\t\t\t\tpackedTokens: 0,\n\t\t\t\t\tstoragePath,\n\t\t\t\t\tkey,\n\t\t\t\t};\n\t\t\t\trecord.digest = options.curation?.resolveDigest?.(key);\n\t\t\t\toptions.curation?.onPacked?.(record, originalText);\n\t\t\t\tconst packed = makePackedSemanticMemoryMessage(message, record);\n\t\t\t\trecord.packedTokens = estimateTokens(packed);\n\t\t\t\tnextMessages[index] = packed;\n\t\t\t\tbaseReport.records.push(record);\n\t\t\t\tbaseReport.originalTokens += record.originalTokens;\n\t\t\t\tbaseReport.packedTokens += record.packedTokens;\n\t\t\t\tchanged = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif (message.role !== \"toolResult\") continue;\n\t\tif (!eligibleTools.has(message.toolName)) continue;\n\t\tif (index >= recentStart) continue;\n\n\t\tconst originalText = toolResultText(message);\n\t\tif (originalText.length < options.minToolResultChars) continue;\n\n\t\tconst call = plan.calls.get(message.toolCallId);\n\t\tconst path = normalizeToolPath(options.cwd, call?.args.path);\n\t\tlet reason: ContextGcPackedRecord[\"reason\"] = \"stale-tool-result\";\n\t\tif (message.toolName === \"read\" && path) {\n\t\t\tif (plan.latestReadByPath.get(path) === message.toolCallId) continue;\n\t\t\treason = \"superseded-read\";\n\t\t}\n\n\t\tconst originalTokens = estimateTokens(message);\n\t\tconst key = createHash(\"sha256\")\n\t\t\t.update(message.toolName)\n\t\t\t.update(\"\\0\")\n\t\t\t.update(message.toolCallId)\n\t\t\t.update(\"\\0\")\n\t\t\t.update(originalText)\n\t\t\t.digest(\"hex\")\n\t\t\t.slice(0, 24);\n\t\tconst storagePath = maybeStoreOriginal(options, key, originalText);\n\t\tconst record: ContextGcPackedRecord = {\n\t\t\ttoolName: message.toolName,\n\t\t\ttoolCallId: message.toolCallId,\n\t\t\tmessageIndex: index,\n\t\t\treason,\n\t\t\toriginalChars: originalText.length,\n\t\t\toriginalTokens,\n\t\t\tpackedTokens: 0,\n\t\t\tstoragePath,\n\t\t\tpath,\n\t\t\tcommand: typeof call?.args.command === \"string\" ? call.args.command : undefined,\n\t\t\tkey,\n\t\t};\n\t\trecord.digest = options.curation?.resolveDigest?.(key);\n\t\toptions.curation?.onPacked?.(record, originalText);\n\t\tconst packed = makePackedToolResult(message, record);\n\t\trecord.packedTokens = estimateTokens(packed);\n\t\tnextMessages[index] = packed as AgentMessage;\n\t\tbaseReport.records.push(record);\n\t\tbaseReport.originalTokens += record.originalTokens;\n\t\tbaseReport.packedTokens += record.packedTokens;\n\t\tchanged = true;\n\t}\n\n\tbaseReport.packedCount = baseReport.records.length;\n\tbaseReport.savedTokens = Math.max(0, baseReport.originalTokens - baseReport.packedTokens);\n\treturn { messages: changed ? nextMessages : messages, report: baseReport };\n}\n"]}
1
+ {"version":3,"file":"context-gc.d.ts","sourceRoot":"","sources":["../../src/core/context-gc.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAK9D,MAAM,WAAW,wBAAwB;IACxC,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,0EAA0E;IAC1E,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,yFAAyF;IACzF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,uEAAuE;IACvE,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;CACnB;AAED,MAAM,WAAW,iBAAiB;IACjC,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,oEAAoE;IACpE,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,gFAAgF;IAChF,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,oDAAoD;IACpD,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;IACjB,sFAAsF;IACt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E,MAAM,CAAC;IACvB,YAAY,EAAE,MAAM,CAAC;IACrB,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,qBAAqB,EAAE,CAAC;CACjC;AAED,MAAM,WAAW,eAAe;IAC/B,QAAQ,EAAE,YAAY,EAAE,CAAC;IACzB,MAAM,EAAE,eAAe,CAAC;CACxB;AA2BD,eAAO,MAAM,2BAA2B,EAAE,2BAgCzC,CAAC;AA6CF,wBAAgB,oBAAoB,CAAC,QAAQ,CAAC,EAAE,iBAAiB,GAAG,2BAA2B,CAE9F;AA6OD,wBAAgB,cAAc,CAC7B,QAAQ,EAAE,YAAY,EAAE,EACxB,WAAW,EAAE,iBAAiB,GAAG;IAChC,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,iBAAiB,CAAC,EAAE,MAAM,MAAM,CAAC;IACjC,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,QAAQ,CAAC,EAAE,sBAAsB,CAAC;CAClC,GACC,eAAe,CA0HjB","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { isAbsolute, resolve } from \"node:path\";\nimport type { AgentMessage } from \"@caupulican/pi-agent-core\";\nimport { estimateTokens } from \"@caupulican/pi-agent-core/node\";\nimport type { ToolResultMessage } from \"@caupulican/pi-ai\";\nimport { normalizePath } from \"../utils/paths.ts\";\n\nexport interface SemanticMemoryGcSettings {\n\tenabled?: boolean;\n\t/** Number of newest Automata/Mind injected pages to preserve verbatim. */\n\tpreserveRecentPages?: number;\n\t/** Minimum provider-visible text chars before a stale semantic memory page is packed. */\n\tminChars?: number;\n\t/** Markers that identify deterministic Automata/Mind context pages. */\n\tmarkers?: string[];\n}\n\nexport interface ContextGcSettings {\n\tenabled?: boolean;\n\t/** Number of most recent AgentMessage rows to preserve verbatim. */\n\tpreserveRecentMessages?: number;\n\t/** Minimum provider-visible text chars before a stale tool result is packed. */\n\tminToolResultChars?: number;\n\t/** Tool names eligible for stale result packing. */\n\ttools?: string[];\n\t/** Provider-context control for deterministic Automata/Mind semantic memory pages. */\n\tsemanticMemory?: SemanticMemoryGcSettings;\n}\n\nexport interface NormalizedContextGcSettings extends Omit<Required<ContextGcSettings>, \"semanticMemory\"> {\n\tsemanticMemory: Required<SemanticMemoryGcSettings>;\n}\n\n/**\n * Brain-curation hooks (both optional; absent hooks are byte-for-byte today's behavior).\n * `resolveDigest` is a pure lookup keyed by the record's content hash — it must return the digest\n * already fenced in the untrusted-content boundary (e.g. BrainCurator.getDigest), with the fence's\n * nonce fixed once at store time, since GC re-renders the stub from raw messages on every request\n * and renders the returned string VERBATIM. `onPacked` lets the caller enqueue digest work with the\n * exact original text at the moment it is packed.\n */\nexport interface ContextGcCurationHooks {\n\tresolveDigest?: (digestKey: string) => string | undefined;\n\tonPacked?: (record: ContextGcPackedRecord, originalText: string) => void;\n}\n\nexport interface ContextGcOptions extends NormalizedContextGcSettings {\n\tcwd: string;\n\tstorageDir?: string;\n\t/** Acquire the leased store only when an eligible payload is actually written. */\n\tacquireStorageDir?: () => string;\n\twritePayloads?: boolean;\n\tcuration?: ContextGcCurationHooks;\n}\n\nexport interface ContextGcPackedRecord {\n\ttoolName: string;\n\ttoolCallId: string;\n\tmessageIndex: number;\n\treason: \"superseded-read\" | \"stale-tool-result\" | \"stale-semantic-memory\";\n\toriginalChars: number;\n\toriginalTokens: number;\n\tpackedTokens: number;\n\tstoragePath?: string;\n\tpath?: string;\n\tcommand?: string;\n\tkey?: string;\n\t/** Brain-curator semantic digest of the packed content (model-generated; advisory only). Arrives\n\t * already fenced in the untrusted-content boundary (see ContextGcCurationHooks.resolveDigest) —\n\t * render verbatim, never re-wrap. */\n\tdigest?: string;\n}\n\nexport interface ContextGcReport {\n\tenabled: boolean;\n\tpackedCount: number;\n\toriginalTokens: number;\n\tpackedTokens: number;\n\tsavedTokens: number;\n\trecords: ContextGcPackedRecord[];\n}\n\nexport interface ContextGcResult {\n\tmessages: AgentMessage[];\n\treport: ContextGcReport;\n}\n\nconst DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS: Required<SemanticMemoryGcSettings> = {\n\tenabled: true,\n\tpreserveRecentPages: 1,\n\tminChars: 900,\n\tmarkers: [\n\t\t// Generic memory-subsystem recall page marker (brand-free). Provider-specific markers are\n\t\t// merged in dynamically at runtime via MemoryManager.getContextMarkers().\n\t\t\"<memory_context\",\n\t\t// Pre-existing provider-specific markers (to be generalized to provider-declared markers).\n\t\t\"<automata_context\",\n\t\t\"<automata_response\",\n\t\t\"<automata_query\",\n\t\t\"<automata_fetch\",\n\t\t\"<memory_lifecycle_audit\",\n\t\t\"<memory_lifecycle_purge\",\n\t\t\"<automata_doctor\",\n\t\t\"<automata_optimizer\",\n\t\t\"<automata_mesh\",\n\t\t// Injected task_steps checklist page (tasks/task-state.ts formatTaskStepsContext), re-derived\n\t\t// fresh every turn from live TaskStepsState -- same GC treatment as a memory recall page (Bug\n\t\t// #7 lineage): pack stale turn-copies down to the most recent one instead of accumulating.\n\t\t\"<task_steps_context\",\n\t],\n};\n\nexport const DEFAULT_CONTEXT_GC_SETTINGS: NormalizedContextGcSettings = {\n\tenabled: true,\n\tpreserveRecentMessages: 8,\n\tminToolResultChars: 1200,\n\ttools: [\n\t\t\"read\",\n\t\t\"bash\",\n\t\t\"python\",\n\t\t\"powershell\",\n\t\t\"rg\",\n\t\t\"grep\",\n\t\t\"find\",\n\t\t\"run_toolkit_script\",\n\t\t\"ls\",\n\t\t\"skill_open\",\n\t\t\"automata_graph_status\",\n\t\t\"automata_graph_search\",\n\t\t\"automata_graph_query\",\n\t\t\"automata_graph_neighbors\",\n\t\t\"automata_graph_path\",\n\t\t\"automata_graph_pointer_pack\",\n\t\t\"learning_query_memory\",\n\t\t\"subagent\",\n\t\t\"delegate\",\n\t\t\"task_steps\",\n\t\t\"task_background\",\n\t\t\"task_goal\",\n\t\t\"run_ledger\",\n\t\t\"context_headroom_retrieve\",\n\t\t\"headroom_retrieve\",\n\t],\n\tsemanticMemory: DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS,\n};\n\ntype ToolCallMeta = {\n\tid: string;\n\tname: string;\n\targs: Record<string, unknown>;\n\tmessageIndex: number;\n};\n\nfunction cap(text: string, limit = 220): string {\n\tconst compact = text.replace(/\\s+/g, \" \").trim();\n\treturn compact.length > limit ? `${compact.slice(0, Math.max(0, limit - 1))}…` : compact;\n}\n\nfunction normalizeSemanticMemoryGcSettings(settings?: SemanticMemoryGcSettings): Required<SemanticMemoryGcSettings> {\n\treturn {\n\t\tenabled: settings?.enabled ?? DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS.enabled,\n\t\tpreserveRecentPages: Math.max(\n\t\t\t0,\n\t\t\tMath.floor(settings?.preserveRecentPages ?? DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS.preserveRecentPages),\n\t\t),\n\t\tminChars: Math.max(0, Math.floor(settings?.minChars ?? DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS.minChars)),\n\t\tmarkers:\n\t\t\tsettings?.markers && settings.markers.length > 0\n\t\t\t\t? settings.markers\n\t\t\t\t: DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS.markers,\n\t};\n}\n\nfunction normalizeContextGcSettings(settings?: ContextGcSettings): NormalizedContextGcSettings {\n\treturn {\n\t\tenabled: settings?.enabled ?? DEFAULT_CONTEXT_GC_SETTINGS.enabled,\n\t\tpreserveRecentMessages: Math.max(\n\t\t\t0,\n\t\t\tMath.floor(settings?.preserveRecentMessages ?? DEFAULT_CONTEXT_GC_SETTINGS.preserveRecentMessages),\n\t\t),\n\t\tminToolResultChars: Math.max(\n\t\t\t0,\n\t\t\tMath.floor(settings?.minToolResultChars ?? DEFAULT_CONTEXT_GC_SETTINGS.minToolResultChars),\n\t\t),\n\t\ttools: settings?.tools && settings.tools.length > 0 ? settings.tools : DEFAULT_CONTEXT_GC_SETTINGS.tools,\n\t\tsemanticMemory: normalizeSemanticMemoryGcSettings(settings?.semanticMemory),\n\t};\n}\n\nexport function getContextGcSettings(settings?: ContextGcSettings): NormalizedContextGcSettings {\n\treturn normalizeContextGcSettings(settings);\n}\n\nfunction textContentParts(content: unknown): string[] | undefined {\n\tif (typeof content === \"string\") return [content];\n\tif (!Array.isArray(content)) return undefined;\n\tconst parts: string[] = [];\n\tfor (const part of content) {\n\t\tif (typeof part !== \"object\" || part === null) return undefined;\n\t\tconst typed = part as { type?: string; text?: string; mimeType?: string };\n\t\tif (typed.type === \"text\" && typeof typed.text === \"string\") parts.push(typed.text);\n\t\telse if (typed.type === \"image\") return undefined;\n\t\telse return undefined;\n\t}\n\treturn parts;\n}\n\nfunction joinTextParts(parts: readonly string[]): string {\n\tif (parts.length === 0) return \"\";\n\tif (parts.length === 1) return parts[0];\n\treturn parts.join(\"\\n\");\n}\n\nfunction contentText(content: unknown): string | undefined {\n\tif (typeof content === \"string\") return content;\n\tconst parts = textContentParts(content);\n\treturn parts ? joinTextParts(parts) : undefined;\n}\n\nfunction toolResultParts(message: ToolResultMessage): string[] {\n\tconst parts: string[] = [];\n\tfor (const part of message.content) {\n\t\tif (part.type === \"text\" && part.text) parts.push(part.text);\n\t\telse if (part.type === \"image\") parts.push(`[image ${part.mimeType}]`);\n\t}\n\treturn parts;\n}\n\nfunction toolResultText(message: ToolResultMessage): string {\n\treturn joinTextParts(toolResultParts(message));\n}\n\nfunction smallStringSlice(value: string, start?: number, end?: number): string {\n\tconst sliced = value.slice(start, end);\n\treturn sliced ? ` ${sliced}`.slice(1) : \"\";\n}\n\nfunction joinedPartsContainMarker(parts: string[], marker: string): boolean {\n\tif (marker.length === 0) return true;\n\tconst tailLength = marker.length - 1;\n\tlet tail = \"\";\n\tlet first = true;\n\tfor (const part of parts) {\n\t\tif (part.includes(marker)) return true;\n\t\tif (!first && `${tail}\\n${smallStringSlice(part, 0, tailLength)}`.includes(marker)) return true;\n\t\tif (tailLength === 0) tail = \"\";\n\t\telse if (part.length >= tailLength) tail = smallStringSlice(part, -tailLength);\n\t\telse tail = `${tail}${first ? \"\" : \"\\n\"}${part}`.slice(-tailLength);\n\t\tfirst = false;\n\t}\n\treturn false;\n}\n\nfunction joinedPartsContainAnyMarker(parts: string[], markers: readonly string[]): boolean {\n\treturn markers.some((marker) => joinedPartsContainMarker(parts, marker));\n}\n\n// Gates which custom-message types are eligible for the semantic-memory packer below. Despite the\n// name, this now also covers the injected task_steps checklist page (customType \"task_steps_context\",\n// see agent-session.ts) -- it is a deterministic, re-derivable-from-live-state context page exactly\n// like a memory recall page, so it gets the same GC treatment. A marker match alone\n// is not enough: semanticMessageHasMarker/agentMessageText only inspect a custom message's text at all\n// once it passes this gate, so a customType that doesn't match here never reaches the marker check.\nfunction isSemanticMemoryCustomMessage(message: AgentMessage): boolean {\n\tif (message.role !== \"custom\") return false;\n\tconst customType = String((message as { customType?: unknown }).customType ?? \"\").toLowerCase();\n\treturn (\n\t\tcustomType.includes(\"automata\") ||\n\t\tcustomType.includes(\"memory\") ||\n\t\tcustomType.includes(\"mind\") ||\n\t\tcustomType.includes(\"task_steps\")\n\t);\n}\n\nfunction agentMessageText(message: AgentMessage): string | undefined {\n\tif (message.role === \"toolResult\") return toolResultText(message);\n\tif (isSemanticMemoryCustomMessage(message)) return contentText((message as { content?: unknown }).content);\n\treturn undefined;\n}\n\nfunction semanticMessageHasMarker(message: AgentMessage, settings: Required<SemanticMemoryGcSettings>): boolean {\n\tif (message.role === \"toolResult\") return joinedPartsContainAnyMarker(toolResultParts(message), settings.markers);\n\tif (isSemanticMemoryCustomMessage(message)) {\n\t\tconst parts = textContentParts((message as { content?: unknown }).content);\n\t\treturn parts ? joinedPartsContainAnyMarker(parts, settings.markers) : false;\n\t}\n\treturn false;\n}\n\ninterface ContextGcPlan {\n\tcalls: Map<string, ToolCallMeta>;\n\tlatestReadByPath: Map<string, string>;\n\tsemanticIndexes: number[];\n}\n\nfunction normalizeToolPath(cwd: string, value: unknown): string | undefined {\n\tif (typeof value !== \"string\" || value.trim() === \"\") return undefined;\n\tconst path = value.trim();\n\treturn normalizePath(isAbsolute(path) ? path : resolve(cwd, path));\n}\n\nfunction collectContextGcPlan(\n\tmessages: AgentMessage[],\n\tcwd: string,\n\tsemanticSettings: Required<SemanticMemoryGcSettings>,\n): ContextGcPlan {\n\tconst calls = new Map<string, ToolCallMeta>();\n\tconst readResultCallIds: string[] = [];\n\tconst semanticIndexes: number[] = [];\n\n\tfor (let messageIndex = 0; messageIndex < messages.length; messageIndex++) {\n\t\tconst message = messages[messageIndex];\n\t\tif (message.role === \"assistant\") {\n\t\t\tfor (const part of message.content) {\n\t\t\t\tif (part.type !== \"toolCall\") continue;\n\t\t\t\tcalls.set(part.id, {\n\t\t\t\t\tid: part.id,\n\t\t\t\t\tname: part.name,\n\t\t\t\t\targs: part.arguments ?? {},\n\t\t\t\t\tmessageIndex,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (message.role === \"toolResult\" && message.toolName === \"read\") {\n\t\t\treadResultCallIds.push(message.toolCallId);\n\t\t}\n\n\t\tif (semanticSettings.enabled && semanticMessageHasMarker(message, semanticSettings)) {\n\t\t\tsemanticIndexes.push(messageIndex);\n\t\t}\n\t}\n\n\tconst latestReadByPath = new Map<string, string>();\n\tfor (const toolCallId of readResultCallIds) {\n\t\tconst call = calls.get(toolCallId);\n\t\tconst path = normalizeToolPath(cwd, call?.args.path);\n\t\tif (path) latestReadByPath.set(path, toolCallId);\n\t}\n\n\treturn { calls, latestReadByPath, semanticIndexes };\n}\n\nfunction storagePathFor(storageDir: string | undefined, key: string): string | undefined {\n\tif (!storageDir || !isAbsolute(storageDir)) return undefined;\n\treturn resolve(storageDir, `${key}.txt`);\n}\n\nfunction maybeStoreOriginal(options: ContextGcOptions, key: string, original: string): string | undefined {\n\tconst plannedPath = storagePathFor(options.storageDir, key);\n\tif (!plannedPath || !options.writePayloads) return plannedPath;\n\ttry {\n\t\tconst storageDir = options.acquireStorageDir?.() ?? options.storageDir;\n\t\tconst path = storagePathFor(storageDir, key);\n\t\tif (!path || !storageDir) return undefined;\n\t\tmkdirSync(storageDir, { recursive: true });\n\t\tif (!existsSync(path)) writeFileSync(path, original, \"utf8\");\n\t\treturn path;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction reasonText(record: ContextGcPackedRecord): string {\n\tif (record.reason === \"superseded-read\") return \"older read snapshot superseded by a later read of the same file\";\n\tif (record.reason === \"stale-semantic-memory\") {\n\t\treturn \"older Automata/Mind semantic context page outside the semantic-memory freshness window\";\n\t}\n\treturn \"stale bulky tool output outside the recent context window\";\n}\n\nfunction buildSummary(record: ContextGcPackedRecord): string {\n\tconst semantic = record.reason === \"stale-semantic-memory\";\n\tconst lines = [\n\t\tsemantic ? \"[Semantic GC packed stale Automata/Mind context page]\" : \"[Context GC packed stale tool result]\",\n\t\tsemantic ? undefined : `tool: ${record.toolName}`,\n\t\trecord.path ? `path: ${record.path}` : undefined,\n\t\trecord.command ? `command: ${cap(record.command)}` : undefined,\n\t\t`reason: ${reasonText(record)}`,\n\t\t`original: ${record.originalChars} chars (~${record.originalTokens} tokens)`,\n\t\t// The digest arrives PRE-FENCED from the curator (brain-curator.ts wraps it once, in the\n\t\t// standard untrusted-content boundary — the same treatment memory recall pages get — at the\n\t\t// moment it is stored, not here). Render it VERBATIM: re-wrapping on every GC render would\n\t\t// regenerate the fence's nonce each time, making the packed stub byte-different on every\n\t\t// provider request and busting prompt caching (BUG E).\n\t\trecord.digest ? `summary (auto-digest, machine paraphrase, not authoritative): ${record.digest}` : undefined,\n\t\trecord.storagePath\n\t\t\t? `exact old provider-visible text stored at: ${record.storagePath}`\n\t\t\t: \"exact old provider-visible text retained in the session log, not inline in provider context\",\n\t\tsemantic\n\t\t\t? \"If this memory context matters, query Automata/Mind again with the same topic/filter or fetch the drawer pointers from the stored page.\"\n\t\t\t: record.path\n\t\t\t\t? \"For current file contents, use the read tool on the path above. For the exact old output, read the stored payload path if present.\"\n\t\t\t\t: \"If this exact old output matters, retrieve/read the stored payload path if present or rerun the tool command.\",\n\t\t\"Do not rely on this summary as the original content.\",\n\t].filter((line): line is string => line !== undefined);\n\treturn lines.join(\"\\n\");\n}\n\nfunction gcDetails(message: { details?: unknown }, record: ContextGcPackedRecord): Record<string, unknown> {\n\treturn {\n\t\t...(typeof message.details === \"object\" && message.details !== null ? message.details : {}),\n\t\tcontextGc: {\n\t\t\tpacked: true,\n\t\t\toriginalChars: record.originalChars,\n\t\t\toriginalTokens: record.originalTokens,\n\t\t\tstoragePath: record.storagePath,\n\t\t\treason: record.reason,\n\t\t},\n\t};\n}\n\nfunction makePackedToolResult(message: ToolResultMessage, record: ContextGcPackedRecord): ToolResultMessage {\n\tconst summary = buildSummary(record);\n\treturn {\n\t\t...message,\n\t\tcontent: [{ type: \"text\", text: summary }],\n\t\tdetails: gcDetails(message, record),\n\t};\n}\n\nfunction makePackedSemanticMemoryMessage(message: AgentMessage, record: ContextGcPackedRecord): AgentMessage {\n\tconst summary = buildSummary(record);\n\treturn {\n\t\t...(message as unknown as Record<string, unknown>),\n\t\tcontent: [{ type: \"text\", text: summary }],\n\t\tdetails: gcDetails(message as { details?: unknown }, record),\n\t} as AgentMessage;\n}\n\nexport function applyContextGc(\n\tmessages: AgentMessage[],\n\trawSettings: ContextGcSettings & {\n\t\tcwd?: string;\n\t\tstorageDir?: string;\n\t\tacquireStorageDir?: () => string;\n\t\twritePayloads?: boolean;\n\t\tcuration?: ContextGcCurationHooks;\n\t},\n): ContextGcResult {\n\tconst settings = normalizeContextGcSettings(rawSettings);\n\tconst baseReport: ContextGcReport = {\n\t\tenabled: settings.enabled,\n\t\tpackedCount: 0,\n\t\toriginalTokens: 0,\n\t\tpackedTokens: 0,\n\t\tsavedTokens: 0,\n\t\trecords: [],\n\t};\n\tif (!settings.enabled) return { messages, report: baseReport };\n\n\tconst options: ContextGcOptions = {\n\t\t...settings,\n\t\tcwd: rawSettings.cwd ?? process.cwd(),\n\t\tstorageDir: rawSettings.storageDir,\n\t\tacquireStorageDir: rawSettings.acquireStorageDir,\n\t\twritePayloads: rawSettings.writePayloads ?? true,\n\t\tcuration: rawSettings.curation,\n\t};\n\tconst eligibleTools = new Set(options.tools);\n\tconst plan = collectContextGcPlan(messages, options.cwd, options.semanticMemory);\n\tconst recentStart = Math.max(0, messages.length - options.preserveRecentMessages);\n\tconst semanticIndexSet = new Set(plan.semanticIndexes);\n\tconst preservedSemanticIndexes = new Set(\n\t\toptions.semanticMemory.preserveRecentPages > 0\n\t\t\t? plan.semanticIndexes.slice(-options.semanticMemory.preserveRecentPages)\n\t\t\t: [],\n\t);\n\tconst nextMessages = messages.slice();\n\tlet changed = false;\n\n\tfor (let index = 0; index < messages.length; index++) {\n\t\tconst message = messages[index];\n\t\tif (semanticIndexSet.has(index) && !preservedSemanticIndexes.has(index) && index < recentStart) {\n\t\t\tconst originalText = agentMessageText(message);\n\t\t\tif (originalText && originalText.length >= options.semanticMemory.minChars) {\n\t\t\t\tconst originalTokens = estimateTokens(message);\n\t\t\t\tconst key = createHash(\"sha256\")\n\t\t\t\t\t.update(\"semantic-memory\\0\")\n\t\t\t\t\t.update(String(index))\n\t\t\t\t\t.update(\"\\0\")\n\t\t\t\t\t.update(originalText)\n\t\t\t\t\t.digest(\"hex\")\n\t\t\t\t\t.slice(0, 24);\n\t\t\t\tconst storagePath = maybeStoreOriginal(options, key, originalText);\n\t\t\t\tconst record: ContextGcPackedRecord = {\n\t\t\t\t\ttoolName: \"automata-mind\",\n\t\t\t\t\ttoolCallId: `semantic-${index}`,\n\t\t\t\t\tmessageIndex: index,\n\t\t\t\t\treason: \"stale-semantic-memory\",\n\t\t\t\t\toriginalChars: originalText.length,\n\t\t\t\t\toriginalTokens,\n\t\t\t\t\tpackedTokens: 0,\n\t\t\t\t\tstoragePath,\n\t\t\t\t\tkey,\n\t\t\t\t};\n\t\t\t\trecord.digest = options.curation?.resolveDigest?.(key);\n\t\t\t\toptions.curation?.onPacked?.(record, originalText);\n\t\t\t\tconst packed = makePackedSemanticMemoryMessage(message, record);\n\t\t\t\trecord.packedTokens = estimateTokens(packed);\n\t\t\t\tnextMessages[index] = packed;\n\t\t\t\tbaseReport.records.push(record);\n\t\t\t\tbaseReport.originalTokens += record.originalTokens;\n\t\t\t\tbaseReport.packedTokens += record.packedTokens;\n\t\t\t\tchanged = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif (message.role !== \"toolResult\") continue;\n\t\tif (!eligibleTools.has(message.toolName)) continue;\n\t\tif (index >= recentStart) continue;\n\n\t\tconst originalText = toolResultText(message);\n\t\tif (originalText.length < options.minToolResultChars) continue;\n\n\t\tconst call = plan.calls.get(message.toolCallId);\n\t\tconst path = normalizeToolPath(options.cwd, call?.args.path);\n\t\tlet reason: ContextGcPackedRecord[\"reason\"] = \"stale-tool-result\";\n\t\tif (message.toolName === \"read\" && path) {\n\t\t\tif (plan.latestReadByPath.get(path) === message.toolCallId) continue;\n\t\t\treason = \"superseded-read\";\n\t\t}\n\n\t\tconst originalTokens = estimateTokens(message);\n\t\tconst key = createHash(\"sha256\")\n\t\t\t.update(message.toolName)\n\t\t\t.update(\"\\0\")\n\t\t\t.update(message.toolCallId)\n\t\t\t.update(\"\\0\")\n\t\t\t.update(originalText)\n\t\t\t.digest(\"hex\")\n\t\t\t.slice(0, 24);\n\t\tconst storagePath = maybeStoreOriginal(options, key, originalText);\n\t\tconst record: ContextGcPackedRecord = {\n\t\t\ttoolName: message.toolName,\n\t\t\ttoolCallId: message.toolCallId,\n\t\t\tmessageIndex: index,\n\t\t\treason,\n\t\t\toriginalChars: originalText.length,\n\t\t\toriginalTokens,\n\t\t\tpackedTokens: 0,\n\t\t\tstoragePath,\n\t\t\tpath,\n\t\t\tcommand: typeof call?.args.command === \"string\" ? call.args.command : undefined,\n\t\t\tkey,\n\t\t};\n\t\trecord.digest = options.curation?.resolveDigest?.(key);\n\t\toptions.curation?.onPacked?.(record, originalText);\n\t\tconst packed = makePackedToolResult(message, record);\n\t\trecord.packedTokens = estimateTokens(packed);\n\t\tnextMessages[index] = packed as AgentMessage;\n\t\tbaseReport.records.push(record);\n\t\tbaseReport.originalTokens += record.originalTokens;\n\t\tbaseReport.packedTokens += record.packedTokens;\n\t\tchanged = true;\n\t}\n\n\tbaseReport.packedCount = baseReport.records.length;\n\tbaseReport.savedTokens = Math.max(0, baseReport.originalTokens - baseReport.packedTokens);\n\treturn { messages: changed ? nextMessages : messages, report: baseReport };\n}\n"]}
@@ -236,18 +236,22 @@ function storagePathFor(storageDir, key) {
236
236
  return resolve(storageDir, `${key}.txt`);
237
237
  }
238
238
  function maybeStoreOriginal(options, key, original) {
239
- const path = storagePathFor(options.storageDir, key);
240
- if (!path || !options.writePayloads)
241
- return path;
239
+ const plannedPath = storagePathFor(options.storageDir, key);
240
+ if (!plannedPath || !options.writePayloads)
241
+ return plannedPath;
242
242
  try {
243
- mkdirSync(options.storageDir, { recursive: true });
243
+ const storageDir = options.acquireStorageDir?.() ?? options.storageDir;
244
+ const path = storagePathFor(storageDir, key);
245
+ if (!path || !storageDir)
246
+ return undefined;
247
+ mkdirSync(storageDir, { recursive: true });
244
248
  if (!existsSync(path))
245
249
  writeFileSync(path, original, "utf8");
250
+ return path;
246
251
  }
247
252
  catch {
248
253
  return undefined;
249
254
  }
250
- return path;
251
255
  }
252
256
  function reasonText(record) {
253
257
  if (record.reason === "superseded-read")
@@ -328,6 +332,7 @@ export function applyContextGc(messages, rawSettings) {
328
332
  ...settings,
329
333
  cwd: rawSettings.cwd ?? process.cwd(),
330
334
  storageDir: rawSettings.storageDir,
335
+ acquireStorageDir: rawSettings.acquireStorageDir,
331
336
  writePayloads: rawSettings.writePayloads ?? true,
332
337
  curation: rawSettings.curation,
333
338
  };