@caupulican/pi-adaptative 0.81.42 → 0.81.43

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 (1406) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/bun/cli.d.ts.map +1 -1
  3. package/dist/bun/cli.js.map +1 -1
  4. package/dist/bun/register-bedrock.d.ts.map +1 -1
  5. package/dist/bun/restore-sandbox-env.d.ts.map +1 -1
  6. package/dist/bun/restore-sandbox-env.js.map +1 -1
  7. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.d.ts.map +1 -1
  8. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.js.map +1 -1
  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 +52 -49
  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 +62 -57
  13. package/dist/bundled-resources/prompts/skillify.md +1 -1
  14. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/fs.py +16 -19
  15. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/search.py +12 -26
  16. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/strings.py +15 -121
  17. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/text.py +52 -79
  18. package/dist/bundled-resources/runtimes/pi-shell-engine/escapes.py +70 -0
  19. package/dist/bundled-resources/runtimes/pi-shell-engine/exec.py +110 -61
  20. package/dist/bundled-resources/runtimes/pi-shell-engine/main.py +106 -23
  21. package/dist/bundled-resources/runtimes/pi-shell-engine/paths.py +10 -0
  22. package/dist/bundled-resources/runtimes/pi-shell-engine/proc.py +12 -4
  23. package/dist/bundled-resources/runtimes/pi-shell-engine/shell_args.py +22 -0
  24. package/dist/bundled-resources/runtimes/pi-shell-engine/state.py +9 -2
  25. package/dist/bundled-resources/runtimes/pi-shell-engine/tokens.py +129 -259
  26. package/dist/bundled-resources/skills/authorized-web-security-audit/SKILL.md +187 -0
  27. package/dist/bundled-resources/skills/authorized-web-security-audit/references/assessment-contract.md +92 -0
  28. package/dist/bundled-resources/skills/deduplicate-by-evidence/SKILL.md +134 -0
  29. package/dist/bundled-resources/skills/evidence-gated-tdd/SKILL.md +93 -0
  30. package/dist/bundled-resources/skills/evidence-gated-tdd/references/evidence-model.md +27 -0
  31. package/dist/bundled-resources/skills/evidence-gated-tdd/references/security-scanners.md +24 -0
  32. package/dist/bundled-resources/skills/harness-self-adaptation/SKILL.md +4 -2
  33. package/dist/bundled-resources/skills/secure-agent-tool-surfaces/SKILL.md +217 -0
  34. package/dist/bundled-resources/skills/secure-agent-tool-surfaces/references/defensive-exploit-catalogue.md +175 -0
  35. package/dist/bundled-resources/skills/secure-agent-tool-surfaces/references/tool-boundary-checklist.md +87 -0
  36. package/dist/bundled-resources/skills/skill-architect/SKILL.md +2 -2
  37. package/dist/bundled-resources/skills/skill-creator/SKILL.md +188 -0
  38. package/dist/bundled-resources/skills/skill-creator/references/pi-skill-contract.md +73 -0
  39. package/dist/bundled-resources/skills/skill-creator/scripts/init-skill.mjs +142 -0
  40. package/dist/bundled-resources/skills/skill-creator/scripts/validate-skill.mjs +122 -0
  41. package/dist/cli/args.d.ts.map +1 -1
  42. package/dist/cli/args.js.map +1 -1
  43. package/dist/cli/config-selector.d.ts.map +1 -1
  44. package/dist/cli/config-selector.js.map +1 -1
  45. package/dist/cli/file-processor.d.ts.map +1 -1
  46. package/dist/cli/file-processor.js +8 -8
  47. package/dist/cli/file-processor.js.map +1 -1
  48. package/dist/cli/initial-message.d.ts +1 -1
  49. package/dist/cli/initial-message.d.ts.map +1 -1
  50. package/dist/cli/initial-message.js.map +1 -1
  51. package/dist/cli/list-models.d.ts.map +1 -1
  52. package/dist/cli/list-models.js.map +1 -1
  53. package/dist/cli/piped-stdin.d.ts +4 -0
  54. package/dist/cli/piped-stdin.d.ts.map +1 -0
  55. package/dist/cli/piped-stdin.js +13 -0
  56. package/dist/cli/piped-stdin.js.map +1 -0
  57. package/dist/cli/session-picker.d.ts.map +1 -1
  58. package/dist/cli/session-picker.js.map +1 -1
  59. package/dist/cli.d.ts.map +1 -1
  60. package/dist/cli.js.map +1 -1
  61. package/dist/config.d.ts.map +1 -1
  62. package/dist/config.js +9 -14
  63. package/dist/config.js.map +1 -1
  64. package/dist/core/agent-directory-layout.d.ts.map +1 -1
  65. package/dist/core/agent-directory-layout.js.map +1 -1
  66. package/dist/core/agent-paths.d.ts.map +1 -1
  67. package/dist/core/agent-paths.js.map +1 -1
  68. package/dist/core/agent-session-contracts.d.ts +5 -9
  69. package/dist/core/agent-session-contracts.d.ts.map +1 -1
  70. package/dist/core/agent-session-contracts.js +1 -12
  71. package/dist/core/agent-session-contracts.js.map +1 -1
  72. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  73. package/dist/core/agent-session-runtime.js +10 -25
  74. package/dist/core/agent-session-runtime.js.map +1 -1
  75. package/dist/core/agent-session-services.d.ts.map +1 -1
  76. package/dist/core/agent-session-services.js.map +1 -1
  77. package/dist/core/agent-session.d.ts +24 -1
  78. package/dist/core/agent-session.d.ts.map +1 -1
  79. package/dist/core/agent-session.js +210 -237
  80. package/dist/core/agent-session.js.map +1 -1
  81. package/dist/core/auth-guidance.d.ts.map +1 -1
  82. package/dist/core/auth-guidance.js.map +1 -1
  83. package/dist/core/auth-storage.d.ts +4 -1
  84. package/dist/core/auth-storage.d.ts.map +1 -1
  85. package/dist/core/auth-storage.js +13 -39
  86. package/dist/core/auth-storage.js.map +1 -1
  87. package/dist/core/autonomy/approval-gate.d.ts.map +1 -1
  88. package/dist/core/autonomy/approval-gate.js.map +1 -1
  89. package/dist/core/autonomy/bounded-completion.d.ts.map +1 -1
  90. package/dist/core/autonomy/bounded-completion.js.map +1 -1
  91. package/dist/core/autonomy/contracts.d.ts.map +1 -1
  92. package/dist/core/autonomy/envelope-enforcement.d.ts.map +1 -1
  93. package/dist/core/autonomy/envelope-enforcement.js.map +1 -1
  94. package/dist/core/autonomy/evidence-finding-projection.d.ts +11 -0
  95. package/dist/core/autonomy/evidence-finding-projection.d.ts.map +1 -0
  96. package/dist/core/autonomy/evidence-finding-projection.js +37 -0
  97. package/dist/core/autonomy/evidence-finding-projection.js.map +1 -0
  98. package/dist/core/autonomy/foreground-envelope.d.ts.map +1 -1
  99. package/dist/core/autonomy/foreground-envelope.js.map +1 -1
  100. package/dist/core/autonomy/gates.d.ts.map +1 -1
  101. package/dist/core/autonomy/gates.js.map +1 -1
  102. package/dist/core/autonomy/lane-private-paths.d.ts.map +1 -1
  103. package/dist/core/autonomy/lane-private-paths.js.map +1 -1
  104. package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
  105. package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
  106. package/dist/core/autonomy/lane-tracker.d.ts.map +1 -1
  107. package/dist/core/autonomy/lane-tracker.js +2 -3
  108. package/dist/core/autonomy/lane-tracker.js.map +1 -1
  109. package/dist/core/autonomy/path-scope.d.ts.map +1 -1
  110. package/dist/core/autonomy/path-scope.js.map +1 -1
  111. package/dist/core/autonomy/risk-assessment.d.ts.map +1 -1
  112. package/dist/core/autonomy/session-lane-record.d.ts.map +1 -1
  113. package/dist/core/autonomy/session-lane-record.js.map +1 -1
  114. package/dist/core/autonomy/status.d.ts.map +1 -1
  115. package/dist/core/autonomy/status.js.map +1 -1
  116. package/dist/core/autonomy/subagent-prompt.d.ts.map +1 -1
  117. package/dist/core/autonomy/subagent-prompt.js.map +1 -1
  118. package/dist/core/autonomy/telemetry-events.d.ts.map +1 -1
  119. package/dist/core/autonomy/telemetry-events.js.map +1 -1
  120. package/dist/core/autonomy-telemetry.d.ts.map +1 -1
  121. package/dist/core/autonomy-telemetry.js +2 -4
  122. package/dist/core/autonomy-telemetry.js.map +1 -1
  123. package/dist/core/background-lane-controller.d.ts.map +1 -1
  124. package/dist/core/background-lane-controller.js +2 -15
  125. package/dist/core/background-lane-controller.js.map +1 -1
  126. package/dist/core/background-tool-task-controller.d.ts +88 -0
  127. package/dist/core/background-tool-task-controller.d.ts.map +1 -0
  128. package/dist/core/background-tool-task-controller.js +470 -0
  129. package/dist/core/background-tool-task-controller.js.map +1 -0
  130. package/dist/core/bash-execution-controller.d.ts +1 -0
  131. package/dist/core/bash-execution-controller.d.ts.map +1 -1
  132. package/dist/core/bash-execution-controller.js +5 -4
  133. package/dist/core/bash-execution-controller.js.map +1 -1
  134. package/dist/core/bash-executor.d.ts.map +1 -1
  135. package/dist/core/bash-executor.js.map +1 -1
  136. package/dist/core/bedrock-sso-login.d.ts.map +1 -1
  137. package/dist/core/bedrock-sso-login.js.map +1 -1
  138. package/dist/core/billing-failover-controller.d.ts.map +1 -1
  139. package/dist/core/billing-failover-controller.js +3 -3
  140. package/dist/core/billing-failover-controller.js.map +1 -1
  141. package/dist/core/billing-failover.d.ts.map +1 -1
  142. package/dist/core/billing-failover.js.map +1 -1
  143. package/dist/core/capability-contract.d.ts.map +1 -1
  144. package/dist/core/catalog-manager.d.ts.map +1 -1
  145. package/dist/core/catalog-manager.js +0 -0
  146. package/dist/core/catalog-manager.js.map +1 -1
  147. package/dist/core/compaction-controller.d.ts +2 -0
  148. package/dist/core/compaction-controller.d.ts.map +1 -1
  149. package/dist/core/compaction-controller.js +21 -8
  150. package/dist/core/compaction-controller.js.map +1 -1
  151. package/dist/core/compaction-support.d.ts +8 -0
  152. package/dist/core/compaction-support.d.ts.map +1 -1
  153. package/dist/core/compaction-support.js +0 -2
  154. package/dist/core/compaction-support.js.map +1 -1
  155. package/dist/core/context/artifact-retrieval.d.ts.map +1 -1
  156. package/dist/core/context/artifact-retrieval.js.map +1 -1
  157. package/dist/core/context/brain-curator.d.ts.map +1 -1
  158. package/dist/core/context/brain-curator.js +14 -33
  159. package/dist/core/context/brain-curator.js.map +1 -1
  160. package/dist/core/context/context-artifacts.d.ts.map +1 -1
  161. package/dist/core/context/context-artifacts.js +16 -24
  162. package/dist/core/context/context-artifacts.js.map +1 -1
  163. package/dist/core/context/context-audit.d.ts.map +1 -1
  164. package/dist/core/context/context-audit.js +3 -17
  165. package/dist/core/context/context-audit.js.map +1 -1
  166. package/dist/core/context/context-composition.d.ts.map +1 -1
  167. package/dist/core/context/context-composition.js.map +1 -1
  168. package/dist/core/context/context-item.d.ts.map +1 -1
  169. package/dist/core/context/context-item.js.map +1 -1
  170. package/dist/core/context/context-prompt-enforcement.d.ts.map +1 -1
  171. package/dist/core/context/context-prompt-enforcement.js +3 -16
  172. package/dist/core/context/context-prompt-enforcement.js.map +1 -1
  173. package/dist/core/context/context-prompt-policy.d.ts.map +1 -1
  174. package/dist/core/context/context-prompt-policy.js.map +1 -1
  175. package/dist/core/context/context-retention.d.ts.map +1 -1
  176. package/dist/core/context/context-retention.js.map +1 -1
  177. package/dist/core/context/context-store-retention.d.ts.map +1 -1
  178. package/dist/core/context/context-store-retention.js.map +1 -1
  179. package/dist/core/context/context-store.d.ts.map +1 -1
  180. package/dist/core/context/context-store.js.map +1 -1
  181. package/dist/core/context/context-tool-result.d.ts +4 -0
  182. package/dist/core/context/context-tool-result.d.ts.map +1 -0
  183. package/dist/core/context/context-tool-result.js +15 -0
  184. package/dist/core/context/context-tool-result.js.map +1 -0
  185. package/dist/core/context/current-work-memory.d.ts.map +1 -1
  186. package/dist/core/context/current-work-memory.js.map +1 -1
  187. package/dist/core/context/file-store-memory-provider.d.ts.map +1 -1
  188. package/dist/core/context/file-store-memory-provider.js +7 -28
  189. package/dist/core/context/file-store-memory-provider.js.map +1 -1
  190. package/dist/core/context/local-memory-search.d.ts +11 -0
  191. package/dist/core/context/local-memory-search.d.ts.map +1 -0
  192. package/dist/core/context/local-memory-search.js +37 -0
  193. package/dist/core/context/local-memory-search.js.map +1 -0
  194. package/dist/core/context/long-term-memory-trigger.d.ts.map +1 -1
  195. package/dist/core/context/long-term-memory-trigger.js.map +1 -1
  196. package/dist/core/context/memory-diagnostics.d.ts.map +1 -1
  197. package/dist/core/context/memory-diagnostics.js.map +1 -1
  198. package/dist/core/context/memory-index-store.d.ts.map +1 -1
  199. package/dist/core/context/memory-index-store.js.map +1 -1
  200. package/dist/core/context/memory-prompt-block.d.ts.map +1 -1
  201. package/dist/core/context/memory-prompt-block.js.map +1 -1
  202. package/dist/core/context/memory-prompt-budget.d.ts.map +1 -1
  203. package/dist/core/context/memory-prompt-budget.js.map +1 -1
  204. package/dist/core/context/memory-provider-contract.d.ts.map +1 -1
  205. package/dist/core/context/memory-provider-contract.js.map +1 -1
  206. package/dist/core/context/memory-retrieval.d.ts.map +1 -1
  207. package/dist/core/context/memory-retrieval.js.map +1 -1
  208. package/dist/core/context/memory-tier-composer.d.ts.map +1 -1
  209. package/dist/core/context/memory-tier-composer.js.map +1 -1
  210. package/dist/core/context/message-text.d.ts +7 -0
  211. package/dist/core/context/message-text.d.ts.map +1 -0
  212. package/dist/core/context/message-text.js +68 -0
  213. package/dist/core/context/message-text.js.map +1 -0
  214. package/dist/core/context/okf-memory-provider.d.ts.map +1 -1
  215. package/dist/core/context/okf-memory-provider.js +4 -30
  216. package/dist/core/context/okf-memory-provider.js.map +1 -1
  217. package/dist/core/context/okf-memory.d.ts.map +1 -1
  218. package/dist/core/context/okf-memory.js.map +1 -1
  219. package/dist/core/context/policy-engine.d.ts.map +1 -1
  220. package/dist/core/context/policy-engine.js.map +1 -1
  221. package/dist/core/context/policy-types.d.ts.map +1 -1
  222. package/dist/core/context/sqlite-runtime-index.d.ts.map +1 -1
  223. package/dist/core/context/sqlite-runtime-index.js.map +1 -1
  224. package/dist/core/context/storage-authority.d.ts.map +1 -1
  225. package/dist/core/context/tool-output-packer.d.ts.map +1 -1
  226. package/dist/core/context/tool-output-packer.js.map +1 -1
  227. package/dist/core/context-gc.d.ts.map +1 -1
  228. package/dist/core/context-gc.js +14 -21
  229. package/dist/core/context-gc.js.map +1 -1
  230. package/dist/core/context-pipeline.d.ts +1 -3
  231. package/dist/core/context-pipeline.d.ts.map +1 -1
  232. package/dist/core/context-pipeline.js +64 -145
  233. package/dist/core/context-pipeline.js.map +1 -1
  234. package/dist/core/cost/cost-summary.d.ts.map +1 -1
  235. package/dist/core/cost/cost-summary.js.map +1 -1
  236. package/dist/core/cost/daily-usage.d.ts.map +1 -1
  237. package/dist/core/cost/daily-usage.js.map +1 -1
  238. package/dist/core/cost/session-usage.d.ts.map +1 -1
  239. package/dist/core/cost/session-usage.js.map +1 -1
  240. package/dist/core/cost-guard.d.ts.map +1 -1
  241. package/dist/core/cost-guard.js.map +1 -1
  242. package/dist/core/default-tool-surface.d.ts.map +1 -1
  243. package/dist/core/default-tool-surface.js +1 -0
  244. package/dist/core/default-tool-surface.js.map +1 -1
  245. package/dist/core/defaults.d.ts.map +1 -1
  246. package/dist/core/delegation/managed-lane-controller.d.ts.map +1 -1
  247. package/dist/core/delegation/managed-lane-controller.js +2 -6
  248. package/dist/core/delegation/managed-lane-controller.js.map +1 -1
  249. package/dist/core/delegation/session-worker-claim.d.ts.map +1 -1
  250. package/dist/core/delegation/session-worker-claim.js.map +1 -1
  251. package/dist/core/delegation/worker-action-journal.d.ts.map +1 -1
  252. package/dist/core/delegation/worker-action-journal.js +0 -4
  253. package/dist/core/delegation/worker-action-journal.js.map +1 -1
  254. package/dist/core/delegation/worker-actions.d.ts.map +1 -1
  255. package/dist/core/delegation/worker-actions.js.map +1 -1
  256. package/dist/core/delegation/worker-agent-control-coordinator.d.ts +1 -0
  257. package/dist/core/delegation/worker-agent-control-coordinator.d.ts.map +1 -1
  258. package/dist/core/delegation/worker-agent-control-coordinator.js +13 -15
  259. package/dist/core/delegation/worker-agent-control-coordinator.js.map +1 -1
  260. package/dist/core/delegation/worker-agent-control.d.ts.map +1 -1
  261. package/dist/core/delegation/worker-agent-control.js +1 -4
  262. package/dist/core/delegation/worker-agent-control.js.map +1 -1
  263. package/dist/core/delegation/worker-attempt-executor.d.ts.map +1 -1
  264. package/dist/core/delegation/worker-attempt-executor.js.map +1 -1
  265. package/dist/core/delegation/worker-claim.d.ts.map +1 -1
  266. package/dist/core/delegation/worker-claim.js.map +1 -1
  267. package/dist/core/delegation/worker-conversation-store.d.ts.map +1 -1
  268. package/dist/core/delegation/worker-conversation-store.js +0 -2
  269. package/dist/core/delegation/worker-conversation-store.js.map +1 -1
  270. package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -1
  271. package/dist/core/delegation/worker-delegation-controller.js +5 -14
  272. package/dist/core/delegation/worker-delegation-controller.js.map +1 -1
  273. package/dist/core/delegation/worker-delegation-request.d.ts.map +1 -1
  274. package/dist/core/delegation/worker-dispatch-scheduler.d.ts.map +1 -1
  275. package/dist/core/delegation/worker-dispatch-scheduler.js +5 -6
  276. package/dist/core/delegation/worker-dispatch-scheduler.js.map +1 -1
  277. package/dist/core/delegation/worker-execution-policy.d.ts.map +1 -1
  278. package/dist/core/delegation/worker-execution-policy.js.map +1 -1
  279. package/dist/core/delegation/worker-lane-projection.d.ts.map +1 -1
  280. package/dist/core/delegation/worker-lane-projection.js.map +1 -1
  281. package/dist/core/delegation/worker-lifecycle.d.ts.map +1 -1
  282. package/dist/core/delegation/worker-lifecycle.js +0 -3
  283. package/dist/core/delegation/worker-lifecycle.js.map +1 -1
  284. package/dist/core/delegation/worker-notification-coordinator.d.ts.map +1 -1
  285. package/dist/core/delegation/worker-notification-coordinator.js +4 -5
  286. package/dist/core/delegation/worker-notification-coordinator.js.map +1 -1
  287. package/dist/core/delegation/worker-process-owner.d.ts.map +1 -1
  288. package/dist/core/delegation/worker-process-owner.js.map +1 -1
  289. package/dist/core/delegation/worker-profile-resolver.d.ts.map +1 -1
  290. package/dist/core/delegation/worker-profile-resolver.js +1 -2
  291. package/dist/core/delegation/worker-profile-resolver.js.map +1 -1
  292. package/dist/core/delegation/worker-recovery-coordinator.d.ts.map +1 -1
  293. package/dist/core/delegation/worker-recovery-coordinator.js +3 -4
  294. package/dist/core/delegation/worker-recovery-coordinator.js.map +1 -1
  295. package/dist/core/delegation/worker-resource-catalog.d.ts.map +1 -1
  296. package/dist/core/delegation/worker-resource-catalog.js.map +1 -1
  297. package/dist/core/delegation/worker-resource-materializer.d.ts.map +1 -1
  298. package/dist/core/delegation/worker-resource-materializer.js +1 -4
  299. package/dist/core/delegation/worker-resource-materializer.js.map +1 -1
  300. package/dist/core/delegation/worker-runner.d.ts +2 -4
  301. package/dist/core/delegation/worker-runner.d.ts.map +1 -1
  302. package/dist/core/delegation/worker-runner.js +6 -18
  303. package/dist/core/delegation/worker-runner.js.map +1 -1
  304. package/dist/core/delegation/worker-task-label.d.ts.map +1 -1
  305. package/dist/core/delegation/worker-task-label.js.map +1 -1
  306. package/dist/core/delegation/worker-terminal-finalizer.d.ts.map +1 -1
  307. package/dist/core/delegation/worker-terminal-finalizer.js.map +1 -1
  308. package/dist/core/delegation/worker-write-reservation-coordinator.d.ts.map +1 -1
  309. package/dist/core/delegation/worker-write-reservation-coordinator.js +1 -4
  310. package/dist/core/delegation/worker-write-reservation-coordinator.js.map +1 -1
  311. package/dist/core/delegation/worker-write-reservation.d.ts.map +1 -1
  312. package/dist/core/delegation/worker-write-reservation.js +0 -2
  313. package/dist/core/delegation/worker-write-reservation.js.map +1 -1
  314. package/dist/core/diagnostics.d.ts.map +1 -1
  315. package/dist/core/doctor.d.ts.map +1 -1
  316. package/dist/core/doctor.js.map +1 -1
  317. package/dist/core/event-bus.d.ts.map +1 -1
  318. package/dist/core/event-bus.js.map +1 -1
  319. package/dist/core/exec.d.ts.map +1 -1
  320. package/dist/core/exec.js +26 -7
  321. package/dist/core/exec.js.map +1 -1
  322. package/dist/core/export-html/ansi-to-html.d.ts.map +1 -1
  323. package/dist/core/export-html/ansi-to-html.js +21 -74
  324. package/dist/core/export-html/ansi-to-html.js.map +1 -1
  325. package/dist/core/export-html/index.d.ts.map +1 -1
  326. package/dist/core/export-html/index.js +4 -0
  327. package/dist/core/export-html/index.js.map +1 -1
  328. package/dist/core/export-html/session-tree-foundations.d.mts +67 -0
  329. package/dist/core/export-html/session-tree-foundations.mjs +313 -0
  330. package/dist/core/export-html/template.css +14 -41
  331. package/dist/core/export-html/template.html +3 -1
  332. package/dist/core/export-html/template.js +26 -435
  333. package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
  334. package/dist/core/export-html/tool-renderer.js.map +1 -1
  335. package/dist/core/extension-import-authority.d.ts.map +1 -1
  336. package/dist/core/extension-import-authority.js.map +1 -1
  337. package/dist/core/extension-metadata.d.ts.map +1 -1
  338. package/dist/core/extension-metadata.js.map +1 -1
  339. package/dist/core/extensions/builtin.d.ts +17 -0
  340. package/dist/core/extensions/builtin.d.ts.map +1 -1
  341. package/dist/core/extensions/builtin.js +18 -54
  342. package/dist/core/extensions/builtin.js.map +1 -1
  343. package/dist/core/extensions/entry-resolution.d.ts +3 -0
  344. package/dist/core/extensions/entry-resolution.d.ts.map +1 -0
  345. package/dist/core/extensions/entry-resolution.js +17 -0
  346. package/dist/core/extensions/entry-resolution.js.map +1 -0
  347. package/dist/core/extensions/index.d.ts.map +1 -1
  348. package/dist/core/extensions/loader.d.ts.map +1 -1
  349. package/dist/core/extensions/loader.js +76 -21
  350. package/dist/core/extensions/loader.js.map +1 -1
  351. package/dist/core/extensions/runner.d.ts +2 -0
  352. package/dist/core/extensions/runner.d.ts.map +1 -1
  353. package/dist/core/extensions/runner.js +41 -112
  354. package/dist/core/extensions/runner.js.map +1 -1
  355. package/dist/core/extensions/stale-context.d.ts.map +1 -1
  356. package/dist/core/extensions/storage.d.ts.map +1 -1
  357. package/dist/core/extensions/storage.js.map +1 -1
  358. package/dist/core/extensions/types.d.ts.map +1 -1
  359. package/dist/core/extensions/types.js.map +1 -1
  360. package/dist/core/extensions/wrapper.d.ts.map +1 -1
  361. package/dist/core/extensions/wrapper.js.map +1 -1
  362. package/dist/core/failure-corpus.d.ts.map +1 -1
  363. package/dist/core/failure-corpus.js +2 -5
  364. package/dist/core/failure-corpus.js.map +1 -1
  365. package/dist/core/footer-data-provider.d.ts.map +1 -1
  366. package/dist/core/footer-data-provider.js +27 -33
  367. package/dist/core/footer-data-provider.js.map +1 -1
  368. package/dist/core/foreground-recovery-controller.d.ts.map +1 -1
  369. package/dist/core/foreground-recovery-controller.js +0 -4
  370. package/dist/core/foreground-recovery-controller.js.map +1 -1
  371. package/dist/core/gateways/channel-provider.d.ts.map +1 -1
  372. package/dist/core/gateways/channel-provider.js +7 -5
  373. package/dist/core/gateways/channel-provider.js.map +1 -1
  374. package/dist/core/goal-loop-controller.d.ts.map +1 -1
  375. package/dist/core/goal-loop-controller.js +0 -1
  376. package/dist/core/goal-loop-controller.js.map +1 -1
  377. package/dist/core/goals/compact-goal-context.d.ts.map +1 -1
  378. package/dist/core/goals/compact-goal-context.js +2 -4
  379. package/dist/core/goals/compact-goal-context.js.map +1 -1
  380. package/dist/core/goals/goal-acceptance.d.ts.map +1 -1
  381. package/dist/core/goals/goal-acceptance.js.map +1 -1
  382. package/dist/core/goals/goal-auto-continue-controller.d.ts.map +1 -1
  383. package/dist/core/goals/goal-auto-continue-controller.js +1 -3
  384. package/dist/core/goals/goal-auto-continue-controller.js.map +1 -1
  385. package/dist/core/goals/goal-continuation-controller.d.ts.map +1 -1
  386. package/dist/core/goals/goal-continuation-controller.js.map +1 -1
  387. package/dist/core/goals/goal-continuation-defaults.d.ts.map +1 -1
  388. package/dist/core/goals/goal-continuation-prompt.d.ts.map +1 -1
  389. package/dist/core/goals/goal-continuation-prompt.js.map +1 -1
  390. package/dist/core/goals/goal-lifecycle.d.ts.map +1 -1
  391. package/dist/core/goals/goal-lifecycle.js.map +1 -1
  392. package/dist/core/goals/goal-record.d.ts.map +1 -1
  393. package/dist/core/goals/goal-record.js.map +1 -1
  394. package/dist/core/goals/goal-runtime-snapshot.d.ts.map +1 -1
  395. package/dist/core/goals/goal-runtime-snapshot.js.map +1 -1
  396. package/dist/core/goals/goal-session-controller.d.ts +15 -0
  397. package/dist/core/goals/goal-session-controller.d.ts.map +1 -1
  398. package/dist/core/goals/goal-session-controller.js +27 -3
  399. package/dist/core/goals/goal-session-controller.js.map +1 -1
  400. package/dist/core/goals/goal-state.d.ts.map +1 -1
  401. package/dist/core/goals/goal-state.js +35 -51
  402. package/dist/core/goals/goal-state.js.map +1 -1
  403. package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
  404. package/dist/core/goals/goal-tool-core.js.map +1 -1
  405. package/dist/core/goals/natural-language-goal.d.ts +9 -0
  406. package/dist/core/goals/natural-language-goal.d.ts.map +1 -0
  407. package/dist/core/goals/natural-language-goal.js +23 -0
  408. package/dist/core/goals/natural-language-goal.js.map +1 -0
  409. package/dist/core/goals/session-goal-state.d.ts.map +1 -1
  410. package/dist/core/goals/session-goal-state.js.map +1 -1
  411. package/dist/core/http-dispatcher.d.ts.map +1 -1
  412. package/dist/core/http-dispatcher.js.map +1 -1
  413. package/dist/core/human-input-controller.d.ts.map +1 -1
  414. package/dist/core/human-input-controller.js +2 -3
  415. package/dist/core/human-input-controller.js.map +1 -1
  416. package/dist/core/human-input.d.ts.map +1 -1
  417. package/dist/core/human-input.js.map +1 -1
  418. package/dist/core/improvement-loop.d.ts.map +1 -1
  419. package/dist/core/improvement-loop.js +11 -11
  420. package/dist/core/improvement-loop.js.map +1 -1
  421. package/dist/core/index.d.ts.map +1 -1
  422. package/dist/core/install-telemetry.d.ts.map +1 -1
  423. package/dist/core/install-telemetry.js.map +1 -1
  424. package/dist/core/isolated-text-completion.d.ts +17 -0
  425. package/dist/core/isolated-text-completion.d.ts.map +1 -0
  426. package/dist/core/isolated-text-completion.js +15 -0
  427. package/dist/core/isolated-text-completion.js.map +1 -0
  428. package/dist/core/keybindings.d.ts +47 -2
  429. package/dist/core/keybindings.d.ts.map +1 -1
  430. package/dist/core/keybindings.js +12 -1
  431. package/dist/core/keybindings.js.map +1 -1
  432. package/dist/core/learning/learning-audit.d.ts.map +1 -1
  433. package/dist/core/learning/learning-audit.js.map +1 -1
  434. package/dist/core/learning/learning-gate.d.ts.map +1 -1
  435. package/dist/core/learning/learning-gate.js.map +1 -1
  436. package/dist/core/learning/observation-store.d.ts.map +1 -1
  437. package/dist/core/learning/observation-store.js +0 -2
  438. package/dist/core/learning/observation-store.js.map +1 -1
  439. package/dist/core/learning/reflection-engine.d.ts +1 -1
  440. package/dist/core/learning/reflection-engine.d.ts.map +1 -1
  441. package/dist/core/learning/reflection-engine.js +3 -0
  442. package/dist/core/learning/reflection-engine.js.map +1 -1
  443. package/dist/core/learning/reflection-turn-analysis.d.ts +20 -0
  444. package/dist/core/learning/reflection-turn-analysis.d.ts.map +1 -0
  445. package/dist/core/learning/reflection-turn-analysis.js +136 -0
  446. package/dist/core/learning/reflection-turn-analysis.js.map +1 -0
  447. package/dist/core/learning/session-learning-decision.d.ts.map +1 -1
  448. package/dist/core/learning/session-learning-decision.js.map +1 -1
  449. package/dist/core/learning/skill-curator.d.ts.map +1 -1
  450. package/dist/core/learning/skill-curator.js +0 -3
  451. package/dist/core/learning/skill-curator.js.map +1 -1
  452. package/dist/core/local-runtime-controller.d.ts +39 -0
  453. package/dist/core/local-runtime-controller.d.ts.map +1 -1
  454. package/dist/core/local-runtime-controller.js +41 -62
  455. package/dist/core/local-runtime-controller.js.map +1 -1
  456. package/dist/core/memory/effectiveness-tracker.d.ts.map +1 -1
  457. package/dist/core/memory/effectiveness-tracker.js +4 -2
  458. package/dist/core/memory/effectiveness-tracker.js.map +1 -1
  459. package/dist/core/memory/memory-manager.d.ts.map +1 -1
  460. package/dist/core/memory/memory-manager.js +7 -7
  461. package/dist/core/memory/memory-manager.js.map +1 -1
  462. package/dist/core/memory/memory-provider.d.ts.map +1 -1
  463. package/dist/core/memory/providers/file-store.d.ts +7 -0
  464. package/dist/core/memory/providers/file-store.d.ts.map +1 -1
  465. package/dist/core/memory/providers/file-store.js +48 -13
  466. package/dist/core/memory/providers/file-store.js.map +1 -1
  467. package/dist/core/memory/providers/transcript-recall-worker-protocol.d.ts +47 -0
  468. package/dist/core/memory/providers/transcript-recall-worker-protocol.d.ts.map +1 -0
  469. package/dist/core/memory/providers/transcript-recall-worker-protocol.js +50 -0
  470. package/dist/core/memory/providers/transcript-recall-worker-protocol.js.map +1 -0
  471. package/dist/core/memory/providers/transcript-recall-worker.d.ts +2 -0
  472. package/dist/core/memory/providers/transcript-recall-worker.d.ts.map +1 -0
  473. package/dist/core/memory/providers/transcript-recall-worker.js +143 -0
  474. package/dist/core/memory/providers/transcript-recall-worker.js.map +1 -0
  475. package/dist/core/memory/providers/transcript-recall.d.ts +24 -13
  476. package/dist/core/memory/providers/transcript-recall.d.ts.map +1 -1
  477. package/dist/core/memory/providers/transcript-recall.js +143 -141
  478. package/dist/core/memory/providers/transcript-recall.js.map +1 -1
  479. package/dist/core/memory/providers/user-memory-archive.d.ts +39 -0
  480. package/dist/core/memory/providers/user-memory-archive.d.ts.map +1 -0
  481. package/dist/core/memory/providers/user-memory-archive.js +258 -0
  482. package/dist/core/memory/providers/user-memory-archive.js.map +1 -0
  483. package/dist/core/memory/transcript-index.d.ts.map +1 -1
  484. package/dist/core/memory/transcript-index.js +1 -1
  485. package/dist/core/memory/transcript-index.js.map +1 -1
  486. package/dist/core/memory-controller.d.ts +9 -0
  487. package/dist/core/memory-controller.d.ts.map +1 -1
  488. package/dist/core/memory-controller.js +57 -16
  489. package/dist/core/memory-controller.js.map +1 -1
  490. package/dist/core/model-capability.d.ts.map +1 -1
  491. package/dist/core/model-capability.js.map +1 -1
  492. package/dist/core/model-output-json.d.ts +10 -0
  493. package/dist/core/model-output-json.d.ts.map +1 -0
  494. package/dist/core/model-output-json.js +43 -0
  495. package/dist/core/model-output-json.js.map +1 -0
  496. package/dist/core/model-registry.d.ts +8 -8
  497. package/dist/core/model-registry.d.ts.map +1 -1
  498. package/dist/core/model-registry.js +29 -52
  499. package/dist/core/model-registry.js.map +1 -1
  500. package/dist/core/model-resolver.d.ts.map +1 -1
  501. package/dist/core/model-resolver.js +1 -1
  502. package/dist/core/model-resolver.js.map +1 -1
  503. package/dist/core/model-router/config-diagnostics.d.ts.map +1 -1
  504. package/dist/core/model-router/config-diagnostics.js.map +1 -1
  505. package/dist/core/model-router/executor-route.d.ts.map +1 -1
  506. package/dist/core/model-router/executor-route.js.map +1 -1
  507. package/dist/core/model-router/fitness-gate.d.ts.map +1 -1
  508. package/dist/core/model-router/fitness-gate.js.map +1 -1
  509. package/dist/core/model-router/intent-classifier.d.ts.map +1 -1
  510. package/dist/core/model-router/route-judge.d.ts.map +1 -1
  511. package/dist/core/model-router/route-judge.js +18 -36
  512. package/dist/core/model-router/route-judge.js.map +1 -1
  513. package/dist/core/model-router/session-buffer.d.ts.map +1 -1
  514. package/dist/core/model-router/session-buffer.js.map +1 -1
  515. package/dist/core/model-router/status.d.ts.map +1 -1
  516. package/dist/core/model-router/status.js.map +1 -1
  517. package/dist/core/model-router/tool-escalation.d.ts.map +1 -1
  518. package/dist/core/model-router/tool-escalation.js.map +1 -1
  519. package/dist/core/model-router-controller.d.ts +1 -0
  520. package/dist/core/model-router-controller.d.ts.map +1 -1
  521. package/dist/core/model-router-controller.js +25 -56
  522. package/dist/core/model-router-controller.js.map +1 -1
  523. package/dist/core/model-selection-controller.d.ts +10 -0
  524. package/dist/core/model-selection-controller.d.ts.map +1 -1
  525. package/dist/core/model-selection-controller.js +0 -1
  526. package/dist/core/model-selection-controller.js.map +1 -1
  527. package/dist/core/model-tool-protocol.d.ts.map +1 -1
  528. package/dist/core/model-tool-protocol.js.map +1 -1
  529. package/dist/core/models/adaptation-store.d.ts.map +1 -1
  530. package/dist/core/models/adaptation-store.js +0 -1
  531. package/dist/core/models/adaptation-store.js.map +1 -1
  532. package/dist/core/models/context-sizing.d.ts.map +1 -1
  533. package/dist/core/models/context-sizing.js.map +1 -1
  534. package/dist/core/models/default-model-suggestions.d.ts.map +1 -1
  535. package/dist/core/models/default-model-suggestions.js.map +1 -1
  536. package/dist/core/models/fitness-store.d.ts.map +1 -1
  537. package/dist/core/models/fitness-store.js +0 -1
  538. package/dist/core/models/fitness-store.js.map +1 -1
  539. package/dist/core/models/host-state-store.d.ts.map +1 -1
  540. package/dist/core/models/host-state-store.js +1 -6
  541. package/dist/core/models/host-state-store.js.map +1 -1
  542. package/dist/core/models/llamacpp-runtime.d.ts +4 -19
  543. package/dist/core/models/llamacpp-runtime.d.ts.map +1 -1
  544. package/dist/core/models/llamacpp-runtime.js +32 -136
  545. package/dist/core/models/llamacpp-runtime.js.map +1 -1
  546. package/dist/core/models/local-registration.d.ts.map +1 -1
  547. package/dist/core/models/local-registration.js +82 -115
  548. package/dist/core/models/local-registration.js.map +1 -1
  549. package/dist/core/models/local-runtime.d.ts +12 -18
  550. package/dist/core/models/local-runtime.d.ts.map +1 -1
  551. package/dist/core/models/local-runtime.js +60 -204
  552. package/dist/core/models/local-runtime.js.map +1 -1
  553. package/dist/core/models/model-endpoint.d.ts.map +1 -1
  554. package/dist/core/models/model-endpoint.js.map +1 -1
  555. package/dist/core/models/model-ref.d.ts.map +1 -1
  556. package/dist/core/models/model-ref.js.map +1 -1
  557. package/dist/core/models/needle-runtime.d.ts +7 -3
  558. package/dist/core/models/needle-runtime.d.ts.map +1 -1
  559. package/dist/core/models/needle-runtime.js +16 -92
  560. package/dist/core/models/needle-runtime.js.map +1 -1
  561. package/dist/core/models/perf-profile.d.ts +1 -1
  562. package/dist/core/models/perf-profile.d.ts.map +1 -1
  563. package/dist/core/models/perf-profile.js +6 -13
  564. package/dist/core/models/perf-profile.js.map +1 -1
  565. package/dist/core/models/prism-llamacpp-lifecycle.d.ts.map +1 -1
  566. package/dist/core/models/prism-llamacpp-lifecycle.js.map +1 -1
  567. package/dist/core/models/runtime-arbiter.d.ts.map +1 -1
  568. package/dist/core/models/runtime-arbiter.js +3 -15
  569. package/dist/core/models/runtime-arbiter.js.map +1 -1
  570. package/dist/core/models/runtime-process.d.ts +100 -0
  571. package/dist/core/models/runtime-process.d.ts.map +1 -0
  572. package/dist/core/models/runtime-process.js +183 -0
  573. package/dist/core/models/runtime-process.js.map +1 -0
  574. package/dist/core/orchestration/agent-resume.d.ts.map +1 -1
  575. package/dist/core/orchestration/agent-resume.js.map +1 -1
  576. package/dist/core/orchestration/attempt-usage.d.ts.map +1 -1
  577. package/dist/core/orchestration/attempt-usage.js.map +1 -1
  578. package/dist/core/orchestration/capability-gateway.d.ts.map +1 -1
  579. package/dist/core/orchestration/capability-gateway.js +0 -14
  580. package/dist/core/orchestration/capability-gateway.js.map +1 -1
  581. package/dist/core/orchestration/contracts.d.ts.map +1 -1
  582. package/dist/core/orchestration/contracts.js.map +1 -1
  583. package/dist/core/orchestration/delegation-ledger.d.ts.map +1 -1
  584. package/dist/core/orchestration/delegation-ledger.js +0 -2
  585. package/dist/core/orchestration/delegation-ledger.js.map +1 -1
  586. package/dist/core/orchestration/event-store.d.ts.map +1 -1
  587. package/dist/core/orchestration/event-store.js +1 -14
  588. package/dist/core/orchestration/event-store.js.map +1 -1
  589. package/dist/core/orchestration/lane-tool-manifests.d.ts.map +1 -1
  590. package/dist/core/orchestration/lane-tool-manifests.js.map +1 -1
  591. package/dist/core/orchestration/model-binding.d.ts.map +1 -1
  592. package/dist/core/orchestration/model-binding.js.map +1 -1
  593. package/dist/core/orchestration/policy-compiler.d.ts.map +1 -1
  594. package/dist/core/orchestration/policy-compiler.js +0 -3
  595. package/dist/core/orchestration/policy-compiler.js.map +1 -1
  596. package/dist/core/orchestration/policy-gate.d.ts.map +1 -1
  597. package/dist/core/orchestration/policy-gate.js +0 -2
  598. package/dist/core/orchestration/policy-gate.js.map +1 -1
  599. package/dist/core/orchestration/profile-registry.d.ts.map +1 -1
  600. package/dist/core/orchestration/profile-registry.js +1 -1
  601. package/dist/core/orchestration/profile-registry.js.map +1 -1
  602. package/dist/core/orchestration/profile-store.d.ts.map +1 -1
  603. package/dist/core/orchestration/profile-store.js +0 -3
  604. package/dist/core/orchestration/profile-store.js.map +1 -1
  605. package/dist/core/orchestration/risk-budget.d.ts.map +1 -1
  606. package/dist/core/orchestration/risk-budget.js.map +1 -1
  607. package/dist/core/orchestration/task-runtime.d.ts +1 -0
  608. package/dist/core/orchestration/task-runtime.d.ts.map +1 -1
  609. package/dist/core/orchestration/task-runtime.js +27 -42
  610. package/dist/core/orchestration/task-runtime.js.map +1 -1
  611. package/dist/core/orchestration/work-state-projection.d.ts.map +1 -1
  612. package/dist/core/orchestration/work-state-projection.js.map +1 -1
  613. package/dist/core/orchestration/worker-execution-contract.d.ts.map +1 -1
  614. package/dist/core/orchestration/worker-execution-contract.js.map +1 -1
  615. package/dist/core/orchestration/worker-result-adapter.d.ts.map +1 -1
  616. package/dist/core/orchestration/worker-result-adapter.js.map +1 -1
  617. package/dist/core/output-guard.d.ts.map +1 -1
  618. package/dist/core/output-guard.js.map +1 -1
  619. package/dist/core/package-manager.d.ts +3 -0
  620. package/dist/core/package-manager.d.ts.map +1 -1
  621. package/dist/core/package-manager.js +88 -353
  622. package/dist/core/package-manager.js.map +1 -1
  623. package/dist/core/process-identity.d.ts.map +1 -1
  624. package/dist/core/process-identity.js.map +1 -1
  625. package/dist/core/process-liveness.d.ts +3 -0
  626. package/dist/core/process-liveness.d.ts.map +1 -0
  627. package/dist/core/process-liveness.js +17 -0
  628. package/dist/core/process-liveness.js.map +1 -0
  629. package/dist/core/process-matrix/codes.d.ts.map +1 -1
  630. package/dist/core/process-matrix/resume-launcher.d.ts.map +1 -1
  631. package/dist/core/process-matrix/resume-launcher.js.map +1 -1
  632. package/dist/core/process-matrix/runtime.d.ts.map +1 -1
  633. package/dist/core/process-matrix/runtime.js.map +1 -1
  634. package/dist/core/process-matrix/store.d.ts.map +1 -1
  635. package/dist/core/process-matrix/store.js.map +1 -1
  636. package/dist/core/process-matrix/supervisor.d.ts.map +1 -1
  637. package/dist/core/process-matrix/supervisor.js.map +1 -1
  638. package/dist/core/profile-filter-controller.d.ts.map +1 -1
  639. package/dist/core/profile-filter-controller.js +7 -8
  640. package/dist/core/profile-filter-controller.js.map +1 -1
  641. package/dist/core/profile-registry.d.ts.map +1 -1
  642. package/dist/core/profile-registry.js +1 -2
  643. package/dist/core/profile-registry.js.map +1 -1
  644. package/dist/core/profile-resource-selection.d.ts.map +1 -1
  645. package/dist/core/profile-resource-selection.js +18 -59
  646. package/dist/core/profile-resource-selection.js.map +1 -1
  647. package/dist/core/prompt-markup.d.ts +3 -0
  648. package/dist/core/prompt-markup.d.ts.map +1 -0
  649. package/dist/core/prompt-markup.js +7 -0
  650. package/dist/core/prompt-markup.js.map +1 -0
  651. package/dist/core/prompt-templates.d.ts.map +1 -1
  652. package/dist/core/prompt-templates.js +13 -39
  653. package/dist/core/prompt-templates.js.map +1 -1
  654. package/dist/core/provider-display-names.d.ts.map +1 -1
  655. package/dist/core/python-runtime.d.ts.map +1 -1
  656. package/dist/core/python-runtime.js.map +1 -1
  657. package/dist/core/reflection-controller.d.ts +22 -1
  658. package/dist/core/reflection-controller.d.ts.map +1 -1
  659. package/dist/core/reflection-controller.js +143 -25
  660. package/dist/core/reflection-controller.js.map +1 -1
  661. package/dist/core/reload-blockers.d.ts +2 -1
  662. package/dist/core/reload-blockers.d.ts.map +1 -1
  663. package/dist/core/reload-blockers.js +4 -14
  664. package/dist/core/reload-blockers.js.map +1 -1
  665. package/dist/core/request-auth.d.ts.map +1 -1
  666. package/dist/core/request-auth.js.map +1 -1
  667. package/dist/core/research/automata-provider.d.ts.map +1 -1
  668. package/dist/core/research/automata-provider.js.map +1 -1
  669. package/dist/core/research/evidence-bundle.d.ts.map +1 -1
  670. package/dist/core/research/evidence-bundle.js.map +1 -1
  671. package/dist/core/research/lane-model-resolver.d.ts.map +1 -1
  672. package/dist/core/research/lane-model-resolver.js +0 -1
  673. package/dist/core/research/lane-model-resolver.js.map +1 -1
  674. package/dist/core/research/model-fitness-controller.d.ts.map +1 -1
  675. package/dist/core/research/model-fitness-controller.js +17 -33
  676. package/dist/core/research/model-fitness-controller.js.map +1 -1
  677. package/dist/core/research/model-fitness.d.ts.map +1 -1
  678. package/dist/core/research/model-fitness.js +4 -25
  679. package/dist/core/research/model-fitness.js.map +1 -1
  680. package/dist/core/research/research-gate.d.ts.map +1 -1
  681. package/dist/core/research/research-gate.js.map +1 -1
  682. package/dist/core/research/research-lane-controller.d.ts.map +1 -1
  683. package/dist/core/research/research-lane-controller.js +5 -10
  684. package/dist/core/research/research-lane-controller.js.map +1 -1
  685. package/dist/core/research/research-runner.d.ts +2 -4
  686. package/dist/core/research/research-runner.d.ts.map +1 -1
  687. package/dist/core/research/research-runner.js +17 -48
  688. package/dist/core/research/research-runner.js.map +1 -1
  689. package/dist/core/research/session-evidence-bundle.d.ts.map +1 -1
  690. package/dist/core/research/session-evidence-bundle.js.map +1 -1
  691. package/dist/core/research/workspace-collector.d.ts.map +1 -1
  692. package/dist/core/research/workspace-collector.js.map +1 -1
  693. package/dist/core/resolve-config-value.d.ts.map +1 -1
  694. package/dist/core/resolve-config-value.js.map +1 -1
  695. package/dist/core/resource-ignore.d.ts +6 -0
  696. package/dist/core/resource-ignore.d.ts.map +1 -0
  697. package/dist/core/resource-ignore.js +44 -0
  698. package/dist/core/resource-ignore.js.map +1 -0
  699. package/dist/core/resource-loader.d.ts +0 -1
  700. package/dist/core/resource-loader.d.ts.map +1 -1
  701. package/dist/core/resource-loader.js +52 -187
  702. package/dist/core/resource-loader.js.map +1 -1
  703. package/dist/core/resource-profile-blocks.d.ts +3 -1
  704. package/dist/core/resource-profile-blocks.d.ts.map +1 -1
  705. package/dist/core/resource-profile-blocks.js +8 -5
  706. package/dist/core/resource-profile-blocks.js.map +1 -1
  707. package/dist/core/resource-profile-equality.d.ts.map +1 -1
  708. package/dist/core/resource-profile-equality.js.map +1 -1
  709. package/dist/core/resource-traversal.d.ts +43 -0
  710. package/dist/core/resource-traversal.d.ts.map +1 -0
  711. package/dist/core/resource-traversal.js +84 -0
  712. package/dist/core/resource-traversal.js.map +1 -0
  713. package/dist/core/risk-classifier.d.ts.map +1 -1
  714. package/dist/core/risk-classifier.js.map +1 -1
  715. package/dist/core/runtime-builder.d.ts +4 -1
  716. package/dist/core/runtime-builder.d.ts.map +1 -1
  717. package/dist/core/runtime-builder.js +25 -50
  718. package/dist/core/runtime-builder.js.map +1 -1
  719. package/dist/core/scout-controller.d.ts.map +1 -1
  720. package/dist/core/scout-controller.js +0 -1
  721. package/dist/core/scout-controller.js.map +1 -1
  722. package/dist/core/sdk.d.ts.map +1 -1
  723. package/dist/core/sdk.js.map +1 -1
  724. package/dist/core/secrets/credential-exposure-guard.d.ts.map +1 -1
  725. package/dist/core/secrets/credential-exposure-guard.js +70 -44
  726. package/dist/core/secrets/credential-exposure-guard.js.map +1 -1
  727. package/dist/core/secrets/secret-dotenv.d.ts.map +1 -1
  728. package/dist/core/secrets/secret-dotenv.js +0 -1
  729. package/dist/core/secrets/secret-dotenv.js.map +1 -1
  730. package/dist/core/secrets/secret-vault-format.d.ts.map +1 -1
  731. package/dist/core/secrets/secret-vault-format.js +0 -1
  732. package/dist/core/secrets/secret-vault-format.js.map +1 -1
  733. package/dist/core/secrets/secret-vault.d.ts.map +1 -1
  734. package/dist/core/secrets/secret-vault.js +2 -10
  735. package/dist/core/secrets/secret-vault.js.map +1 -1
  736. package/dist/core/security/secret-text.d.ts.map +1 -1
  737. package/dist/core/security/secret-text.js.map +1 -1
  738. package/dist/core/security/untrusted-boundary.d.ts.map +1 -1
  739. package/dist/core/security/untrusted-boundary.js.map +1 -1
  740. package/dist/core/session-analytics.d.ts.map +1 -1
  741. package/dist/core/session-analytics.js +18 -50
  742. package/dist/core/session-analytics.js.map +1 -1
  743. package/dist/core/session-artifact-bundle.d.ts.map +1 -1
  744. package/dist/core/session-artifact-bundle.js.map +1 -1
  745. package/dist/core/session-cwd.d.ts.map +1 -1
  746. package/dist/core/session-cwd.js +0 -1
  747. package/dist/core/session-cwd.js.map +1 -1
  748. package/dist/core/session-entry-index.d.ts +8 -0
  749. package/dist/core/session-entry-index.d.ts.map +1 -0
  750. package/dist/core/session-entry-index.js +16 -0
  751. package/dist/core/session-entry-index.js.map +1 -0
  752. package/dist/core/session-image-store.d.ts.map +1 -1
  753. package/dist/core/session-image-store.js +0 -3
  754. package/dist/core/session-image-store.js.map +1 -1
  755. package/dist/core/session-jsonl-writer.d.ts +3 -0
  756. package/dist/core/session-jsonl-writer.d.ts.map +1 -0
  757. package/dist/core/session-jsonl-writer.js +38 -0
  758. package/dist/core/session-jsonl-writer.js.map +1 -0
  759. package/dist/core/session-manager-factory.d.ts.map +1 -1
  760. package/dist/core/session-manager-factory.js.map +1 -1
  761. package/dist/core/session-role.d.ts.map +1 -1
  762. package/dist/core/session-role.js.map +1 -1
  763. package/dist/core/session-snapshot.d.ts.map +1 -1
  764. package/dist/core/session-snapshot.js.map +1 -1
  765. package/dist/core/session-supervision-runtime.d.ts.map +1 -1
  766. package/dist/core/session-supervision-runtime.js +1 -4
  767. package/dist/core/session-supervision-runtime.js.map +1 -1
  768. package/dist/core/session-tree-navigator.d.ts.map +1 -1
  769. package/dist/core/session-tree-navigator.js +0 -1
  770. package/dist/core/session-tree-navigator.js.map +1 -1
  771. package/dist/core/settings-manager.d.ts +2 -1
  772. package/dist/core/settings-manager.d.ts.map +1 -1
  773. package/dist/core/settings-manager.js +64 -162
  774. package/dist/core/settings-manager.js.map +1 -1
  775. package/dist/core/skill-block.d.mts +8 -0
  776. package/dist/core/skill-block.mjs +52 -0
  777. package/dist/core/skill-discovery.d.ts +5 -0
  778. package/dist/core/skill-discovery.d.ts.map +1 -0
  779. package/dist/core/skill-discovery.js +34 -0
  780. package/dist/core/skill-discovery.js.map +1 -0
  781. package/dist/core/skills.d.ts.map +1 -1
  782. package/dist/core/skills.js +23 -159
  783. package/dist/core/skills.js.map +1 -1
  784. package/dist/core/slash-commands.d.ts.map +1 -1
  785. package/dist/core/source-info.d.ts.map +1 -1
  786. package/dist/core/source-info.js.map +1 -1
  787. package/dist/core/spawned-usage.d.ts +21 -0
  788. package/dist/core/spawned-usage.d.ts.map +1 -0
  789. package/dist/core/spawned-usage.js +29 -0
  790. package/dist/core/spawned-usage.js.map +1 -0
  791. package/dist/core/system-prompt-builder.d.ts +4 -0
  792. package/dist/core/system-prompt-builder.d.ts.map +1 -1
  793. package/dist/core/system-prompt-builder.js +15 -8
  794. package/dist/core/system-prompt-builder.js.map +1 -1
  795. package/dist/core/system-prompt.d.ts.map +1 -1
  796. package/dist/core/system-prompt.js +52 -35
  797. package/dist/core/system-prompt.js.map +1 -1
  798. package/dist/core/tasks/session-task-state.d.ts.map +1 -1
  799. package/dist/core/tasks/session-task-state.js.map +1 -1
  800. package/dist/core/tasks/task-command.d.ts.map +1 -1
  801. package/dist/core/tasks/task-command.js.map +1 -1
  802. package/dist/core/tasks/task-contract-monitor.d.ts.map +1 -1
  803. package/dist/core/tasks/task-contract-monitor.js.map +1 -1
  804. package/dist/core/tasks/task-projection.d.ts.map +1 -1
  805. package/dist/core/tasks/task-projection.js.map +1 -1
  806. package/dist/core/tasks/task-state.d.ts.map +1 -1
  807. package/dist/core/tasks/task-state.js.map +1 -1
  808. package/dist/core/text-preview.d.ts +4 -0
  809. package/dist/core/text-preview.d.ts.map +1 -0
  810. package/dist/core/text-preview.js +33 -0
  811. package/dist/core/text-preview.js.map +1 -0
  812. package/dist/core/timings.d.ts.map +1 -1
  813. package/dist/core/timings.js.map +1 -1
  814. package/dist/core/tool-capability-policy.d.ts.map +1 -1
  815. package/dist/core/tool-capability-policy.js.map +1 -1
  816. package/dist/core/tool-gate-controller.d.ts.map +1 -1
  817. package/dist/core/tool-gate-controller.js +86 -87
  818. package/dist/core/tool-gate-controller.js.map +1 -1
  819. package/dist/core/tool-protocol-controller.d.ts +4 -1
  820. package/dist/core/tool-protocol-controller.d.ts.map +1 -1
  821. package/dist/core/tool-protocol-controller.js +19 -23
  822. package/dist/core/tool-protocol-controller.js.map +1 -1
  823. package/dist/core/tool-recovery-log-records.d.ts.map +1 -1
  824. package/dist/core/tool-recovery-log-records.js.map +1 -1
  825. package/dist/core/tool-recovery-log-worker.d.ts.map +1 -1
  826. package/dist/core/tool-recovery-log-worker.js.map +1 -1
  827. package/dist/core/tool-recovery-logger.d.ts.map +1 -1
  828. package/dist/core/tool-recovery-logger.js +12 -24
  829. package/dist/core/tool-recovery-logger.js.map +1 -1
  830. package/dist/core/tool-recovery-stats.d.ts.map +1 -1
  831. package/dist/core/tool-recovery-stats.js +16 -22
  832. package/dist/core/tool-recovery-stats.js.map +1 -1
  833. package/dist/core/tool-repair-health.d.ts.map +1 -1
  834. package/dist/core/tool-repair-health.js.map +1 -1
  835. package/dist/core/tool-repair-settings.d.ts.map +1 -1
  836. package/dist/core/tool-repair-settings.js.map +1 -1
  837. package/dist/core/tool-selection/expected-utility.d.ts.map +1 -1
  838. package/dist/core/tool-selection/expected-utility.js.map +1 -1
  839. package/dist/core/tool-selection/promotion.d.ts.map +1 -1
  840. package/dist/core/tool-selection/promotion.js.map +1 -1
  841. package/dist/core/tool-selection/tool-performance-store.d.ts +2 -0
  842. package/dist/core/tool-selection/tool-performance-store.d.ts.map +1 -1
  843. package/dist/core/tool-selection/tool-performance-store.js +49 -7
  844. package/dist/core/tool-selection/tool-performance-store.js.map +1 -1
  845. package/dist/core/tool-selection/tool-phase-timing.d.ts +19 -0
  846. package/dist/core/tool-selection/tool-phase-timing.d.ts.map +1 -0
  847. package/dist/core/tool-selection/tool-phase-timing.js +63 -0
  848. package/dist/core/tool-selection/tool-phase-timing.js.map +1 -0
  849. package/dist/core/tool-selection/tool-selection-controller.d.ts +2 -5
  850. package/dist/core/tool-selection/tool-selection-controller.d.ts.map +1 -1
  851. package/dist/core/tool-selection/tool-selection-controller.js +50 -30
  852. package/dist/core/tool-selection/tool-selection-controller.js.map +1 -1
  853. package/dist/core/toolkit/reflex-interpreter.d.ts +16 -0
  854. package/dist/core/toolkit/reflex-interpreter.d.ts.map +1 -1
  855. package/dist/core/toolkit/reflex-interpreter.js +21 -0
  856. package/dist/core/toolkit/reflex-interpreter.js.map +1 -1
  857. package/dist/core/toolkit/script-registry.d.ts.map +1 -1
  858. package/dist/core/toolkit/script-registry.js.map +1 -1
  859. package/dist/core/toolkit/script-runner.d.ts.map +1 -1
  860. package/dist/core/toolkit/script-runner.js.map +1 -1
  861. package/dist/core/tools/artifact-retrieve.d.ts.map +1 -1
  862. package/dist/core/tools/artifact-retrieve.js.map +1 -1
  863. package/dist/core/tools/ask-question.d.ts +2 -3
  864. package/dist/core/tools/ask-question.d.ts.map +1 -1
  865. package/dist/core/tools/ask-question.js +14 -40
  866. package/dist/core/tools/ask-question.js.map +1 -1
  867. package/dist/core/tools/bash.d.ts +2 -0
  868. package/dist/core/tools/bash.d.ts.map +1 -1
  869. package/dist/core/tools/bash.js +83 -30
  870. package/dist/core/tools/bash.js.map +1 -1
  871. package/dist/core/tools/context-scout.d.ts.map +1 -1
  872. package/dist/core/tools/context-scout.js.map +1 -1
  873. package/dist/core/tools/delegate-status.d.ts.map +1 -1
  874. package/dist/core/tools/delegate-status.js +9 -7
  875. package/dist/core/tools/delegate-status.js.map +1 -1
  876. package/dist/core/tools/delegate.d.ts.map +1 -1
  877. package/dist/core/tools/delegate.js +6 -6
  878. package/dist/core/tools/delegate.js.map +1 -1
  879. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  880. package/dist/core/tools/edit-diff.js.map +1 -1
  881. package/dist/core/tools/edit.d.ts.map +1 -1
  882. package/dist/core/tools/edit.js.map +1 -1
  883. package/dist/core/tools/extensionify.d.ts.map +1 -1
  884. package/dist/core/tools/extensionify.js.map +1 -1
  885. package/dist/core/tools/fff-search-backend.d.ts +19 -0
  886. package/dist/core/tools/fff-search-backend.d.ts.map +1 -1
  887. package/dist/core/tools/fff-search-backend.js +28 -2
  888. package/dist/core/tools/fff-search-backend.js.map +1 -1
  889. package/dist/core/tools/file-encoding-policy.d.ts.map +1 -1
  890. package/dist/core/tools/file-encoding-policy.js.map +1 -1
  891. package/dist/core/tools/file-mutation-queue.d.ts.map +1 -1
  892. package/dist/core/tools/file-mutation-queue.js.map +1 -1
  893. package/dist/core/tools/find.d.ts +1 -1
  894. package/dist/core/tools/find.d.ts.map +1 -1
  895. package/dist/core/tools/find.js +44 -108
  896. package/dist/core/tools/find.js.map +1 -1
  897. package/dist/core/tools/git-filter.d.ts.map +1 -1
  898. package/dist/core/tools/git-filter.js.map +1 -1
  899. package/dist/core/tools/goal.d.ts.map +1 -1
  900. package/dist/core/tools/goal.js +7 -7
  901. package/dist/core/tools/goal.js.map +1 -1
  902. package/dist/core/tools/grep.d.ts +1 -1
  903. package/dist/core/tools/grep.d.ts.map +1 -1
  904. package/dist/core/tools/grep.js +42 -102
  905. package/dist/core/tools/grep.js.map +1 -1
  906. package/dist/core/tools/index.d.ts.map +1 -1
  907. package/dist/core/tools/index.js.map +1 -1
  908. package/dist/core/tools/ls.d.ts.map +1 -1
  909. package/dist/core/tools/ls.js +20 -36
  910. package/dist/core/tools/ls.js.map +1 -1
  911. package/dist/core/tools/model-fitness.d.ts.map +1 -1
  912. package/dist/core/tools/model-fitness.js.map +1 -1
  913. package/dist/core/tools/orchestration-panel.d.ts +5 -0
  914. package/dist/core/tools/orchestration-panel.d.ts.map +1 -1
  915. package/dist/core/tools/orchestration-panel.js +5 -5
  916. package/dist/core/tools/orchestration-panel.js.map +1 -1
  917. package/dist/core/tools/output-accumulator.d.ts +2 -0
  918. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  919. package/dist/core/tools/output-accumulator.js +24 -36
  920. package/dist/core/tools/output-accumulator.js.map +1 -1
  921. package/dist/core/tools/path-utils.d.ts.map +1 -1
  922. package/dist/core/tools/path-utils.js.map +1 -1
  923. package/dist/core/tools/persistent-process-coordinator.d.ts +31 -0
  924. package/dist/core/tools/persistent-process-coordinator.d.ts.map +1 -0
  925. package/dist/core/tools/persistent-process-coordinator.js +123 -0
  926. package/dist/core/tools/persistent-process-coordinator.js.map +1 -0
  927. package/dist/core/tools/python.d.ts.map +1 -1
  928. package/dist/core/tools/python.js.map +1 -1
  929. package/dist/core/tools/read.d.ts.map +1 -1
  930. package/dist/core/tools/read.js +14 -13
  931. package/dist/core/tools/read.js.map +1 -1
  932. package/dist/core/tools/render-utils.d.ts +29 -0
  933. package/dist/core/tools/render-utils.d.ts.map +1 -1
  934. package/dist/core/tools/render-utils.js +31 -1
  935. package/dist/core/tools/render-utils.js.map +1 -1
  936. package/dist/core/tools/run-process.d.ts.map +1 -1
  937. package/dist/core/tools/run-process.js.map +1 -1
  938. package/dist/core/tools/run-toolkit-script.d.ts.map +1 -1
  939. package/dist/core/tools/run-toolkit-script.js.map +1 -1
  940. package/dist/core/tools/search-command-guard.d.ts +10 -0
  941. package/dist/core/tools/search-command-guard.d.ts.map +1 -1
  942. package/dist/core/tools/search-command-guard.js +118 -31
  943. package/dist/core/tools/search-command-guard.js.map +1 -1
  944. package/dist/core/tools/search-router.d.ts.map +1 -1
  945. package/dist/core/tools/search-router.js.map +1 -1
  946. package/dist/core/tools/search-tool-runtime.d.ts +19 -0
  947. package/dist/core/tools/search-tool-runtime.d.ts.map +1 -0
  948. package/dist/core/tools/search-tool-runtime.js +12 -0
  949. package/dist/core/tools/search-tool-runtime.js.map +1 -0
  950. package/dist/core/tools/secret-store.d.ts.map +1 -1
  951. package/dist/core/tools/secret-store.js.map +1 -1
  952. package/dist/core/tools/shell-command-parser.d.ts.map +1 -1
  953. package/dist/core/tools/shell-command-parser.js.map +1 -1
  954. package/dist/core/tools/shell-contract-router.d.ts.map +1 -1
  955. package/dist/core/tools/shell-contract-router.js +4 -1
  956. package/dist/core/tools/shell-contract-router.js.map +1 -1
  957. package/dist/core/tools/shell-execution-session.d.ts +4 -0
  958. package/dist/core/tools/shell-execution-session.d.ts.map +1 -0
  959. package/dist/core/tools/shell-execution-session.js +11 -0
  960. package/dist/core/tools/shell-execution-session.js.map +1 -0
  961. package/dist/core/tools/shell-output-projection.d.ts +49 -0
  962. package/dist/core/tools/shell-output-projection.d.ts.map +1 -0
  963. package/dist/core/tools/shell-output-projection.js +381 -0
  964. package/dist/core/tools/shell-output-projection.js.map +1 -0
  965. package/dist/core/tools/shell-session.d.ts +2 -13
  966. package/dist/core/tools/shell-session.d.ts.map +1 -1
  967. package/dist/core/tools/shell-session.js +36 -136
  968. package/dist/core/tools/shell-session.js.map +1 -1
  969. package/dist/core/tools/skill-audit.d.ts.map +1 -1
  970. package/dist/core/tools/skill-audit.js.map +1 -1
  971. package/dist/core/tools/skillify.d.ts.map +1 -1
  972. package/dist/core/tools/skillify.js.map +1 -1
  973. package/dist/core/tools/task-steps.d.ts +8 -8
  974. package/dist/core/tools/task-steps.d.ts.map +1 -1
  975. package/dist/core/tools/task-steps.js +17 -18
  976. package/dist/core/tools/task-steps.js.map +1 -1
  977. package/dist/core/tools/tmux-dispatch.d.ts.map +1 -1
  978. package/dist/core/tools/tmux-dispatch.js.map +1 -1
  979. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
  980. package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
  981. package/dist/core/tools/tool-task.d.ts +23 -0
  982. package/dist/core/tools/tool-task.d.ts.map +1 -0
  983. package/dist/core/tools/tool-task.js +93 -0
  984. package/dist/core/tools/tool-task.js.map +1 -0
  985. package/dist/core/tools/windows-shell-engine.d.ts +17 -11
  986. package/dist/core/tools/windows-shell-engine.d.ts.map +1 -1
  987. package/dist/core/tools/windows-shell-engine.js +339 -117
  988. package/dist/core/tools/windows-shell-engine.js.map +1 -1
  989. package/dist/core/tools/windows-shell-state.d.ts.map +1 -1
  990. package/dist/core/tools/windows-shell-state.js.map +1 -1
  991. package/dist/core/tools/worktree-sync.d.ts.map +1 -1
  992. package/dist/core/tools/worktree-sync.js +8 -12
  993. package/dist/core/tools/worktree-sync.js.map +1 -1
  994. package/dist/core/tools/write.d.ts.map +1 -1
  995. package/dist/core/tools/write.js +0 -1
  996. package/dist/core/tools/write.js.map +1 -1
  997. package/dist/core/trust-manager.d.ts.map +1 -1
  998. package/dist/core/trust-manager.js +7 -40
  999. package/dist/core/trust-manager.js.map +1 -1
  1000. package/dist/core/util/atomic-file.d.ts +19 -0
  1001. package/dist/core/util/atomic-file.d.ts.map +1 -1
  1002. package/dist/core/util/atomic-file.js +50 -15
  1003. package/dist/core/util/atomic-file.js.map +1 -1
  1004. package/dist/core/util/bounded-file.d.ts.map +1 -1
  1005. package/dist/core/util/bounded-file.js.map +1 -1
  1006. package/dist/core/util/bounded-jsonl.d.ts.map +1 -1
  1007. package/dist/core/util/bounded-jsonl.js +2 -9
  1008. package/dist/core/util/bounded-jsonl.js.map +1 -1
  1009. package/dist/core/util/bounded-value.d.ts.map +1 -1
  1010. package/dist/core/util/bounded-value.js.map +1 -1
  1011. package/dist/core/util/json-size.d.ts +3 -0
  1012. package/dist/core/util/json-size.d.ts.map +1 -0
  1013. package/dist/core/util/json-size.js +95 -0
  1014. package/dist/core/util/json-size.js.map +1 -0
  1015. package/dist/core/util/minimatch-cache.d.ts.map +1 -1
  1016. package/dist/core/util/minimatch-cache.js.map +1 -1
  1017. package/dist/core/util/value-guards.d.ts.map +1 -1
  1018. package/dist/core/util/value-guards.js.map +1 -1
  1019. package/dist/core/worktree-sync/codes.d.ts.map +1 -1
  1020. package/dist/core/worktree-sync/git-engine.d.ts.map +1 -1
  1021. package/dist/core/worktree-sync/git-engine.js +20 -36
  1022. package/dist/core/worktree-sync/git-engine.js.map +1 -1
  1023. package/dist/core/worktree-sync/lane-gate.d.ts.map +1 -1
  1024. package/dist/core/worktree-sync/lane-gate.js +1 -4
  1025. package/dist/core/worktree-sync/lane-gate.js.map +1 -1
  1026. package/dist/core/worktree-sync/runtime.d.ts.map +1 -1
  1027. package/dist/core/worktree-sync/runtime.js.map +1 -1
  1028. package/dist/core/worktree-sync/store.d.ts.map +1 -1
  1029. package/dist/core/worktree-sync/store.js.map +1 -1
  1030. package/dist/core/worktree-sync/watcher.d.ts.map +1 -1
  1031. package/dist/core/worktree-sync/watcher.js.map +1 -1
  1032. package/dist/index.d.ts.map +1 -1
  1033. package/dist/index.js.map +1 -1
  1034. package/dist/main.d.ts.map +1 -1
  1035. package/dist/main.js +10 -32
  1036. package/dist/main.js.map +1 -1
  1037. package/dist/migrations.d.ts.map +1 -1
  1038. package/dist/migrations.js +6 -19
  1039. package/dist/migrations.js.map +1 -1
  1040. package/dist/modes/index.d.ts.map +1 -1
  1041. package/dist/modes/interactive/auth-dialogs-controller.d.ts +3 -0
  1042. package/dist/modes/interactive/auth-dialogs-controller.d.ts.map +1 -1
  1043. package/dist/modes/interactive/auth-dialogs-controller.js +96 -132
  1044. package/dist/modes/interactive/auth-dialogs-controller.js.map +1 -1
  1045. package/dist/modes/interactive/auto-learn-controller.d.ts +1 -31
  1046. package/dist/modes/interactive/auto-learn-controller.d.ts.map +1 -1
  1047. package/dist/modes/interactive/auto-learn-controller.js +86 -307
  1048. package/dist/modes/interactive/auto-learn-controller.js.map +1 -1
  1049. package/dist/modes/interactive/autocomplete-provider.d.ts.map +1 -1
  1050. package/dist/modes/interactive/autocomplete-provider.js.map +1 -1
  1051. package/dist/modes/interactive/autonomy-commands.d.ts.map +1 -1
  1052. package/dist/modes/interactive/autonomy-commands.js +2 -8
  1053. package/dist/modes/interactive/autonomy-commands.js.map +1 -1
  1054. package/dist/modes/interactive/clipboard-input.d.ts +5 -1
  1055. package/dist/modes/interactive/clipboard-input.d.ts.map +1 -1
  1056. package/dist/modes/interactive/clipboard-input.js +17 -0
  1057. package/dist/modes/interactive/clipboard-input.js.map +1 -1
  1058. package/dist/modes/interactive/compaction-queue.d.ts.map +1 -1
  1059. package/dist/modes/interactive/compaction-queue.js +13 -18
  1060. package/dist/modes/interactive/compaction-queue.js.map +1 -1
  1061. package/dist/modes/interactive/components/activity-lane.d.ts.map +1 -1
  1062. package/dist/modes/interactive/components/activity-lane.js +6 -10
  1063. package/dist/modes/interactive/components/activity-lane.js.map +1 -1
  1064. package/dist/modes/interactive/components/armin.d.ts +1 -0
  1065. package/dist/modes/interactive/components/armin.d.ts.map +1 -1
  1066. package/dist/modes/interactive/components/armin.js +10 -21
  1067. package/dist/modes/interactive/components/armin.js.map +1 -1
  1068. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  1069. package/dist/modes/interactive/components/assistant-message.js +1 -6
  1070. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  1071. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  1072. package/dist/modes/interactive/components/bash-execution.js +4 -9
  1073. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  1074. package/dist/modes/interactive/components/bordered-loader.d.ts.map +1 -1
  1075. package/dist/modes/interactive/components/bordered-loader.js +0 -3
  1076. package/dist/modes/interactive/components/bordered-loader.js.map +1 -1
  1077. package/dist/modes/interactive/components/branch-summary-message.d.ts +3 -8
  1078. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
  1079. package/dist/modes/interactive/components/branch-summary-message.js +13 -35
  1080. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
  1081. package/dist/modes/interactive/components/compaction-summary-message.d.ts +3 -8
  1082. package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -1
  1083. package/dist/modes/interactive/components/compaction-summary-message.js +14 -36
  1084. package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -1
  1085. package/dist/modes/interactive/components/config-selector.d.ts +1 -0
  1086. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  1087. package/dist/modes/interactive/components/config-selector.js +20 -43
  1088. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  1089. package/dist/modes/interactive/components/countdown-timer.d.ts.map +1 -1
  1090. package/dist/modes/interactive/components/countdown-timer.js +0 -5
  1091. package/dist/modes/interactive/components/countdown-timer.js.map +1 -1
  1092. package/dist/modes/interactive/components/custom-editor.d.ts +2 -0
  1093. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  1094. package/dist/modes/interactive/components/custom-editor.js +4 -8
  1095. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  1096. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
  1097. package/dist/modes/interactive/components/custom-message.js +1 -6
  1098. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  1099. package/dist/modes/interactive/components/daxnuts.d.ts.map +1 -1
  1100. package/dist/modes/interactive/components/daxnuts.js +6 -8
  1101. package/dist/modes/interactive/components/daxnuts.js.map +1 -1
  1102. package/dist/modes/interactive/components/diff.d.ts.map +1 -1
  1103. package/dist/modes/interactive/components/diff.js.map +1 -1
  1104. package/dist/modes/interactive/components/dynamic-border.d.ts.map +1 -1
  1105. package/dist/modes/interactive/components/dynamic-border.js +0 -1
  1106. package/dist/modes/interactive/components/dynamic-border.js.map +1 -1
  1107. package/dist/modes/interactive/components/earendil-announcement.d.ts.map +1 -1
  1108. package/dist/modes/interactive/components/earendil-announcement.js.map +1 -1
  1109. package/dist/modes/interactive/components/expandable-markdown-message.d.ts +21 -0
  1110. package/dist/modes/interactive/components/expandable-markdown-message.d.ts.map +1 -0
  1111. package/dist/modes/interactive/components/expandable-markdown-message.js +48 -0
  1112. package/dist/modes/interactive/components/expandable-markdown-message.js.map +1 -0
  1113. package/dist/modes/interactive/components/expandable-text.d.ts.map +1 -1
  1114. package/dist/modes/interactive/components/expandable-text.js +0 -2
  1115. package/dist/modes/interactive/components/expandable-text.js.map +1 -1
  1116. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
  1117. package/dist/modes/interactive/components/extension-editor.js +1 -9
  1118. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  1119. package/dist/modes/interactive/components/extension-input.d.ts.map +1 -1
  1120. package/dist/modes/interactive/components/extension-input.js +2 -8
  1121. package/dist/modes/interactive/components/extension-input.js.map +1 -1
  1122. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  1123. package/dist/modes/interactive/components/extension-selector.js +5 -20
  1124. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  1125. package/dist/modes/interactive/components/fitness-role-selector.d.ts.map +1 -1
  1126. package/dist/modes/interactive/components/fitness-role-selector.js +0 -1
  1127. package/dist/modes/interactive/components/fitness-role-selector.js.map +1 -1
  1128. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  1129. package/dist/modes/interactive/components/footer.js +1 -5
  1130. package/dist/modes/interactive/components/footer.js.map +1 -1
  1131. package/dist/modes/interactive/components/index.d.ts.map +1 -1
  1132. package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
  1133. package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
  1134. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  1135. package/dist/modes/interactive/components/login-dialog.js +4 -10
  1136. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  1137. package/dist/modes/interactive/components/model-selector.d.ts +2 -2
  1138. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  1139. package/dist/modes/interactive/components/model-selector.js +21 -44
  1140. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  1141. package/dist/modes/interactive/components/model-suggestion-selector.d.ts.map +1 -1
  1142. package/dist/modes/interactive/components/model-suggestion-selector.js +0 -1
  1143. package/dist/modes/interactive/components/model-suggestion-selector.js.map +1 -1
  1144. package/dist/modes/interactive/components/oauth-selector.d.ts +1 -1
  1145. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  1146. package/dist/modes/interactive/components/oauth-selector.js +16 -32
  1147. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  1148. package/dist/modes/interactive/components/profile-resource-editor.d.ts +3 -4
  1149. package/dist/modes/interactive/components/profile-resource-editor.d.ts.map +1 -1
  1150. package/dist/modes/interactive/components/profile-resource-editor.js +34 -93
  1151. package/dist/modes/interactive/components/profile-resource-editor.js.map +1 -1
  1152. package/dist/modes/interactive/components/profile-selector.d.ts.map +1 -1
  1153. package/dist/modes/interactive/components/profile-selector.js +0 -1
  1154. package/dist/modes/interactive/components/profile-selector.js.map +1 -1
  1155. package/dist/modes/interactive/components/scoped-models-selector.d.ts +3 -4
  1156. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  1157. package/dist/modes/interactive/components/scoped-models-selector.js +34 -79
  1158. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  1159. package/dist/modes/interactive/components/selector-list.d.ts +63 -0
  1160. package/dist/modes/interactive/components/selector-list.d.ts.map +1 -0
  1161. package/dist/modes/interactive/components/selector-list.js +186 -0
  1162. package/dist/modes/interactive/components/selector-list.js.map +1 -0
  1163. package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -1
  1164. package/dist/modes/interactive/components/session-selector-search.js.map +1 -1
  1165. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  1166. package/dist/modes/interactive/components/session-selector.js +34 -59
  1167. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  1168. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  1169. package/dist/modes/interactive/components/settings-selector.js +40 -138
  1170. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  1171. package/dist/modes/interactive/components/show-images-selector.d.ts +2 -4
  1172. package/dist/modes/interactive/components/show-images-selector.d.ts.map +1 -1
  1173. package/dist/modes/interactive/components/show-images-selector.js +9 -28
  1174. package/dist/modes/interactive/components/show-images-selector.js.map +1 -1
  1175. package/dist/modes/interactive/components/skill-invocation-message.d.ts +3 -8
  1176. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
  1177. package/dist/modes/interactive/components/skill-invocation-message.js +12 -40
  1178. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
  1179. package/dist/modes/interactive/components/theme-selector.d.ts +2 -5
  1180. package/dist/modes/interactive/components/theme-selector.d.ts.map +1 -1
  1181. package/dist/modes/interactive/components/theme-selector.js +11 -37
  1182. package/dist/modes/interactive/components/theme-selector.js.map +1 -1
  1183. package/dist/modes/interactive/components/thinking-selector.d.ts +2 -4
  1184. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  1185. package/dist/modes/interactive/components/thinking-selector.js +9 -31
  1186. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  1187. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  1188. package/dist/modes/interactive/components/tool-execution.js +9 -28
  1189. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  1190. package/dist/modes/interactive/components/tool-group.d.ts.map +1 -1
  1191. package/dist/modes/interactive/components/tool-group.js +2 -3
  1192. package/dist/modes/interactive/components/tool-group.js.map +1 -1
  1193. package/dist/modes/interactive/components/tool-panel-registry.d.ts.map +1 -1
  1194. package/dist/modes/interactive/components/tool-panel-registry.js +5 -3
  1195. package/dist/modes/interactive/components/tool-panel-registry.js.map +1 -1
  1196. package/dist/modes/interactive/components/tool-title.d.ts.map +1 -1
  1197. package/dist/modes/interactive/components/tool-title.js +0 -4
  1198. package/dist/modes/interactive/components/tool-title.js.map +1 -1
  1199. package/dist/modes/interactive/components/transcript-pager.d.ts +26 -0
  1200. package/dist/modes/interactive/components/transcript-pager.d.ts.map +1 -0
  1201. package/dist/modes/interactive/components/transcript-pager.js +81 -0
  1202. package/dist/modes/interactive/components/transcript-pager.js.map +1 -0
  1203. package/dist/modes/interactive/components/tree-selector.d.ts +1 -12
  1204. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  1205. package/dist/modes/interactive/components/tree-selector.js +42 -402
  1206. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  1207. package/dist/modes/interactive/components/trust-selector.d.ts.map +1 -1
  1208. package/dist/modes/interactive/components/trust-selector.js +4 -16
  1209. package/dist/modes/interactive/components/trust-selector.js.map +1 -1
  1210. package/dist/modes/interactive/components/usage-action-selector.d.ts.map +1 -1
  1211. package/dist/modes/interactive/components/usage-action-selector.js +2 -10
  1212. package/dist/modes/interactive/components/usage-action-selector.js.map +1 -1
  1213. package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -1
  1214. package/dist/modes/interactive/components/user-message-selector.js +3 -6
  1215. package/dist/modes/interactive/components/user-message-selector.js.map +1 -1
  1216. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  1217. package/dist/modes/interactive/components/user-message.js +0 -1
  1218. package/dist/modes/interactive/components/user-message.js.map +1 -1
  1219. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
  1220. package/dist/modes/interactive/components/visual-truncate.js.map +1 -1
  1221. package/dist/modes/interactive/config-backup.d.ts.map +1 -1
  1222. package/dist/modes/interactive/config-backup.js.map +1 -1
  1223. package/dist/modes/interactive/editor-overlay-host.d.ts.map +1 -1
  1224. package/dist/modes/interactive/editor-overlay-host.js +0 -3
  1225. package/dist/modes/interactive/editor-overlay-host.js.map +1 -1
  1226. package/dist/modes/interactive/extension-ui-host.d.ts +2 -0
  1227. package/dist/modes/interactive/extension-ui-host.d.ts.map +1 -1
  1228. package/dist/modes/interactive/extension-ui-host.js +51 -72
  1229. package/dist/modes/interactive/extension-ui-host.js.map +1 -1
  1230. package/dist/modes/interactive/external-editor.d.ts.map +1 -1
  1231. package/dist/modes/interactive/external-editor.js +2 -15
  1232. package/dist/modes/interactive/external-editor.js.map +1 -1
  1233. package/dist/modes/interactive/history-reload-math.d.ts.map +1 -1
  1234. package/dist/modes/interactive/history-reload-math.js.map +1 -1
  1235. package/dist/modes/interactive/interactive-event-controller.d.ts.map +1 -1
  1236. package/dist/modes/interactive/interactive-event-controller.js +23 -16
  1237. package/dist/modes/interactive/interactive-event-controller.js.map +1 -1
  1238. package/dist/modes/interactive/interactive-mode.d.ts +13 -4
  1239. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  1240. package/dist/modes/interactive/interactive-mode.js +123 -204
  1241. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  1242. package/dist/modes/interactive/interactive-selection-prompts.d.ts +20 -0
  1243. package/dist/modes/interactive/interactive-selection-prompts.d.ts.map +1 -0
  1244. package/dist/modes/interactive/interactive-selection-prompts.js +43 -0
  1245. package/dist/modes/interactive/interactive-selection-prompts.js.map +1 -0
  1246. package/dist/modes/interactive/key-handlers.d.ts +2 -1
  1247. package/dist/modes/interactive/key-handlers.d.ts.map +1 -1
  1248. package/dist/modes/interactive/key-handlers.js +4 -2
  1249. package/dist/modes/interactive/key-handlers.js.map +1 -1
  1250. package/dist/modes/interactive/loaded-resources-view.d.ts.map +1 -1
  1251. package/dist/modes/interactive/loaded-resources-view.js.map +1 -1
  1252. package/dist/modes/interactive/local-model-commands.d.ts.map +1 -1
  1253. package/dist/modes/interactive/local-model-commands.js +4 -9
  1254. package/dist/modes/interactive/local-model-commands.js.map +1 -1
  1255. package/dist/modes/interactive/model-fitness-presentation.d.ts +21 -0
  1256. package/dist/modes/interactive/model-fitness-presentation.d.ts.map +1 -0
  1257. package/dist/modes/interactive/model-fitness-presentation.js +13 -0
  1258. package/dist/modes/interactive/model-fitness-presentation.js.map +1 -0
  1259. package/dist/modes/interactive/profile-menu-controller.d.ts +2 -0
  1260. package/dist/modes/interactive/profile-menu-controller.d.ts.map +1 -1
  1261. package/dist/modes/interactive/profile-menu-controller.js +79 -171
  1262. package/dist/modes/interactive/profile-menu-controller.js.map +1 -1
  1263. package/dist/modes/interactive/report-commands.d.ts +2 -0
  1264. package/dist/modes/interactive/report-commands.d.ts.map +1 -1
  1265. package/dist/modes/interactive/report-commands.js +12 -6
  1266. package/dist/modes/interactive/report-commands.js.map +1 -1
  1267. package/dist/modes/interactive/resource-display.d.ts.map +1 -1
  1268. package/dist/modes/interactive/resource-display.js.map +1 -1
  1269. package/dist/modes/interactive/resource-shell-commands.d.ts.map +1 -1
  1270. package/dist/modes/interactive/resource-shell-commands.js +6 -23
  1271. package/dist/modes/interactive/resource-shell-commands.js.map +1 -1
  1272. package/dist/modes/interactive/session-flow-commands.d.ts.map +1 -1
  1273. package/dist/modes/interactive/session-flow-commands.js +21 -25
  1274. package/dist/modes/interactive/session-flow-commands.js.map +1 -1
  1275. package/dist/modes/interactive/session-io-commands.d.ts.map +1 -1
  1276. package/dist/modes/interactive/session-io-commands.js.map +1 -1
  1277. package/dist/modes/interactive/session-replacement-errors.d.ts.map +1 -1
  1278. package/dist/modes/interactive/session-replacement-errors.js.map +1 -1
  1279. package/dist/modes/interactive/settings-selector-flow.d.ts.map +1 -1
  1280. package/dist/modes/interactive/settings-selector-flow.js.map +1 -1
  1281. package/dist/modes/interactive/signal-lifecycle.d.ts.map +1 -1
  1282. package/dist/modes/interactive/signal-lifecycle.js.map +1 -1
  1283. package/dist/modes/interactive/startup-checks.d.ts.map +1 -1
  1284. package/dist/modes/interactive/startup-checks.js +12 -8
  1285. package/dist/modes/interactive/startup-checks.js.map +1 -1
  1286. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  1287. package/dist/modes/interactive/theme/theme.js +10 -76
  1288. package/dist/modes/interactive/theme/theme.js.map +1 -1
  1289. package/dist/modes/interactive/usage-commands.d.ts.map +1 -1
  1290. package/dist/modes/interactive/usage-commands.js.map +1 -1
  1291. package/dist/modes/print-mode.d.ts.map +1 -1
  1292. package/dist/modes/print-mode.js +5 -22
  1293. package/dist/modes/print-mode.js.map +1 -1
  1294. package/dist/modes/rpc/jsonl.d.ts.map +1 -1
  1295. package/dist/modes/rpc/jsonl.js +1 -1
  1296. package/dist/modes/rpc/jsonl.js.map +1 -1
  1297. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  1298. package/dist/modes/rpc/rpc-client.js +7 -8
  1299. package/dist/modes/rpc/rpc-client.js.map +1 -1
  1300. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  1301. package/dist/modes/rpc/rpc-mode.js +5 -20
  1302. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  1303. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  1304. package/dist/modes/rpc/rpc-types.js.map +1 -1
  1305. package/dist/modes/termination-signals.d.ts +4 -0
  1306. package/dist/modes/termination-signals.d.ts.map +1 -0
  1307. package/dist/modes/termination-signals.js +21 -0
  1308. package/dist/modes/termination-signals.js.map +1 -0
  1309. package/dist/package-manager-cli.d.ts.map +1 -1
  1310. package/dist/package-manager-cli.js.map +1 -1
  1311. package/dist/utils/ansi-colors.d.ts +5 -0
  1312. package/dist/utils/ansi-colors.d.ts.map +1 -0
  1313. package/dist/utils/ansi-colors.js +38 -0
  1314. package/dist/utils/ansi-colors.js.map +1 -0
  1315. package/dist/utils/ansi.d.ts.map +1 -1
  1316. package/dist/utils/ansi.js.map +1 -1
  1317. package/dist/utils/changelog.d.ts.map +1 -1
  1318. package/dist/utils/changelog.js.map +1 -1
  1319. package/dist/utils/child-process.d.ts.map +1 -1
  1320. package/dist/utils/child-process.js.map +1 -1
  1321. package/dist/utils/clipboard-image.d.ts.map +1 -1
  1322. package/dist/utils/clipboard-image.js.map +1 -1
  1323. package/dist/utils/clipboard-native.d.ts.map +1 -1
  1324. package/dist/utils/clipboard-native.js.map +1 -1
  1325. package/dist/utils/clipboard.d.ts.map +1 -1
  1326. package/dist/utils/clipboard.js.map +1 -1
  1327. package/dist/utils/deprecation.d.ts.map +1 -1
  1328. package/dist/utils/deprecation.js.map +1 -1
  1329. package/dist/utils/exif-orientation.d.ts.map +1 -1
  1330. package/dist/utils/exif-orientation.js.map +1 -1
  1331. package/dist/utils/external-editor-command.d.ts.map +1 -1
  1332. package/dist/utils/external-editor-command.js.map +1 -1
  1333. package/dist/utils/frontmatter.d.ts.map +1 -1
  1334. package/dist/utils/frontmatter.js.map +1 -1
  1335. package/dist/utils/fs-watch.d.ts.map +1 -1
  1336. package/dist/utils/fs-watch.js.map +1 -1
  1337. package/dist/utils/git.d.ts.map +1 -1
  1338. package/dist/utils/git.js +20 -28
  1339. package/dist/utils/git.js.map +1 -1
  1340. package/dist/utils/highlight-js-languages.d.ts.map +1 -1
  1341. package/dist/utils/html.d.ts.map +1 -1
  1342. package/dist/utils/html.js.map +1 -1
  1343. package/dist/utils/image-convert.d.ts.map +1 -1
  1344. package/dist/utils/image-convert.js.map +1 -1
  1345. package/dist/utils/image-resize-core.d.ts.map +1 -1
  1346. package/dist/utils/image-resize-core.js.map +1 -1
  1347. package/dist/utils/image-resize-worker.d.ts.map +1 -1
  1348. package/dist/utils/image-resize-worker.js.map +1 -1
  1349. package/dist/utils/image-resize.d.ts.map +1 -1
  1350. package/dist/utils/image-resize.js.map +1 -1
  1351. package/dist/utils/json.d.ts.map +1 -1
  1352. package/dist/utils/json.js.map +1 -1
  1353. package/dist/utils/mime.d.ts.map +1 -1
  1354. package/dist/utils/mime.js.map +1 -1
  1355. package/dist/utils/open-browser.d.ts.map +1 -1
  1356. package/dist/utils/open-browser.js.map +1 -1
  1357. package/dist/utils/paths.d.ts.map +1 -1
  1358. package/dist/utils/paths.js.map +1 -1
  1359. package/dist/utils/photon.d.ts.map +1 -1
  1360. package/dist/utils/photon.js.map +1 -1
  1361. package/dist/utils/pi-user-agent.d.ts.map +1 -1
  1362. package/dist/utils/pi-user-agent.js.map +1 -1
  1363. package/dist/utils/platform.d.ts.map +1 -1
  1364. package/dist/utils/platform.js.map +1 -1
  1365. package/dist/utils/process-memory.d.ts.map +1 -1
  1366. package/dist/utils/process-memory.js.map +1 -1
  1367. package/dist/utils/safe-write-stream.d.ts.map +1 -1
  1368. package/dist/utils/safe-write-stream.js.map +1 -1
  1369. package/dist/utils/shell.d.ts.map +1 -1
  1370. package/dist/utils/shell.js.map +1 -1
  1371. package/dist/utils/sleep.d.ts.map +1 -1
  1372. package/dist/utils/sleep.js +2 -15
  1373. package/dist/utils/sleep.js.map +1 -1
  1374. package/dist/utils/stdin-events.d.ts +8 -0
  1375. package/dist/utils/stdin-events.d.ts.map +1 -0
  1376. package/dist/utils/stdin-events.js +19 -0
  1377. package/dist/utils/stdin-events.js.map +1 -0
  1378. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  1379. package/dist/utils/syntax-highlight.js +20 -13
  1380. package/dist/utils/syntax-highlight.js.map +1 -1
  1381. package/dist/utils/tools-manager.d.ts.map +1 -1
  1382. package/dist/utils/tools-manager.js.map +1 -1
  1383. package/dist/utils/version-check.d.ts.map +1 -1
  1384. package/dist/utils/version-check.js.map +1 -1
  1385. package/dist/utils/windows-self-update.d.ts.map +1 -1
  1386. package/dist/utils/windows-self-update.js.map +1 -1
  1387. package/dist/utils/work-directory.d.ts.map +1 -1
  1388. package/dist/utils/work-directory.js.map +1 -1
  1389. package/docs/compaction.md +11 -3
  1390. package/docs/sessions.md +6 -0
  1391. package/docs/settings.md +1 -1
  1392. package/docs/windows.md +26 -1
  1393. package/docs/work-directory.md +9 -1
  1394. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  1395. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  1396. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  1397. package/examples/extensions/sandbox/package-lock.json +2 -2
  1398. package/examples/extensions/sandbox/package.json +1 -1
  1399. package/examples/extensions/with-deps/package-lock.json +2 -2
  1400. package/examples/extensions/with-deps/package.json +1 -1
  1401. package/npm-shrinkwrap.json +16 -16
  1402. package/package.json +10 -10
  1403. package/dist/utils/streaming-lines.d.ts +0 -20
  1404. package/dist/utils/streaming-lines.d.ts.map +0 -1
  1405. package/dist/utils/streaming-lines.js +0 -79
  1406. package/dist/utils/streaming-lines.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;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,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,sBA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AAI,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
