nova-personal-agent-server 0.0.0-stage → 0.4.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 (345) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +30 -2
  3. package/bin/novapersonal-server.mjs +4 -0
  4. package/package.json +61 -4
  5. package/resources/endpointing/volcengine-v1/LICENSE.silero-vad.txt +21 -0
  6. package/resources/endpointing/volcengine-v1/MANIFEST.json +31 -0
  7. package/resources/endpointing/volcengine-v1/silence-16k-s16le.pcm +0 -0
  8. package/resources/endpointing/volcengine-v1/speech-16k-s16le.pcm +0 -0
  9. package/resources/native/codex-sandbox-probe +0 -0
  10. package/resources/native/project-native/nova_project_native.node +0 -0
  11. package/resources/native-resources-v1.json +1 -0
  12. package/runtime/dist/eval/demos.js +156 -0
  13. package/runtime/dist/eval/fixture-host.js +385 -0
  14. package/runtime/dist/eval/fixtures.js +319 -0
  15. package/runtime/dist/eval/realtime/session-fixtures.js +474 -0
  16. package/runtime/dist/eval/scorecard.js +285 -0
  17. package/runtime/dist/eval/sim.js +43 -0
  18. package/runtime/dist/src/cascaded-text-provider.js +31 -0
  19. package/runtime/dist/src/cli.js +96 -0
  20. package/runtime/dist/src/composition/assembly.js +352 -0
  21. package/runtime/dist/src/composition/cascaded-realtime-assembly.js +455 -0
  22. package/runtime/dist/src/composition/production-composition.js +389 -0
  23. package/runtime/dist/src/composition/realtime-assembly.js +1330 -0
  24. package/runtime/dist/src/config/capability-registry.js +315 -0
  25. package/runtime/dist/src/config/cascaded-realtime-config.js +146 -0
  26. package/runtime/dist/src/config/coding-backends.js +8 -0
  27. package/runtime/dist/src/config/coding-profiles.js +98 -0
  28. package/runtime/dist/src/config/config.js +857 -0
  29. package/runtime/dist/src/config/diagnostics.js +139 -0
  30. package/runtime/dist/src/config/environment-contract.js +202 -0
  31. package/runtime/dist/src/config/self-hosted.js +23 -0
  32. package/runtime/dist/src/connectors/composio/client.js +195 -0
  33. package/runtime/dist/src/connectors/composio/google.js +208 -0
  34. package/runtime/dist/src/connectors/composio/index.js +334 -0
  35. package/runtime/dist/src/connectors/feishu/cli.js +220 -0
  36. package/runtime/dist/src/connectors/feishu/index.js +980 -0
  37. package/runtime/dist/src/connectors/macos/calendar.js +35 -0
  38. package/runtime/dist/src/connectors/macos/mail.js +32 -0
  39. package/runtime/dist/src/connectors/macos/reader.js +62 -0
  40. package/runtime/dist/src/conversation-voice-provider.js +41 -0
  41. package/runtime/dist/src/core/approval-port.js +9 -0
  42. package/runtime/dist/src/core/approval.js +1328 -0
  43. package/runtime/dist/src/core/calls.js +35 -0
  44. package/runtime/dist/src/core/camera-session.js +32 -0
  45. package/runtime/dist/src/core/causal-runtime.js +650 -0
  46. package/runtime/dist/src/core/clock.js +139 -0
  47. package/runtime/dist/src/core/context-view.js +156 -0
  48. package/runtime/dist/src/core/effects.js +62 -0
  49. package/runtime/dist/src/core/events.js +217 -0
  50. package/runtime/dist/src/core/executor-diagnostic.js +9 -0
  51. package/runtime/dist/src/core/ids.js +32 -0
  52. package/runtime/dist/src/core/media-store.js +104 -0
  53. package/runtime/dist/src/core/memory.js +296 -0
  54. package/runtime/dist/src/core/pending-decision.js +64 -0
  55. package/runtime/dist/src/core/ports.js +125 -0
  56. package/runtime/dist/src/core/runtime.js +1459 -0
  57. package/runtime/dist/src/core/schedule-tools.js +15 -0
  58. package/runtime/dist/src/core/sims.js +186 -0
  59. package/runtime/dist/src/core/slots.js +97 -0
  60. package/runtime/dist/src/core/source-processing-instructions.js +3 -0
  61. package/runtime/dist/src/core/source-processing-tools.js +12 -0
  62. package/runtime/dist/src/core/suggestions.js +143 -0
  63. package/runtime/dist/src/core/task-tools.js +22 -0
  64. package/runtime/dist/src/core/tool-schema.js +212 -0
  65. package/runtime/dist/src/core/trace.js +34 -0
  66. package/runtime/dist/src/core/work-tools.js +94 -0
  67. package/runtime/dist/src/desktop/desktop-camera-source.js +31 -0
  68. package/runtime/dist/src/desktop/desktop-camera.js +281 -0
  69. package/runtime/dist/src/desktop/desktop-control.js +140 -0
  70. package/runtime/dist/src/desktop/desktop-progress.js +162 -0
  71. package/runtime/dist/src/desktop/desktop-session.js +2106 -0
  72. package/runtime/dist/src/desktop/desktop-tasks.js +80 -0
  73. package/runtime/dist/src/desktop/desktop-wire.js +605 -0
  74. package/runtime/dist/src/desktop/phone-desktop-entry.js +17 -0
  75. package/runtime/dist/src/desktop/startup-error.js +18 -0
  76. package/runtime/dist/src/desktop/workbench-acceptance.js +262 -0
  77. package/runtime/dist/src/desktop-entry.js +106 -0
  78. package/runtime/dist/src/desktop.js +1092 -0
  79. package/runtime/dist/src/executors/acp/backends.js +105 -0
  80. package/runtime/dist/src/executors/acp/mcp.js +81 -0
  81. package/runtime/dist/src/executors/acp/preflight.js +14 -0
  82. package/runtime/dist/src/executors/acp/process-owner.js +112 -0
  83. package/runtime/dist/src/executors/acp/transport.js +760 -0
  84. package/runtime/dist/src/executors/acp/windows-launch.js +68 -0
  85. package/runtime/dist/src/executors/agent-controller.js +244 -0
  86. package/runtime/dist/src/executors/autoglm.js +376 -0
  87. package/runtime/dist/src/executors/browser-device.js +102 -0
  88. package/runtime/dist/src/executors/browser.js +61 -0
  89. package/runtime/dist/src/executors/camera.js +101 -0
  90. package/runtime/dist/src/executors/chromium-frame-source.js +173 -0
  91. package/runtime/dist/src/executors/codex/adapter-live.js +292 -0
  92. package/runtime/dist/src/executors/codex/adapter-project.js +1306 -0
  93. package/runtime/dist/src/executors/codex/app-server-schema.js +712 -0
  94. package/runtime/dist/src/executors/codex/app-server-transport.js +1798 -0
  95. package/runtime/dist/src/executors/codex/approval-protocol.js +439 -0
  96. package/runtime/dist/src/executors/codex/common.js +655 -0
  97. package/runtime/dist/src/executors/codex/contract.js +581 -0
  98. package/runtime/dist/src/executors/codex/controller.js +141 -0
  99. package/runtime/dist/src/executors/codex/credential-snapshot.js +195 -0
  100. package/runtime/dist/src/executors/codex/factory.js +463 -0
  101. package/runtime/dist/src/executors/codex/host-config.js +238 -0
  102. package/runtime/dist/src/executors/codex/host.js +17 -0
  103. package/runtime/dist/src/executors/codex/index.js +19 -0
  104. package/runtime/dist/src/executors/codex/launch-profile.js +37 -0
  105. package/runtime/dist/src/executors/codex/local-sessions.js +119 -0
  106. package/runtime/dist/src/executors/codex/managed-mcp.js +196 -0
  107. package/runtime/dist/src/executors/codex/process-owner.js +398 -0
  108. package/runtime/dist/src/executors/codex/production-host.js +887 -0
  109. package/runtime/dist/src/executors/codex/progress-instructions.js +10 -0
  110. package/runtime/dist/src/executors/codex/protocol.js +581 -0
  111. package/runtime/dist/src/executors/codex/safe-json.js +87 -0
  112. package/runtime/dist/src/executors/codex/session-title.js +61 -0
  113. package/runtime/dist/src/executors/codex/shared-home.js +29 -0
  114. package/runtime/dist/src/executors/codex/spawn-env.js +162 -0
  115. package/runtime/dist/src/executors/codex/turn-projection.js +435 -0
  116. package/runtime/dist/src/executors/codex/version.js +38 -0
  117. package/runtime/dist/src/executors/codex/windows-guardian.js +716 -0
  118. package/runtime/dist/src/executors/coding/intake-model.js +103 -0
  119. package/runtime/dist/src/executors/coding/intake.js +824 -0
  120. package/runtime/dist/src/executors/coding/json-completion.js +14 -0
  121. package/runtime/dist/src/executors/coding/target-resolution.js +61 -0
  122. package/runtime/dist/src/executors/coding/work-order.js +50 -0
  123. package/runtime/dist/src/executors/coding-executor.js +23 -0
  124. package/runtime/dist/src/executors/computer-backend.js +188 -0
  125. package/runtime/dist/src/executors/computer-device.js +187 -0
  126. package/runtime/dist/src/executors/computer-worker.js +125 -0
  127. package/runtime/dist/src/executors/computer.js +100 -0
  128. package/runtime/dist/src/executors/device-lock.js +127 -0
  129. package/runtime/dist/src/executors/frame-source.js +29 -0
  130. package/runtime/dist/src/executors/gui-evidence.js +30 -0
  131. package/runtime/dist/src/executors/gui-execution.js +237 -0
  132. package/runtime/dist/src/executors/gui-runner.js +88 -0
  133. package/runtime/dist/src/executors/host-executor-capability.js +12 -0
  134. package/runtime/dist/src/executors/index.js +13 -0
  135. package/runtime/dist/src/executors/mcp-client.js +198 -0
  136. package/runtime/dist/src/executors/mcp.js +210 -0
  137. package/runtime/dist/src/executors/mobile-android.js +180 -0
  138. package/runtime/dist/src/executors/mobile-ios.js +303 -0
  139. package/runtime/dist/src/executors/mobile.js +78 -0
  140. package/runtime/dist/src/executors/search-mcp.js +146 -0
  141. package/runtime/dist/src/executors/search.js +524 -0
  142. package/runtime/dist/src/executors/task-resources.js +38 -0
  143. package/runtime/dist/src/executors/vision/assess.js +296 -0
  144. package/runtime/dist/src/executors/vision/controller-core.js +373 -0
  145. package/runtime/dist/src/executors/vision/controller.js +164 -0
  146. package/runtime/dist/src/executors/vision/lifecycle.js +69 -0
  147. package/runtime/dist/src/executors/vision.js +5 -0
  148. package/runtime/dist/src/executors/watcher.js +718 -0
  149. package/runtime/dist/src/http/bounded-response.js +37 -0
  150. package/runtime/dist/src/index.js +56 -0
  151. package/runtime/dist/src/knowledge/assembly.js +60 -0
  152. package/runtime/dist/src/knowledge/documents.js +520 -0
  153. package/runtime/dist/src/knowledge/embeddings.js +201 -0
  154. package/runtime/dist/src/knowledge/mcp.js +218 -0
  155. package/runtime/dist/src/knowledge/parse-worker.js +122 -0
  156. package/runtime/dist/src/knowledge/references.js +51 -0
  157. package/runtime/dist/src/knowledge/service.js +526 -0
  158. package/runtime/dist/src/knowledge/store-client.js +185 -0
  159. package/runtime/dist/src/knowledge/store-worker.js +843 -0
  160. package/runtime/dist/src/knowledge/types.js +2 -0
  161. package/runtime/dist/src/mcp/http-server.js +177 -0
  162. package/runtime/dist/src/mem0/resource.js +35 -0
  163. package/runtime/dist/src/mem0/store-worker.js +330 -0
  164. package/runtime/dist/src/memory/blackboard-session.js +205 -0
  165. package/runtime/dist/src/memory/blackboard-store.js +194 -0
  166. package/runtime/dist/src/memory/blackboard-worker.js +369 -0
  167. package/runtime/dist/src/memory/entry.js +39 -0
  168. package/runtime/dist/src/memory/factory.js +20 -0
  169. package/runtime/dist/src/memory/personal-memory-inspection.js +18 -0
  170. package/runtime/dist/src/memory/personal-memory.js +10 -0
  171. package/runtime/dist/src/memory/prerecall.js +20 -0
  172. package/runtime/dist/src/memory/provenance.js +17 -0
  173. package/runtime/dist/src/memory/remote-personal-memory.js +194 -0
  174. package/runtime/dist/src/memory/retrieval.js +235 -0
  175. package/runtime/dist/src/memory/sensitivity.js +261 -0
  176. package/runtime/dist/src/memory-ledger/models.js +98 -0
  177. package/runtime/dist/src/memory-ledger/store-client.js +210 -0
  178. package/runtime/dist/src/memory-ledger/store-worker.js +130 -0
  179. package/runtime/dist/src/memory-ledger/store.js +597 -0
  180. package/runtime/dist/src/memory-substrate/candidates.js +16 -0
  181. package/runtime/dist/src/memory-substrate/consolidation.js +124 -0
  182. package/runtime/dist/src/memory-substrate/file-authority.js +111 -0
  183. package/runtime/dist/src/memory-substrate/life-operations.js +280 -0
  184. package/runtime/dist/src/memory-substrate/markdown-repository.js +610 -0
  185. package/runtime/dist/src/memory-substrate/migration.js +87 -0
  186. package/runtime/dist/src/memory-substrate/profile-source-input.js +9 -0
  187. package/runtime/dist/src/memory-substrate/purge.js +398 -0
  188. package/runtime/dist/src/memory-substrate/resolution.js +32 -0
  189. package/runtime/dist/src/memory-substrate/resource.js +867 -0
  190. package/runtime/dist/src/memory-substrate/retrieval.js +85 -0
  191. package/runtime/dist/src/memory-substrate/source-operations.js +306 -0
  192. package/runtime/dist/src/memory-substrate/source-processing.js +326 -0
  193. package/runtime/dist/src/memory-substrate/source-state.js +93 -0
  194. package/runtime/dist/src/memory-substrate/store.js +534 -0
  195. package/runtime/dist/src/memory-substrate/workspace-projections.js +106 -0
  196. package/runtime/dist/src/memory-substrate/workspace.js +21 -0
  197. package/runtime/dist/src/model/jev-client.js +25 -0
  198. package/runtime/dist/src/model/model-adapters.js +64 -0
  199. package/runtime/dist/src/model/model-gateway.js +399 -0
  200. package/runtime/dist/src/model/model-lane.js +34 -0
  201. package/runtime/dist/src/model/model-purpose.js +5 -0
  202. package/runtime/dist/src/model/personal-writer.js +361 -0
  203. package/runtime/dist/src/model/proactivity.js +72 -0
  204. package/runtime/dist/src/model/prompting.js +279 -0
  205. package/runtime/dist/src/model/task-verifier.js +217 -0
  206. package/runtime/dist/src/model/vision-capability.js +10 -0
  207. package/runtime/dist/src/news/feeds.js +114 -0
  208. package/runtime/dist/src/news/jev-ranking.js +25 -0
  209. package/runtime/dist/src/news/ranking.js +26 -0
  210. package/runtime/dist/src/news/service.js +262 -0
  211. package/runtime/dist/src/notifications/adapters/feishu.js +10 -0
  212. package/runtime/dist/src/notifications/adapters/nova.js +15 -0
  213. package/runtime/dist/src/notifications/content.js +15 -0
  214. package/runtime/dist/src/notifications/contracts.js +9 -0
  215. package/runtime/dist/src/notifications/feed.js +8 -0
  216. package/runtime/dist/src/notifications/service.js +412 -0
  217. package/runtime/dist/src/notifications/store.js +4 -0
  218. package/runtime/dist/src/personal-agent/app-context.js +113 -0
  219. package/runtime/dist/src/personal-agent/approval-scope.js +8 -0
  220. package/runtime/dist/src/personal-agent/coding-targets.js +82 -0
  221. package/runtime/dist/src/personal-agent/context-candidates.js +94 -0
  222. package/runtime/dist/src/personal-agent/contracts.js +32 -0
  223. package/runtime/dist/src/personal-agent/conversation-runtime.js +536 -0
  224. package/runtime/dist/src/personal-agent/conversations.js +187 -0
  225. package/runtime/dist/src/personal-agent/daily-brief.js +53 -0
  226. package/runtime/dist/src/personal-agent/host.js +2403 -0
  227. package/runtime/dist/src/personal-agent/intake-task.js +37 -0
  228. package/runtime/dist/src/personal-agent/life.js +260 -0
  229. package/runtime/dist/src/personal-agent/memory-overview.js +19 -0
  230. package/runtime/dist/src/personal-agent/profile-sources.js +34 -0
  231. package/runtime/dist/src/personal-agent/profile-warmup.js +244 -0
  232. package/runtime/dist/src/personal-agent/project-digests.js +242 -0
  233. package/runtime/dist/src/personal-agent/sampling.js +20 -0
  234. package/runtime/dist/src/personal-agent/schedule-agent.js +60 -0
  235. package/runtime/dist/src/personal-agent/schedule-api.js +61 -0
  236. package/runtime/dist/src/personal-agent/schedule-presets.js +13 -0
  237. package/runtime/dist/src/personal-agent/schedule-reference.js +3 -0
  238. package/runtime/dist/src/personal-agent/scheduled-response-scope.js +38 -0
  239. package/runtime/dist/src/personal-agent/scheduled-run-authority.js +44 -0
  240. package/runtime/dist/src/personal-agent/scheduled-tasks.js +280 -0
  241. package/runtime/dist/src/personal-agent/scheduled-time.js +99 -0
  242. package/runtime/dist/src/personal-agent/scheduled-tool-runtime.js +109 -0
  243. package/runtime/dist/src/personal-agent/source-priority.js +142 -0
  244. package/runtime/dist/src/personal-agent/source-processing-agent.js +158 -0
  245. package/runtime/dist/src/personal-agent/source-walk.js +25 -0
  246. package/runtime/dist/src/personal-agent/sources.js +1484 -0
  247. package/runtime/dist/src/personal-agent/store-lock-worker.js +17 -0
  248. package/runtime/dist/src/personal-agent/store.js +146 -0
  249. package/runtime/dist/src/personal-agent/task-loop.js +163 -0
  250. package/runtime/dist/src/personal-agent/tasks.js +920 -0
  251. package/runtime/dist/src/personal-agent/turn-deadline.js +55 -0
  252. package/runtime/dist/src/personal-agent/understanding.js +160 -0
  253. package/runtime/dist/src/personal-agent/workbench-context.js +239 -0
  254. package/runtime/dist/src/projects/confirmed-project-capability.js +60 -0
  255. package/runtime/dist/src/projects/host-paths.js +133 -0
  256. package/runtime/dist/src/projects/managed-workspace-maintenance.js +351 -0
  257. package/runtime/dist/src/projects/project-confirmation.js +486 -0
  258. package/runtime/dist/src/projects/project-native-resource.js +284 -0
  259. package/runtime/dist/src/projects/project-node-files.js +169 -0
  260. package/runtime/dist/src/projects/project-root-file.js +16 -0
  261. package/runtime/dist/src/projects/project-state.js +504 -0
  262. package/runtime/dist/src/projects/project-store-files.js +1271 -0
  263. package/runtime/dist/src/projects/project-store.js +1345 -0
  264. package/runtime/dist/src/realtime/aoq.js +141 -0
  265. package/runtime/dist/src/realtime/bridge.js +652 -0
  266. package/runtime/dist/src/realtime/cascaded/adapter.js +1669 -0
  267. package/runtime/dist/src/realtime/cascaded/ark-llm.js +219 -0
  268. package/runtime/dist/src/realtime/cascaded/chat-completions-llm.js +478 -0
  269. package/runtime/dist/src/realtime/cascaded/gemini-speech.js +232 -0
  270. package/runtime/dist/src/realtime/cascaded/llm.js +37 -0
  271. package/runtime/dist/src/realtime/cascaded/ports.js +2 -0
  272. package/runtime/dist/src/realtime/cascaded/provider.js +216 -0
  273. package/runtime/dist/src/realtime/cascaded/qwen-llm.js +7 -0
  274. package/runtime/dist/src/realtime/cascaded/self-hosted-asr.js +110 -0
  275. package/runtime/dist/src/realtime/cascaded/self-hosted-tts.js +137 -0
  276. package/runtime/dist/src/realtime/cascaded/transcribe.js +42 -0
  277. package/runtime/dist/src/realtime/coding-progress-narration.js +28 -0
  278. package/runtime/dist/src/realtime/confirmation-turn-isolation.js +586 -0
  279. package/runtime/dist/src/realtime/dictation.js +28 -0
  280. package/runtime/dist/src/realtime/evidence.js +276 -0
  281. package/runtime/dist/src/realtime/floor.js +43 -0
  282. package/runtime/dist/src/realtime/frontend-instructions.js +195 -0
  283. package/runtime/dist/src/realtime/gemini.js +517 -0
  284. package/runtime/dist/src/realtime/history.js +122 -0
  285. package/runtime/dist/src/realtime/host-delivery.js +1711 -0
  286. package/runtime/dist/src/realtime/integrated-wire-profile.js +128 -0
  287. package/runtime/dist/src/realtime/memory-board.js +105 -0
  288. package/runtime/dist/src/realtime/openai-wire-profile.js +46 -0
  289. package/runtime/dist/src/realtime/playback.js +242 -0
  290. package/runtime/dist/src/realtime/project-confirmation-flow.js +1428 -0
  291. package/runtime/dist/src/realtime/prompt-language.js +17 -0
  292. package/runtime/dist/src/realtime/protocol.js +428 -0
  293. package/runtime/dist/src/realtime/provider-projection.js +526 -0
  294. package/runtime/dist/src/realtime/provider-session.js +491 -0
  295. package/runtime/dist/src/realtime/qwen-transport.js +144 -0
  296. package/runtime/dist/src/realtime/qwen.js +1377 -0
  297. package/runtime/dist/src/realtime/recall.js +341 -0
  298. package/runtime/dist/src/realtime/service-ports.js +8 -0
  299. package/runtime/dist/src/realtime/service-state.js +259 -0
  300. package/runtime/dist/src/realtime/service.js +1726 -0
  301. package/runtime/dist/src/realtime/session-state.js +684 -0
  302. package/runtime/dist/src/realtime/session.js +1976 -0
  303. package/runtime/dist/src/realtime/speech-prep.js +63 -0
  304. package/runtime/dist/src/realtime/streaming-speech.js +120 -0
  305. package/runtime/dist/src/realtime/system-prompts.en.js +136 -0
  306. package/runtime/dist/src/realtime/telemetry.js +144 -0
  307. package/runtime/dist/src/realtime/tool-continuations.js +1510 -0
  308. package/runtime/dist/src/realtime/transport.js +8 -0
  309. package/runtime/dist/src/realtime/usage.js +55 -0
  310. package/runtime/dist/src/realtime/user-origin-binding.js +173 -0
  311. package/runtime/dist/src/realtime/volcengine/ark.js +428 -0
  312. package/runtime/dist/src/realtime/volcengine/asr.js +573 -0
  313. package/runtime/dist/src/realtime/volcengine/audio.js +39 -0
  314. package/runtime/dist/src/realtime/volcengine/endpointing-capability.js +834 -0
  315. package/runtime/dist/src/realtime/volcengine/livekit-endpointing.js +714 -0
  316. package/runtime/dist/src/realtime/volcengine/local-eot-executor.js +33 -0
  317. package/runtime/dist/src/realtime/volcengine/protocol.js +247 -0
  318. package/runtime/dist/src/realtime/volcengine/silence-endpointing.js +237 -0
  319. package/runtime/dist/src/realtime/volcengine/tts.js +444 -0
  320. package/runtime/dist/src/realtime/volcengine/websocket.js +293 -0
  321. package/runtime/dist/src/server/aoq-chat-server.js +497 -0
  322. package/runtime/dist/src/server/client-pairing.js +192 -0
  323. package/runtime/dist/src/server/client-protocol.js +87 -0
  324. package/runtime/dist/src/server/client-server.js +312 -0
  325. package/runtime/dist/src/server/server-config.js +72 -0
  326. package/runtime/dist/src/server-entry.js +135 -0
  327. package/runtime/dist/src/storage/bounded-json.js +63 -0
  328. package/runtime/dist/src/storage/native-file-lock.js +8 -0
  329. package/runtime/dist/src/storage/native-resource-snapshot.js +41 -0
  330. package/runtime/dist/src/storage/private-database.js +120 -0
  331. package/runtime/dist/src/text/canonical-json.js +60 -0
  332. package/runtime/dist/src/text/python-number.js +18 -0
  333. package/runtime/dist/src/text/python-text.js +92 -0
  334. package/runtime/dist/src/text/unicode-casefold.js +29 -0
  335. package/runtime/dist/src/text/unicode-normalize.js +138 -0
  336. package/runtime/dist/src/text/unicode-tables.js +210 -0
  337. package/runtime/dist/src/understanding/candidates.js +77 -0
  338. package/runtime/dist/src/understanding/fixture.js +7 -0
  339. package/runtime/dist/src/understanding/jev.js +20 -0
  340. package/runtime/dist/src/understanding/pipeline.js +38 -0
  341. package/runtime/dist/src/voicemem/store-client.js +476 -0
  342. package/runtime/dist/src/voicemem/store-worker.js +380 -0
  343. package/runtime/dist/src/voicemem/versioned-memory.js +170 -0
  344. package/runtime/scripts/pair-device.mjs +109 -0
  345. package/src/command.mjs +48 -0
