@jungjaehoon/mama-core 2.4.1 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (371) hide show
  1. package/README.md +76 -239
  2. package/db/migrations/030-case-first-memory-substrate.sql +13 -98
  3. package/db/migrations/034-add-connector-event-scope-columns.sql +9 -13
  4. package/db/migrations/039-add-connector-event-operator-ingest-seq.sql +9 -95
  5. package/db/migrations/062-refresh-connector-event-sequences.sql +9 -113
  6. package/db/migrations/063-refresh-legacy-connector-event-updates.sql +9 -32
  7. package/db/migrations/067-add-connector-event-source-entity-id.sql +9 -13
  8. package/db/migrations/069-create-registry-nodes.sql +52 -0
  9. package/db/migrations/070-record-identity.sql +35 -0
  10. package/db/migrations/071-service-operation-origins.sql +187 -0
  11. package/db/migrations/072-observation-versions.sql +29 -0
  12. package/db/migrations/073-registry-corrections.sql +45 -0
  13. package/db/migrations/074-work-graph-ref-kinds.sql +39 -0
  14. package/db/migrations/075-agent-judgments.sql +58 -0
  15. package/db/migrations/076-scoped-checkpoint-bindings.sql +15 -0
  16. package/db/migrations/077-legacy-record-kind.sql +6 -0
  17. package/db/migrations/078-source-ingest-commands.sql +18 -0
  18. package/db/migrations/079-twin-edge-relations.sql +43 -0
  19. package/db/migrations/080-restore-duration-days.sql +7 -0
  20. package/db/migrations/081-mailbox.sql +61 -0
  21. package/db/migrations/082-commitments-row-id.sql +12 -0
  22. package/db/migrations/083-observation-is-the-evidence.sql +49 -0
  23. package/db/migrations/084-scope-kind-is-not-the-cores-to-list.sql +34 -0
  24. package/db/migrations/085-a-migration-has-a-source.sql +37 -0
  25. package/db/migrations/086-the-mailbox-is-generic.sql +110 -0
  26. package/db/migrations/087-mailbox-payload.sql +5 -0
  27. package/db/migrations/088-native-input-journal.sql +14 -0
  28. package/db/migrations/089-native-turn-receipt-lookup.sql +3 -0
  29. package/db/migrations/090-model-run-native-inputs.sql +29 -0
  30. package/db/migrations/091-native-turn-results.sql +11 -0
  31. package/db/migrations/092-restore-decision-fts.sql +34 -0
  32. package/db/migrations/093-native-turn-primary-kind.sql +14 -0
  33. package/db/migrations/094-commitment-run-provenance.sql +9 -0
  34. package/db/migrations/095-model-run-native-input-identity.sql +39 -0
  35. package/db/migrations/096-drop-connector-event-index-fts.sql +9 -0
  36. package/db/migrations/097-native-input-json-validity.sql +37 -0
  37. package/db/migrations/098-workflow-memory-kind.sql +105 -0
  38. package/dist/action-contracts.d.ts +212 -0
  39. package/dist/action-contracts.js +10 -0
  40. package/dist/api/catalog.d.ts +118 -0
  41. package/dist/api/catalog.js +1756 -0
  42. package/dist/api/dispatch.d.ts +76 -0
  43. package/dist/api/dispatch.js +372 -0
  44. package/dist/canonicalize.d.ts +2 -2
  45. package/dist/canonicalize.js +3 -3
  46. package/dist/client/client.d.ts +33 -0
  47. package/dist/client/client.js +123 -0
  48. package/dist/client/ipc.d.ts +81 -0
  49. package/dist/client/ipc.js +314 -0
  50. package/dist/db-adapter/base-adapter.d.ts +6 -66
  51. package/dist/db-adapter/base-adapter.js +6 -6
  52. package/dist/db-adapter/index.d.ts +5 -5
  53. package/dist/db-adapter/index.js +2 -5
  54. package/dist/db-adapter/node-sqlite-adapter.d.ts +85 -15
  55. package/dist/db-adapter/node-sqlite-adapter.js +1968 -570
  56. package/dist/db-manager.d.ts +53 -97
  57. package/dist/db-manager.js +121 -603
  58. package/dist/embedding/embedder.d.ts +132 -0
  59. package/dist/embedding/embedder.js +299 -0
  60. package/dist/identity/principal-repository.d.ts +2 -2
  61. package/dist/index.d.ts +43 -58
  62. package/dist/index.js +97 -145
  63. package/dist/{context-compile/channel-grant.d.ts → knowledge/access.d.ts} +12 -17
  64. package/dist/knowledge/access.js +663 -0
  65. package/dist/knowledge/case-errors.d.ts +31 -0
  66. package/dist/knowledge/case-errors.js +40 -0
  67. package/dist/{cases/search-rollup.d.ts → knowledge/case-search-rollup.d.ts} +5 -4
  68. package/dist/{cases/search-rollup.js → knowledge/case-search-rollup.js} +6 -8
  69. package/dist/{cases/store.d.ts → knowledge/case-store.d.ts} +3 -6
  70. package/dist/{cases/store.js → knowledge/case-store.js} +7 -42
  71. package/dist/{cases/timeline-range.d.ts → knowledge/case-timeline-range.d.ts} +3 -3
  72. package/dist/{cases/timeline-range.js → knowledge/case-timeline-range.js} +47 -25
  73. package/dist/{cases/types.d.ts → knowledge/case-types.d.ts} +8 -2
  74. package/dist/{cases/types.js → knowledge/case-types.js} +1 -1
  75. package/dist/knowledge/commitments.d.ts +188 -0
  76. package/dist/knowledge/commitments.js +370 -0
  77. package/dist/knowledge/decision-edges.d.ts +70 -0
  78. package/dist/knowledge/decision-edges.js +123 -0
  79. package/dist/{agent-graph/types.d.ts → knowledge/graph-query.d.ts} +80 -70
  80. package/dist/knowledge/graph-query.js +1585 -0
  81. package/dist/knowledge/identity.d.ts +16 -0
  82. package/dist/knowledge/identity.js +22 -0
  83. package/dist/knowledge/index.d.ts +47 -0
  84. package/dist/knowledge/index.js +90 -0
  85. package/dist/knowledge/judgments.d.ts +118 -0
  86. package/dist/knowledge/judgments.js +808 -0
  87. package/dist/knowledge/observations.d.ts +160 -0
  88. package/dist/knowledge/observations.js +449 -0
  89. package/dist/knowledge/question-type.d.ts +34 -0
  90. package/dist/knowledge/question-type.js +70 -0
  91. package/dist/{search → knowledge}/ranker-features.js +1 -1
  92. package/dist/{search → knowledge}/search-quality.d.ts +0 -1
  93. package/dist/knowledge/search.d.ts +38 -0
  94. package/dist/knowledge/search.js +91 -0
  95. package/dist/knowledge/source-ingest.d.ts +65 -0
  96. package/dist/knowledge/source-ingest.js +174 -0
  97. package/dist/{edges/types.d.ts → knowledge/twin-edge-types.d.ts} +31 -4
  98. package/dist/{edges/types.js → knowledge/twin-edge-types.js} +13 -2
  99. package/dist/knowledge/work-dates.d.ts +49 -0
  100. package/dist/knowledge/work-dates.js +120 -0
  101. package/dist/mama-api.d.ts +114 -778
  102. package/dist/mama-api.js +313 -2461
  103. package/dist/memory/api.d.ts +264 -24
  104. package/dist/memory/api.js +1633 -843
  105. package/dist/memory/bootstrap-builder.d.ts +2 -1
  106. package/dist/memory/bootstrap-builder.js +5 -5
  107. package/dist/memory/channel-summary-state-store.d.ts +3 -2
  108. package/dist/memory/channel-summary-state-store.js +53 -51
  109. package/dist/memory/channel-summary-store.d.ts +5 -3
  110. package/dist/memory/channel-summary-store.js +3 -8
  111. package/dist/memory/dashboard-read.d.ts +46 -0
  112. package/dist/memory/dashboard-read.js +94 -0
  113. package/dist/memory/event-store.d.ts +3 -3
  114. package/dist/memory/event-store.js +3 -10
  115. package/dist/memory/finding-store.d.ts +3 -2
  116. package/dist/memory/finding-store.js +2 -7
  117. package/dist/memory/graph-read.d.ts +52 -0
  118. package/dist/memory/graph-read.js +130 -0
  119. package/dist/memory/judgment-types.d.ts +394 -0
  120. package/dist/memory/judgment-types.js +16 -0
  121. package/dist/memory/provenance-audit.d.ts +5 -2
  122. package/dist/memory/provenance-audit.js +8 -14
  123. package/dist/memory/provenance-live.d.ts +141 -0
  124. package/dist/memory/provenance-live.js +409 -0
  125. package/dist/memory/provenance-query.d.ts +5 -4
  126. package/dist/memory/provenance-query.js +21 -29
  127. package/dist/memory/provenance-resolver.d.ts +191 -0
  128. package/dist/memory/provenance-resolver.js +155 -0
  129. package/dist/memory/provenance.d.ts +1 -11
  130. package/dist/memory/provenance.js +2 -33
  131. package/dist/memory/recall-sanitize.d.ts +55 -0
  132. package/dist/memory/recall-sanitize.js +144 -0
  133. package/dist/memory/secret-filter.d.ts +32 -0
  134. package/dist/memory/secret-filter.js +126 -0
  135. package/dist/memory/truth-store.d.ts +2 -1
  136. package/dist/memory/truth-store.js +1 -4
  137. package/dist/memory/types.d.ts +74 -24
  138. package/dist/memory/types.js +75 -5
  139. package/dist/memory/write-adapters.d.ts +98 -0
  140. package/dist/memory/write-adapters.js +242 -0
  141. package/dist/operations/owner-action-effects.d.ts +53 -0
  142. package/dist/operations/owner-action-effects.js +96 -0
  143. package/dist/provenance/source-ref.d.ts +1 -1
  144. package/dist/provenance/source-ref.js +0 -2
  145. package/dist/registry/corrections.d.ts +31 -0
  146. package/dist/registry/corrections.js +332 -0
  147. package/dist/registry/record-identity.d.ts +49 -0
  148. package/dist/registry/record-identity.js +133 -0
  149. package/dist/registry/store.d.ts +101 -0
  150. package/dist/registry/store.js +395 -0
  151. package/dist/registry/types.d.ts +28 -0
  152. package/dist/registry/types.js +5 -0
  153. package/dist/relevance-scorer.js +2 -2
  154. package/dist/runtime/agent-event-bus.d.ts +50 -0
  155. package/dist/runtime/agent-event-bus.js +101 -0
  156. package/dist/runtime/drivers/claude-cli-wrapper.d.ts +155 -0
  157. package/dist/runtime/drivers/claude-cli-wrapper.js +392 -0
  158. package/dist/runtime/drivers/cli-arg-redaction.d.ts +2 -0
  159. package/dist/runtime/drivers/cli-arg-redaction.js +18 -0
  160. package/dist/runtime/drivers/cli-secret-redaction.d.ts +17 -0
  161. package/dist/runtime/drivers/cli-secret-redaction.js +126 -0
  162. package/dist/runtime/drivers/codex-app-server-process.d.ts +277 -0
  163. package/dist/runtime/drivers/codex-app-server-process.js +2342 -0
  164. package/dist/runtime/drivers/codex-auxiliary-tools.d.ts +17 -0
  165. package/dist/runtime/drivers/codex-auxiliary-tools.js +267 -0
  166. package/dist/runtime/drivers/codex-home.d.ts +20 -0
  167. package/dist/runtime/drivers/codex-home.js +674 -0
  168. package/dist/runtime/drivers/codex-thread-registry.d.ts +63 -0
  169. package/dist/runtime/drivers/codex-thread-registry.js +433 -0
  170. package/dist/runtime/drivers/persistent-cli-adapter.d.ts +160 -0
  171. package/dist/runtime/drivers/persistent-cli-adapter.js +396 -0
  172. package/dist/runtime/drivers/persistent-cli-process.d.ts +424 -0
  173. package/dist/runtime/drivers/persistent-cli-process.js +1543 -0
  174. package/dist/runtime/drivers/types.d.ts +456 -0
  175. package/dist/runtime/drivers/types.js +110 -0
  176. package/dist/runtime/mailbox.d.ts +223 -0
  177. package/dist/runtime/mailbox.js +582 -0
  178. package/dist/runtime/model-run-store.d.ts +28 -0
  179. package/dist/{model-runs/store.js → runtime/model-run-store.js} +81 -41
  180. package/dist/{model-runs/types.d.ts → runtime/model-run-types.d.ts} +33 -4
  181. package/dist/{model-runs/types.js → runtime/model-run-types.js} +1 -1
  182. package/dist/runtime/native-effect-observer.d.ts +22 -0
  183. package/dist/runtime/native-effect-observer.js +103 -0
  184. package/dist/runtime/native-input-journal.d.ts +46 -0
  185. package/dist/runtime/native-input-journal.js +308 -0
  186. package/dist/runtime/native-prompt.d.ts +118 -0
  187. package/dist/runtime/native-prompt.js +496 -0
  188. package/dist/runtime/native-session.d.ts +10 -0
  189. package/dist/{agent-graph/index.js → runtime/native-session.js} +9 -6
  190. package/dist/runtime/native-tool-trace-observer.d.ts +5 -0
  191. package/dist/runtime/native-tool-trace-observer.js +65 -0
  192. package/dist/runtime/native-turn.d.ts +272 -0
  193. package/dist/runtime/native-turn.js +1041 -0
  194. package/dist/runtime/operations.d.ts +236 -0
  195. package/dist/runtime/operations.js +565 -0
  196. package/dist/runtime/post-tool-handler.d.ts +74 -0
  197. package/dist/runtime/post-tool-handler.js +137 -0
  198. package/dist/runtime/prompt-layers.d.ts +126 -0
  199. package/dist/runtime/prompt-layers.js +239 -0
  200. package/dist/runtime/runtime-process.d.ts +102 -0
  201. package/dist/runtime/runtime-process.js +206 -0
  202. package/dist/runtime/runtime.d.ts +278 -0
  203. package/dist/runtime/runtime.js +563 -0
  204. package/dist/runtime/session-pool.d.ts +176 -0
  205. package/dist/runtime/session-pool.js +369 -0
  206. package/dist/runtime/stimulus-payload.d.ts +5 -0
  207. package/dist/runtime/stimulus-payload.js +50 -0
  208. package/dist/runtime/subagent-bridge.d.ts +24 -0
  209. package/dist/{agent-graph/types.js → runtime/subagent-bridge.js} +1 -1
  210. package/dist/runtime/text-completion.d.ts +22 -0
  211. package/dist/{agent-situation/types.js → runtime/text-completion.js} +1 -1
  212. package/dist/runtime/token-estimator.d.ts +25 -0
  213. package/dist/runtime/token-estimator.js +75 -0
  214. package/dist/runtime/tool-trace-store.d.ts +22 -0
  215. package/dist/{model-runs → runtime}/tool-trace-store.js +46 -27
  216. package/dist/runtime/trace-summary.d.ts +5 -0
  217. package/dist/runtime/trace-summary.js +74 -0
  218. package/dist/runtime/turn-text.d.ts +23 -0
  219. package/dist/runtime/turn-text.js +41 -0
  220. package/dist/storage/database.d.ts +67 -0
  221. package/dist/storage/database.js +158 -0
  222. package/package.json +20 -34
  223. package/dist/agent-graph/alias-write.d.ts +0 -3
  224. package/dist/agent-graph/alias-write.js +0 -234
  225. package/dist/agent-graph/entity-resolve.d.ts +0 -3
  226. package/dist/agent-graph/entity-resolve.js +0 -271
  227. package/dist/agent-graph/errors.d.ts +0 -4
  228. package/dist/agent-graph/errors.js +0 -11
  229. package/dist/agent-graph/graph-query.d.ts +0 -5
  230. package/dist/agent-graph/graph-query.js +0 -360
  231. package/dist/agent-graph/index.d.ts +0 -6
  232. package/dist/agent-situation/builder.d.ts +0 -8
  233. package/dist/agent-situation/builder.js +0 -239
  234. package/dist/agent-situation/cache-key.d.ts +0 -4
  235. package/dist/agent-situation/cache-key.js +0 -64
  236. package/dist/agent-situation/index.d.ts +0 -7
  237. package/dist/agent-situation/index.js +0 -28
  238. package/dist/agent-situation/packet-store.d.ts +0 -27
  239. package/dist/agent-situation/packet-store.js +0 -228
  240. package/dist/agent-situation/ranking-policy.d.ts +0 -18
  241. package/dist/agent-situation/ranking-policy.js +0 -75
  242. package/dist/agent-situation/source-readers.d.ts +0 -52
  243. package/dist/agent-situation/source-readers.js +0 -300
  244. package/dist/agent-situation/types.d.ts +0 -195
  245. package/dist/cases/wiki-page-index.d.ts +0 -37
  246. package/dist/cases/wiki-page-index.js +0 -201
  247. package/dist/config-loader.d.ts +0 -68
  248. package/dist/config-loader.js +0 -239
  249. package/dist/connectors/event-index.d.ts +0 -24
  250. package/dist/connectors/event-index.js +0 -245
  251. package/dist/connectors/raw-query.d.ts +0 -40
  252. package/dist/connectors/raw-query.js +0 -412
  253. package/dist/connectors/types.d.ts +0 -117
  254. package/dist/connectors/types.js +0 -3
  255. package/dist/context-compile/boundary-defaults.d.ts +0 -12
  256. package/dist/context-compile/boundary-defaults.js +0 -105
  257. package/dist/context-compile/channel-grant.js +0 -66
  258. package/dist/context-compile/compiler-policy.d.ts +0 -39
  259. package/dist/context-compile/compiler-policy.js +0 -147
  260. package/dist/context-compile/compiler.d.ts +0 -18
  261. package/dist/context-compile/compiler.js +0 -404
  262. package/dist/context-compile/index.d.ts +0 -10
  263. package/dist/context-compile/index.js +0 -26
  264. package/dist/context-compile/packet-store.d.ts +0 -8
  265. package/dist/context-compile/packet-store.js +0 -239
  266. package/dist/context-compile/ref.d.ts +0 -7
  267. package/dist/context-compile/ref.js +0 -102
  268. package/dist/context-compile/source-readers.d.ts +0 -70
  269. package/dist/context-compile/source-readers.js +0 -840
  270. package/dist/context-compile/types.d.ts +0 -155
  271. package/dist/context-compile/types.js +0 -11
  272. package/dist/context-compile/visibility.d.ts +0 -21
  273. package/dist/context-compile/visibility.js +0 -224
  274. package/dist/decision-tracker.d.ts +0 -206
  275. package/dist/decision-tracker.js +0 -481
  276. package/dist/edges/ref-validation.d.ts +0 -7
  277. package/dist/edges/ref-validation.js +0 -321
  278. package/dist/edges/store.d.ts +0 -8
  279. package/dist/edges/store.js +0 -129
  280. package/dist/embedding-client.d.ts +0 -28
  281. package/dist/embedding-client.js +0 -53
  282. package/dist/embedding-server/index.d.ts +0 -67
  283. package/dist/embedding-server/index.js +0 -405
  284. package/dist/embedding-server/mobile/auth.d.ts +0 -44
  285. package/dist/embedding-server/mobile/auth.js +0 -150
  286. package/dist/embedding-server/mobile/daemon.d.ts +0 -129
  287. package/dist/embedding-server/mobile/daemon.js +0 -313
  288. package/dist/embedding-server/mobile/output-parser.d.ts +0 -115
  289. package/dist/embedding-server/mobile/output-parser.js +0 -241
  290. package/dist/embedding-server/mobile/session-api.d.ts +0 -57
  291. package/dist/embedding-server/mobile/session-api.js +0 -261
  292. package/dist/embedding-server/mobile/session-manager.d.ts +0 -138
  293. package/dist/embedding-server/mobile/session-manager.js +0 -378
  294. package/dist/embedding-server/mobile/websocket-handler.d.ts +0 -137
  295. package/dist/embedding-server/mobile/websocket-handler.js +0 -486
  296. package/dist/embeddings.d.ts +0 -68
  297. package/dist/embeddings.js +0 -244
  298. package/dist/entities/audit-metrics.d.ts +0 -68
  299. package/dist/entities/audit-metrics.js +0 -124
  300. package/dist/entities/candidate-generator.d.ts +0 -8
  301. package/dist/entities/candidate-generator.js +0 -24
  302. package/dist/entities/entity-linked-decision-counts.d.ts +0 -2
  303. package/dist/entities/entity-linked-decision-counts.js +0 -29
  304. package/dist/entities/entity-list.d.ts +0 -22
  305. package/dist/entities/entity-list.js +0 -3
  306. package/dist/entities/entity-orphan-list.d.ts +0 -17
  307. package/dist/entities/entity-orphan-list.js +0 -3
  308. package/dist/entities/entity-search.d.ts +0 -20
  309. package/dist/entities/entity-search.js +0 -3
  310. package/dist/entities/errors.d.ts +0 -55
  311. package/dist/entities/errors.js +0 -100
  312. package/dist/entities/lineage-store.d.ts +0 -28
  313. package/dist/entities/lineage-store.js +0 -204
  314. package/dist/entities/normalization.d.ts +0 -14
  315. package/dist/entities/normalization.js +0 -63
  316. package/dist/entities/policy-store.d.ts +0 -8
  317. package/dist/entities/policy-store.js +0 -75
  318. package/dist/entities/policy-types.d.ts +0 -72
  319. package/dist/entities/policy-types.js +0 -59
  320. package/dist/entities/projection.d.ts +0 -8
  321. package/dist/entities/projection.js +0 -82
  322. package/dist/entities/provenance-query.d.ts +0 -32
  323. package/dist/entities/provenance-query.js +0 -3
  324. package/dist/entities/read-identity.d.ts +0 -31
  325. package/dist/entities/read-identity.js +0 -264
  326. package/dist/entities/recall-bridge.d.ts +0 -5
  327. package/dist/entities/recall-bridge.js +0 -171
  328. package/dist/entities/resolution-engine.d.ts +0 -8
  329. package/dist/entities/resolution-engine.js +0 -3
  330. package/dist/entities/rollback-preview.d.ts +0 -35
  331. package/dist/entities/rollback-preview.js +0 -3
  332. package/dist/entities/source-locator.d.ts +0 -3
  333. package/dist/entities/source-locator.js +0 -32
  334. package/dist/entities/store.d.ts +0 -69
  335. package/dist/entities/store.js +0 -544
  336. package/dist/entities/types.d.ts +0 -166
  337. package/dist/entities/types.js +0 -30
  338. package/dist/memory/extraction-prompt.d.ts +0 -4
  339. package/dist/memory/extraction-prompt.js +0 -89
  340. package/dist/memory/scope-backfill.d.ts +0 -14
  341. package/dist/memory/scope-backfill.js +0 -3
  342. package/dist/memory/scope-store.d.ts +0 -4
  343. package/dist/memory/scope-store.js +0 -9
  344. package/dist/memory-store.d.ts +0 -87
  345. package/dist/memory-store.js +0 -78
  346. package/dist/model-runs/store.d.ts +0 -13
  347. package/dist/model-runs/tool-trace-store.d.ts +0 -8
  348. package/dist/notification-manager.d.ts +0 -7
  349. package/dist/notification-manager.js +0 -12
  350. package/dist/outcome-tracker.d.ts +0 -151
  351. package/dist/outcome-tracker.js +0 -271
  352. package/dist/query-intent.d.ts +0 -23
  353. package/dist/query-intent.js +0 -114
  354. package/dist/runtime/trusted-provenance.d.ts +0 -3
  355. package/dist/runtime/trusted-provenance.js +0 -6
  356. package/dist/search/question-type.d.ts +0 -5
  357. package/dist/search/question-type.js +0 -41
  358. package/dist/test-utils.d.ts +0 -80
  359. package/dist/test-utils.js +0 -218
  360. package/dist/tier-validator.d.ts +0 -43
  361. package/dist/tier-validator.js +0 -159
  362. package/dist/time-formatter.d.ts +0 -25
  363. package/dist/time-formatter.js +0 -93
  364. /package/dist/{search → knowledge}/feedback-store.d.ts +0 -0
  365. /package/dist/{search → knowledge}/feedback-store.js +0 -0
  366. /package/dist/{search → knowledge}/ranker-features.d.ts +0 -0
  367. /package/dist/{search → knowledge}/ranker-rescore.d.ts +0 -0
  368. /package/dist/{search → knowledge}/ranker-rescore.js +0 -0
  369. /package/dist/{search → knowledge}/ranker-trainer.d.ts +0 -0
  370. /package/dist/{search → knowledge}/ranker-trainer.js +0 -0
  371. /package/dist/{search → knowledge}/search-quality.js +0 -0