+ {"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,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AC,IAAI,CAAC,4BAA4B,CAAC,CAAC;IAClG,IAAI,OAAO,CAAC,UAAU,KAAK,SAAS,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;AACnB,CAAC","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":"policy-engine.d.ts","sourceRoot":"","sources":["../../../src/core/context/policy-engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG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AE,KAAK,GAAG,QAAQ,GAAG,MAAM,CAAC;CACtC;AAED;;;;GAIG;AACH,wBAAgB,8BAA8B,CAAC,KAAK,EAAE,8BAA8B,GAAG,oBAAoB,CAkC1G;AAgBD,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,wBAAwB,GAAG,MAAM,CAEjF;AAED,kFAAkF;AAClF,wBAAgB,qBAAqB,CAAC,SAAS,EAAE,IAAI,CAAC,oBAAoB,EAAE,QAAQ,GAAG,aAAa,CAAC,GAAG,MAAM,CAQ7G","sourcesContent":["/**\n * Pure policy-engine primitives (Phase 0.6): a hard-constraint evaluator, break-even\n * scoring helpers, and reason-code formatting. No provider calls, no I/O, no wiring into\n * prompt construction, model routing, or validation yet.\n *\n * The one invariant every helper here must uphold: a hard constraint can never be\n * overridden by a positive expected saving. Scoring only runs for candidates that already\n * cleared the hard-constraint layer.\n */\n\nimport type {\n\tHardConstraintFlags,\n\tPolicyAction,\n\tPolicyCandidateScore,\n\tPolicyFeatures,\n\tPolicyHardConstraintCode,\n} from \"./policy-types.ts\";\n\nconst AGGRESSIVE_CONTEXT_ACTIONS: ReadonlySet<PolicyAction> = new Set([\n\t\"summarize\",\n\t\"drop_from_prompt\",\n\t\"pack_to_artifact\",\n]);\n\nfunction pushUnique(codes: PolicyHardConstraintCode[], code: PolicyHardConstraintCode): void {\n\tif (!codes.includes(code)) codes.push(code);\n}\n\n/**\n * Evaluate hard constraints for a single candidate action. Returns the (possibly empty)\n * list of violated constraint codes; any non-empty result means the action must be\n * rejected outright, never merely down-weighted by scoring.\n */\nexport function evaluateHardConstraints(\n\taction: PolicyAction,\n\tfeatures: PolicyFeatures,\n\tflags: HardConstraintFlags,\n): PolicyHardConstraintCode[] {\n\tconst codes: PolicyHardConstraintCode[] = [];\n\n\tif (AGGRESSIVE_CONTEXT_ACTIONS.has(action)) {\n\t\tif (features.isPinned) pushUnique(codes, \"pinned_user_instruction\");\n\t\tif (flags.isApprovalOrDenial) pushUnique(codes, \"approval_or_denial\");\n\t\tif (flags.isSafetyConstraint) pushUnique(codes, \"safety_constraint\");\n\t\tif (features.isOpenRequirement) pushUnique(codes, \"open_requirement\");\n\t\tif (flags.isActiveBlocker) pushUnique(codes, \"active_blocker\");\n\t\tif (features.isLatestFailure) pushUnique(codes, \"latest_unresolved_failure\");\n\t\tif (features.isCurrentDiff) pushUnique(codes, \"current_diff_summary\");\n\t\tif (flags.isCurrentValidationResult) pushUnique(codes, \"current_validation_result\");\n\t\tif (flags.isPathOrToolScope) pushUnique(codes, \"path_or_tool_scope\");\n\t}\n\n\t// drop_from_prompt discards content outright, so it requires a retrieval path that\n\t// already exists. pack_to_artifact is the first-capture operation that *creates* the\n\t// retrieval path (tool-output-artifacts.md: measure -> digest/preview/artifact -> prompt\n\t// item), so it must not be rejected merely for lacking one; it only needs a working\n\t// artifact store to write into.\n\tif (action === \"drop_from_prompt\" && !flags.hasAvailableRetrievalPath) {\n\t\tpushUnique(codes, \"missing_retrieval_path\");\n\t}\n\tif (action === \"pack_to_artifact\" && !flags.artifactStoreAvailable) {\n\t\tpushUnique(codes, \"missing_retrieval_path\");\n\t}\n\n\tif (action === \"summarize\" && features.isDecisionBearing && !flags.hasEvidenceRefForSummary) {\n\t\tpushUnique(codes, \"missing_retrieval_path\");\n\t}\n\n\tif (action === \"route_cheap\") {\n\t\tif (features.taskRisk === \"high\" || features.taskRisk === \"unknown\" || features.taskRisk === undefined) {\n\t\t\tpushUnique(codes, \"unknown_risk\");\n\t\t}\n\t\tif (flags.isHighImpactOrBroadMultiFileEdit) pushUnique(codes, \"unknown_risk\");\n\t\tif (flags.priorAttemptFailedForReasoningOrArchitecture) pushUnique(codes, \"unknown_risk\");\n\t\tif (!flags.validationAvailableAndStrong) pushUnique(codes, \"unknown_risk\");\n\t\tif (!flags.pathOrToolBoundariesEnforced) pushUnique(codes, \"path_or_tool_scope\");\n\t}\n\n\treturn codes;\n}\n\n/**\n * Inputs to the context-retention break-even formula from decision-math-and-research.md:\n * saving(i) = N_remaining * (T_raw - T_digest) * C_token - C_pack - P_need*C_retrieve\n * - P_error*C_error - C_cache\n */\nexport interface ContextRetentionSavingInputs {\n\trawTokens: number;\n\tcompactTokens: number;\n\texpectedRemainingTurns: number;\n\tmarginalInputTokenCost: number;\n\tpackCostTokens: number;\n\tprobabilityNeededAgain: number;\n\tretrievalCostTokens: number;\n\tprobabilityErrorIfDropped: number;\n\terrorCostTokens: number;\n\tcacheImpactTokens: number;\n}\n\nexport function computeContextRetentionSaving(inputs: ContextRetentionSavingInputs): number {\n\tconst rawCost = inputs.expectedRemainingTurns * inputs.rawTokens * inputs.marginalInputTokenCost;\n\tconst compactCost = inputs.expectedRemainingTurns * inputs.compactTokens * inputs.marginalInputTokenCost;\n\tconst oneTimeCost =\n\t\tinputs.packCostTokens +\n\t\tinputs.probabilityNeededAgain * inputs.retrievalCostTokens +\n\t\tinputs.probabilityErrorIfDropped * inputs.errorCostTokens +\n\t\tinputs.cacheImpactTokens;\n\treturn rawCost - compactCost - oneTimeCost;\n}\n\n/**\n * N_break_even(i) from decision-math-and-research.md: the number of remaining turns at\n * which packing/summarizing first becomes worthwhile. Returns +Infinity when the raw vs.\n * compact token gap never pays for itself (per-turn saving is zero or negative).\n */\nexport function computeBreakEvenRemainingTurns(\n\tinputs: Omit<ContextRetentionSavingInputs, \"expectedRemainingTurns\"> & { margin: number },\n): number {\n\tconst perTurnSaving = (inputs.rawTokens - inputs.compactTokens) * inputs.marginalInputTokenCost;\n\tif (perTurnSaving <= 0) return Number.POSITIVE_INFINITY;\n\tconst oneTimeCost =\n\t\tinputs.packCostTokens +\n\t\tinputs.probabilityNeededAgain * inputs.retrievalCostTokens +\n\t\tinputs.probabilityErrorIfDropped * inputs.errorCostTokens +\n\t\tinputs.cacheImpactTokens +\n\t\tinputs.margin;\n\treturn oneTimeCost / perTurnSaving;\n}\n\n/**\n * Hard cap override from policy-engine-spec.md: oversized raw tool output must be packed\n * regardless of break-even math, unless the item is pinned, current, or the latest\n * failure.\n */\nexport function exceedsHardOutputCap(\n\trawTokens: number,\n\tmaxRawToolOutputTokens: number,\n\tfeatures: Pick<PolicyFeatures, \"isPinned\" | \"isCurrentDiff\" | \"isLatestFailure\">,\n): boolean {\n\tif (features.isPinned || features.isCurrentDiff || features.isLatestFailure) return false;\n\treturn rawTokens > maxRawToolOutputTokens;\n}\n\nexport interface ContextRetentionCandidateInput {\n\taction: PolicyAction;\n\tfeatures: PolicyFeatures;\n\tflags: HardConstraintFlags;\n\tsaving: ContextRetentionSavingInputs;\n\tmargin: number;\n\tconfidence: \"low\" | \"medium\" | \"high\";\n}\n\n/**\n * Score one context-retention candidate. Hard constraints are checked first and, if any\n * fire, the candidate is returned as unappliable (infinite cost, zero savings) no matter\n * what the break-even math says — a hard constraint can never be overridden by savings.\n */\nexport function scoreContextRetentionCandidate(input: ContextRetentionCandidateInput): PolicyCandidateScore {\n\tconst hardConstraints = evaluateHardConstraints(input.action, input.features, input.flags);\n\tif (hardConstraints.length > 0) {\n\t\treturn {\n\t\t\taction: input.action,\n\t\t\texpectedCostTokens: Number.POSITIVE_INFINITY,\n\t\t\texpectedSavingsTokens: 0,\n\t\t\texpectedReliabilityRisk: 1,\n\t\t\tcacheImpactTokens: input.saving.cacheImpactTokens,\n\t\t\treworkRiskTokens: input.saving.probabilityErrorIfDropped * input.saving.errorCostTokens,\n\t\t\tconfidence: \"low\",\n\t\t\treasonCodes: hardConstraints,\n\t\t};\n\t}\n\n\tconst saving = computeContextRetentionSaving(input.saving);\n\tconst applied = saving > input.margin;\n\tconst decisionBearingLowConfidence = input.features.isDecisionBearing && input.confidence === \"low\";\n\n\treturn {\n\t\taction: input.action,\n\t\texpectedCostTokens: input.saving.packCostTokens + input.saving.cacheImpactTokens,\n\t\texpectedSavingsTokens: Math.max(0, saving),\n\t\texpectedReliabilityRisk: input.saving.probabilityErrorIfDropped,\n\t\tcacheImpactTokens: input.saving.cacheImpactTokens,\n\t\treworkRiskTokens: input.saving.probabilityErrorIfDropped * input.saving.errorCostTokens,\n\t\tconfidence: input.confidence,\n\t\treasonCodes:\n\t\t\tapplied && !decisionBearingLowConfidence\n\t\t\t\t? [\"saving_above_margin\"]\n\t\t\t\t: decisionBearingLowConfidence\n\t\t\t\t\t? [\"low_confidence_decision_bearing\"]\n\t\t\t\t\t: [\"saving_below_margin\"],\n\t};\n}\n\nconst HARD_CONSTRAINT_REASON_TEXT: Record<PolicyHardConstraintCode, string> = {\n\tpinned_user_instruction: \"item is a pinned user instruction and must remain present verbatim\",\n\tapproval_or_denial: \"item records a user approval or denial and cannot be summarized or dropped\",\n\tsafety_constraint: \"item is a safety/security constraint and must remain present verbatim\",\n\topen_requirement: \"item is an open requirement for the active goal and cannot be dropped while active\",\n\tactive_blocker: \"item is an active blocker and must remain present until resolved\",\n\tlatest_unresolved_failure: \"item is the latest unresolved failure; dropping it risks repeating the mistake\",\n\tcurrent_diff_summary: \"item is the current diff summary during active code changes\",\n\tcurrent_validation_result: \"item is the current validation command/result and cannot be dropped while pending\",\n\tmissing_retrieval_path: \"no retrieval path (artifact/evidence ref) exists to recover this content if evicted\",\n\tpath_or_tool_scope: \"item encodes an active path/tool scope restriction that must stay enforced\",\n\tunknown_risk: \"task risk is high or unknown and this action requires stronger reliability guarantees\",\n};\n\nexport function formatHardConstraintReason(code: PolicyHardConstraintCode): string {\n\treturn HARD_CONSTRAINT_REASON_TEXT[code];\n}\n\n/** Human-readable, deterministic summary of a scored candidate's reason codes. */\nexport function formatCandidateReason(candidate: Pick<PolicyCandidateScore, \"action\" | \"reasonCodes\">): string {\n\tconst hardCodes = candidate.reasonCodes.filter(\n\t\t(code): code is PolicyHardConstraintCode => code in HARD_CONSTRAINT_REASON_TEXT,\n\t);\n\tif (hardCodes.length > 0) {\n\t\treturn `${candidate.action} rejected: ${hardCodes.map(formatHardConstraintReason).join(\"; \")}`;\n\t}\n\treturn `${candidate.action}: ${candidate.reasonCodes.join(\", \")}`;\n}\n"]}
1
+ {"version":3,"file":"policy-engine.d.ts","sourceRoot":"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EAAoC,EAAE,CAAC,IAAI,IAAI,2BAA2B,CAC/E,CAAC;IACF,IAAI,SAAS,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC1B,OAAO,GAAG,SAAS,CAAC,MAAM,cAAc,SAAS,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;IAChG,CAAC;IACD,OAAO,GAAG,SAAS,CAAC,MAAM,KAAK,SAAS,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;AAAA,CAClE","sourcesContent":["/**\n * Pure policy-engine primitives (Phase 0.6): a hard-constraint evaluator, break-even\n * scoring helpers, and reason-code formatting. No provider calls, no I/O, no wiring into\n * prompt construction, model routing, or validation yet.\n *\n * The one invariant every helper here must uphold: a hard constraint can never be\n * overridden by a positive expected saving. Scoring only runs for candidates that already\n * cleared the hard-constraint layer.\n */\n\nimport type {\n\tHardConstraintFlags,\n\tPolicyAction,\n\tPolicyCandidateScore,\n\tPolicyFeatures,\n\tPolicyHardConstraintCode,\n} from \"./policy-types.ts\";\n\nconst AGGRESSIVE_CONTEXT_ACTIONS: ReadonlySet<PolicyAction> = new Set([\n\t\"summarize\",\n\t\"drop_from_prompt\",\n\t\"pack_to_artifact\",\n]);\n\nfunction pushUnique(codes: PolicyHardConstraintCode[], code: PolicyHardConstraintCode): void {\n\tif (!codes.includes(code)) codes.push(code);\n}\n\n/**\n * Evaluate hard constraints for a single candidate action. Returns the (possibly empty)\n * list of violated constraint codes; any non-empty result means the action must be\n * rejected outright, never merely down-weighted by scoring.\n */\nexport function evaluateHardConstraints(\n\taction: PolicyAction,\n\tfeatures: PolicyFeatures,\n\tflags: HardConstraintFlags,\n): PolicyHardConstraintCode[] {\n\tconst codes: PolicyHardConstraintCode[] = [];\n\n\tif (AGGRESSIVE_CONTEXT_ACTIONS.has(action)) {\n\t\tif (features.isPinned) pushUnique(codes, \"pinned_user_instruction\");\n\t\tif (flags.isApprovalOrDenial) pushUnique(codes, \"approval_or_denial\");\n\t\tif (flags.isSafetyConstraint) pushUnique(codes, \"safety_constraint\");\n\t\tif (features.isOpenRequirement) pushUnique(codes, \"open_requirement\");\n\t\tif (flags.isActiveBlocker) pushUnique(codes, \"active_blocker\");\n\t\tif (features.isLatestFailure) pushUnique(codes, \"latest_unresolved_failure\");\n\t\tif (features.isCurrentDiff) pushUnique(codes, \"current_diff_summary\");\n\t\tif (flags.isCurrentValidationResult) pushUnique(codes, \"current_validation_result\");\n\t\tif (flags.isPathOrToolScope) pushUnique(codes, \"path_or_tool_scope\");\n\t}\n\n\t// drop_from_prompt discards content outright, so it requires a retrieval path that\n\t// already exists. pack_to_artifact is the first-capture operation that *creates* the\n\t// retrieval path (tool-output-artifacts.md: measure -> digest/preview/artifact -> prompt\n\t// item), so it must not be rejected merely for lacking one; it only needs a working\n\t// artifact store to write into.\n\tif (action === \"drop_from_prompt\" && !flags.hasAvailableRetrievalPath) {\n\t\tpushUnique(codes, \"missing_retrieval_path\");\n\t}\n\tif (action === \"pack_to_artifact\" && !flags.artifactStoreAvailable) {\n\t\tpushUnique(codes, \"missing_retrieval_path\");\n\t}\n\n\tif (action === \"summarize\" && features.isDecisionBearing && !flags.hasEvidenceRefForSummary) {\n\t\tpushUnique(codes, \"missing_retrieval_path\");\n\t}\n\n\tif (action === \"route_cheap\") {\n\t\tif (features.taskRisk === \"high\" || features.taskRisk === \"unknown\" || features.taskRisk === undefined) {\n\t\t\tpushUnique(codes, \"unknown_risk\");\n\t\t}\n\t\tif (flags.isHighImpactOrBroadMultiFileEdit) pushUnique(codes, \"unknown_risk\");\n\t\tif (flags.priorAttemptFailedForReasoningOrArchitecture) pushUnique(codes, \"unknown_risk\");\n\t\tif (!flags.validationAvailableAndStrong) pushUnique(codes, \"unknown_risk\");\n\t\tif (!flags.pathOrToolBoundariesEnforced) pushUnique(codes, \"path_or_tool_scope\");\n\t}\n\n\treturn codes;\n}\n\n/**\n * Inputs to the context-retention break-even formula from decision-math-and-research.md:\n * saving(i) = N_remaining * (T_raw - T_digest) * C_token - C_pack - P_need*C_retrieve\n * - P_error*C_error - C_cache\n */\nexport interface ContextRetentionSavingInputs {\n\trawTokens: number;\n\tcompactTokens: number;\n\texpectedRemainingTurns: number;\n\tmarginalInputTokenCost: number;\n\tpackCostTokens: number;\n\tprobabilityNeededAgain: number;\n\tretrievalCostTokens: number;\n\tprobabilityErrorIfDropped: number;\n\terrorCostTokens: number;\n\tcacheImpactTokens: number;\n}\n\nexport function computeContextRetentionSaving(inputs: ContextRetentionSavingInputs): number {\n\tconst rawCost = inputs.expectedRemainingTurns * inputs.rawTokens * inputs.marginalInputTokenCost;\n\tconst compactCost = inputs.expectedRemainingTurns * inputs.compactTokens * inputs.marginalInputTokenCost;\n\tconst oneTimeCost =\n\t\tinputs.packCostTokens +\n\t\tinputs.probabilityNeededAgain * inputs.retrievalCostTokens +\n\t\tinputs.probabilityErrorIfDropped * inputs.errorCostTokens +\n\t\tinputs.cacheImpactTokens;\n\treturn rawCost - compactCost - oneTimeCost;\n}\n\n/**\n * N_break_even(i) from decision-math-and-research.md: the number of remaining turns at\n * which packing/summarizing first becomes worthwhile. Returns +Infinity when the raw vs.\n * compact token gap never pays for itself (per-turn saving is zero or negative).\n */\nexport function computeBreakEvenRemainingTurns(\n\tinputs: Omit<ContextRetentionSavingInputs, \"expectedRemainingTurns\"> & { margin: number },\n): number {\n\tconst perTurnSaving = (inputs.rawTokens - inputs.compactTokens) * inputs.marginalInputTokenCost;\n\tif (perTurnSaving <= 0) return Number.POSITIVE_INFINITY;\n\tconst oneTimeCost =\n\t\tinputs.packCostTokens +\n\t\tinputs.probabilityNeededAgain * inputs.retrievalCostTokens +\n\t\tinputs.probabilityErrorIfDropped * inputs.errorCostTokens +\n\t\tinputs.cacheImpactTokens +\n\t\tinputs.margin;\n\treturn oneTimeCost / perTurnSaving;\n}\n\n/**\n * Hard cap override from policy-engine-spec.md: oversized raw tool output must be packed\n * regardless of break-even math, unless the item is pinned, current, or the latest\n * failure.\n */\nexport function exceedsHardOutputCap(\n\trawTokens: number,\n\tmaxRawToolOutputTokens: number,\n\tfeatures: Pick<PolicyFeatures, \"isPinned\" | \"isCurrentDiff\" | \"isLatestFailure\">,\n): boolean {\n\tif (features.isPinned || features.isCurrentDiff || features.isLatestFailure) return false;\n\treturn rawTokens > maxRawToolOutputTokens;\n}\n\nexport interface ContextRetentionCandidateInput {\n\taction: PolicyAction;\n\tfeatures: PolicyFeatures;\n\tflags: HardConstraintFlags;\n\tsaving: ContextRetentionSavingInputs;\n\tmargin: number;\n\tconfidence: \"low\" | \"medium\" | \"high\";\n}\n\n/**\n * Score one context-retention candidate. Hard constraints are checked first and, if any\n * fire, the candidate is returned as unappliable (infinite cost, zero savings) no matter\n * what the break-even math says — a hard constraint can never be overridden by savings.\n */\nexport function scoreContextRetentionCandidate(input: ContextRetentionCandidateInput): PolicyCandidateScore {\n\tconst hardConstraints = evaluateHardConstraints(input.action, input.features, input.flags);\n\tif (hardConstraints.length > 0) {\n\t\treturn {\n\t\t\taction: input.action,\n\t\t\texpectedCostTokens: Number.POSITIVE_INFINITY,\n\t\t\texpectedSavingsTokens: 0,\n\t\t\texpectedReliabilityRisk: 1,\n\t\t\tcacheImpactTokens: input.saving.cacheImpactTokens,\n\t\t\treworkRiskTokens: input.saving.probabilityErrorIfDropped * input.saving.errorCostTokens,\n\t\t\tconfidence: \"low\",\n\t\t\treasonCodes: hardConstraints,\n\t\t};\n\t}\n\n\tconst saving = computeContextRetentionSaving(input.saving);\n\tconst applied = saving > input.margin;\n\tconst decisionBearingLowConfidence = input.features.isDecisionBearing && input.confidence === \"low\";\n\n\treturn {\n\t\taction: input.action,\n\t\texpectedCostTokens: input.saving.packCostTokens + input.saving.cacheImpactTokens,\n\t\texpectedSavingsTokens: Math.max(0, saving),\n\t\texpectedReliabilityRisk: input.saving.probabilityErrorIfDropped,\n\t\tcacheImpactTokens: input.saving.cacheImpactTokens,\n\t\treworkRiskTokens: input.saving.probabilityErrorIfDropped * input.saving.errorCostTokens,\n\t\tconfidence: input.confidence,\n\t\treasonCodes:\n\t\t\tapplied && !decisionBearingLowConfidence\n\t\t\t\t? [\"saving_above_margin\"]\n\t\t\t\t: decisionBearingLowConfidence\n\t\t\t\t\t? [\"low_confidence_decision_bearing\"]\n\t\t\t\t\t: [\"saving_below_margin\"],\n\t};\n}\n\nconst HARD_CONSTRAINT_REASON_TEXT: Record<PolicyHardConstraintCode, string> = {\n\tpinned_user_instruction: \"item is a pinned user instruction and must remain present verbatim\",\n\tapproval_or_denial: \"item records a user approval or denial and cannot be summarized or dropped\",\n\tsafety_constraint: \"item is a safety/security constraint and must remain present verbatim\",\n\topen_requirement: \"item is an open requirement for the active goal and cannot be dropped while active\",\n\tactive_blocker: \"item is an active blocker and must remain present until resolved\",\n\tlatest_unresolved_failure: \"item is the latest unresolved failure; dropping it risks repeating the mistake\",\n\tcurrent_diff_summary: \"item is the current diff summary during active code changes\",\n\tcurrent_validation_result: \"item is the current validation command/result and cannot be dropped while pending\",\n\tmissing_retrieval_path: \"no retrieval path (artifact/evidence ref) exists to recover this content if evicted\",\n\tpath_or_tool_scope: \"item encodes an active path/tool scope restriction that must stay enforced\",\n\tunknown_risk: \"task risk is high or unknown and this action requires stronger reliability guarantees\",\n};\n\nexport function formatHardConstraintReason(code: PolicyHardConstraintCode): string {\n\treturn HARD_CONSTRAINT_REASON_TEXT[code];\n}\n\n/** Human-readable, deterministic summary of a scored candidate's reason codes. */\nexport function formatCandidateReason(candidate: Pick<PolicyCandidateScore, \"action\" | \"reasonCodes\">): string {\n\tconst hardCodes = candidate.reasonCodes.filter(\n\t\t(code): code is PolicyHardConstraintCode => code in HARD_CONSTRAINT_REASON_TEXT,\n\t);\n\tif (hardCodes.length > 0) {\n\t\treturn `${candidate.action} rejected: ${hardCodes.map(formatHardConstraintReason).join(\"; \")}`;\n\t}\n\treturn `${candidate.action}: ${candidate.reasonCodes.join(\", \")}`;\n}\n"]}
1
+ {"version":3,"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AAC,4BAA4B;YACvC,CAAC,CAAC,CAAC,qBAAqB,CAAC;YACzB,CAAC,CAAC,4BAA4B;gBAC7B,CAAC,CAAC,CAAC,iCAAiC,CAAC;gBACrC,CAAC,CAAC,CAAC,qBAAqB,CAAC;KAC5B,CAAC;AACH,CAAC;AAED,MAAM,2BAA2B,GAA6C;IAC7E,uBAAuB,EAAE,oEAAoE;IAC7F,kBAAkB,EAAE,4EAA4E;IAChG,iBAAiB,EAAE,uEAAuE;IAC1F,gBAAgB,EAAE,oFAAoF;IACtG,cAAc,EAAE,kEAAkE;IAClF,yBAAyB,EAAE,gFAAgF;IAC3G,oBAAoB,EAAE,6DAA6D;IACnF,yBAAyB,EAAE,mFAAmF;IAC9G,sBAAsB,EAAE,qFAAqF;IAC7G,kBAAkB,EAAE,4EAA4E;IAChG,YAAY,EAAE,uFAAuF;CACrG,CAAC;AAEF,MAAM,UAAU,0BAA0B,CAAC,IAA8B;IACxE,OAAO,2BAA2B,CAAC,IAAI,CAAC,CAAC;AAC1C,CAAC;AAED,kFAAkF;AAClF,MAAM,UAAU,qBAAqB,CAAC,SAA+D;IACpG,MAAM,SAAS,GAAG,SAAS,CAAC,WAAW,CAAC,MAAM,CAC7C,CAAC,IAAI,EAAoC,EAAE,CAAC,IAAI,IAAI,2BAA2B,CAC/E,CAAC;IACF,IAAI,SAAS,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC1B,OAAO,GAAG,SAAS,CAAC,MAAM,cAAc,SAAS,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;IAChG,CAAC;IACD,OAAO,GAAG,SAAS,CAAC,MAAM,KAAK,SAAS,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;AACnE,CAAC","sourcesContent":["/**\n * Pure policy-engine primitives (Phase 0.6): a hard-constraint evaluator, break-even\n * scoring helpers, and reason-code formatting. No provider calls, no I/O, no wiring into\n * prompt construction, model routing, or validation yet.\n *\n * The one invariant every helper here must uphold: a hard constraint can never be\n * overridden by a positive expected saving. Scoring only runs for candidates that already\n * cleared the hard-constraint layer.\n */\n\nimport type {\n\tHardConstraintFlags,\n\tPolicyAction,\n\tPolicyCandidateScore,\n\tPolicyFeatures,\n\tPolicyHardConstraintCode,\n} from \"./policy-types.ts\";\n\nconst AGGRESSIVE_CONTEXT_ACTIONS: ReadonlySet<PolicyAction> = new Set([\n\t\"summarize\",\n\t\"drop_from_prompt\",\n\t\"pack_to_artifact\",\n]);\n\nfunction pushUnique(codes: PolicyHardConstraintCode[], code: PolicyHardConstraintCode): void {\n\tif (!codes.includes(code)) codes.push(code);\n}\n\n/**\n * Evaluate hard constraints for a single candidate action. Returns the (possibly empty)\n * list of violated constraint codes; any non-empty result means the action must be\n * rejected outright, never merely down-weighted by scoring.\n */\nexport function evaluateHardConstraints(\n\taction: PolicyAction,\n\tfeatures: PolicyFeatures,\n\tflags: HardConstraintFlags,\n): PolicyHardConstraintCode[] {\n\tconst codes: PolicyHardConstraintCode[] = [];\n\n\tif (AGGRESSIVE_CONTEXT_ACTIONS.has(action)) {\n\t\tif (features.isPinned) pushUnique(codes, \"pinned_user_instruction\");\n\t\tif (flags.isApprovalOrDenial) pushUnique(codes, \"approval_or_denial\");\n\t\tif (flags.isSafetyConstraint) pushUnique(codes, \"safety_constraint\");\n\t\tif (features.isOpenRequirement) pushUnique(codes, \"open_requirement\");\n\t\tif (flags.isActiveBlocker) pushUnique(codes, \"active_blocker\");\n\t\tif (features.isLatestFailure) pushUnique(codes, \"latest_unresolved_failure\");\n\t\tif (features.isCurrentDiff) pushUnique(codes, \"current_diff_summary\");\n\t\tif (flags.isCurrentValidationResult) pushUnique(codes, \"current_validation_result\");\n\t\tif (flags.isPathOrToolScope) pushUnique(codes, \"path_or_tool_scope\");\n\t}\n\n\t// drop_from_prompt discards content outright, so it requires a retrieval path that\n\t// already exists. pack_to_artifact is the first-capture operation that *creates* the\n\t// retrieval path (tool-output-artifacts.md: measure -> digest/preview/artifact -> prompt\n\t// item), so it must not be rejected merely for lacking one; it only needs a working\n\t// artifact store to write into.\n\tif (action === \"drop_from_prompt\" && !flags.hasAvailableRetrievalPath) {\n\t\tpushUnique(codes, \"missing_retrieval_path\");\n\t}\n\tif (action === \"pack_to_artifact\" && !flags.artifactStoreAvailable) {\n\t\tpushUnique(codes, \"missing_retrieval_path\");\n\t}\n\n\tif (action === \"summarize\" && features.isDecisionBearing && !flags.hasEvidenceRefForSummary) {\n\t\tpushUnique(codes, \"missing_retrieval_path\");\n\t}\n\n\tif (action === \"route_cheap\") {\n\t\tif (features.taskRisk === \"high\" || features.taskRisk === \"unknown\" || features.taskRisk === undefined) {\n\t\t\tpushUnique(codes, \"unknown_risk\");\n\t\t}\n\t\tif (flags.isHighImpactOrBroadMultiFileEdit) pushUnique(codes, \"unknown_risk\");\n\t\tif (flags.priorAttemptFailedForReasoningOrArchitecture) pushUnique(codes, \"unknown_risk\");\n\t\tif (!flags.validationAvailableAndStrong) pushUnique(codes, \"unknown_risk\");\n\t\tif (!flags.pathOrToolBoundariesEnforced) pushUnique(codes, \"path_or_tool_scope\");\n\t}\n\n\treturn codes;\n}\n\n/**\n * Inputs to the context-retention break-even formula from decision-math-and-research.md:\n * saving(i) = N_remaining * (T_raw - T_digest) * C_token - C_pack - P_need*C_retrieve\n * - P_error*C_error - C_cache\n */\nexport interface ContextRetentionSavingInputs {\n\trawTokens: number;\n\tcompactTokens: number;\n\texpectedRemainingTurns: number;\n\tmarginalInputTokenCost: number;\n\tpackCostTokens: number;\n\tprobabilityNeededAgain: number;\n\tretrievalCostTokens: number;\n\tprobabilityErrorIfDropped: number;\n\terrorCostTokens: number;\n\tcacheImpactTokens: number;\n}\n\nexport function computeContextRetentionSaving(inputs: ContextRetentionSavingInputs): number {\n\tconst rawCost = inputs.expectedRemainingTurns * inputs.rawTokens * inputs.marginalInputTokenCost;\n\tconst compactCost = inputs.expectedRemainingTurns * inputs.compactTokens * inputs.marginalInputTokenCost;\n\tconst oneTimeCost =\n\t\tinputs.packCostTokens +\n\t\tinputs.probabilityNeededAgain * inputs.retrievalCostTokens +\n\t\tinputs.probabilityErrorIfDropped * inputs.errorCostTokens +\n\t\tinputs.cacheImpactTokens;\n\treturn rawCost - compactCost - oneTimeCost;\n}\n\n/**\n * N_break_even(i) from decision-math-and-research.md: the number of remaining turns at\n * which packing/summarizing first becomes worthwhile. Returns +Infinity when the raw vs.\n * compact token gap never pays for itself (per-turn saving is zero or negative).\n */\nexport function computeBreakEvenRemainingTurns(\n\tinputs: Omit<ContextRetentionSavingInputs, \"expectedRemainingTurns\"> & { margin: number },\n): number {\n\tconst perTurnSaving = (inputs.rawTokens - inputs.compactTokens) * inputs.marginalInputTokenCost;\n\tif (perTurnSaving <= 0) return Number.POSITIVE_INFINITY;\n\tconst oneTimeCost =\n\t\tinputs.packCostTokens +\n\t\tinputs.probabilityNeededAgain * inputs.retrievalCostTokens +\n\t\tinputs.probabilityErrorIfDropped * inputs.errorCostTokens +\n\t\tinputs.cacheImpactTokens +\n\t\tinputs.margin;\n\treturn oneTimeCost / perTurnSaving;\n}\n\n/**\n * Hard cap override from policy-engine-spec.md: oversized raw tool output must be packed\n * regardless of break-even math, unless the item is pinned, current, or the latest\n * failure.\n */\nexport function exceedsHardOutputCap(\n\trawTokens: number,\n\tmaxRawToolOutputTokens: number,\n\tfeatures: Pick<PolicyFeatures, \"isPinned\" | \"isCurrentDiff\" | \"isLatestFailure\">,\n): boolean {\n\tif (features.isPinned || features.isCurrentDiff || features.isLatestFailure) return false;\n\treturn rawTokens > maxRawToolOutputTokens;\n}\n\nexport interface ContextRetentionCandidateInput {\n\taction: PolicyAction;\n\tfeatures: PolicyFeatures;\n\tflags: HardConstraintFlags;\n\tsaving: ContextRetentionSavingInputs;\n\tmargin: number;\n\tconfidence: \"low\" | \"medium\" | \"high\";\n}\n\n/**\n * Score one context-retention candidate. Hard constraints are checked first and, if any\n * fire, the candidate is returned as unappliable (infinite cost, zero savings) no matter\n * what the break-even math says — a hard constraint can never be overridden by savings.\n */\nexport function scoreContextRetentionCandidate(input: ContextRetentionCandidateInput): PolicyCandidateScore {\n\tconst hardConstraints = evaluateHardConstraints(input.action, input.features, input.flags);\n\tif (hardConstraints.length > 0) {\n\t\treturn {\n\t\t\taction: input.action,\n\t\t\texpectedCostTokens: Number.POSITIVE_INFINITY,\n\t\t\texpectedSavingsTokens: 0,\n\t\t\texpectedReliabilityRisk: 1,\n\t\t\tcacheImpactTokens: input.saving.cacheImpactTokens,\n\t\t\treworkRiskTokens: input.saving.probabilityErrorIfDropped * input.saving.errorCostTokens,\n\t\t\tconfidence: \"low\",\n\t\t\treasonCodes: hardConstraints,\n\t\t};\n\t}\n\n\tconst saving = computeContextRetentionSaving(input.saving);\n\tconst applied = saving > input.margin;\n\tconst decisionBearingLowConfidence = input.features.isDecisionBearing && input.confidence === \"low\";\n\n\treturn {\n\t\taction: input.action,\n\t\texpectedCostTokens: input.saving.packCostTokens + input.saving.cacheImpactTokens,\n\t\texpectedSavingsTokens: Math.max(0, saving),\n\t\texpectedReliabilityRisk: input.saving.probabilityErrorIfDropped,\n\t\tcacheImpactTokens: input.saving.cacheImpactTokens,\n\t\treworkRiskTokens: input.saving.probabilityErrorIfDropped * input.saving.errorCostTokens,\n\t\tconfidence: input.confidence,\n\t\treasonCodes:\n\t\t\tapplied && !decisionBearingLowConfidence\n\t\t\t\t? [\"saving_above_margin\"]\n\t\t\t\t: decisionBearingLowConfidence\n\t\t\t\t\t? [\"low_confidence_decision_bearing\"]\n\t\t\t\t\t: [\"saving_below_margin\"],\n\t};\n}\n\nconst HARD_CONSTRAINT_REASON_TEXT: Record<PolicyHardConstraintCode, string> = {\n\tpinned_user_instruction: \"item is a pinned user instruction and must remain present verbatim\",\n\tapproval_or_denial: \"item records a user approval or denial and cannot be summarized or dropped\",\n\tsafety_constraint: \"item is a safety/security constraint and must remain present verbatim\",\n\topen_requirement: \"item is an open requirement for the active goal and cannot be dropped while active\",\n\tactive_blocker: \"item is an active blocker and must remain present until resolved\",\n\tlatest_unresolved_failure: \"item is the latest unresolved failure; dropping it risks repeating the mistake\",\n\tcurrent_diff_summary: \"item is the current diff summary during active code changes\",\n\tcurrent_validation_result: \"item is the current validation command/result and cannot be dropped while pending\",\n\tmissing_retrieval_path: \"no retrieval path (artifact/evidence ref) exists to recover this content if evicted\",\n\tpath_or_tool_scope: \"item encodes an active path/tool scope restriction that must stay enforced\",\n\tunknown_risk: \"task risk is high or unknown and this action requires stronger reliability guarantees\",\n};\n\nexport function formatHardConstraintReason(code: PolicyHardConstraintCode): string {\n\treturn HARD_CONSTRAINT_REASON_TEXT[code];\n}\n\n/** Human-readable, deterministic summary of a scored candidate's reason codes. */\nexport function formatCandidateReason(candidate: Pick<PolicyCandidateScore, \"action\" | \"reasonCodes\">): string {\n\tconst hardCodes = candidate.reasonCodes.filter(\n\t\t(code): code is PolicyHardConstraintCode => code in HARD_CONSTRAINT_REASON_TEXT,\n\t);\n\tif (hardCodes.length > 0) {\n\t\treturn `${candidate.action} rejected: ${hardCodes.map(formatHardConstraintReason).join(\"; \")}`;\n\t}\n\treturn `${candidate.action}: ${candidate.reasonCodes.join(\", \")}`;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"policy-types.d.ts","sourceRoot":"","sources":["../../../src/core/context/policy-types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAEvG,MAAM,MAAM,UAAU,GAAG,KAAK,GAAG,QAAQ,GAAG,cAAc,GAAG,aAAa,CAAC;AAE3E,MAAM,MAAM,kBAAkB,GAC3B,mBAAmB,GACnB,oBAAoB,GACpB,YAAY,GACZ,aAAa,GACb,YAAY,GACZ,mBAAmB,CAAC;AAEvB,MAAM,MAAM,YAAY,GACrB,UAAU,GACV,kBAAkB,GAClB,WAAW,GACX,kBAAkB,GAClB,yBAAyB,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nC,sBAAsB,EAAE,OAAO,CAAC;IAChC,0FAA0F;IAC1F,wBAAwB,EAAE,OAAO,CAAC;IAClC,kEAAkE;IAClE,4BAA4B,EAAE,OAAO,CAAC;IACtC,kEAAkE;IAClE,4BAA4B,EAAE,OAAO,CAAC;IACtC,kEAAkE;IAClE,4CAA4C,EAAE,OAAO,CAAC;IACtD,kEAAkE;IAClE,gCAAgC,EAAE,OAAO,CAAC;CAC1C","sourcesContent":["/**\n * Pure policy-engine contracts (Phase 0.6). No behavior change: nothing here is wired\n * into prompt construction, model routing, or validation yet. See\n * docs/context-management-rework/policy-engine-spec.md for the design this mirrors.\n */\n\nimport type { ContextArtifactRef, ContextEvidenceRef, ContextRetentionClass } from \"./context-item.ts\";\n\nexport type PolicyMode = \"off\" | \"shadow\" | \"enforce_safe\" | \"enforce_all\";\n\nexport type PolicyDecisionKind =\n\t| \"context_retention\"\n\t| \"artifact_retrieval\"\n\t| \"tool_rerun\"\n\t| \"model_route\"\n\t| \"validation\"\n\t| \"goal_continuation\";\n\nexport type PolicyAction =\n\t| \"keep_raw\"\n\t| \"pack_to_artifact\"\n\t| \"summarize\"\n\t| \"drop_from_prompt\"\n\t| \"retrieve_artifact_slice\"\n\t| \"rerun_narrowed_tool\"\n\t| \"route_cheap\"\n\t| \"route_medium\"\n\t| \"route_expensive\"\n\t| \"run_validation\"\n\t| \"skip_optional_validation\"\n\t| \"continue_goal\"\n\t| \"stop_and_ask\";\n\n/**\n * Fixed, closed set of hard-constraint reason codes. The policy engine never invents a\n * new code at runtime: every hard rejection maps to one of these.\n */\nexport type PolicyHardConstraintCode =\n\t| \"pinned_user_instruction\"\n\t| \"approval_or_denial\"\n\t| \"safety_constraint\"\n\t| \"open_requirement\"\n\t| \"active_blocker\"\n\t| \"latest_unresolved_failure\"\n\t| \"current_diff_summary\"\n\t| \"current_validation_result\"\n\t| \"missing_retrieval_path\"\n\t| \"path_or_tool_scope\"\n\t| \"unknown_risk\";\n\nexport interface PolicyFeatures {\n\tturnIndex: number;\n\texpectedRemainingTurns: number;\n\tinputTokens: number;\n\toutputTokens: number;\n\tcacheReadTokens: number;\n\tcacheWriteTokens: number;\n\tartifactBytes: number;\n\tcharEstimate: number;\n\tcalibratedTokenEstimate: number;\n\tpromptSection: \"stable_prefix\" | \"volatile_tail\" | \"artifact\" | \"memory\";\n\tretentionClass?: ContextRetentionClass;\n\tisReproducible: boolean;\n\tisDecisionBearing: boolean;\n\tisPinned: boolean;\n\tisOpenRequirement: boolean;\n\tisLatestFailure: boolean;\n\tisCurrentDiff: boolean;\n\tcacheHitProbability?: number;\n\tcacheMissCostTokens?: number;\n\tprobabilityNeededAgain: number;\n\tprobabilityErrorIfDropped: number;\n\tretrievalCostTokens: number;\n\tpackCostTokens: number;\n\tretryCostTokens: number;\n\tfailureCostTokens: number;\n\tvalidationCostTokens: number;\n\tmodelTier?: \"cheap\" | \"medium\" | \"expensive\" | \"learning\";\n\ttaskRisk?: \"low\" | \"medium\" | \"high\" | \"unknown\";\n}\n\nexport interface PolicyCandidateScore {\n\taction: PolicyAction;\n\texpectedCostTokens: number;\n\texpectedSavingsTokens: number;\n\texpectedReliabilityRisk: number;\n\tcacheImpactTokens: number;\n\treworkRiskTokens: number;\n\tconfidence: \"low\" | \"medium\" | \"high\";\n\treasonCodes: string[];\n}\n\nexport interface PolicyDecision {\n\tkind: PolicyDecisionKind;\n\tselectedAction: PolicyAction;\n\tmode: PolicyMode;\n\tapplied: boolean;\n\thardConstraints: PolicyHardConstraintCode[];\n\tcandidates: PolicyCandidateScore[];\n\tselectedReasonCodes: string[];\n\testimatedCostTokens: number;\n\testimatedSavingsTokens: number;\n\testimatedReliabilityRisk: number;\n\tcacheImpactTokens: number;\n\treworkRiskTokens: number;\n\tartifactRefs: ContextArtifactRef[];\n\tevidenceRefs: ContextEvidenceRef[];\n}\n\n/**\n * Flags a caller supplies alongside `PolicyFeatures` so the hard-constraint evaluator can\n * distinguish reason codes `PolicyFeatures` alone does not carry (e.g. approvals/denials\n * and safety constraints are not modeled as separate `PolicyFeatures` booleans).\n */\nexport interface HardConstraintFlags {\n\tisApprovalOrDenial: boolean;\n\tisSafetyConstraint: boolean;\n\tisActiveBlocker: boolean;\n\tisCurrentValidationResult: boolean;\n\tisPathOrToolScope: boolean;\n\t/**\n\t * True only if the item's existing ref is currently resolvable, not merely present.\n\t * An artifact ref is resolvable only if the artifact store/payload is available; a\n\t * transcript/memory/runtime ref is resolvable independent of the artifact store. Callers\n\t * must compute this by checking the concrete ref kind against its backing store, not by\n\t * treating \"some ref is attached\" as sufficient.\n\t */\n\thasAvailableRetrievalPath: boolean;\n\tartifactStoreAvailable: boolean;\n\t/** Only relevant when the candidate action is \"summarize\" on decision-bearing content. */\n\thasEvidenceRefForSummary: boolean;\n\t/** Only relevant for model-routing candidates (\"route_cheap\"). */\n\tpathOrToolBoundariesEnforced: boolean;\n\t/** Only relevant for model-routing candidates (\"route_cheap\"). */\n\tvalidationAvailableAndStrong: boolean;\n\t/** Only relevant for model-routing candidates (\"route_cheap\"). */\n\tpriorAttemptFailedForReasoningOrArchitecture: boolean;\n\t/** Only relevant for model-routing candidates (\"route_cheap\"). */\n\tisHighImpactOrBroadMultiFileEdit: boolean;\n}\n"]}
1
+ {"version":3,"file":"policy-types.d.ts","sourceRoot":"","sources":["../../../src/core/context/policy-types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAEvG,MAAM,MAAM,UAAU,GAAG,KAAK,GAAG,QAAQ,GAAG,cAAc,GAAG,aAAa,CAAC;AAE3E,MAAM,MAAM,kBAAkB,GAC3B,mBAAmB,GACnB,oBAAoB,GACpB,YAAY,GACZ,aAAa,GACb,YAAY,GACZ,mBAAmB,CAAC;AAEvB,MAAM,MAAM,YAAY,GACrB,UAAU,GACV,kBAAkB,GAClB,WAAW,GACX,kBAAkB,GAClB,yBAAyB,GACzB,qBAA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,EAAE,OAAO,CAAC;IAChC,0FAA0F;IAC1F,wBAAwB,EAAE,OAAO,CAAC;IAClC,kEAAkE;IAClE,4BAA4B,EAAE,OAAO,CAAC;IACtC,kEAAkE;IAClE,4BAA4B,EAAE,OAAO,CAAC;IACtC,kEAAkE;IAClE,4CAA4C,EAAE,OAAO,CAAC;IACtD,kEAAkE;IAClE,gCAAgC,EAAE,OAAO,CAAC;CAC1C"}
@@ -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;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
+ {"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,YACvC,eAAe,EACf,mBAAmB,EACnB,oBAAoB,EACpB,kBAAkB,EAClB,mBAAmB,EACnB,cAAc,CACL,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"}
@@ -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;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;AA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AU,EAAE,MAAM,CAAC,CAAC,CAAC;QAAA,CAC7D;QAED,IAAI,CAAC,KAAyC,EAAuB;YACpE,MAAM,IAAI,GAAG,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,WAAW,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;YAC1E,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC;gBAC5B,MAAM,MAAM,GAAG,wBAAwB,CAAC,GAAG,CAAC,CAAC;gBAC7C,OAAO,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;YAAA,CAC5C,CAAC,CAAC;QAAA,CACH;QAED,SAAS,CAAC,UAAkB,EAAE,MAAc,EAAQ;YACnD,MAAM,QAAQ,GAAG,wBAAwB,CAAC,GAAG,CAAC,GAAG,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC;YACvE,IAAI,QAAQ,KAAK,SAAS;gBAAE,OAAO;YACnC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,GAAG,QAAQ,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,EAAE,UAAU,EAAE,MAAM,CAAC,CAAC;QAAA,CAChF;QAED,MAAM,CAAC,UAAkB,EAAE,MAAc,EAAQ;YAChD,MAAM,CAAC,GAAG,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC;QAAA,CAC/B;QAED,KAAK,GAAS;YACb,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC;QAAA,CAC3B;KACD,CAAC;AAAA,CACF","sourcesContent":["import { mkdirSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { DatabaseSync } from \"node:sqlite\";\nimport { 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
+ {"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,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AED,GAAG,CAAC,UAAkB,EAAE,MAAc;YACrC,OAAO,wBAAwB,CAAC,GAAG,CAAC,GAAG,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC;QAC9D,CAAC;QAED,IAAI,CAAC,KAAyC;YAC7C,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;gBAC3B,MAAM,MAAM,GAAG,wBAAwB,CAAC,GAAG,CAAC,CAAC;gBAC7C,OAAO,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;YAC7C,CAAC,CAAC,CAAC;QACJ,CAAC;QAED,SAAS,CAAC,UAAkB,EAAE,MAAc;YAC3C,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;QACjF,CAAC;QAED,MAAM,CAAC,UAAkB,EAAE,MAAc;YACxC,MAAM,CAAC,GAAG,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC;QAChC,CAAC;QAED,KAAK;YACJ,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5B,CAAC;KACD,CAAC;AACH,CAAC","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 +1 @@
1
- {"version":3,"file":"storage-authority.d.ts","sourceRoot":"","sources":["../../../src/core/context/storage-authority.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,MAAM,MAAM,qBAAqB,GAC9B,qBAAqB,GACrB,0BAA0B,GAC1B,uBAAuB,GACvB,uBAAuB,CAAC;AAE3B,MAAM,WAAW,qBAAqB;IACrC,KAAK,EAAE,MAAM,CAAC;IACd,cAAc,EAAE,qBAAqB,CAAC;IACtC,kGAAkG;IAClG,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAC3B,KAAK,EAAE,MAAM,CAAC;CACd;AAED,eAAO,MAAM,+BAA+B,EAAE,SAAS,qBAAqB,EA0C3E,CAAC","sourcesContent":["/**\n * Storage authority/rebuildability metadata for SQLite runtime-index table design (Phase M0/M3).\n *\n * This module records, per runtime-index table, whether its rows are the only copy of\n * something (canonical_local_state), rebuildable from another canonical source\n * (derived_rebuildable), disposable performance data\n * (runtime_cache_disposable), or audit/calibration telemetry whose loss does not affect\n * current task truth (append_only_telemetry). Per memory-architecture.md: cleanup and\n * prompt safety must never depend only on disposable/derived rows.\n */\n\nexport type StorageAuthorityClass =\n\t| \"derived_rebuildable\"\n\t| \"runtime_cache_disposable\"\n\t| \"append_only_telemetry\"\n\t| \"canonical_local_state\";\n\nexport interface StorageTableAuthority {\n\ttable: string;\n\tauthorityClass: StorageAuthorityClass;\n\t/** Canonical sources this table can be rebuilt from, if authorityClass is derived_rebuildable. */\n\trebuildableFrom?: string[];\n\tnotes: string;\n}\n\nexport const CONTEXT_STORAGE_TABLE_AUTHORITY: readonly StorageTableAuthority[] = [\n\t{\n\t\ttable: \"context_items\",\n\t\tauthorityClass: \"derived_rebuildable\",\n\t\trebuildableFrom: [\"transcript\", \"artifacts\"],\n\t\tnotes: \"Working-memory context item metadata; rebuildable from transcript/artifacts if the index is lost.\",\n\t},\n\t{\n\t\ttable: \"artifact_metadata\",\n\t\tauthorityClass: \"canonical_local_state\",\n\t\tnotes:\n\t\t\t\"Artifact id/path/byte-length/reproducibility metadata. The artifact payload file is canonical raw \" +\n\t\t\t\"evidence, but this row is the only index to it; loss here can strand a payload as unreachable, so \" +\n\t\t\t\"treat as canonical_local_state and mirror writes into a durable journal before treating a ref as live.\",\n\t},\n\t{\n\t\ttable: \"policy_score_cache\",\n\t\tauthorityClass: \"runtime_cache_disposable\",\n\t\tnotes:\n\t\t\t\"Cached break-even score computations for context-retention candidates; safe to drop and \" +\n\t\t\t\"recompute on demand, and never consulted for a safety/retention decision by itself.\",\n\t},\n\t{\n\t\ttable: \"policy_decisions\",\n\t\tauthorityClass: \"append_only_telemetry\",\n\t\tnotes: \"Policy decision shadow/enforcement log for calibration and review; loss affects calibration, not current task truth.\",\n\t},\n\t{\n\t\ttable: \"retrieval_records\",\n\t\tauthorityClass: \"append_only_telemetry\",\n\t\tnotes: \"Retrieval/rehydration audit trail; loss affects observability, not current task truth.\",\n\t},\n\t{\n\t\ttable: \"memory_index\",\n\t\tauthorityClass: \"derived_rebuildable\",\n\t\trebuildableFrom: [\"okf_bundle\", \"external_provider\"],\n\t\tnotes:\n\t\t\t\"Index over durable memory sources; rebuildable by re-indexing the OKF bundle/provider content. \" +\n\t\t\t\"Rebuild from an external_provider source is conditional on that provider being enabled, reachable, \" +\n\t\t\t\"and permitted by egress/redaction policy at rebuild time; it is not unconditionally rebuildable \" +\n\t\t\t\"the way the OKF-bundle-backed portion is.\",\n\t},\n];\n"]}
1
+ {"version":3,"file":"storage-authority.d.ts","sourceRoot":"","sources":["../../../src/core/context/storage-authority.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,MAAM,MAAM,qBAAqB,GAC9B,qBAAqB,GACrB,0BAA0B,GAC1B,uBAAuB,GACvB,uBAAuB,CAAC;AAE3B,MAAM,WAAW,qBAAqB;IACrC,KAAK,EAAE,MAAM,CAAC;IACd,cAAc,EAAE,qBAAqB,CAAC;IACtC,kGAAkG;IAClG,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAC3B,KAAK,EAAE,MAAM,CAAC;CACd;AAED,eAAO,MAAM,+BAA+B,EAAE,SAAS,qBAAqB,EA0C3E,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"tool-output-packer.d.ts","sourceRoot":"","sources":["../../../src/core/context/tool-output-packer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,KAAK,iBAAiB,EAAE,KAAK,gBAAgB,EAAgB,MAA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BAA0B,CACzC,OAAO,EAAE,iBAAiB,GAAG,SAAS,EACtC,GAAG,EAAE,MAAM,EACX,qBAAqB,EAAE,MAAM,GAC3B,MAAM,GAAG,SAAS,CAKpB","sourcesContent":["/**\n * Tool output digesting and packing (Phase 3): \"measure -> digest/preview/artifact ->\n * prompt item\", per tool-output-artifacts.md's boundary rule. Large raw tool output is\n * captured to an artifact BEFORE truncation, so the artifact holds the exact raw payload;\n * the model only ever sees the bounded preview plus an artifact reference.\n *\n * This module is pure with respect to wiring: it takes an `ArtifactStore` by dependency\n * injection and does not know about sessions, transcripts, or prompt construction. A tool\n * (grep/find) that never passes an `ArtifactStore` gets byte-for-byte its prior behavior --\n * packing is opt-in per call site, not a global switch.\n */\n\nimport { type TruncationOptions, type TruncationResult, truncateHead } from \"@caupulican/pi-agent-core/node\";\nimport type { ArtifactStore } from \"./context-artifacts.ts\";\n\nexport interface PackToolOutputRequest {\n\ttoolName: string;\n\tcommand?: string;\n\tpath?: string;\n\trawContent: string;\n\tsessionEntryId?: string;\n\t/**\n\t * Turn number for artifact capture identity. Real session-turn wiring lands in a later\n\t * slice; callers that don't track turns yet may pass 0.\n\t */\n\tcreatedAtTurn?: number;\n\t/** Whether re-running the same tool call would reproduce this content. Default: true. */\n\treproducible?: boolean;\n\ttruncation?: TruncationOptions;\n}\n\nexport interface PackedToolOutput {\n\t/**\n\t * Bounded preview content -- exactly what `truncateHead` alone would have produced.\n\t * No footer/notice text is appended here; callers already have their own per-tool\n\t * footer conventions (grep's vs. find's bracket ordering differ) and own formatting\n\t * the artifact notice into their own notice list via `formatArtifactNotice`.\n\t */\n\tcontent: string;\n\ttruncation: TruncationResult;\n\t/** Present only if packing succeeded and the artifact is protected from cleanup. */\n\tartifactId?: string;\n\tpacked: boolean;\n}\n\n/** Footer notice text for a packed artifact, for callers to fold into their own notices. */\nexport function formatArtifactNotice(artifactId: string): string {\n\treturn `Full output: artifact tool-output:${artifactId}`;\n}\n\n/**\n * Measure `request.rawContent`; if it fits within the caps, return it unchanged (small\n * output stays exactly as readable as before this module existed). If it's oversized and\n * an `ArtifactStore` is provided, capture the exact raw payload as an artifact first, then\n * return the same bounded preview `truncateHead` would have produced anyway.\n *\n * Fails closed: if the artifact write succeeds but registering `holderId` as a reference\n * fails (`addReference` returns false), the artifact is not claimed in the result at all --\n * the caller falls back to the bounded/truncated content exactly as if no store had been\n * provided, since an unprotected artifact could be cleaned up at any time.\n */\nexport function packToolOutput(\n\trequest: PackToolOutputRequest,\n\tartifactStore: ArtifactStore | undefined,\n\tholderId: string,\n): PackedToolOutput {\n\tconst truncation = truncateHead(request.rawContent, request.truncation);\n\n\tif (!truncation.truncated || !artifactStore) {\n\t\treturn { content: truncation.content, truncation, packed: false };\n\t}\n\n\tconst { ref } = artifactStore.write({\n\t\tkind: \"tool_output\",\n\t\tcontent: request.rawContent,\n\t\ttoolName: request.toolName,\n\t\tcommand: request.command,\n\t\tpath: request.path,\n\t\tsessionEntryId: request.sessionEntryId,\n\t\tcreatedAtTurn: request.createdAtTurn ?? 0,\n\t\treproducible: request.reproducible ?? true,\n\t});\n\n\tif (!artifactStore.addReference(ref.id, holderId)) {\n\t\treturn { content: truncation.content, truncation, packed: false };\n\t}\n\n\treturn { content: truncation.content, truncation, artifactId: ref.id, packed: true };\n}\n\nexport interface BroadQueryTracker {\n\t/** Record one more broad occurrence of `key`; returns the cumulative count including this one. */\n\trecordBroadQuery(key: string): number;\n}\n\nexport function createInMemoryBroadQueryTracker(): BroadQueryTracker {\n\tconst counts = new Map<string, number>();\n\treturn {\n\t\trecordBroadQuery(key: string): number {\n\t\t\tconst next = (counts.get(key) ?? 0) + 1;\n\t\t\tcounts.set(key, next);\n\t\t\treturn next;\n\t\t},\n\t};\n}\n\n/** Normalize a search-tool call into a stable repetition key: same query, same broadness. */\nexport function normalizeBroadQueryKey(input: {\n\ttoolName: string;\n\tpattern?: string;\n\tpath?: string;\n\tglob?: string;\n}): string {\n\treturn [input.toolName, input.pattern ?? \"\", input.path ?? \"\", input.glob ?? \"\"].join(\"␟\");\n}\n\nconst REPEATED_BROAD_QUERY_THRESHOLD = 2;\n\n/**\n * When a broad-query condition (match/result limit hit, or byte truncation) repeats for\n * the same normalized query, produce a compact \"do not repeat\" style note. This is only\n * the Phase 3 signal; the durable invalidation ledger (supersession/expiry rules) is\n * Phase 6 per implementation-phases.md.\n */\nexport function broadQueryInvalidationNote(\n\ttracker: BroadQueryTracker | undefined,\n\tkey: string,\n\thumanQueryDescription: string,\n): string | undefined {\n\tif (!tracker) return undefined;\n\tconst count = tracker.recordBroadQuery(key);\n\tif (count < REPEATED_BROAD_QUERY_THRESHOLD) return undefined;\n\treturn `Do not repeat: ${humanQueryDescription} has produced broad/truncated results ${count} times in this session. Narrow the path/glob/pattern.`;\n}\n"]}
1
+ {"version":3,"file":"tool-output-packer.d.ts","sourceRoot":"","sources":["../../../src/core/context/tool-output-packer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,KAAK,iBAAiB,EAAE,KAAK,gBAAgB,EAAgB,MAAM,gCAAgC,CAAC;AAC7G,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAE5D,MAAM,WAAW,qBAAqB;IACrC,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;IACnB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;;OAGG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,yFAAyF;IACzF,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,UAAU,CAAC,EAAE,iBAAiB,CAAC;CAC/B;AAED,MAAM,WAAW,gBAAgB;IAChC;;;;;OAKG;IACH,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,gBAAgB,CAAC;IAC7B,oFAAoF;IACpF,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,MAAM,EAAE,OAAO,CAAC;CAChB;AAED,4FAA4F;AAC5F,wBAAgB,oBAAoB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAE/D;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,cAAc,CAC7B,OAAO,EAAE,qBAAqB,EAC9B,aAAa,EAAE,aAAa,GAAG,SAAS,EACxC,QAAQ,EAAE,MAAM,GACd,gBAAgB,CAuBlB;AAED,MAAM,WAAW,iBAAiB;IACjC,kGAAkG;IAClG,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC;CACtC;AAED,wBAAgB,+BAA+B,IAAI,iBAAiB,CASnE;AAED,6FAA6F;AAC7F,wBAAgB,sBAAsB,CAAC,KAAK,EAAE;IAC7C,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;CACd,GAAG,MAAM,CAET;AAID;;;;;GAKG;AACH,wBAAgB,0BAA0B,CACzC,OAAO,EAAE,iBAAiB,GAAG,SAAS,EACtC,GAAG,EAAE,MAAM,EACX,qBAAqB,EAAE,MAAM,GAC3B,MAAM,GAAG,SAAS,CAKpB"}
@@ -1 +1 @@
1
- {"version":3,"file":"tool-output-packer.js","sourceRoot":"","sources":["../../../src/core/context/tool-output-packer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAiD,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAiC7G,4FAA4F;AAC5F,MAAM,UAAU,oBAAoB,CAAC,UAAkB,EAAU;IAChE,OAAO,qCAAqC,UAAU,EAAE,CAAC;AAAA,CACzD;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,cAAc,CAC7B,OAA8B,EAC9B,aAAwC,EACxC,QAAgB,EACG;IACnB,MAAM,UAAU,GAAG,YAAY,CAAC,OAAO,CAAC,UAAU,EAAE,OAAO,CAA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AC;QAAA,CACZ;KACD,CAAC;AAAA,CACF;AAED,6FAA6F;AAC7F,MAAM,UAAU,sBAAsB,CAAC,KAKtC,EAAU;IACV,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,OAAO,IAAI,EAAE,EAAE,KAAK,CAAC,IAAI,IAAI,EAAE,EAAE,KAAK,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,KAAG,CAAC,CAAC;AAAA,CAC3F;AAED,MAAM,8BAA8B,GAAG,CAAC,CAAC;AAEzC;;;;;GAKG;AACH,MAAM,UAAU,0BAA0B,CACzC,OAAsC,EACtC,GAAW,EACX,qBAA6B,EACR;IACrB,IAAI,CAAC,OAAO;QAAE,OAAO,SAAS,CAAC;IAC/B,MAAM,KAAK,GAAG,OAAO,CAAC,gBAAgB,CAAC,GAAG,CAAC,CAAC;IAC5C,IAAI,KAAK,GAAG,8BAA8B;QAAE,OAAO,SAAS,CAAC;IAC7D,OAAO,kBAAkB,qBAAqB,yCAAyC,KAAK,uDAAuD,CAAC;AAAA,CACpJ","sourcesContent":["/**\n * Tool output digesting and packing (Phase 3): \"measure -> digest/preview/artifact ->\n * prompt item\", per tool-output-artifacts.md's boundary rule. Large raw tool output is\n * captured to an artifact BEFORE truncation, so the artifact holds the exact raw payload;\n * the model only ever sees the bounded preview plus an artifact reference.\n *\n * This module is pure with respect to wiring: it takes an `ArtifactStore` by dependency\n * injection and does not know about sessions, transcripts, or prompt construction. A tool\n * (grep/find) that never passes an `ArtifactStore` gets byte-for-byte its prior behavior --\n * packing is opt-in per call site, not a global switch.\n */\n\nimport { type TruncationOptions, type TruncationResult, truncateHead } from \"@caupulican/pi-agent-core/node\";\nimport type { ArtifactStore } from \"./context-artifacts.ts\";\n\nexport interface PackToolOutputRequest {\n\ttoolName: string;\n\tcommand?: string;\n\tpath?: string;\n\trawContent: string;\n\tsessionEntryId?: string;\n\t/**\n\t * Turn number for artifact capture identity. Real session-turn wiring lands in a later\n\t * slice; callers that don't track turns yet may pass 0.\n\t */\n\tcreatedAtTurn?: number;\n\t/** Whether re-running the same tool call would reproduce this content. Default: true. */\n\treproducible?: boolean;\n\ttruncation?: TruncationOptions;\n}\n\nexport interface PackedToolOutput {\n\t/**\n\t * Bounded preview content -- exactly what `truncateHead` alone would have produced.\n\t * No footer/notice text is appended here; callers already have their own per-tool\n\t * footer conventions (grep's vs. find's bracket ordering differ) and own formatting\n\t * the artifact notice into their own notice list via `formatArtifactNotice`.\n\t */\n\tcontent: string;\n\ttruncation: TruncationResult;\n\t/** Present only if packing succeeded and the artifact is protected from cleanup. */\n\tartifactId?: string;\n\tpacked: boolean;\n}\n\n/** Footer notice text for a packed artifact, for callers to fold into their own notices. */\nexport function formatArtifactNotice(artifactId: string): string {\n\treturn `Full output: artifact tool-output:${artifactId}`;\n}\n\n/**\n * Measure `request.rawContent`; if it fits within the caps, return it unchanged (small\n * output stays exactly as readable as before this module existed). If it's oversized and\n * an `ArtifactStore` is provided, capture the exact raw payload as an artifact first, then\n * return the same bounded preview `truncateHead` would have produced anyway.\n *\n * Fails closed: if the artifact write succeeds but registering `holderId` as a reference\n * fails (`addReference` returns false), the artifact is not claimed in the result at all --\n * the caller falls back to the bounded/truncated content exactly as if no store had been\n * provided, since an unprotected artifact could be cleaned up at any time.\n */\nexport function packToolOutput(\n\trequest: PackToolOutputRequest,\n\tartifactStore: ArtifactStore | undefined,\n\tholderId: string,\n): PackedToolOutput {\n\tconst truncation = truncateHead(request.rawContent, request.truncation);\n\n\tif (!truncation.truncated || !artifactStore) {\n\t\treturn { content: truncation.content, truncation, packed: false };\n\t}\n\n\tconst { ref } = artifactStore.write({\n\t\tkind: \"tool_output\",\n\t\tcontent: request.rawContent,\n\t\ttoolName: request.toolName,\n\t\tcommand: request.command,\n\t\tpath: request.path,\n\t\tsessionEntryId: request.sessionEntryId,\n\t\tcreatedAtTurn: request.createdAtTurn ?? 0,\n\t\treproducible: request.reproducible ?? true,\n\t});\n\n\tif (!artifactStore.addReference(ref.id, holderId)) {\n\t\treturn { content: truncation.content, truncation, packed: false };\n\t}\n\n\treturn { content: truncation.content, truncation, artifactId: ref.id, packed: true };\n}\n\nexport interface BroadQueryTracker {\n\t/** Record one more broad occurrence of `key`; returns the cumulative count including this one. */\n\trecordBroadQuery(key: string): number;\n}\n\nexport function createInMemoryBroadQueryTracker(): BroadQueryTracker {\n\tconst counts = new Map<string, number>();\n\treturn {\n\t\trecordBroadQuery(key: string): number {\n\t\t\tconst next = (counts.get(key) ?? 0) + 1;\n\t\t\tcounts.set(key, next);\n\t\t\treturn next;\n\t\t},\n\t};\n}\n\n/** Normalize a search-tool call into a stable repetition key: same query, same broadness. */\nexport function normalizeBroadQueryKey(input: {\n\ttoolName: string;\n\tpattern?: string;\n\tpath?: string;\n\tglob?: string;\n}): string {\n\treturn [input.toolName, input.pattern ?? \"\", input.path ?? \"\", input.glob ?? \"\"].join(\"␟\");\n}\n\nconst REPEATED_BROAD_QUERY_THRESHOLD = 2;\n\n/**\n * When a broad-query condition (match/result limit hit, or byte truncation) repeats for\n * the same normalized query, produce a compact \"do not repeat\" style note. This is only\n * the Phase 3 signal; the durable invalidation ledger (supersession/expiry rules) is\n * Phase 6 per implementation-phases.md.\n */\nexport function broadQueryInvalidationNote(\n\ttracker: BroadQueryTracker | undefined,\n\tkey: string,\n\thumanQueryDescription: string,\n): string | undefined {\n\tif (!tracker) return undefined;\n\tconst count = tracker.recordBroadQuery(key);\n\tif (count < REPEATED_BROAD_QUERY_THRESHOLD) return undefined;\n\treturn `Do not repeat: ${humanQueryDescription} has produced broad/truncated results ${count} times in this session. Narrow the path/glob/pattern.`;\n}\n"]}
1
+ {"version":3,"file":"tool-output-packer.js","sourceRoot":"","sources":["../../../src/core/context/tool-output-packer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAiD,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAiC7G,4FAA4F;AAC5F,MAAM,UAAU,oBAAoB,CAAC,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,gBAAgB,CAAC,GAAW;YAC3B,MAAM,IAAI,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC;YACxC,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;YACtB,OAAO,IAAI,CAAC;QACb,CAAC;KACD,CAAC;AACH,CAAC;AAED,6FAA6F;AAC7F,MAAM,UAAU,sBAAsB,CAAC,KAKtC;IACA,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,OAAO,IAAI,EAAE,EAAE,KAAK,CAAC,IAAI,IAAI,EAAE,EAAE,KAAK,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC5F,CAAC;AAED,MAAM,8BAA8B,GAAG,CAAC,CAAC;AAEzC;;;;;GAKG;AACH,MAAM,UAAU,0BAA0B,CACzC,OAAsC,EACtC,GAAW,EACX,qBAA6B;IAE7B,IAAI,CAAC,OAAO;QAAE,OAAO,SAAS,CAAC;IAC/B,MAAM,KAAK,GAAG,OAAO,CAAC,gBAAgB,CAAC,GAAG,CAAC,CAAC;IAC5C,IAAI,KAAK,GAAG,8BAA8B;QAAE,OAAO,SAAS,CAAC;IAC7D,OAAO,kBAAkB,qBAAqB,yCAAyC,KAAK,uDAAuD,CAAC;AACrJ,CAAC","sourcesContent":["/**\n * Tool output digesting and packing (Phase 3): \"measure -> digest/preview/artifact ->\n * prompt item\", per tool-output-artifacts.md's boundary rule. Large raw tool output is\n * captured to an artifact BEFORE truncation, so the artifact holds the exact raw payload;\n * the model only ever sees the bounded preview plus an artifact reference.\n *\n * This module is pure with respect to wiring: it takes an `ArtifactStore` by dependency\n * injection and does not know about sessions, transcripts, or prompt construction. A tool\n * (grep/find) that never passes an `ArtifactStore` gets byte-for-byte its prior behavior --\n * packing is opt-in per call site, not a global switch.\n */\n\nimport { type TruncationOptions, type TruncationResult, truncateHead } from \"@caupulican/pi-agent-core/node\";\nimport type { ArtifactStore } from \"./context-artifacts.ts\";\n\nexport interface PackToolOutputRequest {\n\ttoolName: string;\n\tcommand?: string;\n\tpath?: string;\n\trawContent: string;\n\tsessionEntryId?: string;\n\t/**\n\t * Turn number for artifact capture identity. Real session-turn wiring lands in a later\n\t * slice; callers that don't track turns yet may pass 0.\n\t */\n\tcreatedAtTurn?: number;\n\t/** Whether re-running the same tool call would reproduce this content. Default: true. */\n\treproducible?: boolean;\n\ttruncation?: TruncationOptions;\n}\n\nexport interface PackedToolOutput {\n\t/**\n\t * Bounded preview content -- exactly what `truncateHead` alone would have produced.\n\t * No footer/notice text is appended here; callers already have their own per-tool\n\t * footer conventions (grep's vs. find's bracket ordering differ) and own formatting\n\t * the artifact notice into their own notice list via `formatArtifactNotice`.\n\t */\n\tcontent: string;\n\ttruncation: TruncationResult;\n\t/** Present only if packing succeeded and the artifact is protected from cleanup. */\n\tartifactId?: string;\n\tpacked: boolean;\n}\n\n/** Footer notice text for a packed artifact, for callers to fold into their own notices. */\nexport function formatArtifactNotice(artifactId: string): string {\n\treturn `Full output: artifact tool-output:${artifactId}`;\n}\n\n/**\n * Measure `request.rawContent`; if it fits within the caps, return it unchanged (small\n * output stays exactly as readable as before this module existed). If it's oversized and\n * an `ArtifactStore` is provided, capture the exact raw payload as an artifact first, then\n * return the same bounded preview `truncateHead` would have produced anyway.\n *\n * Fails closed: if the artifact write succeeds but registering `holderId` as a reference\n * fails (`addReference` returns false), the artifact is not claimed in the result at all --\n * the caller falls back to the bounded/truncated content exactly as if no store had been\n * provided, since an unprotected artifact could be cleaned up at any time.\n */\nexport function packToolOutput(\n\trequest: PackToolOutputRequest,\n\tartifactStore: ArtifactStore | undefined,\n\tholderId: string,\n): PackedToolOutput {\n\tconst truncation = truncateHead(request.rawContent, request.truncation);\n\n\tif (!truncation.truncated || !artifactStore) {\n\t\treturn { content: truncation.content, truncation, packed: false };\n\t}\n\n\tconst { ref } = artifactStore.write({\n\t\tkind: \"tool_output\",\n\t\tcontent: request.rawContent,\n\t\ttoolName: request.toolName,\n\t\tcommand: request.command,\n\t\tpath: request.path,\n\t\tsessionEntryId: request.sessionEntryId,\n\t\tcreatedAtTurn: request.createdAtTurn ?? 0,\n\t\treproducible: request.reproducible ?? true,\n\t});\n\n\tif (!artifactStore.addReference(ref.id, holderId)) {\n\t\treturn { content: truncation.content, truncation, packed: false };\n\t}\n\n\treturn { content: truncation.content, truncation, artifactId: ref.id, packed: true };\n}\n\nexport interface BroadQueryTracker {\n\t/** Record one more broad occurrence of `key`; returns the cumulative count including this one. */\n\trecordBroadQuery(key: string): number;\n}\n\nexport function createInMemoryBroadQueryTracker(): BroadQueryTracker {\n\tconst counts = new Map<string, number>();\n\treturn {\n\t\trecordBroadQuery(key: string): number {\n\t\t\tconst next = (counts.get(key) ?? 0) + 1;\n\t\t\tcounts.set(key, next);\n\t\t\treturn next;\n\t\t},\n\t};\n}\n\n/** Normalize a search-tool call into a stable repetition key: same query, same broadness. */\nexport function normalizeBroadQueryKey(input: {\n\ttoolName: string;\n\tpattern?: string;\n\tpath?: string;\n\tglob?: string;\n}): string {\n\treturn [input.toolName, input.pattern ?? \"\", input.path ?? \"\", input.glob ?? \"\"].join(\"␟\");\n}\n\nconst REPEATED_BROAD_QUERY_THRESHOLD = 2;\n\n/**\n * When a broad-query condition (match/result limit hit, or byte truncation) repeats for\n * the same normalized query, produce a compact \"do not repeat\" style note. This is only\n * the Phase 3 signal; the durable invalidation ledger (supersession/expiry rules) is\n * Phase 6 per implementation-phases.md.\n */\nexport function broadQueryInvalidationNote(\n\ttracker: BroadQueryTracker | undefined,\n\tkey: string,\n\thumanQueryDescription: string,\n): string | undefined {\n\tif (!tracker) return undefined;\n\tconst count = tracker.recordBroadQuery(key);\n\tif (count < REPEATED_BROAD_QUERY_THRESHOLD) return undefined;\n\treturn `Do not repeat: ${humanQueryDescription} has produced broad/truncated results ${count} times in this session. Narrow the path/glob/pattern.`;\n}\n"]}
@@ -1 +1 @@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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"]}
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;AAM9D,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;AA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