@@ -0,0 +1,534 @@
1
+ import { imMetadataSchema } from '../memory/provenance.js';
2
+ import { initializePurge, isPermanentlyPurged } from './purge.js';
3
+ import { normalizeWorkspaceContent, projectWorkspaceRevision } from './workspace-projections.js';
4
+ import { initializeLife, lifeOperation, normalizeLifeContent } from './life-operations.js';
5
+ import { queueMemoryFiles, flushMemoryFiles, readMemoryFiles } from './file-authority.js';
6
+ import { initializeRetrieval, memoryRetrieval } from './retrieval.js';
7
+ import { createHash } from 'node:crypto';
8
+ import { z } from 'zod';
9
+ import { canonicalJson } from '../text/canonical-json.js';
10
+ import { trustSchema } from '../core/events.js';
11
+ import { initializeSourceState, correctionProcessingGrant, isCurrentEvidence, allowsProcessing, readProcessingGrant, sourceObjectFor, readConnection, sha256 } from './source-state.js';
12
+ import { sourceOperation } from './source-operations.js';
13
+ import { SensitiveContentPolicy } from '../memory/sensitivity.js';
14
+ import { initializeSourceProcessing, sourceProcessingOperation } from './source-processing.js';
15
+ const id = z.string().min(1).max(512);
16
+ const date = z.iso.datetime({ offset: true });
17
+ const object = z.record(z.string(), z.json());
18
+ export const EvidenceRecordSchema = z.object({
19
+ id, source_id: id, source_kind: z.enum(['conversation', 'file', 'mail', 'calendar', 'im', 'task_result', 'user_correction']),
20
+ consent: z.object({ provider_fingerprint: id }).optional(),
21
+ source_metadata: imMetadataSchema.optional(),
22
+ locator: z.string().max(4096), cursor: z.string().max(4096).nullable().default(null),
23
+ observed_at: date, recorded_at: date, raw_text: z.string().max(100_000).nullable(),
24
+ extracted: object.default({}), hash: z.string().min(1).max(128),
25
+ sensitivity: z.object({ policy_version: z.string(), redactions: z.array(z.string()) }).default({ policy_version: '1', redactions: [] }),
26
+ retention_until: date.nullable().default(null), trust: trustSchema,
27
+ }).strict();
28
+ export const CandidateSchema = z.object({
29
+ entry_id: id, expected_revision: z.number().int().nonnegative().optional(),
30
+ kind: z.enum(['fact', 'preference', 'plan', 'concern', 'commitment', 'entity', 'topic', 'LogicalWorkspace', 'WorkspaceInstance', 'RelationCard', 'todo', 'idea', 'goal', 'profile', 'memory_summary']),
31
+ origin: z.enum(['stated', 'inferred']), written_by: z.enum(['merge', 'user_correction']),
32
+ evidence_refs: z.array(id).min(1).max(256), entity_refs: z.array(id).max(256).default([]),
33
+ content: object, valid_until: date.nullable().default(null),
34
+ op: z.enum(['add', 'update', 'tombstone']).optional(), recorded_at: date,
35
+ }).strict().superRefine((value, ctx) => {
36
+ if (value.kind === 'commitment' && value.op !== 'tombstone') {
37
+ if ((typeof value.content.direction !== 'string' || !['owed_by_me', 'owed_to_me'].includes(value.content.direction)) || (typeof value.content.status !== 'string' || !['open', 'done', 'dropped'].includes(value.content.status)) || !(value.content.due === null || date.safeParse(value.content.due).success))
38
+ ctx.addIssue({ code: 'custom', message: 'invalid commitment' });
39
+ }
40
+ if (value.written_by === 'user_correction' && value.origin !== 'stated')
41
+ ctx.addIssue({ code: 'custom', message: 'corrections must be stated' });
42
+ });
43
+ export const EntryRevisionSchema = z.object({
44
+ entry_id: id, revision: z.number().int().positive(), supersedes: z.number().int().positive().nullable(),
45
+ kind: z.string(), origin: z.enum(['stated', 'inferred']), written_by: z.enum(['merge', 'user_correction']),
46
+ evidence_refs: z.array(id).min(1), entity_refs: z.array(id), content: object, valid_until: date.nullable(),
47
+ op: z.enum(['add', 'update', 'tombstone']), recorded_at: date,
48
+ }).strict();
49
+ export function contentHash(text) { return createHash('sha256').update(text.normalize('NFKC').trim().replace(/\s+/gu, ' ').toLowerCase()).digest('hex'); }
50
+ function normalized(value) {
51
+ if (typeof value === 'string')
52
+ return value.normalize('NFKC').trim().replace(/\s+/gu, ' ');
53
+ if (Array.isArray(value))
54
+ return value.map(normalized);
55
+ if (value && typeof value === 'object')
56
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, normalized(item)]));
57
+ return value;
58
+ }
59
+ /** The sole revision decision; caller supplies persisted suppression and deletion state. */
60
+ export function merge(current, candidate, policy = {}) {
61
+ if (candidate.expected_revision !== undefined && candidate.expected_revision !== (current?.revision ?? 0))
62
+ throw new Error('STORE_STALE_REVISION');
63
+ if (policy.suppressed && candidate.written_by !== 'user_correction')
64
+ return null;
65
+ if (current?.origin === 'stated' && candidate.origin === 'inferred' && !policy.evidenceDeleted)
66
+ return null;
67
+ if (current?.written_by === 'user_correction' && candidate.written_by !== 'user_correction' && !policy.evidenceDeleted)
68
+ return null;
69
+ if (current?.op === 'tombstone' && candidate.op === 'tombstone')
70
+ return null;
71
+ if (current && current.op !== 'tombstone' && candidate.op !== 'tombstone' && current.kind === candidate.kind && canonicalJson(normalized(current.content)) === canonicalJson(normalized(candidate.content)) && current.origin === candidate.origin && current.valid_until === candidate.valid_until && canonicalJson(current.evidence_refs) === canonicalJson(candidate.evidence_refs) && canonicalJson(current.entity_refs) === canonicalJson(candidate.entity_refs))
72
+ return null;
73
+ const fields = { ...candidate };
74
+ delete fields.expected_revision;
75
+ return EntryRevisionSchema.parse({ ...fields, revision: (current?.revision ?? 0) + 1, supersedes: current?.revision ?? null, op: candidate.op === 'tombstone' ? 'tombstone' : current ? 'update' : 'add' });
76
+ }
77
+ export function initializeMemory(database) {
78
+ initializePurge(database);
79
+ initializeLife(database);
80
+ initializeSourceState(database);
81
+ initializeRetrieval(database);
82
+ database.exec(`CREATE TABLE IF NOT EXISTS memory_evidence(id TEXT PRIMARY KEY,source_id TEXT NOT NULL,hash TEXT NOT NULL,payload_json TEXT NOT NULL);
83
+ CREATE TABLE IF NOT EXISTS memory_message_heads(key TEXT PRIMARY KEY,evidence_id TEXT NOT NULL REFERENCES memory_evidence(id) ON DELETE CASCADE);
84
+ CREATE INDEX IF NOT EXISTS memory_evidence_source ON memory_evidence(source_id);
85
+ CREATE INDEX IF NOT EXISTS memory_evidence_profile_time ON memory_evidence(json_extract(payload_json,'$.observed_at') DESC,id DESC) WHERE json_extract(payload_json,'$.source_kind') IN ('im','mail');
86
+ CREATE TABLE IF NOT EXISTS memory_revisions(entry_id TEXT NOT NULL,revision INTEGER NOT NULL,payload_json TEXT NOT NULL,PRIMARY KEY(entry_id,revision));
87
+ CREATE TABLE IF NOT EXISTS memory_suppressed(hash TEXT PRIMARY KEY);
88
+ CREATE TABLE IF NOT EXISTS memory_deleted_sources(source_id TEXT PRIMARY KEY);
89
+ CREATE TABLE IF NOT EXISTS memory_legacy_suppressed(scope TEXT NOT NULL,hash TEXT NOT NULL,PRIMARY KEY(scope,hash));
90
+ CREATE TABLE IF NOT EXISTS memory_file_outbox(slot INTEGER PRIMARY KEY CHECK(slot=1),payload_json TEXT NOT NULL);
91
+ CREATE TABLE IF NOT EXISTS memory_extractions(evidence_id TEXT NOT NULL,attempt_id TEXT NOT NULL,payload_json TEXT NOT NULL,PRIMARY KEY(evidence_id,attempt_id));`);
92
+ initializeSourceProcessing(database);
93
+ }
94
+ const scrubber = new SensitiveContentPolicy();
95
+ function scrub(value, redactions, path = 'content') {
96
+ if (typeof value === 'string') {
97
+ const result = scrubber.scrub(path, value);
98
+ if (result.kind === 'clean')
99
+ return value;
100
+ redactions.push(path);
101
+ return result.kind === 'redacted' ? result.value : null;
102
+ }
103
+ if (Array.isArray(value))
104
+ return value.map((item, index) => scrub(item, redactions, `${path}.${index}`));
105
+ if (value && typeof value === 'object')
106
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, scrub(item, redactions, `${path}.${key}`)]));
107
+ return value;
108
+ }
109
+ function rows(db, sql, ...args) { return db.prepare(sql).all(...args).map(row => JSON.parse(String(row.payload_json))); }
110
+ function current(db, entryId) { const row = db.prepare('SELECT payload_json FROM memory_revisions WHERE entry_id=? ORDER BY revision DESC LIMIT 1').get(entryId); return row ? EntryRevisionSchema.parse(JSON.parse(String(row.payload_json))) : null; }
111
+ function all(db) { return rows(db, 'SELECT r.payload_json FROM memory_revisions r JOIN (SELECT entry_id,MAX(revision) revision FROM memory_revisions GROUP BY entry_id) latest USING(entry_id,revision) ORDER BY r.entry_id').map(row => EntryRevisionSchema.parse(row)); }
112
+ export function fileDerivedInference(db, row) {
113
+ return row.origin === 'inferred' && row.written_by !== 'user_correction' && row.evidence_refs.some(ref => evidence(db, ref)?.source_kind === 'file');
114
+ }
115
+ function evidence(db, evidenceId) { const row = db.prepare('SELECT payload_json FROM memory_evidence WHERE id=?').get(evidenceId); return row ? EvidenceRecordSchema.parse(JSON.parse(String(row.payload_json))) : null; }
116
+ export function effectiveEvidence(db, evidenceId, options = { purpose: 'local' }) {
117
+ const ref = evidence(db, evidenceId);
118
+ if (!ref)
119
+ return null;
120
+ if (!isCurrentEvidence(db, ref.id, ref.source_id))
121
+ return null;
122
+ if (ref.retention_until !== null && Date.parse(ref.retention_until) <= Date.now())
123
+ return null;
124
+ if (options.purpose !== 'local' && (!options.provider || !allowsProcessing(db, ref.source_id, options.purpose, options.provider)))
125
+ return null;
126
+ if (db.prepare('SELECT hash FROM memory_suppressed WHERE hash=?').get(ref.hash))
127
+ return null;
128
+ if (ref.raw_text !== null && db.prepare('SELECT hash FROM memory_legacy_suppressed WHERE hash=? AND substr(?,1,length(scope))=scope').get(createHash('sha256').update(ref.raw_text.normalize('NFKC').trim().toLowerCase()).digest('hex'), ref.source_id))
129
+ return null;
130
+ return ref;
131
+ }
132
+ export function processingStamp(db, ids, purpose, provider) {
133
+ const records = ids.map(id => effectiveEvidence(db, id, { purpose, provider }));
134
+ if (!records.length || records.some(e => e === null))
135
+ return null;
136
+ return sha256(canonicalJson(records.map(e => { const object = sourceObjectFor(db, e.source_id); return { id: e.id, grant: readProcessingGrant(db, e.source_id), activation: object?.activation_revision ?? null, fence: object ? readConnection(db, object.connection_id)?.fence : null }; })));
137
+ }
138
+ export const retrievalEvidence = (db, id) => effectiveEvidence(db, id);
139
+ function write(db, candidate, deleted = false) {
140
+ if (isPermanentlyPurged(db, candidate.entry_id))
141
+ throw Error('STORE_PURGED_ID');
142
+ const previous = current(db, candidate.entry_id);
143
+ if (candidate.expected_revision !== undefined && candidate.expected_revision !== (previous?.revision ?? 0))
144
+ throw Error('STORE_STALE_REVISION');
145
+ const refs = candidate.evidence_refs.map(ref => evidence(db, ref));
146
+ if (!deleted && candidate.written_by !== 'user_correction' && refs.some(ref => ref && db.prepare('SELECT 1 FROM memory_suppressed WHERE hash=?').get(ref.hash)))
147
+ return previous;
148
+ if (!deleted && refs.some(ref => ref !== null && !retrievalEvidence(db, ref.id)))
149
+ throw Error('STORE_NOT_FOUND');
150
+ if (!deleted && (refs.every(ref => ref === null) || refs.some((ref, index) => ref === null && !previous?.evidence_refs.includes(candidate.evidence_refs[index]))))
151
+ throw new Error('STORE_NOT_FOUND');
152
+ if (candidate.origin === 'stated' && refs.every(ref => ref?.trust !== 'trusted_user'))
153
+ throw new Error('STORE_STATED_EVIDENCE_REQUIRED');
154
+ const redactions = [];
155
+ candidate = CandidateSchema.parse({ ...candidate, content: candidate.op === 'tombstone' ? scrub(candidate.content, redactions) : normalizeWorkspaceContent(candidate.kind, normalizeLifeContent(candidate.kind, scrub(candidate.content, redactions), previous?.content), previous?.content, candidate.written_by === 'user_correction') });
156
+ const next = merge(previous, candidate, { suppressed: refs.some(ref => ref && (db.prepare('SELECT hash FROM memory_suppressed WHERE hash=?').get(ref.hash) !== undefined || (ref.raw_text !== null && db.prepare('SELECT hash FROM memory_legacy_suppressed WHERE hash=? AND substr(?,1,length(scope))=scope').get(createHash('sha256').update(ref.raw_text.normalize('NFKC').trim().toLowerCase()).digest('hex'), ref.source_id) !== undefined))), evidenceDeleted: deleted });
157
+ if (next) {
158
+ db.prepare('INSERT INTO memory_revisions VALUES(?,?,?)').run(next.entry_id, next.revision, canonicalJson(next));
159
+ db.prepare('DELETE FROM memory_vectors WHERE entry_id=?').run(next.entry_id);
160
+ projectWorkspaceRevision(db, next, previous);
161
+ queueMemoryFiles(db);
162
+ if (previous && candidate.written_by === 'user_correction') {
163
+ for (const ref of previous.evidence_refs) {
164
+ const old = evidence(db, ref);
165
+ if (old && !candidate.evidence_refs.includes(ref))
166
+ db.prepare('INSERT OR IGNORE INTO memory_suppressed VALUES(?)').run(old.hash);
167
+ }
168
+ db.exec("DELETE FROM memory_vectors WHERE entry_id IN (SELECT r.entry_id FROM memory_revisions r,json_each(r.payload_json,'$.evidence_refs') refs JOIN memory_evidence e ON e.id=refs.value JOIN memory_suppressed s ON s.hash=e.hash)");
169
+ }
170
+ }
171
+ return next ?? current(db, candidate.entry_id);
172
+ }
173
+ export function memoryOperation(db, operation, input, transaction = true) {
174
+ const value = z.record(z.string(), z.unknown()).parse(input);
175
+ const ledgerOnly = isLedgerOnlyOperation(operation, value);
176
+ if (transaction && !ledgerOnly)
177
+ reconcileMemoryFiles(db);
178
+ if (transaction)
179
+ db.exec('BEGIN IMMEDIATE');
180
+ let committed = false;
181
+ try {
182
+ let result = null;
183
+ switch (operation) {
184
+ case 'source_processing':
185
+ result = sourceProcessingOperation(db, input);
186
+ break;
187
+ case 'life_load':
188
+ case 'life_mutate':
189
+ case 'life_capture_im':
190
+ result = lifeOperation(db, operation, input, (op, v) => memoryOperation(db, op, v, false));
191
+ break;
192
+ case 'source_connection':
193
+ case 'source_apply_page':
194
+ case 'source_pending':
195
+ case 'source_revision':
196
+ case 'source_grant':
197
+ case 'extraction_ticket':
198
+ case 'commit_extraction':
199
+ case 'source_events':
200
+ result = sourceOperation(db, operation, input, (op, v) => memoryOperation(db, op, v, false));
201
+ break;
202
+ case 'conversation_snapshot': {
203
+ const q = z.object({ entry_prefix: id, consumer: id }).strict().parse(value);
204
+ const now = Date.now();
205
+ result = all(db).filter(row => row.entry_id.startsWith(q.entry_prefix) && row.op !== 'tombstone' && !fileDerivedInference(db, row) && (row.valid_until === null || Date.parse(row.valid_until) > now) && row.evidence_refs.every(ref => effectiveEvidence(db, ref, { purpose: 'conversation', provider: q.consumer }) !== null));
206
+ break;
207
+ }
208
+ case 'processing_stamp':
209
+ result = processingStamp(db, z.array(id).min(1).max(256).parse(value.ids), z.enum(['extraction', 'embedding', 'conversation']).parse(value.purpose), id.parse(value.provider));
210
+ break;
211
+ case 'profile_evidence': {
212
+ const q = z.object({ source_prefix: z.string().min(1).startsWith('personal:').endsWith(':'), provider: id, ids: z.array(id).max(256).optional() }).strict().parse(input);
213
+ const records = [], counts = new Map();
214
+ if (q.ids?.some(value => !value.startsWith(q.source_prefix)))
215
+ throw Error('STORE_INVALID_OPERATION');
216
+ const candidates = q.ids ? q.ids.map(id => ({ id })) : db.prepare(`SELECT id FROM memory_evidence WHERE substr(source_id,1,?)=? AND json_extract(payload_json,'$.source_kind') IN ('im','mail') AND (
217
+ (json_extract(payload_json,'$.source_kind')='im' AND (json_extract(payload_json,'$.source_metadata.sender_id')=json_extract(payload_json,'$.source_metadata.recipient_id') OR json_extract(payload_json,'$.source_metadata.mention')='direct')) OR
218
+ (json_extract(payload_json,'$.source_kind')='mail' AND json_extract(payload_json,'$.source_metadata.sender_id')=json_extract(payload_json,'$.source_metadata.account_id')))
219
+ ORDER BY json_extract(payload_json,'$.observed_at') DESC,id DESC LIMIT 1024`).all(q.source_prefix.length, q.source_prefix);
220
+ for (const row of candidates) {
221
+ const record = effectiveEvidence(db, String(row.id), { purpose: 'extraction', provider: q.provider });
222
+ const metadata = record?.source_metadata;
223
+ const own = record?.source_kind === 'im' ? metadata?.sender_id === metadata?.recipient_id : record?.source_kind === 'mail' && metadata?.sender_id === metadata?.account_id;
224
+ const bucket = record?.source_kind + ':' + (own ? 'self' : 'addressed');
225
+ const head = record && db.prepare('SELECT evidence_id FROM memory_message_heads WHERE key=?').get(createHash('sha256').update(canonicalJson([record.source_id, record.locator])).digest('hex'));
226
+ const superseded = head ? head.evidence_id !== record?.id : record && db.prepare("SELECT 1 FROM memory_evidence WHERE source_id=? AND json_extract(payload_json,'$.locator')=? AND rowid>(SELECT rowid FROM memory_evidence WHERE id=?) LIMIT 1").get(record.source_id, record.locator, record.id);
227
+ if (superseded || !record?.raw_text || !metadata || (!own && !(record.source_kind === 'im' && metadata.mention === 'direct')) || Date.parse(record.observed_at) > Date.now() || (!q.ids && (counts.get(bucket) ?? 0) >= 32))
228
+ continue;
229
+ records.push(record);
230
+ counts.set(bucket, (counts.get(bucket) ?? 0) + 1);
231
+ if (!q.ids && records.length === 96)
232
+ break;
233
+ }
234
+ result = records;
235
+ break;
236
+ }
237
+ case 'im_context': {
238
+ const q = z.object({ source_prefix: z.string().min(1).startsWith('personal:').endsWith(':'), provider: id, account_id: id, chat_id: id }).strict().parse(input);
239
+ const context = [], now = Date.now();
240
+ const candidates = db.prepare("SELECT id FROM memory_evidence WHERE substr(source_id,1,?)=? AND json_extract(payload_json,'$.source_kind')='im' AND json_extract(payload_json,'$.source_metadata.account_id')=? AND json_extract(payload_json,'$.source_metadata.chat_id')=? ORDER BY json_extract(payload_json,'$.observed_at') DESC,id DESC").all(q.source_prefix.length, q.source_prefix, q.account_id, q.chat_id);
241
+ for (const row of candidates) {
242
+ const ref = effectiveEvidence(db, String(row.id), { purpose: 'extraction', provider: q.provider });
243
+ if (!ref || Date.parse(ref.observed_at) > now)
244
+ continue;
245
+ context.push(ref);
246
+ if (context.length === 12)
247
+ break;
248
+ }
249
+ result = context;
250
+ break;
251
+ }
252
+ case 'daily_evidence': {
253
+ const q = z.object({ source_prefix: z.string().min(1).startsWith('personal:').endsWith(':'), provider: id }).strict().parse(input);
254
+ result = db.prepare("SELECT id FROM memory_evidence WHERE substr(source_id,1,?)=? AND json_extract(payload_json,'$.source_kind') IN ('calendar','im')").all(q.source_prefix.length, q.source_prefix).flatMap(row => {
255
+ const ref = effectiveEvidence(db, String(row.id), { purpose: 'extraction', provider: q.provider });
256
+ if (!ref || (ref.source_kind !== 'calendar' && (ref.source_kind !== 'im' || ref.source_metadata?.mention !== 'direct')))
257
+ return [];
258
+ if (ref.source_kind === 'im') {
259
+ const metadata = ref.source_metadata;
260
+ if (metadata?.chat_id && metadata.message_id) {
261
+ const messageKey = sha256(canonicalJson([metadata.account_id, metadata.chat_id, metadata.message_id]));
262
+ if (db.prepare('SELECT 1 FROM memory_life_im_receipts WHERE namespace=? AND message_key=?').get(q.source_prefix + 'life:', messageKey))
263
+ return [];
264
+ }
265
+ }
266
+ const calendar = ref.source_kind === 'calendar' ? sourceObjectFor(db, ref.source_id)?.metadata : undefined;
267
+ return [{ ...ref, ...(calendar ? { extracted: { ...ref.extracted, calendar } } : {}) }];
268
+ });
269
+ break;
270
+ }
271
+ case 'processing_evidence':
272
+ result = effectiveEvidence(db, id.parse(value.id), { purpose: z.enum(['extraction', 'embedding', 'conversation']).parse(value.purpose), provider: id.parse(value.provider) });
273
+ break;
274
+ case 'invalidate_message': {
275
+ const q = z.object({ source_id: id, locator: z.string().min(1).max(4096) }).strict().parse(input);
276
+ const records = rows(db, "SELECT payload_json FROM memory_evidence WHERE source_id=? AND json_extract(payload_json,'$.source_kind')='im' AND json_extract(payload_json,'$.locator')=?", q.source_id, q.locator).map(row => EvidenceRecordSchema.parse(row));
277
+ for (let offset = 0; offset < records.length; offset += 256)
278
+ memoryOperation(db, 'invalidate_evidence', { ids: records.slice(offset, offset + 256).map(record => record.id) }, false);
279
+ for (const record of records)
280
+ db.prepare('UPDATE memory_evidence SET payload_json=? WHERE id=?').run(JSON.stringify({ ...record, raw_text: null }), record.id);
281
+ break;
282
+ }
283
+ case 'invalidate_evidence': {
284
+ const ids = z.array(id).max(256).parse(value.ids);
285
+ for (const entry of all(db))
286
+ if (entry.op !== 'tombstone' && entry.origin === 'inferred' && entry.evidence_refs.some(ref => ids.includes(ref))) {
287
+ const fields = { ...entry };
288
+ Reflect.deleteProperty(fields, 'revision');
289
+ Reflect.deleteProperty(fields, 'supersedes');
290
+ write(db, CandidateSchema.parse({ ...fields, op: 'tombstone', content: { reason: 'evidence_superseded' }, recorded_at: new Date().toISOString() }), true);
291
+ for (const ref of entry.evidence_refs)
292
+ if (retrievalEvidence(db, ref)) {
293
+ db.prepare('DELETE FROM memory_extractions WHERE evidence_id=?').run(ref);
294
+ db.prepare("DELETE FROM source_extractions WHERE json_extract(payload_json,'$.ticket.evidence_id')=?").run(ref);
295
+ }
296
+ }
297
+ break;
298
+ }
299
+ case 'pending_vectors':
300
+ case 'write_vectors':
301
+ case 'search':
302
+ result = memoryRetrieval(db, operation, input);
303
+ break;
304
+ case 'append_evidence': {
305
+ const parsed = EvidenceRecordSchema.parse(value);
306
+ if (isPermanentlyPurged(db, parsed.id))
307
+ throw Error('STORE_PURGED_ID');
308
+ if (db.prepare('SELECT source_id FROM memory_deleted_sources WHERE source_id=?').get(parsed.source_id))
309
+ throw new Error('STORE_INVALID_OPERATION');
310
+ if (['file', 'mail', 'calendar', 'im'].includes(parsed.source_kind) && parsed.trust !== 'untrusted_external')
311
+ throw new Error('STORE_INVALID_OPERATION');
312
+ const redactions = [...parsed.sensitivity.redactions];
313
+ const safe = EvidenceRecordSchema.parse({ ...parsed, raw_text: scrub(parsed.raw_text, redactions, 'raw_text'), locator: scrub(parsed.locator, redactions, 'locator') ?? '[redacted]', extracted: scrub(parsed.extracted, redactions, 'extracted'), sensitivity: { policy_version: '1', redactions }, retention_until: parsed.retention_until ?? (parsed.source_kind === 'im' ? new Date(Date.parse(parsed.recorded_at) + 30 * 86400000).toISOString() : null) });
314
+ const existing = evidence(db, safe.id);
315
+ if (existing && (existing.hash !== safe.hash || existing.source_id !== safe.source_id || existing.locator !== safe.locator))
316
+ throw new Error('STORE_IDEMPOTENCY_CONFLICT');
317
+ if (!existing)
318
+ db.prepare('INSERT INTO memory_evidence VALUES(?,?,?,?)').run(safe.id, safe.source_id, safe.hash, canonicalJson(safe));
319
+ if (['im', 'mail'].includes(safe.source_kind))
320
+ db.prepare('INSERT INTO memory_message_heads VALUES(?,?) ON CONFLICT(key) DO UPDATE SET evidence_id=excluded.evidence_id').run(createHash('sha256').update(canonicalJson([safe.source_id, safe.locator])).digest('hex'), safe.id);
321
+ result = existing ?? safe;
322
+ break;
323
+ }
324
+ case 'commit_consolidation': {
325
+ const q = z.object({ entry_prefix: id, provider: id, candidate: CandidateSchema, contexts: z.array(z.object({ entry_id: id, revision: z.number().int().positive(), stamp: z.string().min(1) }).strict()).min(1).max(32) }).strict().parse(value);
326
+ const c = q.candidate;
327
+ if (c.kind !== 'memory_summary' || c.origin !== 'inferred' || c.written_by !== 'merge' || c.op === 'tombstone' || c.expected_revision === undefined || !c.entry_id.startsWith(q.entry_prefix) || new Set(q.contexts.map(r => r.entry_id)).size !== q.contexts.length)
328
+ throw Error('STORE_INVALID_OPERATION');
329
+ const basis = z.array(z.object({ id, revision: z.number().int().positive() }).strict()).parse(c.content.basis);
330
+ const expected = q.contexts.map(r => ({ id: r.entry_id, revision: r.revision })).sort((a, b) => a.id.localeCompare(b.id));
331
+ if (canonicalJson([...basis].sort((a, b) => a.id.localeCompare(b.id))) !== canonicalJson(expected))
332
+ throw Error('STORE_INVALID_OPERATION');
333
+ const refs = new Set();
334
+ let valid = true;
335
+ for (const context of q.contexts) {
336
+ const row = current(db, context.entry_id);
337
+ if (!row || !row.entry_id.startsWith(q.entry_prefix) || row.kind === 'memory_summary' || row.op === 'tombstone' || row.revision !== context.revision || (row.valid_until !== null && Date.parse(row.valid_until) <= Date.now()) || processingStamp(db, row.evidence_refs, 'extraction', q.provider) !== context.stamp) {
338
+ valid = false;
339
+ break;
340
+ }
341
+ for (const ref of row.evidence_refs)
342
+ refs.add(ref);
343
+ }
344
+ if (!valid) {
345
+ result = { applied: false };
346
+ break;
347
+ }
348
+ if (canonicalJson([...refs].sort()) !== canonicalJson([...new Set(c.evidence_refs)].sort()))
349
+ throw Error('STORE_INVALID_OPERATION');
350
+ if ((current(db, c.entry_id)?.revision ?? 0) !== c.expected_revision) {
351
+ result = { applied: false };
352
+ break;
353
+ }
354
+ result = { applied: write(db, c) !== null };
355
+ break;
356
+ }
357
+ case 'merge':
358
+ result = write(db, CandidateSchema.parse(value));
359
+ break;
360
+ case 'list': {
361
+ const now = date.parse(value.now ?? new Date().toISOString());
362
+ const includeHistory = z.boolean().parse(value.include_history ?? false), excludeFileInferences = z.boolean().parse(value.exclude_file_inferences ?? false);
363
+ result = all(db).filter(entry => (includeHistory || (entry.op !== 'tombstone' && (entry.valid_until === null || Date.parse(entry.valid_until) > Date.parse(now)))) && (!excludeFileInferences || !fileDerivedInference(db, entry)));
364
+ break;
365
+ }
366
+ case 'history':
367
+ result = rows(db, 'SELECT payload_json FROM memory_revisions WHERE entry_id=? ORDER BY revision', id.parse(value.entry_id));
368
+ break;
369
+ case 'evidence':
370
+ result = evidence(db, id.parse(value.id));
371
+ break;
372
+ case 'retrieval_evidence':
373
+ result = retrievalEvidence(db, id.parse(value.id));
374
+ break;
375
+ case 'extraction_done':
376
+ result = db.prepare('SELECT 1 FROM memory_extractions WHERE evidence_id=? LIMIT 1').get(id.parse(value.id)) !== undefined;
377
+ break;
378
+ case 'pending_evidence': {
379
+ const prefix = id.parse(value.source_prefix);
380
+ const provider = value.provider === undefined ? '' : id.parse(value.provider);
381
+ const limit = z.number().int().min(1).max(100).parse(value.limit ?? 100);
382
+ result = rows(db, `SELECT e.payload_json FROM memory_evidence e WHERE substr(e.source_id,1,length(?))=?
383
+ AND json_extract(e.payload_json,'$.raw_text') IS NOT NULL AND json_extract(e.payload_json,'$.source_kind') NOT IN ('user_correction','file')
384
+ AND (json_extract(e.payload_json,'$.retention_until') IS NULL OR julianday(json_extract(e.payload_json,'$.retention_until'))>julianday('now'))
385
+ AND (?='' OR EXISTS (SELECT 1 FROM source_grants g WHERE g.source_id=e.source_id AND json_extract(g.payload_json,'$.extraction_provider')=?))
386
+ AND (?='' OR NOT EXISTS (SELECT 1 FROM source_objects o JOIN source_connections c ON c.id=o.connection_id JOIN source_grants g ON g.source_id=e.source_id WHERE json_extract(o.payload_json,'$.source_id')=e.source_id AND (json_extract(c.payload_json,'$.state')<>'connected' OR json_extract(c.payload_json,'$.fence.scope_revision')<>json_extract(g.payload_json,'$.scope_revision'))))
387
+ AND (?='' OR NOT EXISTS (SELECT 1 FROM source_objects o JOIN source_connections c ON c.id=o.connection_id JOIN source_grants g ON g.source_id=e.source_id JOIN source_grants cg ON cg.source_id=c.id WHERE json_extract(o.payload_json,'$.source_id')=e.source_id AND (json_extract(cg.payload_json,'$.revision') IS NOT json_extract(g.payload_json,'$.revision') OR json_extract(cg.payload_json,'$.scope_revision') IS NOT json_extract(g.payload_json,'$.scope_revision') OR json_extract(cg.payload_json,'$.extraction_provider') IS NOT json_extract(g.payload_json,'$.extraction_provider'))))
388
+ AND NOT EXISTS (SELECT 1 FROM memory_suppressed s WHERE s.hash=e.hash)
389
+ AND NOT EXISTS (SELECT 1 FROM memory_extractions x WHERE x.evidence_id=e.id)
390
+ AND NOT EXISTS (SELECT 1 FROM source_objects o JOIN source_connections c ON c.id=o.connection_id WHERE json_extract(o.payload_json,'$.source_id')=e.source_id AND
391
+ (o.generation<>json_extract(c.payload_json,'$.fence.generation') OR NOT EXISTS (SELECT 1 FROM json_each(o.payload_json,'$.current_evidence_ids') r WHERE r.value=e.id)))
392
+ ORDER BY CASE WHEN json_extract(e.payload_json,'$.source_metadata.mention')='direct' THEN 0 ELSE 1 END, json_extract(e.payload_json,'$.observed_at') DESC, e.id LIMIT ?`, prefix, prefix, provider, provider, provider, provider, String(limit)).map(row => EvidenceRecordSchema.parse(row)).filter(row => retrievalEvidence(db, row.id) !== null);
393
+ break;
394
+ }
395
+ case 'append_evidence_batch': {
396
+ const q = z.object({ items: z.array(EvidenceRecordSchema).min(1).max(256) }).strict().parse(value);
397
+ let changed = false;
398
+ const records = q.items.map(item => {
399
+ const head = ['im', 'mail'].includes(item.source_kind) ? db.prepare('SELECT evidence_id FROM memory_message_heads WHERE key=?').get(createHash('sha256').update(canonicalJson([item.source_id, item.locator])).digest('hex')) : undefined;
400
+ if (!evidence(db, item.id) || (['im', 'mail'].includes(item.source_kind) && head?.evidence_id !== item.id))
401
+ changed = true;
402
+ return memoryOperation(db, 'append_evidence', item, false);
403
+ });
404
+ result = { records, changed };
405
+ break;
406
+ }
407
+ case 'record_evidence_batch': {
408
+ // One transaction for a document's chunks: each is admitted, then marked as already extracted.
409
+ const q = z.object({ items: z.array(z.object({ evidence: z.unknown(), attempt_id: id }).strict()).min(1).max(256) }).strict().parse(value);
410
+ result = q.items.map(item => { const saved = EvidenceRecordSchema.parse(memoryOperation(db, 'append_evidence', item.evidence, false)); memoryOperation(db, 'record_extraction', { evidence_id: saved.id, attempt_id: item.attempt_id, extracted: {} }, false); return saved; });
411
+ break;
412
+ }
413
+ case 'record_extraction': {
414
+ const evidenceId = id.parse(value.evidence_id);
415
+ if (!evidence(db, evidenceId))
416
+ throw new Error('STORE_NOT_FOUND');
417
+ const attempt = id.parse(value.attempt_id);
418
+ const redactions = [];
419
+ const payload = canonicalJson(scrub(object.parse(value.extracted), redactions));
420
+ db.prepare('INSERT OR IGNORE INTO memory_extractions VALUES(?,?,?)').run(evidenceId, attempt, payload);
421
+ break;
422
+ }
423
+ case 'forget': {
424
+ const entry = current(db, id.parse(value.entry_id));
425
+ if (!entry)
426
+ throw new Error('STORE_NOT_FOUND');
427
+ const correction = CandidateSchema.parse(value.candidate);
428
+ if (correction.entry_id !== entry.entry_id || correction.written_by !== 'user_correction' || correction.op !== 'tombstone')
429
+ throw new Error('STORE_INVALID_OPERATION');
430
+ result = write(db, correction);
431
+ for (const ref of entry.evidence_refs) {
432
+ const source = evidence(db, ref);
433
+ if (source)
434
+ db.prepare('INSERT OR IGNORE INTO memory_suppressed VALUES(?)').run(source.hash);
435
+ }
436
+ break;
437
+ }
438
+ case 'delete_source': {
439
+ const source = id.parse(value.source_id);
440
+ const affected = rows(db, 'SELECT payload_json FROM memory_evidence WHERE source_id=?', source).map(row => EvidenceRecordSchema.parse(row).id);
441
+ for (const ref of affected) {
442
+ db.prepare('DELETE FROM memory_extractions WHERE evidence_id=?').run(ref);
443
+ db.prepare("DELETE FROM source_extractions WHERE json_extract(payload_json,'$.ticket.evidence_id')=?").run(ref);
444
+ }
445
+ for (const entry of all(db))
446
+ if (entry.evidence_refs.some(ref => affected.includes(ref)))
447
+ db.prepare('DELETE FROM memory_vectors WHERE entry_id=?').run(entry.entry_id);
448
+ db.prepare('INSERT OR IGNORE INTO memory_deleted_sources VALUES(?)').run(source);
449
+ db.prepare('DELETE FROM memory_evidence WHERE source_id=?').run(source);
450
+ result = [];
451
+ for (const entry of all(db)) {
452
+ if (entry.op !== 'tombstone' && entry.evidence_refs.every(ref => evidence(db, ref) === null)) {
453
+ const fields = { ...entry };
454
+ Reflect.deleteProperty(fields, 'revision');
455
+ Reflect.deleteProperty(fields, 'supersedes');
456
+ const candidate = CandidateSchema.parse({ ...fields, op: 'tombstone', origin: 'inferred', written_by: 'merge', content: { reason: 'evidence_deleted' }, recorded_at: new Date().toISOString() });
457
+ result.push(write(db, candidate, true));
458
+ }
459
+ }
460
+ break;
461
+ }
462
+ case 'expire': {
463
+ const now = Date.parse(date.parse(value.now ?? new Date().toISOString()));
464
+ let count = 0;
465
+ for (const raw of rows(db, 'SELECT payload_json FROM memory_evidence')) {
466
+ const record = EvidenceRecordSchema.parse(raw);
467
+ if (record.raw_text !== null && record.retention_until !== null && Date.parse(record.retention_until) <= now) {
468
+ db.prepare('UPDATE memory_evidence SET payload_json=? WHERE id=?').run(canonicalJson({ ...record, raw_text: null }), record.id);
469
+ count++;
470
+ }
471
+ }
472
+ result = count;
473
+ break;
474
+ }
475
+ default: throw new Error('STORE_INVALID_OPERATION');
476
+ }
477
+ if (transaction) {
478
+ db.exec('COMMIT');
479
+ committed = true;
480
+ if (!ledgerOnly)
481
+ flushMemoryFiles(db);
482
+ }
483
+ return result;
484
+ }
485
+ catch (error) {
486
+ if (transaction && !committed)
487
+ db.exec('ROLLBACK');
488
+ throw error;
489
+ }
490
+ }
491
+ /** Hand edits become normal user corrections, never an untracked authoritative override. */
492
+ export function reconcileMemoryFiles(db) {
493
+ const snapshot = readMemoryFiles(db);
494
+ if (!snapshot?.edits.length)
495
+ return;
496
+ db.exec('BEGIN IMMEDIATE');
497
+ let committed = false;
498
+ try {
499
+ for (const edit of snapshot.edits) {
500
+ const previous = current(db, edit.entry_id);
501
+ if (previous?.revision !== edit.expected_revision)
502
+ throw Error('STORE_STALE_REVISION');
503
+ const prefix = previous.entry_id.startsWith('personal:') ? previous.entry_id.split(':').slice(0, 2).join(':') + ':' : 'workspace:';
504
+ const evidenceId = prefix + 'e:' + contentHash(edit.entry_id + ':' + edit.expected_revision + ':' + edit.hash);
505
+ const now = new Date().toISOString(), text = typeof edit.content.text === 'string' ? edit.content.text : canonicalJson(edit.content);
506
+ memoryOperation(db, 'append_evidence', { id: evidenceId, source_id: prefix + 'manual:' + contentHash(edit.entry_id), source_kind: 'user_correction', locator: 'markdown:' + edit.path, observed_at: now, recorded_at: now, raw_text: text, hash: contentHash(evidenceId + text), trust: 'trusted_user' }, false);
507
+ const originalSources = previous.evidence_refs.map(ref => evidence(db, ref)?.source_id);
508
+ const inheritedGrant = originalSources.some(source => source === undefined) ? null : correctionProcessingGrant(db, originalSources);
509
+ if (inheritedGrant) {
510
+ const sourceId = prefix + 'manual:' + contentHash(edit.entry_id), revision = readProcessingGrant(db, sourceId)?.revision ?? 0;
511
+ memoryOperation(db, 'source_grant', { source_id: sourceId, expected_revision: revision, grant: { ...inheritedGrant, revision: revision + 1 } }, false);
512
+ }
513
+ write(db, CandidateSchema.parse({ entry_id: edit.entry_id, expected_revision: edit.expected_revision, kind: previous.kind, origin: 'stated', written_by: 'user_correction', evidence_refs: [evidenceId], entity_refs: previous.entity_refs, content: edit.content, valid_until: previous.valid_until, recorded_at: now }));
514
+ }
515
+ db.exec('COMMIT');
516
+ committed = true;
517
+ flushMemoryFiles(db);
518
+ }
519
+ catch (error) {
520
+ if (!committed)
521
+ db.exec('ROLLBACK');
522
+ throw error;
523
+ }
524
+ }
525
+ /** Raw admission and permission fences remain usable when editable documents need repair. */
526
+ export function isLedgerOnlyOperation(operation, value) {
527
+ if (['source_processing', 'append_evidence_batch', 'profile_evidence', 'append_evidence', 'evidence', 'retrieval_evidence', 'processing_evidence', 'processing_stamp', 'source_grant', 'expire', 'source_revision', 'extraction_ticket', 'source_pending', 'source_events'].includes(operation))
528
+ return true;
529
+ // An extraction marker only records that an attempt ran; it never writes entries.
530
+ if (operation === 'record_extraction' || operation === 'record_evidence_batch')
531
+ return true;
532
+ return operation === 'source_connection' && ['get', 'list', 'create', 'fence', 'sync_status', 'reset_sync'].includes(String(value.action));
533
+ }
534
+ //# sourceMappingURL=store.js.map