@@ -1,3 +1,4 @@
1
+ import type { DatabaseAdapter } from '../db-manager.js';
1
2
  import type { MemoryAgentBootstrap, MemoryScopeRef } from './types.js';
2
3
  interface BuildMemoryAgentBootstrapParams {
3
4
  scopes: MemoryScopeRef[];
@@ -5,6 +6,6 @@ interface BuildMemoryAgentBootstrapParams {
5
6
  currentGoal?: string;
6
7
  mainAgentState?: MemoryAgentBootstrap['main_agent_state'];
7
8
  }
8
- export declare function buildMemoryAgentBootstrap(params: BuildMemoryAgentBootstrapParams): Promise<MemoryAgentBootstrap>;
9
+ export declare function buildMemoryAgentBootstrap(adapter: DatabaseAdapter, params: BuildMemoryAgentBootstrapParams): Promise<MemoryAgentBootstrap>;
9
10
  export {};
10
11
  //# sourceMappingURL=bootstrap-builder.d.ts.map
@@ -6,16 +6,16 @@ const finding_store_js_1 = require("./finding-store.js");
6
6
  const profile_builder_js_1 = require("./profile-builder.js");
7
7
  const truth_store_js_1 = require("./truth-store.js");
8
8
  const channel_summary_store_js_1 = require("./channel-summary-store.js");
9
- async function buildMemoryAgentBootstrap(params) {
9
+ async function buildMemoryAgentBootstrap(adapter, params) {
10
10
  const [truthRows, findings, recentEvents, channelSummary] = await Promise.all([
11
- (0, truth_store_js_1.queryRelevantTruth)({
11
+ (0, truth_store_js_1.queryRelevantTruth)(adapter, {
12
12
  query: '',
13
13
  scopes: params.scopes,
14
14
  includeHistory: false,
15
15
  }),
16
- (0, finding_store_js_1.listOpenAuditFindings)(),
17
- (0, event_store_js_1.listRecentMemoryEvents)(10),
18
- params.channelKey ? (0, channel_summary_store_js_1.getChannelSummary)(params.channelKey) : Promise.resolve(null),
16
+ (0, finding_store_js_1.listOpenAuditFindings)(adapter),
17
+ (0, event_store_js_1.listRecentMemoryEvents)(adapter, 10),
18
+ params.channelKey ? (0, channel_summary_store_js_1.getChannelSummary)(adapter, params.channelKey) : Promise.resolve(null),
19
19
  ]);
20
20
  const scopedTruth = truthRows.filter((row) => row.scope_refs.some((scopeRef) => params.scopes.some((scope) => scope.kind === scopeRef.kind && scope.id === scopeRef.id)));
21
21
  const profile = (0, profile_builder_js_1.classifyProfileEntries)(scopedTruth.map((row) => ({
@@ -1,6 +1,7 @@
1
+ import type { DatabaseAdapter } from '../db-manager.js';
1
2
  import type { ChannelSummaryStateRecord, MemoryAuditAck, MemoryScopeRef } from './types.js';
2
- export declare function getChannelSummaryState(channelKey: string): Promise<ChannelSummaryStateRecord | null>;
3
- export declare function recordChannelAudit(input: {
3
+ export declare function getChannelSummaryState(adapter: DatabaseAdapter, channelKey: string): Promise<ChannelSummaryStateRecord | null>;
4
+ export declare function recordChannelAudit(adapter: DatabaseAdapter, input: {
4
5
  channelKey: string;
5
6
  turnId: string;
6
7
  topic: string;
@@ -6,7 +6,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.getChannelSummaryState = getChannelSummaryState;
7
7
  exports.recordChannelAudit = recordChannelAudit;
8
8
  const node_crypto_1 = __importDefault(require("node:crypto"));
9
- const db_manager_js_1 = require("../db-manager.js");
10
9
  const channel_summary_store_js_1 = require("./channel-summary-store.js");
11
10
  const event_store_js_1 = require("./event-store.js");
12
11
  const finding_store_js_1 = require("./finding-store.js");
@@ -143,9 +142,7 @@ function reduceState(previous, input) {
143
142
  state_hash: stateHash,
144
143
  };
145
144
  }
146
- async function getChannelSummaryState(channelKey) {
147
- await (0, db_manager_js_1.initDB)();
148
- const adapter = (0, db_manager_js_1.getAdapter)();
145
+ async function getChannelSummaryState(adapter, channelKey) {
149
146
  const row = adapter
150
147
  .prepare(`
151
148
  SELECT channel_key, state_json, state_hash, updated_at
@@ -155,68 +152,73 @@ async function getChannelSummaryState(channelKey) {
155
152
  .get(channelKey);
156
153
  return row ? deserializeState(row) : null;
157
154
  }
158
- async function recordChannelAudit(input) {
159
- await (0, db_manager_js_1.initDB)();
160
- const adapter = (0, db_manager_js_1.getAdapter)();
155
+ async function recordChannelAudit(adapter, input) {
161
156
  const timestamp = Date.now();
162
- const legacySummary = await (0, channel_summary_store_js_1.getChannelSummary)(input.channelKey);
163
- const previous = (await getChannelSummaryState(input.channelKey)) ??
157
+ const legacySummary = await (0, channel_summary_store_js_1.getChannelSummary)(adapter, input.channelKey);
158
+ const previous = (await getChannelSummaryState(adapter, input.channelKey)) ??
164
159
  (legacySummary
165
160
  ? createLegacySeedState(input.channelKey, legacySummary)
166
161
  : createEmptyState(input.channelKey));
167
- const eventIds = [];
168
- const findingIds = [];
169
162
  const eventType = input.ack.status === 'failed'
170
163
  ? 'audit_failed'
171
164
  : input.ack.action === 'no_op'
172
165
  ? 'no_op'
173
166
  : input.ack.action;
174
- eventIds.push(await (0, event_store_js_1.appendMemoryEvent)({
175
- event_type: eventType,
176
- actor: 'memory_agent',
177
- source_turn_id: input.turnId,
178
- memory_id: input.savedMemories?.[0]?.id,
179
- topic: input.topic,
180
- scope_refs: input.scopeRefs,
181
- reason: input.ack.reason,
182
- created_at: timestamp,
183
- }));
184
- if (input.ack.status === 'failed') {
185
- findingIds.push(await (0, finding_store_js_1.createAuditFinding)({
186
- kind: 'unsupported_claim',
187
- severity: 'high',
188
- summary: input.ack.reason ?? `memory audit failed for ${input.topic}`,
189
- evidence_refs: eventIds,
190
- affected_memory_ids: input.savedMemories?.map((memory) => memory.id) ?? [],
191
- recommended_action: 'consult_memory',
192
- }));
193
- }
194
167
  const state = reduceState(previous, {
195
168
  topic: input.topic,
196
169
  ack: input.ack,
197
170
  savedMemories: input.savedMemories,
198
171
  timestamp,
199
172
  });
200
- adapter
201
- .prepare(`
202
- INSERT OR REPLACE INTO channel_summary_state (
203
- channel_key,
204
- state_json,
205
- state_hash,
206
- updated_at
207
- )
208
- VALUES (?, ?, ?, ?)
209
- `)
210
- .run(input.channelKey, JSON.stringify({
211
- active_topic: state.active_topic,
212
- active_decisions: state.active_decisions,
213
- recent_milestones: state.recent_milestones,
214
- recent_audit_outcomes: state.recent_audit_outcomes,
215
- }), state.state_hash, timestamp);
216
- await (0, channel_summary_store_js_1.upsertChannelSummary)({
217
- channelKey: input.channelKey,
218
- summaryMarkdown: renderChannelSummaryMarkdown(state),
219
- deltaHash: state.state_hash,
173
+ // One audit produces an event, its finding, the reduced state and the legacy
174
+ // summary. Written separately, a failure after the first leaves an event whose
175
+ // finding never existed - a record asserting something with nothing behind it.
176
+ const { eventIds, findingIds } = adapter.transaction(() => {
177
+ const events = [];
178
+ const findings = [];
179
+ events.push((0, event_store_js_1.insertMemoryEventInTransaction)(adapter, {
180
+ event_type: eventType,
181
+ actor: 'memory_agent',
182
+ source_turn_id: input.turnId,
183
+ memory_id: input.savedMemories?.[0]?.id,
184
+ topic: input.topic,
185
+ scope_refs: input.scopeRefs,
186
+ reason: input.ack.reason,
187
+ created_at: timestamp,
188
+ }));
189
+ if (input.ack.status === 'failed') {
190
+ findings.push((0, finding_store_js_1.createAuditFinding)(adapter, {
191
+ kind: 'unsupported_claim',
192
+ severity: 'high',
193
+ summary: input.ack.reason ?? `memory audit failed for ${input.topic}`,
194
+ evidence_refs: events,
195
+ affected_memory_ids: input.savedMemories?.map((memory) => memory.id) ?? [],
196
+ recommended_action: 'consult_memory',
197
+ }));
198
+ }
199
+ adapter
200
+ .prepare(`
201
+ INSERT OR REPLACE INTO channel_summary_state (
202
+ channel_key,
203
+ state_json,
204
+ state_hash,
205
+ updated_at
206
+ )
207
+ VALUES (?, ?, ?, ?)
208
+ `)
209
+ .run(input.channelKey, JSON.stringify({
210
+ active_topic: state.active_topic,
211
+ active_decisions: state.active_decisions,
212
+ recent_milestones: state.recent_milestones,
213
+ recent_audit_outcomes: state.recent_audit_outcomes,
214
+ }), state.state_hash, timestamp);
215
+ (0, channel_summary_store_js_1.upsertChannelSummary)(adapter, {
216
+ channelKey: input.channelKey,
217
+ summaryMarkdown: renderChannelSummaryMarkdown(state),
218
+ deltaHash: state.state_hash,
219
+ updatedAt: timestamp,
220
+ });
221
+ return { eventIds: events, findingIds: findings };
220
222
  });
221
223
  return { eventIds, findingIds, state };
222
224
  }
@@ -1,8 +1,10 @@
1
+ import type { DatabaseAdapter } from '../db-manager.js';
1
2
  import type { ChannelSummaryRecord } from './types.js';
2
- export declare function upsertChannelSummary(input: {
3
+ export declare function upsertChannelSummary(adapter: Pick<DatabaseAdapter, 'prepare'>, input: {
3
4
  channelKey: string;
4
5
  summaryMarkdown: string;
5
6
  deltaHash?: string;
6
- }): Promise<void>;
7
- export declare function getChannelSummary(channelKey: string): Promise<ChannelSummaryRecord | null>;
7
+ updatedAt?: number;
8
+ }): void;
9
+ export declare function getChannelSummary(adapter: DatabaseAdapter, channelKey: string): Promise<ChannelSummaryRecord | null>;
8
10
  //# sourceMappingURL=channel-summary-store.d.ts.map
@@ -2,7 +2,6 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.upsertChannelSummary = upsertChannelSummary;
4
4
  exports.getChannelSummary = getChannelSummary;
5
- const db_manager_js_1 = require("../db-manager.js");
6
5
  function toChannelSummary(row) {
7
6
  return {
8
7
  channel_key: String(row.channel_key),
@@ -11,9 +10,7 @@ function toChannelSummary(row) {
11
10
  updated_at: Number(row.updated_at),
12
11
  };
13
12
  }
14
- async function upsertChannelSummary(input) {
15
- await (0, db_manager_js_1.initDB)();
16
- const adapter = (0, db_manager_js_1.getAdapter)();
13
+ function upsertChannelSummary(adapter, input) {
17
14
  adapter
18
15
  .prepare(`
19
16
  INSERT OR REPLACE INTO channel_summaries (
@@ -24,11 +21,9 @@ async function upsertChannelSummary(input) {
24
21
  )
25
22
  VALUES (?, ?, ?, ?)
26
23
  `)
27
- .run(input.channelKey, input.summaryMarkdown, input.deltaHash ?? null, Date.now());
24
+ .run(input.channelKey, input.summaryMarkdown, input.deltaHash ?? null, input.updatedAt ?? Date.now());
28
25
  }
29
- async function getChannelSummary(channelKey) {
30
- await (0, db_manager_js_1.initDB)();
31
- const adapter = (0, db_manager_js_1.getAdapter)();
26
+ async function getChannelSummary(adapter, channelKey) {
32
27
  const row = adapter
33
28
  .prepare(`
34
29
  SELECT channel_key, summary_markdown, delta_hash, updated_at
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Listings and rollups over the memory a caller may see.
3
+ *
4
+ * The dashboard asked these of the database directly: which decisions are
5
+ * active and going stale, what changed recently, which projects are busy, and
6
+ * what one project holds. They are reads, so they answer to the caller's
7
+ * scopes — the same join every other admitted read stands on. A principal that
8
+ * admits nothing gets empty lists rather than the whole file.
9
+ */
10
+ import { type DatabaseAdapter } from '../db-manager.js';
11
+ export interface DecisionListingRow {
12
+ id: string;
13
+ topic: string;
14
+ decision: string;
15
+ reasoning?: string | null;
16
+ status: string | null;
17
+ confidence?: number | null;
18
+ created_at: number;
19
+ updated_at: number;
20
+ }
21
+ export interface ProjectRollup {
22
+ project: string;
23
+ activeDecisions: number;
24
+ lastActivity: number;
25
+ }
26
+ export interface ReadScope {
27
+ kind: string;
28
+ id: string;
29
+ }
30
+ /**
31
+ * Recent or stale decisions under the admitted scopes.
32
+ *
33
+ * `order: 'stale'` puts the least recently touched first — what the dashboard
34
+ * calls an alert. `order: 'recent'` is the activity feed. `status` narrows to
35
+ * one lifecycle state when the caller names it.
36
+ */
37
+ export declare function readDecisionListing(adapter: DatabaseAdapter, scopes: readonly ReadScope[], options?: {
38
+ status?: string;
39
+ order?: 'recent' | 'stale';
40
+ limit?: number;
41
+ }): Promise<DecisionListingRow[]>;
42
+ /** Per-project active-decision counts and last activity, over admitted scopes. */
43
+ export declare function readProjectRollups(adapter: DatabaseAdapter, scopes: readonly ReadScope[]): Promise<ProjectRollup[]>;
44
+ /** What one project holds, still bounded by what the caller admits. */
45
+ export declare function readProjectDecisions(adapter: DatabaseAdapter, scopes: readonly ReadScope[], project: string, limit?: number): Promise<DecisionListingRow[]>;
46
+ //# sourceMappingURL=dashboard-read.d.ts.map
@@ -0,0 +1,94 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.readDecisionListing = readDecisionListing;
4
+ exports.readProjectRollups = readProjectRollups;
5
+ exports.readProjectDecisions = readProjectDecisions;
6
+ /**
7
+ * Listings and rollups over the memory a caller may see.
8
+ *
9
+ * The dashboard asked these of the database directly: which decisions are
10
+ * active and going stale, what changed recently, which projects are busy, and
11
+ * what one project holds. They are reads, so they answer to the caller's
12
+ * scopes — the same join every other admitted read stands on. A principal that
13
+ * admits nothing gets empty lists rather than the whole file.
14
+ */
15
+ const db_manager_js_1 = require("../db-manager.js");
16
+ async function admittedScopeIds(adapter, scopes) {
17
+ return Promise.all(scopes.map((scope) => (0, db_manager_js_1.ensureMemoryScope)(adapter, scope.kind, scope.id)));
18
+ }
19
+ /**
20
+ * Recent or stale decisions under the admitted scopes.
21
+ *
22
+ * `order: 'stale'` puts the least recently touched first — what the dashboard
23
+ * calls an alert. `order: 'recent'` is the activity feed. `status` narrows to
24
+ * one lifecycle state when the caller names it.
25
+ */
26
+ async function readDecisionListing(adapter, scopes, options = {}) {
27
+ if (scopes.length === 0) {
28
+ return [];
29
+ }
30
+ const scopeIds = await admittedScopeIds(adapter, scopes);
31
+ const placeholders = scopeIds.map(() => '?').join(', ');
32
+ const status = typeof options.status === 'string' ? options.status.trim() : '';
33
+ const direction = options.order === 'stale' ? 'ASC' : 'DESC';
34
+ const limit = Math.min(Math.max(Math.floor(options.limit ?? 50), 1), 200);
35
+ return (await adapter
36
+ .prepare(`SELECT DISTINCT d.id, d.topic, d.decision, d.reasoning, d.status, d.confidence,
37
+ d.created_at, d.updated_at
38
+ FROM decisions d
39
+ JOIN memory_scope_bindings msb ON msb.memory_id = d.id
40
+ WHERE msb.scope_id IN (${placeholders})
41
+ ${status ? 'AND d.status = ?' : ''}
42
+ ORDER BY d.updated_at ${direction}
43
+ LIMIT ?`)
44
+ .all(...scopeIds, ...(status ? [status] : []), limit));
45
+ }
46
+ /** Per-project active-decision counts and last activity, over admitted scopes. */
47
+ async function readProjectRollups(adapter, scopes) {
48
+ if (scopes.length === 0) {
49
+ return [];
50
+ }
51
+ const scopeIds = await admittedScopeIds(adapter, scopes);
52
+ const placeholders = scopeIds.map(() => '?').join(', ');
53
+ return (await adapter
54
+ .prepare(`SELECT ms.external_id AS project,
55
+ COUNT(DISTINCT d.id) AS activeDecisions,
56
+ MAX(d.updated_at) AS lastActivity
57
+ FROM memory_scopes ms
58
+ JOIN memory_scope_bindings msb ON msb.scope_id = ms.id
59
+ JOIN decisions d ON d.id = msb.memory_id
60
+ WHERE ms.kind = 'project'
61
+ AND d.status = 'active'
62
+ AND EXISTS (
63
+ SELECT 1 FROM memory_scope_bindings admitted
64
+ WHERE admitted.memory_id = d.id AND admitted.scope_id IN (${placeholders})
65
+ )
66
+ GROUP BY ms.external_id
67
+ ORDER BY lastActivity DESC`)
68
+ .all(...scopeIds));
69
+ }
70
+ /** What one project holds, still bounded by what the caller admits. */
71
+ async function readProjectDecisions(adapter, scopes, project, limit = 50) {
72
+ if (scopes.length === 0 || project.trim() === '') {
73
+ return [];
74
+ }
75
+ const scopeIds = await admittedScopeIds(adapter, scopes);
76
+ const placeholders = scopeIds.map(() => '?').join(', ');
77
+ const bounded = Math.min(Math.max(Math.floor(limit), 1), 200);
78
+ return (await adapter
79
+ .prepare(`SELECT DISTINCT d.id, d.topic, d.decision, d.reasoning, d.status, d.confidence,
80
+ d.created_at, d.updated_at
81
+ FROM decisions d
82
+ JOIN memory_scope_bindings msb ON msb.memory_id = d.id
83
+ JOIN memory_scopes ms ON ms.id = msb.scope_id
84
+ WHERE ms.kind = 'project'
85
+ AND ms.external_id = ?
86
+ AND EXISTS (
87
+ SELECT 1 FROM memory_scope_bindings admitted
88
+ WHERE admitted.memory_id = d.id AND admitted.scope_id IN (${placeholders})
89
+ )
90
+ ORDER BY d.updated_at DESC
91
+ LIMIT ?`)
92
+ .all(project, ...scopeIds, bounded));
93
+ }
94
+ //# sourceMappingURL=dashboard-read.js.map
@@ -1,7 +1,7 @@
1
1
  import type { DatabaseAdapter } from '../db-manager.js';
2
2
  import type { MemoryEventRecord } from './types.js';
3
- export declare function appendMemoryEvent(input: Omit<MemoryEventRecord, 'event_id'>): Promise<string>;
3
+ export declare function appendMemoryEvent(adapter: DatabaseAdapter, input: Omit<MemoryEventRecord, 'event_id'>): Promise<string>;
4
4
  export declare function insertMemoryEventInTransaction(adapter: Pick<DatabaseAdapter, 'prepare'>, input: Omit<MemoryEventRecord, 'event_id'>): string;
5
- export declare function listMemoryEventsForMemory(memoryId: string): Promise<MemoryEventRecord[]>;
6
- export declare function listRecentMemoryEvents(limit?: number): Promise<MemoryEventRecord[]>;
5
+ export declare function listMemoryEventsForMemory(adapter: Pick<DatabaseAdapter, 'prepare'>, memoryId: string): Promise<MemoryEventRecord[]>;
6
+ export declare function listRecentMemoryEvents(adapter: Pick<DatabaseAdapter, 'prepare'>, limit?: number): Promise<MemoryEventRecord[]>;
7
7
  //# sourceMappingURL=event-store.d.ts.map
@@ -8,7 +8,6 @@ exports.insertMemoryEventInTransaction = insertMemoryEventInTransaction;
8
8
  exports.listMemoryEventsForMemory = listMemoryEventsForMemory;
9
9
  exports.listRecentMemoryEvents = listRecentMemoryEvents;
10
10
  const node_crypto_1 = __importDefault(require("node:crypto"));
11
- const db_manager_js_1 = require("../db-manager.js");
12
11
  function deserializeEvent(row) {
13
12
  return {
14
13
  event_id: String(row.event_id),
@@ -27,9 +26,7 @@ function deserializeEvent(row) {
27
26
  created_at: Number(row.created_at),
28
27
  };
29
28
  }
30
- async function appendMemoryEvent(input) {
31
- await (0, db_manager_js_1.initDB)();
32
- const adapter = (0, db_manager_js_1.getAdapter)();
29
+ async function appendMemoryEvent(adapter, input) {
33
30
  return insertMemoryEventInTransaction(adapter, input);
34
31
  }
35
32
  function insertMemoryEventInTransaction(adapter, input) {
@@ -45,9 +42,7 @@ function insertMemoryEventInTransaction(adapter, input) {
45
42
  .run(eventId, input.event_type, input.actor, input.source_turn_id ?? null, input.memory_id ?? null, input.topic ?? null, JSON.stringify(input.scope_refs), input.evidence_refs ? JSON.stringify(input.evidence_refs) : null, input.reason ?? null, input.created_at);
46
43
  return eventId;
47
44
  }
48
- async function listMemoryEventsForMemory(memoryId) {
49
- await (0, db_manager_js_1.initDB)();
50
- const adapter = (0, db_manager_js_1.getAdapter)();
45
+ async function listMemoryEventsForMemory(adapter, memoryId) {
51
46
  const rows = adapter
52
47
  .prepare(`
53
48
  SELECT event_id, event_type, actor, source_turn_id, memory_id, topic,
@@ -59,9 +54,7 @@ async function listMemoryEventsForMemory(memoryId) {
59
54
  .all(memoryId);
60
55
  return rows.map(deserializeEvent);
61
56
  }
62
- async function listRecentMemoryEvents(limit = 10) {
63
- await (0, db_manager_js_1.initDB)();
64
- const adapter = (0, db_manager_js_1.getAdapter)();
57
+ async function listRecentMemoryEvents(adapter, limit = 10) {
65
58
  const rows = adapter
66
59
  .prepare(`
67
60
  SELECT event_id, event_type, actor, source_turn_id, memory_id, topic,
@@ -1,4 +1,5 @@
1
+ import type { DatabaseAdapter } from '../db-manager.js';
1
2
  import type { AuditFindingRecord } from './types.js';
2
- export declare function createAuditFinding(input: Omit<AuditFindingRecord, 'finding_id' | 'status' | 'created_at' | 'resolved_at'>): Promise<string>;
3
- export declare function listOpenAuditFindings(): Promise<AuditFindingRecord[]>;
3
+ export declare function createAuditFinding(adapter: Pick<DatabaseAdapter, 'prepare'>, input: Omit<AuditFindingRecord, 'finding_id' | 'status' | 'created_at' | 'resolved_at'>): string;
4
+ export declare function listOpenAuditFindings(adapter: DatabaseAdapter): Promise<AuditFindingRecord[]>;
4
5
  //# sourceMappingURL=finding-store.d.ts.map
@@ -6,7 +6,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.createAuditFinding = createAuditFinding;
7
7
  exports.listOpenAuditFindings = listOpenAuditFindings;
8
8
  const node_crypto_1 = __importDefault(require("node:crypto"));
9
- const db_manager_js_1 = require("../db-manager.js");
10
9
  function safeParseJsonArray(value) {
11
10
  try {
12
11
  return JSON.parse(String(value));
@@ -31,9 +30,7 @@ function deserializeFinding(row) {
31
30
  : Number(row.resolved_at),
32
31
  };
33
32
  }
34
- async function createAuditFinding(input) {
35
- await (0, db_manager_js_1.initDB)();
36
- const adapter = (0, db_manager_js_1.getAdapter)();
33
+ function createAuditFinding(adapter, input) {
37
34
  const findingId = `finding_${node_crypto_1.default.randomUUID().replace(/-/g, '')}`;
38
35
  adapter
39
36
  .prepare(`
@@ -46,9 +43,7 @@ async function createAuditFinding(input) {
46
43
  .run(findingId, input.kind, input.severity, input.summary, JSON.stringify(input.evidence_refs), JSON.stringify(input.affected_memory_ids), input.recommended_action, Date.now());
47
44
  return findingId;
48
45
  }
49
- async function listOpenAuditFindings() {
50
- await (0, db_manager_js_1.initDB)();
51
- const adapter = (0, db_manager_js_1.getAdapter)();
46
+ async function listOpenAuditFindings(adapter) {
52
47
  const rows = adapter
53
48
  .prepare(`
54
49
  SELECT finding_id, kind, severity, summary, evidence_refs, affected_memory_ids,
@@ -0,0 +1,52 @@
1
+ /**
2
+ * The decision graph, as a caller may see it.
3
+ *
4
+ * The viewer drew this by reading `decisions` and `decision_edges` directly and
5
+ * embedding fifty rows in the HTTP process. Those are reads, and a read answers
6
+ * to the caller's scopes: every node here is a memory the caller's grant admits,
7
+ * every edge joins two such nodes, and the totals count the same admitted set.
8
+ * A principal that admits nothing sees an empty graph rather than the file.
9
+ */
10
+ import { type DatabaseAdapter } from '../db-manager.js';
11
+ export interface GraphReadNode {
12
+ id: string;
13
+ topic: string;
14
+ decision: string;
15
+ reasoning?: string | null;
16
+ outcome: string | null;
17
+ confidence: number | null;
18
+ created_at: number;
19
+ }
20
+ export interface GraphReadEdge {
21
+ from: string;
22
+ to: string;
23
+ relationship: string;
24
+ reason: string | null;
25
+ }
26
+ export interface GraphSimilarityEdge extends GraphReadEdge {
27
+ similarity: number;
28
+ }
29
+ export interface GraphScope {
30
+ kind: string;
31
+ id: string;
32
+ }
33
+ export declare function readGraphNodes(adapter: DatabaseAdapter, scopes: readonly GraphScope[], options?: {
34
+ limit?: number | null;
35
+ ids?: readonly string[];
36
+ }): Promise<GraphReadNode[]>;
37
+ export declare function readGraphEdges(adapter: DatabaseAdapter, scopes: readonly GraphScope[]): Promise<GraphReadEdge[]>;
38
+ export declare function countGraphNodes(adapter: DatabaseAdapter, scopes: readonly GraphScope[]): Promise<number>;
39
+ /**
40
+ * Similarity edges over the admitted set.
41
+ *
42
+ * This embeds a bounded window of admitted nodes and asks the vector index what
43
+ * each is near. It lives here rather than in an HTTP handler because that is
44
+ * where the embedder is — a door that embeds is a door that has opinions about
45
+ * what memory means.
46
+ */
47
+ export declare function readGraphSimilarityEdges(adapter: DatabaseAdapter, scopes: readonly GraphScope[], options?: {
48
+ window?: number;
49
+ neighbors?: number;
50
+ threshold?: number;
51
+ }): Promise<GraphSimilarityEdge[]>;
52
+ //# sourceMappingURL=graph-read.d.ts.map
@@ -0,0 +1,130 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.readGraphNodes = readGraphNodes;
4
+ exports.readGraphEdges = readGraphEdges;
5
+ exports.countGraphNodes = countGraphNodes;
6
+ exports.readGraphSimilarityEdges = readGraphSimilarityEdges;
7
+ /**
8
+ * The decision graph, as a caller may see it.
9
+ *
10
+ * The viewer drew this by reading `decisions` and `decision_edges` directly and
11
+ * embedding fifty rows in the HTTP process. Those are reads, and a read answers
12
+ * to the caller's scopes: every node here is a memory the caller's grant admits,
13
+ * every edge joins two such nodes, and the totals count the same admitted set.
14
+ * A principal that admits nothing sees an empty graph rather than the file.
15
+ */
16
+ const db_manager_js_1 = require("../db-manager.js");
17
+ const embedder_js_1 = require("../embedding/embedder.js");
18
+ const search_js_1 = require("../knowledge/search.js");
19
+ /** The admitted-node clause both a node read and an edge read stand on. */
20
+ async function admittedScopeIds(adapter, scopes) {
21
+ return Promise.all(scopes.map((scope) => (0, db_manager_js_1.ensureMemoryScope)(adapter, scope.kind, scope.id)));
22
+ }
23
+ async function readGraphNodes(adapter, scopes, options = {}) {
24
+ if (scopes.length === 0) {
25
+ return [];
26
+ }
27
+ const scopeIds = await admittedScopeIds(adapter, scopes);
28
+ const scopePlaceholders = scopeIds.map(() => '?').join(', ');
29
+ const ids = options.ids ?? [];
30
+ const idClause = ids.length > 0 ? `AND d.id IN (${ids.map(() => '?').join(', ')})` : '';
31
+ const limit = options.limit ?? null;
32
+ const rows = (await adapter
33
+ .prepare(`SELECT DISTINCT d.id, d.topic, d.decision, d.reasoning, d.outcome, d.confidence, d.created_at
34
+ FROM decisions d
35
+ JOIN memory_scope_bindings msb ON msb.memory_id = d.id
36
+ WHERE msb.scope_id IN (${scopePlaceholders})
37
+ ${idClause}
38
+ ORDER BY d.created_at DESC
39
+ ${limit === null ? '' : 'LIMIT ?'}`)
40
+ .all(...scopeIds, ...ids, ...(limit === null ? [] : [limit])));
41
+ return rows;
42
+ }
43
+ async function readGraphEdges(adapter, scopes) {
44
+ if (scopes.length === 0) {
45
+ return [];
46
+ }
47
+ const scopeIds = await admittedScopeIds(adapter, scopes);
48
+ const placeholders = scopeIds.map(() => '?').join(', ');
49
+ // Both ends must be admitted: an edge to a memory this caller cannot read
50
+ // would disclose that it exists, which is the read the join is here to bound.
51
+ const rows = (await adapter
52
+ .prepare(`SELECT e.from_id, e.to_id, e.relationship, e.reason
53
+ FROM decision_edges e
54
+ WHERE EXISTS (
55
+ SELECT 1 FROM memory_scope_bindings b
56
+ WHERE b.memory_id = e.from_id AND b.scope_id IN (${placeholders})
57
+ )
58
+ AND EXISTS (
59
+ SELECT 1 FROM memory_scope_bindings b
60
+ WHERE b.memory_id = e.to_id AND b.scope_id IN (${placeholders})
61
+ )`)
62
+ .all(...scopeIds, ...scopeIds));
63
+ return rows.map((row) => ({
64
+ from: row.from_id,
65
+ to: row.to_id,
66
+ relationship: row.relationship,
67
+ reason: row.reason,
68
+ }));
69
+ }
70
+ async function countGraphNodes(adapter, scopes) {
71
+ if (scopes.length === 0) {
72
+ return 0;
73
+ }
74
+ const scopeIds = await admittedScopeIds(adapter, scopes);
75
+ const placeholders = scopeIds.map(() => '?').join(', ');
76
+ const row = (await adapter
77
+ .prepare(`SELECT COUNT(DISTINCT d.id) as count FROM decisions d
78
+ JOIN memory_scope_bindings msb ON msb.memory_id = d.id
79
+ WHERE msb.scope_id IN (${placeholders})`)
80
+ .get(...scopeIds));
81
+ return row?.count ?? 0;
82
+ }
83
+ /**
84
+ * Similarity edges over the admitted set.
85
+ *
86
+ * This embeds a bounded window of admitted nodes and asks the vector index what
87
+ * each is near. It lives here rather than in an HTTP handler because that is
88
+ * where the embedder is — a door that embeds is a door that has opinions about
89
+ * what memory means.
90
+ */
91
+ async function readGraphSimilarityEdges(adapter, scopes, options = {}) {
92
+ const window = options.window ?? 50;
93
+ const neighbors = options.neighbors ?? 3;
94
+ const threshold = options.threshold ?? 0.7;
95
+ const nodes = await readGraphNodes(adapter, scopes, { limit: Math.max(window * 2, window) });
96
+ if (nodes.length < 2) {
97
+ return [];
98
+ }
99
+ const admitted = new Set(nodes.map((node) => node.id));
100
+ const seen = new Set();
101
+ const edges = [];
102
+ for (const node of nodes.slice(0, window)) {
103
+ const embedding = await (0, embedder_js_1.generateEmbedding)(`${node.topic} ${node.decision}`, 'query');
104
+ const similar = (await (0, search_js_1.vectorSearch)(adapter, embedding, neighbors, threshold));
105
+ for (const match of similar) {
106
+ // A neighbour the caller may not read is not an edge it may see.
107
+ if (match.id === node.id || !admitted.has(match.id)) {
108
+ continue;
109
+ }
110
+ const similarity = match.similarity ?? threshold;
111
+ if (similarity <= threshold) {
112
+ continue;
113
+ }
114
+ const key = [node.id, match.id].sort().join('|');
115
+ if (seen.has(key)) {
116
+ continue;
117
+ }
118
+ seen.add(key);
119
+ edges.push({
120
+ from: node.id,
121
+ to: match.id,
122
+ relationship: 'similar',
123
+ reason: null,
124
+ similarity,
125
+ });
126
+ }
127
+ }
128
+ return edges;
129
+ }
130
+ //# sourceMappingURL=graph-read.js.map