nova-personal-agent-server 0.4.0 → 1.0.2

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 (327) hide show
  1. package/LICENSE +674 -201
  2. package/README.md +12 -2
  3. package/bin/nova-space-host.mjs +4 -0
  4. package/node_modules/@nova-personal-agent/relay/dist/src/cli.js +71 -0
  5. package/node_modules/@nova-personal-agent/relay/dist/src/client.js +340 -0
  6. package/node_modules/@nova-personal-agent/relay/dist/src/crypto.js +167 -0
  7. package/node_modules/@nova-personal-agent/relay/dist/src/live.js +169 -0
  8. package/node_modules/@nova-personal-agent/relay/dist/src/mailbox.js +217 -0
  9. package/node_modules/@nova-personal-agent/relay/dist/src/media.js +320 -0
  10. package/node_modules/@nova-personal-agent/relay/dist/src/pairing.js +13 -0
  11. package/node_modules/@nova-personal-agent/relay/dist/src/protocol.js +50 -0
  12. package/node_modules/@nova-personal-agent/relay/dist/src/security.js +305 -0
  13. package/node_modules/@nova-personal-agent/relay/dist/src/server.js +477 -0
  14. package/node_modules/@nova-personal-agent/relay/dist/src/source-address.js +58 -0
  15. package/node_modules/@nova-personal-agent/relay/package.json +1 -0
  16. package/package.json +13 -6
  17. package/runtime/dist/src/cascaded-text-provider.js +8 -3
  18. package/runtime/dist/src/composition/assembly.js +133 -35
  19. package/runtime/dist/src/composition/cascaded-realtime-assembly.js +114 -59
  20. package/runtime/dist/src/composition/production-composition.js +57 -21
  21. package/runtime/dist/src/composition/realtime-assembly.js +160 -52
  22. package/runtime/dist/src/composition/soul-context.js +22 -0
  23. package/runtime/dist/src/config/capability-registry.js +48 -3
  24. package/runtime/dist/src/config/cascaded-realtime-config.js +23 -10
  25. package/runtime/dist/src/config/config.js +541 -128
  26. package/runtime/dist/src/config/credential-rotation.js +26 -0
  27. package/runtime/dist/src/config/data-root.js +764 -0
  28. package/runtime/dist/src/config/diagnostics.js +3 -1
  29. package/runtime/dist/src/config/environment-contract.js +190 -188
  30. package/runtime/dist/src/config/model-routes.js +140 -0
  31. package/runtime/dist/src/config/voice-credentials.js +55 -0
  32. package/runtime/dist/src/connectors/composio/index.js +9 -0
  33. package/runtime/dist/src/connectors/feishu/index.js +258 -44
  34. package/runtime/dist/src/connectors/macos/mail.js +7 -3
  35. package/runtime/dist/src/connectors/macos/reader.js +3 -1
  36. package/runtime/dist/src/conversation-voice-provider.js +5 -2
  37. package/runtime/dist/src/core/causal-runtime.js +38 -3
  38. package/runtime/dist/src/core/context-view.js +7 -0
  39. package/runtime/dist/src/core/guards.js +32 -0
  40. package/runtime/dist/src/core/runtime.js +3 -0
  41. package/runtime/dist/src/core/schedule-tools.js +2 -2
  42. package/runtime/dist/src/core/source-processing-instructions.js +2 -2
  43. package/runtime/dist/src/core/source-processing-tools.js +3 -1
  44. package/runtime/dist/src/core/tool-schema.js +42 -7
  45. package/runtime/dist/src/desktop/desktop-camera.js +3 -5
  46. package/runtime/dist/src/desktop/desktop-control.js +41 -8
  47. package/runtime/dist/src/desktop/desktop-session.js +90 -19
  48. package/runtime/dist/src/desktop/desktop-wire.js +5 -7
  49. package/runtime/dist/src/desktop/startup-error.js +18 -16
  50. package/runtime/dist/src/desktop/workbench-acceptance.js +52 -14
  51. package/runtime/dist/src/desktop-entry.js +6 -2
  52. package/runtime/dist/src/desktop.js +5 -1
  53. package/runtime/dist/src/device/attempt.js +65 -0
  54. package/runtime/dist/src/device/authority.js +159 -0
  55. package/runtime/dist/src/device/gateway.js +87 -0
  56. package/runtime/dist/src/device/ledger.js +91 -0
  57. package/runtime/dist/src/device/ownership.js +92 -0
  58. package/runtime/dist/src/device/port.js +2 -0
  59. package/runtime/dist/src/device/schedule-ownership.js +103 -0
  60. package/runtime/dist/src/executors/acp/transport.js +2 -0
  61. package/runtime/dist/src/executors/browser.js +4 -3
  62. package/runtime/dist/src/executors/codex/adapter-project.js +58 -12
  63. package/runtime/dist/src/executors/codex/app-server-schema.js +12 -21
  64. package/runtime/dist/src/executors/codex/app-server-transport.js +32 -18
  65. package/runtime/dist/src/executors/codex/common.js +1 -1
  66. package/runtime/dist/src/executors/codex/contract.js +12 -16
  67. package/runtime/dist/src/executors/codex/credential-snapshot.js +1 -9
  68. package/runtime/dist/src/executors/codex/factory.js +54 -32
  69. package/runtime/dist/src/executors/codex/host-config.js +69 -20
  70. package/runtime/dist/src/executors/codex/launch-profile.js +3 -2
  71. package/runtime/dist/src/executors/codex/local-provider-credential.js +39 -0
  72. package/runtime/dist/src/executors/codex/process-owner.js +4 -6
  73. package/runtime/dist/src/executors/codex/production-host.js +33 -34
  74. package/runtime/dist/src/executors/codex/protocol.js +9 -14
  75. package/runtime/dist/src/executors/codex/session-title.js +6 -8
  76. package/runtime/dist/src/executors/codex/spawn-env.js +27 -6
  77. package/runtime/dist/src/executors/codex/turn-projection.js +12 -17
  78. package/runtime/dist/src/executors/codex/windows-guardian.js +4 -6
  79. package/runtime/dist/src/executors/coding/intake.js +12 -7
  80. package/runtime/dist/src/executors/computer-backend.js +18 -10
  81. package/runtime/dist/src/executors/computer-config.js +32 -0
  82. package/runtime/dist/src/executors/computer-device.js +68 -16
  83. package/runtime/dist/src/executors/computer-worker.js +18 -6
  84. package/runtime/dist/src/executors/computer.js +29 -56
  85. package/runtime/dist/src/executors/device-lock.js +14 -5
  86. package/runtime/dist/src/executors/gui-execution.js +2 -0
  87. package/runtime/dist/src/executors/index.js +0 -1
  88. package/runtime/dist/src/executors/mobile.js +9 -8
  89. package/runtime/dist/src/executors/native-process.js +4 -0
  90. package/runtime/dist/src/executors/search.js +3 -5
  91. package/runtime/dist/src/executors/task-resources.js +21 -0
  92. package/runtime/dist/src/executors/watcher.js +2 -4
  93. package/runtime/dist/src/experience/host.js +179 -0
  94. package/runtime/dist/src/index.js +2 -0
  95. package/runtime/dist/src/knowledge/assembly.js +3 -4
  96. package/runtime/dist/src/knowledge/embeddings.js +50 -34
  97. package/runtime/dist/src/knowledge/service.js +1 -0
  98. package/runtime/dist/src/knowledge/store-client.js +1 -6
  99. package/runtime/dist/src/knowledge/store-worker.js +1 -3
  100. package/runtime/dist/src/mem0/resource.js +25 -0
  101. package/runtime/dist/src/mem0/store-worker.js +234 -21
  102. package/runtime/dist/src/memory/consumer.js +31 -0
  103. package/runtime/dist/src/memory/engine-worker.js +210 -0
  104. package/runtime/dist/src/memory/entry.js +8 -1
  105. package/runtime/dist/src/memory/explicit-memory.js +20 -0
  106. package/runtime/dist/src/memory/factory.js +30 -15
  107. package/runtime/dist/src/memory/grounded-voicemem.js +10 -0
  108. package/runtime/dist/src/memory/ledger-recall-engine.js +86 -0
  109. package/runtime/dist/src/memory/prerecall-port.js +27 -0
  110. package/runtime/dist/src/memory/prerecall.js +1 -1
  111. package/runtime/dist/src/memory/production-engine.js +151 -0
  112. package/runtime/dist/src/memory/provenance.js +1 -0
  113. package/runtime/dist/src/memory/remote-personal-memory.js +3 -1
  114. package/runtime/dist/src/memory/retrieval.js +107 -22
  115. package/runtime/dist/src/memory/sensitivity.js +6 -2
  116. package/runtime/dist/src/memory/source-retrieval.js +11 -0
  117. package/runtime/dist/src/memory/tool-capabilities.js +46 -0
  118. package/runtime/dist/src/memory/voicemem-sdk/LICENSE +202 -0
  119. package/runtime/dist/src/memory/voicemem-sdk/NOTICE.md +97 -0
  120. package/runtime/dist/src/memory/voicemem-sdk/PATCH-NOTICE.md +23 -0
  121. package/runtime/dist/src/memory/voicemem-sdk/archive.js +12 -0
  122. package/runtime/dist/src/memory/voicemem-sdk/audio.js +111 -0
  123. package/runtime/dist/src/memory/voicemem-sdk/barge-in.js +59 -0
  124. package/runtime/dist/src/memory/voicemem-sdk/checkpoint.js +56 -0
  125. package/runtime/dist/src/memory/voicemem-sdk/cleanup.js +139 -0
  126. package/runtime/dist/src/memory/voicemem-sdk/dashscope-asr.js +254 -0
  127. package/runtime/dist/src/memory/voicemem-sdk/dashscope-tts.js +247 -0
  128. package/runtime/dist/src/memory/voicemem-sdk/evaluation.js +330 -0
  129. package/runtime/dist/src/memory/voicemem-sdk/extraction.js +220 -0
  130. package/runtime/dist/src/memory/voicemem-sdk/finetune-data.js +115 -0
  131. package/runtime/dist/src/memory/voicemem-sdk/finetune.js +170 -0
  132. package/runtime/dist/src/memory/voicemem-sdk/grounded-reply-preferences.js +81 -0
  133. package/runtime/dist/src/memory/voicemem-sdk/index.js +22 -0
  134. package/runtime/dist/src/memory/voicemem-sdk/local-embedding.js +164 -0
  135. package/runtime/dist/src/memory/voicemem-sdk/local-runtime.js +53 -0
  136. package/runtime/dist/src/memory/voicemem-sdk/local-speaker.js +240 -0
  137. package/runtime/dist/src/memory/voicemem-sdk/memory.js +767 -0
  138. package/runtime/dist/src/memory/voicemem-sdk/model-json.js +14 -0
  139. package/runtime/dist/src/memory/voicemem-sdk/personamem.js +209 -0
  140. package/runtime/dist/src/memory/voicemem-sdk/prompts/addenda.js +215 -0
  141. package/runtime/dist/src/memory/voicemem-sdk/prompts/additive-extraction.js +478 -0
  142. package/runtime/dist/src/memory/voicemem-sdk/prompts/index.js +32 -0
  143. package/runtime/dist/src/memory/voicemem-sdk/prompts/update-memory.js +152 -0
  144. package/runtime/dist/src/memory/voicemem-sdk/providers.js +325 -0
  145. package/runtime/dist/src/memory/voicemem-sdk/ranking.js +65 -0
  146. package/runtime/dist/src/memory/voicemem-sdk/reaction.js +33 -0
  147. package/runtime/dist/src/memory/voicemem-sdk/realtime.js +215 -0
  148. package/runtime/dist/src/memory/voicemem-sdk/reply.js +68 -0
  149. package/runtime/dist/src/memory/voicemem-sdk/routing.js +209 -0
  150. package/runtime/dist/src/memory/voicemem-sdk/slots.js +61 -0
  151. package/runtime/dist/src/memory/voicemem-sdk/speaker-bindings.js +120 -0
  152. package/runtime/dist/src/memory/voicemem-sdk/speaker-profiles.js +327 -0
  153. package/runtime/dist/src/memory/voicemem-sdk/store.js +577 -0
  154. package/runtime/dist/src/memory/voicemem-sdk/stream.js +317 -0
  155. package/runtime/dist/src/memory/voicemem-sdk/subgraph.js +113 -0
  156. package/runtime/dist/src/memory/voicemem-sdk/summaries.js +56 -0
  157. package/runtime/dist/src/memory/voicemem-sdk/time.js +157 -0
  158. package/runtime/dist/src/memory/voicemem-sdk/types.js +2 -0
  159. package/runtime/dist/src/memory-ledger/store-client.js +235 -37
  160. package/runtime/dist/src/memory-ledger/store-worker.js +8 -5
  161. package/runtime/dist/src/memory-ledger/store.js +91 -1
  162. package/runtime/dist/src/memory-substrate/consolidation.js +23 -7
  163. package/runtime/dist/src/memory-substrate/diary.js +27 -0
  164. package/runtime/dist/src/memory-substrate/engine-outbox.js +107 -0
  165. package/runtime/dist/src/memory-substrate/explicit-memory.js +112 -0
  166. package/runtime/dist/src/memory-substrate/fact-fidelity.js +68 -0
  167. package/runtime/dist/src/memory-substrate/feishu-consent.js +41 -0
  168. package/runtime/dist/src/memory-substrate/file-authority.js +29 -6
  169. package/runtime/dist/src/memory-substrate/life-operations.js +35 -9
  170. package/runtime/dist/src/memory-substrate/markdown-repository.js +271 -65
  171. package/runtime/dist/src/memory-substrate/memory-documents.js +96 -0
  172. package/runtime/dist/src/memory-substrate/migration.js +2 -0
  173. package/runtime/dist/src/memory-substrate/purge.js +12 -2
  174. package/runtime/dist/src/memory-substrate/resource.js +514 -129
  175. package/runtime/dist/src/memory-substrate/retrieval.js +8 -5
  176. package/runtime/dist/src/memory-substrate/source-operations.js +9 -1
  177. package/runtime/dist/src/memory-substrate/source-processing.js +436 -40
  178. package/runtime/dist/src/memory-substrate/source-retrieval.js +28 -0
  179. package/runtime/dist/src/memory-substrate/source-state.js +8 -0
  180. package/runtime/dist/src/memory-substrate/space-source-input.js +90 -0
  181. package/runtime/dist/src/memory-substrate/store.js +125 -23
  182. package/runtime/dist/src/model/goal-checkin-writer.js +72 -0
  183. package/runtime/dist/src/model/goal-writer.js +80 -0
  184. package/runtime/dist/src/model/jev-client.js +24 -13
  185. package/runtime/dist/src/model/model-adapters.js +2 -3
  186. package/runtime/dist/src/model/model-catalog.js +80 -0
  187. package/runtime/dist/src/model/model-gateway.js +47 -18
  188. package/runtime/dist/src/model/model-purpose.js +3 -4
  189. package/runtime/dist/src/model/personal-writer.js +536 -44
  190. package/runtime/dist/src/model/proactivity.js +50 -6
  191. package/runtime/dist/src/model/responses-model-gateway.js +59 -0
  192. package/runtime/dist/src/model/task-verifier.js +3 -3
  193. package/runtime/dist/src/model/timeline-anchors.js +77 -0
  194. package/runtime/dist/src/model/timeline-perspective.js +13 -0
  195. package/runtime/dist/src/model/timeline-selection.js +182 -0
  196. package/runtime/dist/src/model/understanding-writer.js +27 -0
  197. package/runtime/dist/src/model/vision-capability.js +3 -1
  198. package/runtime/dist/src/model/workbench-writer.js +96 -0
  199. package/runtime/dist/src/news/feeds.js +6 -10
  200. package/runtime/dist/src/news/interests.js +23 -0
  201. package/runtime/dist/src/news/service.js +87 -31
  202. package/runtime/dist/src/news/sources.json +116 -0
  203. package/runtime/dist/src/notifications/adapters/space-relay.js +4 -0
  204. package/runtime/dist/src/notifications/content.js +41 -0
  205. package/runtime/dist/src/notifications/contracts.js +4 -2
  206. package/runtime/dist/src/notifications/feed.js +6 -2
  207. package/runtime/dist/src/notifications/service.js +27 -14
  208. package/runtime/dist/src/notifications/store.js +3 -1
  209. package/runtime/dist/src/personal-agent/app-context.js +39 -4
  210. package/runtime/dist/src/personal-agent/chat-failure.js +37 -0
  211. package/runtime/dist/src/personal-agent/computer-use/contract.js +42 -0
  212. package/runtime/dist/src/personal-agent/computer-use/session.js +280 -0
  213. package/runtime/dist/src/personal-agent/computer-use/skill.js +18 -0
  214. package/runtime/dist/src/personal-agent/computer-use/tools.js +15 -0
  215. package/runtime/dist/src/personal-agent/context-candidates.js +9 -13
  216. package/runtime/dist/src/personal-agent/context-dependencies.js +28 -0
  217. package/runtime/dist/src/personal-agent/contracts.js +24 -4
  218. package/runtime/dist/src/personal-agent/conversation-runtime.js +440 -42
  219. package/runtime/dist/src/personal-agent/conversation-tool-bridge.js +97 -0
  220. package/runtime/dist/src/personal-agent/conversation-tool-policy.js +22 -0
  221. package/runtime/dist/src/personal-agent/conversations.js +71 -15
  222. package/runtime/dist/src/personal-agent/daily-brief.js +5 -0
  223. package/runtime/dist/src/personal-agent/daily-workbench.js +558 -0
  224. package/runtime/dist/src/personal-agent/discovery-window.js +36 -0
  225. package/runtime/dist/src/personal-agent/goal-checkin.js +53 -0
  226. package/runtime/dist/src/personal-agent/host.js +2379 -223
  227. package/runtime/dist/src/personal-agent/identity-context.js +33 -0
  228. package/runtime/dist/src/personal-agent/life.js +129 -11
  229. package/runtime/dist/src/personal-agent/local-shell.js +181 -0
  230. package/runtime/dist/src/personal-agent/local-tools.js +234 -0
  231. package/runtime/dist/src/personal-agent/preferred-name-sync.js +35 -0
  232. package/runtime/dist/src/personal-agent/profile-warmup.js +100 -39
  233. package/runtime/dist/src/personal-agent/project-digests.js +7 -3
  234. package/runtime/dist/src/personal-agent/project-history.js +36 -0
  235. package/runtime/dist/src/personal-agent/reading-copies.js +183 -0
  236. package/runtime/dist/src/personal-agent/scheduled-tasks.js +50 -13
  237. package/runtime/dist/src/personal-agent/scheduled-tool-runtime.js +26 -10
  238. package/runtime/dist/src/personal-agent/source-processing-agent.js +239 -17
  239. package/runtime/dist/src/personal-agent/sources.js +9 -1
  240. package/runtime/dist/src/personal-agent/store.js +124 -14
  241. package/runtime/dist/src/personal-agent/task-loop.js +3 -0
  242. package/runtime/dist/src/personal-agent/tasks.js +16 -4
  243. package/runtime/dist/src/personal-agent/timeline-brief.js +462 -0
  244. package/runtime/dist/src/personal-agent/timeline-cache.js +191 -0
  245. package/runtime/dist/src/personal-agent/timeline-cluster.js +30 -0
  246. package/runtime/dist/src/personal-agent/timeline-inputs.js +47 -0
  247. package/runtime/dist/src/personal-agent/timeline-time.js +60 -0
  248. package/runtime/dist/src/personal-agent/understanding-products.js +49 -0
  249. package/runtime/dist/src/personal-agent/understanding.js +7 -22
  250. package/runtime/dist/src/personal-agent/workbench-context.js +17 -21
  251. package/runtime/dist/src/personal-agent/workbench-copy.js +124 -0
  252. package/runtime/dist/src/personal-agent/workbench-evidence.js +77 -0
  253. package/runtime/dist/src/personal-agent/workbench-instructions.js +21 -0
  254. package/runtime/dist/src/personal-agent/workbench-runtime.js +1006 -0
  255. package/runtime/dist/src/personal-agent/workbench-shell-class.js +304 -0
  256. package/runtime/dist/src/personal-agent/workbench-store.js +292 -0
  257. package/runtime/dist/src/personal-agent/workbench-temporal.js +66 -0
  258. package/runtime/dist/src/projects/project-native-resource.js +10 -8
  259. package/runtime/dist/src/projects/project-store.js +36 -4
  260. package/runtime/dist/src/realtime/bridge.js +77 -8
  261. package/runtime/dist/src/realtime/capabilities.js +19 -0
  262. package/runtime/dist/src/realtime/cascaded/adapter.js +180 -40
  263. package/runtime/dist/src/realtime/cascaded/ark-llm.js +150 -24
  264. package/runtime/dist/src/realtime/cascaded/chat-completions-llm.js +243 -83
  265. package/runtime/dist/src/realtime/cascaded/llm-stream-limits.js +18 -0
  266. package/runtime/dist/src/realtime/cascaded/llm.js +96 -0
  267. package/runtime/dist/src/realtime/cascaded/openai-compatible-speech.js +251 -0
  268. package/runtime/dist/src/realtime/cascaded/provider.js +8 -0
  269. package/runtime/dist/src/realtime/evidence.js +1 -1
  270. package/runtime/dist/src/realtime/frontend-instructions.js +76 -55
  271. package/runtime/dist/src/realtime/gemini.js +14 -3
  272. package/runtime/dist/src/realtime/host-delivery.js +37 -4
  273. package/runtime/dist/src/realtime/protocol.js +18 -3
  274. package/runtime/dist/src/realtime/provider-projection.js +4 -1
  275. package/runtime/dist/src/realtime/provider-session.js +73 -16
  276. package/runtime/dist/src/realtime/qwen-transport.js +35 -4
  277. package/runtime/dist/src/realtime/qwen.js +144 -9
  278. package/runtime/dist/src/realtime/service-state.js +0 -1
  279. package/runtime/dist/src/realtime/service.js +93 -7
  280. package/runtime/dist/src/realtime/session.js +39 -32
  281. package/runtime/dist/src/realtime/sglang-native.js +214 -0
  282. package/runtime/dist/src/realtime/system-prompts.en.js +14 -2
  283. package/runtime/dist/src/realtime/telemetry.js +6 -3
  284. package/runtime/dist/src/realtime/tool-continuations.js +84 -7
  285. package/runtime/dist/src/realtime/transport.js +17 -0
  286. package/runtime/dist/src/realtime/usage.js +33 -17
  287. package/runtime/dist/src/realtime/volcengine/ark.js +40 -15
  288. package/runtime/dist/src/realtime/volcengine/asr.js +2 -1
  289. package/runtime/dist/src/realtime/volcengine/silence-endpointing.js +1 -7
  290. package/runtime/dist/src/realtime/volcengine/tts.js +2 -1
  291. package/runtime/dist/src/server/aoq-chat-server.js +1 -1
  292. package/runtime/dist/src/server/client-server.js +21 -0
  293. package/runtime/dist/src/server-entry.js +3 -0
  294. package/runtime/dist/src/space-host/admin-socket.js +115 -0
  295. package/runtime/dist/src/space-host/audio-owner.js +44 -0
  296. package/runtime/dist/src/space-host/cli.js +195 -0
  297. package/runtime/dist/src/space-host/config.js +247 -0
  298. package/runtime/dist/src/space-host/context-input.js +12 -0
  299. package/runtime/dist/src/space-host/contracts.js +10 -0
  300. package/runtime/dist/src/space-host/host-admin.js +114 -0
  301. package/runtime/dist/src/space-host/key-delivery.js +28 -0
  302. package/runtime/dist/src/space-host/mobile-tools.js +9 -0
  303. package/runtime/dist/src/space-host/model-settings.js +213 -0
  304. package/runtime/dist/src/space-host/projection.js +37 -0
  305. package/runtime/dist/src/space-host/push.js +137 -0
  306. package/runtime/dist/src/space-host/relay-transport.js +55 -0
  307. package/runtime/dist/src/space-host/service.js +841 -0
  308. package/runtime/dist/src/space-host/voice-crypto.js +240 -0
  309. package/runtime/dist/src/space-host/voice.js +600 -0
  310. package/runtime/dist/src/space-host/windows-secret-key.js +82 -0
  311. package/runtime/dist/src/storage/private-database.js +7 -10
  312. package/runtime/dist/src/text/unicode-normalize.js +5 -1
  313. package/runtime/dist/src/understanding/candidates.js +8 -10
  314. package/runtime/dist/src/understanding/fixture.js +1 -1
  315. package/runtime/dist/src/understanding/pipeline.js +4 -4
  316. package/runtime/dist/src/usage/context.js +23 -0
  317. package/runtime/dist/src/usage/index.js +4 -0
  318. package/runtime/dist/src/usage/ledger-worker.js +90 -0
  319. package/runtime/dist/src/usage/ledger.js +74 -0
  320. package/runtime/dist/src/usage/model-call.js +63 -0
  321. package/runtime/dist/src/usage/pricing.js +68 -0
  322. package/runtime/dist/src/usage/summary.js +69 -0
  323. package/runtime/dist/src/voicemem/store-client.js +104 -21
  324. package/runtime/dist/src/voicemem/store-worker.js +5 -8
  325. package/runtime/dist/src/voicemem/versioned-memory.js +1 -1
  326. package/src/command.mjs +8 -1
  327. package/runtime/dist/src/executors/autoglm.js +0 -376
@@ -1,3 +1,4 @@
1
+ import { memoryDocuments, memoryDocumentEdits, semanticPath, EMPTY_MEMORY_DOCUMENT, MAX_MEMORY_DOCUMENT_BYTES } from './memory-documents.js';
1
2
  import { createHash, randomUUID } from 'node:crypto';
2
3
  import { execFileSync } from 'node:child_process';
3
4
  import { chmodSync, closeSync, constants, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
@@ -5,25 +6,26 @@ import { dirname, join, parse, resolve } from 'node:path';
5
6
  import { z } from 'zod';
6
7
  import { EntryRevisionSchema } from './store.js';
7
8
  import { canonicalJson } from '../text/canonical-json.js';
8
- const MAX_FILE = 8 * 1024 * 1024;
9
+ const MAX_FILE = MAX_MEMORY_DOCUMENT_BYTES;
9
10
  const MAX_BATCH = 64 * 1024 * 1024;
10
11
  const MAX_ENTRIES = 10_000;
11
12
  const MARKER = '.nova-memory.json';
12
13
  const LOCK_POLL_MS = 25;
13
14
  const LOCK_SLEEP = new Int32Array(new SharedArrayBuffer(4));
14
15
  const JOURNAL = '.nova-memory-batch.json';
15
- const markerText = '{"format":"nova-understanding","version":1}\n';
16
+ const legacyMarkerText = '{"format":"nova-understanding","version":1}\n';
17
+ const markerText = '{"format":"nova-understanding","version":2}\n';
16
18
  const hasPath = (path) => lstatSync(path, { throwIfNoEntry: false }) !== undefined;
17
19
  const digest = (text) => createHash('sha256').update(text).digest('hex');
18
20
  const entryPath = (id) => `entries/${digest(id)}.md`;
19
21
  const failure = (code) => new Error(`MEMORY_MARKDOWN_${code}`);
20
- const journalSchema = z.object({ version: z.literal(1), operationId: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/), baseCommit: z.string().regex(/^[a-f0-9]{40,64}$/).nullable(), files: z.array(z.object({ path: z.string().regex(/^(entries\/[a-f0-9]{64}\.md|\.nova-memory\.json)$/), beforeHash: z.string().regex(/^[a-f0-9]{64}$/).nullable(), after: z.string().max(MAX_FILE) }).strict()).max(MAX_ENTRIES + 1) }).strict();
21
- function history(revisions) {
22
+ const journalSchema = z.object({ version: z.literal(1), operationId: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/), baseCommit: z.string().regex(/^[a-f0-9]{40,64}$/).nullable(), files: z.array(z.object({ path: z.string().refine(path => path === MARKER || /^entries\/[a-f0-9]{64}\.md$/u.test(path) || semanticPath.test(path)), beforeHash: z.string().regex(/^[a-f0-9]{64}$/).nullable(), after: z.string().refine(text => Buffer.byteLength(text) <= MAX_FILE) }).strict()).max(MAX_ENTRIES * 3 + 3) }).strict();
23
+ function history(revisions, validated = false) {
22
24
  if (revisions.length > 100_000)
23
25
  throw failure('LIMIT');
24
26
  const result = new Map();
25
27
  for (const value of revisions) {
26
- const revision = EntryRevisionSchema.parse(value);
28
+ const revision = validated ? value : EntryRevisionSchema.parse(value);
27
29
  const list = result.get(revision.entry_id) ?? [];
28
30
  list.push(revision);
29
31
  result.set(revision.entry_id, list);
@@ -53,7 +55,7 @@ function decode(text) {
53
55
  if (!match)
54
56
  throw failure('FORMAT');
55
57
  const metadata = z.object({ format: z.literal(1), revisions: z.array(EntryRevisionSchema).min(1) }).strict().parse(JSON.parse(match[1]));
56
- const grouped = history(metadata.revisions);
58
+ const grouped = history(metadata.revisions, true);
57
59
  if (grouped.size !== 1)
58
60
  throw failure('FORMAT');
59
61
  const current = metadata.revisions.at(-1);
@@ -66,6 +68,7 @@ function decode(text) {
66
68
  export class MarkdownRepository {
67
69
  root;
68
70
  baseline;
71
+ cached;
69
72
  initialized = false;
70
73
  lockWaitMs;
71
74
  constructor(root, options = {}) { this.root = resolve(root); this.lockWaitMs = options.lockWaitMs ?? 0; }
@@ -73,7 +76,8 @@ export class MarkdownRepository {
73
76
  initialize() {
74
77
  if (this.initialized) {
75
78
  this.ensureRoot();
76
- this.assertSafe(join(this.root, 'entries'), true);
79
+ for (const name of ['entries', 'goals', 'todos', 'ideas', 'memory', 'entities'])
80
+ this.assertSafe(join(this.root, name), true);
77
81
  return;
78
82
  }
79
83
  this.ensureRoot();
@@ -89,11 +93,13 @@ export class MarkdownRepository {
89
93
  }
90
94
  else
91
95
  this.git(['init', '--quiet', '--template=']);
92
- const entries = join(this.root, 'entries');
93
- if (!hasPath(entries))
94
- mkdirSync(entries, { mode: 0o700 });
95
- this.assertSafe(entries, true);
96
- chmodSync(entries, 0o700);
96
+ for (const name of ['entries', 'goals', 'todos', 'ideas', 'memory', 'entities']) {
97
+ const directory = join(this.root, name);
98
+ if (!hasPath(directory))
99
+ mkdirSync(directory, { mode: 0o700 });
100
+ this.assertSafe(directory, true);
101
+ chmodSync(directory, 0o700);
102
+ }
97
103
  this.initialized = true;
98
104
  }
99
105
  /** Covers the caller's full SQLite read/admit/commit/file-publication cycle. Never steals a live owner's lock. */
@@ -175,28 +181,113 @@ export class MarkdownRepository {
175
181
  throw failure('UNOWNED_REPOSITORY');
176
182
  this.publish(initialRevisions);
177
183
  }
178
- return this.read();
184
+ const snapshot = this.read();
185
+ if (this.needsDocumentMigration() && !snapshot.edits.length) {
186
+ this.publish(snapshot.revisions);
187
+ return this.read();
188
+ }
189
+ return snapshot;
190
+ }
191
+ needsDocumentMigration() {
192
+ if (!hasPath(join(this.root, MARKER)))
193
+ return false;
194
+ return this.readFile(MARKER) === legacyMarkerText || (!hasPath(join(this.root, 'SOUL.md')) && this.head() !== null && !this.git(['ls-tree', '--name-only', 'HEAD']).split('\n').includes('SOUL.md'));
179
195
  }
180
196
  read() {
181
197
  this.initialize();
182
198
  if (this.pendingOperationId())
183
199
  throw failure('PENDING_OPERATION');
200
+ // Every ledger operation reconciles first. A full scan spawns Git and decodes every document twice,
201
+ // so an unchanged repository returns the snapshot it already validated.
202
+ const fingerprint = this.fingerprint();
203
+ if (fingerprint !== null && this.cached?.fingerprint === fingerprint) {
204
+ this.baseline = { ...this.cached.snapshot.baselines };
205
+ return structuredClone(this.cached.snapshot);
206
+ }
207
+ this.cached = undefined;
208
+ const snapshot = this.readUncached();
209
+ if (fingerprint !== null)
210
+ this.cached = { fingerprint, snapshot: structuredClone(snapshot) };
211
+ return snapshot;
212
+ }
213
+ /** Identifies the last validated snapshot; null when the latest read could not be cached. */
214
+ snapshotToken() { return this.cached?.fingerprint ?? null; }
215
+ /**
216
+ * Digest of every input a scan depends on: the marker, each entry and semantic document, and the
217
+ * Git refs. Objects are content-addressed, so a ref that has not moved names the same history.
218
+ * Lock files and untracked notes are excluded. Any doubt returns null and forces a full scan,
219
+ * which reports the canonical failure.
220
+ */
221
+ fingerprint() {
222
+ try {
223
+ const hash = createHash('sha256'), add = (relative) => { hash.update(relative + '\0'); hash.update(hasPath(join(this.root, relative)) ? this.readFile(relative) : '\u0000absent'); hash.update('\0'); };
224
+ add(MARKER);
225
+ for (const name of ['USER.md', 'MEMORY.md', 'SOUL.md'])
226
+ add(name);
227
+ for (const folder of ['entries', 'goals', 'todos', 'ideas', 'memory', 'entities']) {
228
+ const directory = join(this.root, folder);
229
+ if (!hasPath(directory)) {
230
+ hash.update(folder + '\0absent\0');
231
+ continue;
232
+ }
233
+ this.assertSafe(directory, true);
234
+ const names = readdirSync(directory).sort();
235
+ if (names.length > MAX_ENTRIES)
236
+ return null;
237
+ hash.update(folder + '/\0' + names.join('\0') + '\0');
238
+ for (const name of names)
239
+ add(`${folder}/${name}`);
240
+ }
241
+ const refs = (relative) => {
242
+ const path = join(this.root, relative), stat = lstatSync(path, { throwIfNoEntry: false });
243
+ if (stat === undefined) {
244
+ hash.update(relative + '\0absent\0');
245
+ return;
246
+ }
247
+ if (stat.isSymbolicLink())
248
+ throw failure('UNSAFE_PATH');
249
+ if (stat.isDirectory()) {
250
+ for (const name of readdirSync(path).sort())
251
+ refs(`${relative}/${name}`);
252
+ return;
253
+ }
254
+ add(relative);
255
+ };
256
+ for (const name of ['.git/HEAD', '.git/packed-refs', '.git/refs'])
257
+ refs(name);
258
+ return hash.digest('hex');
259
+ }
260
+ catch {
261
+ return null;
262
+ }
263
+ }
264
+ readUncached() {
184
265
  const revisions = [];
185
266
  const edits = [];
186
267
  const baselines = {};
268
+ let documents = false;
187
269
  if (hasPath(join(this.root, MARKER))) {
188
- if (this.readFile(MARKER) !== markerText)
270
+ const marker = this.readFile(MARKER);
271
+ if (marker !== markerText && marker !== legacyMarkerText)
189
272
  throw failure('FORMAT');
190
- baselines[MARKER] = digest(markerText);
273
+ documents = marker === markerText;
274
+ baselines[MARKER] = digest(marker);
191
275
  }
192
276
  const names = readdirSync(join(this.root, 'entries')).sort();
193
277
  if (names.length > MAX_ENTRIES)
194
278
  throw failure('LIMIT');
195
- const head = this.head();
196
- const tracked = head ? this.git(['ls-tree', '-r', '--name-only', head, '--', 'entries']).split('\n').filter(Boolean) : [];
279
+ const head = this.head(), tracked = head ? this.git(['ls-tree', '-r', '--name-only', head]).split('\n').filter(Boolean) : [];
280
+ // Publication replaces the whole owned Git tree; never drop a foreign tracked file.
197
281
  for (const path of tracked)
282
+ if (path !== MARKER && !/^entries\/[a-f0-9]{64}\.md$/u.test(path) && !semanticPath.test(path))
283
+ throw failure('CONFLICT');
284
+ const recordPaths = tracked.filter(path => path.startsWith('entries/'));
285
+ for (const path of recordPaths)
198
286
  if (!names.includes(path.slice('entries/'.length)))
199
287
  throw failure('CONFLICT');
288
+ const committedFiles = head ? this.committedFiles(head, [...recordPaths, ...(tracked.includes(MARKER) ? [MARKER] : [])]) : new Map();
289
+ if (head && (!committedFiles.has(MARKER) || digest(committedFiles.get(MARKER)) !== baselines[MARKER]))
290
+ throw failure('CONFLICT');
200
291
  let bytes = 0;
201
292
  for (const name of names) {
202
293
  const path = `entries/${name}`;
@@ -207,23 +298,50 @@ export class MarkdownRepository {
207
298
  bytes += Buffer.byteLength(text);
208
299
  if (bytes > MAX_BATCH)
209
300
  throw failure('LIMIT');
210
- const parsed = decode(text);
211
- const current = parsed.revisions.at(-1);
301
+ const parsed = decode(text), current = parsed.revisions.at(-1);
212
302
  if (path !== entryPath(current.entry_id))
213
303
  throw failure('FORMAT');
214
304
  if (head) {
215
- if (!tracked.includes(path))
305
+ if (!recordPaths.includes(path))
216
306
  throw failure('UNADMITTED_EDIT');
217
- const committed = decode(this.git(['show', `${head}:${path}`]));
218
- if (canonicalJson(parsed.revisions) !== canonicalJson(committed.revisions))
307
+ // Identical bytes carry identical history; only a changed file needs its committed header decoded.
308
+ const committedText = committedFiles.get(path);
309
+ if (committedText !== text && canonicalJson(parsed.revisions) !== canonicalJson(decode(committedText).revisions))
219
310
  throw failure('HISTORY_EDIT');
220
311
  }
221
312
  revisions.push(...parsed.revisions);
222
313
  baselines[path] = digest(text);
314
+ // Legacy body edits still enter the same merge path; conflicting document edits are rejected below.
223
315
  if (canonicalJson(parsed.content) !== canonicalJson(current.content))
224
316
  edits.push({ entry_id: current.entry_id, expected_revision: current.revision, content: parsed.content, path, hash: digest(text) });
225
317
  }
226
318
  revisions.sort((a, b) => a.entry_id < b.entry_id ? -1 : a.entry_id > b.entry_id ? 1 : a.revision - b.revision);
319
+ if (documents) {
320
+ const expected = memoryDocuments(revisions), paths = new Set([...expected.keys(), ...tracked.filter(path => semanticPath.test(path))]);
321
+ for (const path of paths) {
322
+ // A pre-SOUL repository needs its empty projection published, not a user-data reset.
323
+ if (path === 'SOUL.md' && !tracked.includes(path) && !hasPath(join(this.root, path)) && !revisions.some(row => row.kind === 'soul'))
324
+ continue;
325
+ if (!tracked.includes(path) || !hasPath(join(this.root, path)))
326
+ throw failure('CONFLICT');
327
+ const text = this.readFile(path);
328
+ bytes += Buffer.byteLength(text);
329
+ if (bytes > MAX_BATCH)
330
+ throw failure('LIMIT');
331
+ baselines[path] = digest(text);
332
+ if (text === (expected.get(path) ?? EMPTY_MEMORY_DOCUMENT))
333
+ continue;
334
+ for (const edit of memoryDocumentEdits(path, text, revisions)) {
335
+ const prior = edits.find(value => value.entry_id === edit.entry.entry_id);
336
+ if (prior) {
337
+ if (canonicalJson(prior.content) !== canonicalJson(edit.content))
338
+ throw failure('CONFLICT');
339
+ continue;
340
+ }
341
+ edits.push({ entry_id: edit.entry.entry_id, expected_revision: edit.entry.revision, content: edit.content, path, hash: digest(text) });
342
+ }
343
+ }
344
+ }
227
345
  this.baseline = { ...baselines };
228
346
  return { revisions, edits, baselines };
229
347
  }
@@ -252,8 +370,14 @@ export class MarkdownRepository {
252
370
  const files = [{ path: MARKER, beforeHash: current.baselines[MARKER] ?? null, after: markerText }];
253
371
  for (const [id, list] of [...grouped].sort(([a], [b]) => a.localeCompare(b)))
254
372
  files.push({ path: entryPath(id), beforeHash: current.baselines[entryPath(id)] ?? null, after: render(list) });
373
+ const documents = memoryDocuments(revisions);
374
+ for (const path of Object.keys(current.baselines))
375
+ if (semanticPath.test(path) && !documents.has(path))
376
+ documents.set(path, EMPTY_MEMORY_DOCUMENT);
377
+ for (const [path, after] of documents)
378
+ files.push({ path, beforeHash: current.baselines[path] ?? null, after });
255
379
  const journal = { version: 1, operationId, baseCommit: this.head(), files };
256
- const text = JSON.stringify(journal);
380
+ const text = JSON.stringify(journalSchema.parse(journal));
257
381
  if (Buffer.byteLength(text) > MAX_BATCH)
258
382
  throw failure('LIMIT');
259
383
  // Exclusive creation is the inter-process batch lock. No stale lock is ever removed implicitly.
@@ -294,17 +418,7 @@ export class MarkdownRepository {
294
418
  }
295
419
  else {
296
420
  // Build exactly the owned understanding tree. Untracked files and the batch journal never enter Git.
297
- const entries = [];
298
- let marker = '';
299
- for (const file of journal.files) {
300
- const blob = this.git(['hash-object', '-w', '--stdin'], file.after).trim();
301
- if (file.path === MARKER)
302
- marker = blob;
303
- else
304
- entries.push(`100644 blob ${blob}\t${file.path.slice('entries/'.length)}\n`);
305
- }
306
- const treeEntries = this.git(['mktree'], entries.sort().join('')).trim();
307
- const tree = this.git(['mktree'], `100644 blob ${marker}\t${MARKER}\n040000 tree ${treeEntries}\tentries\n`).trim();
421
+ const tree = this.documentTree(new Map(journal.files.map(file => [file.path, file.after])), head);
308
422
  const previousTree = head ? this.git(['rev-parse', `${head}^{tree}`]).trim() : null;
309
423
  if (tree !== previousTree) {
310
424
  const commit = this.git(['commit-tree', tree, ...(head ? ['-p', head] : [])], `Nova understanding ${operationId}\n`).trim();
@@ -336,14 +450,19 @@ export class MarkdownRepository {
336
450
  recover(operationId, expectedRevisions) {
337
451
  this.initialize();
338
452
  if (expectedRevisions) {
339
- const journal = this.journal(), expected = history(expectedRevisions);
340
- if (journal.operationId !== operationId || journal.files.length !== expected.size + 1)
341
- throw failure('CONFLICT');
342
- for (const [id, revisions] of expected) {
343
- const file = journal.files.find(item => item.path === entryPath(id));
344
- if (file?.after !== render(revisions))
345
- throw failure('CONFLICT');
453
+ const journal = this.journal(), expected = new Map();
454
+ expected.set(MARKER, journal.files.find(file => file.path === MARKER).after);
455
+ for (const [id, rows] of history(expectedRevisions))
456
+ expected.set(entryPath(id), render(rows));
457
+ if (expected.get(MARKER) === markerText) {
458
+ for (const [path, text] of memoryDocuments(expectedRevisions))
459
+ expected.set(path, text);
460
+ for (const file of journal.files)
461
+ if (semanticPath.test(file.path) && !expected.has(file.path))
462
+ expected.set(file.path, EMPTY_MEMORY_DOCUMENT);
346
463
  }
464
+ if (journal.operationId !== operationId || journal.files.length !== expected.size || journal.files.some(file => file.after !== expected.get(file.path)))
465
+ throw failure('CONFLICT');
347
466
  }
348
467
  this.publishPrepared(operationId);
349
468
  this.finalize(operationId);
@@ -360,18 +479,25 @@ export class MarkdownRepository {
360
479
  const files = new Map([[MARKER, markerText]]);
361
480
  for (const [id, list] of history(revisions))
362
481
  files.set(entryPath(id), render(list));
363
- const check = () => {
364
- for (const [path, expected] of files)
365
- if (this.fileHash(path) !== digest(expected))
482
+ for (const [path, text] of memoryDocuments(revisions))
483
+ files.set(path, text);
484
+ const check = (published = false) => {
485
+ for (const [path, expected] of files) {
486
+ const actual = this.fileHash(path);
487
+ if (actual !== digest(expected) && (published || !semanticPath.test(path) || actual !== baselines[path]))
366
488
  throw failure('CONFLICT');
489
+ }
367
490
  for (const name of readdirSync(join(this.root, 'entries'))) {
368
491
  const path = `entries/${name}`;
369
492
  if (!files.has(path) && (!Object.hasOwn(baselines, path) || this.fileHash(path) !== baselines[path]))
370
493
  throw failure('CONFLICT');
371
494
  }
372
- for (const path of Object.keys(baselines))
373
- if (path !== MARKER && !/^entries\/[a-f0-9]{64}\.md$/.test(path))
495
+ for (const path of Object.keys(baselines)) {
496
+ if (path !== MARKER && !/^entries\/[a-f0-9]{64}\.md$/.test(path) && !semanticPath.test(path))
374
497
  throw failure('UNSAFE_PATH');
498
+ if (!files.has(path) && this.fileHash(path) !== null && this.fileHash(path) !== baselines[path])
499
+ throw failure('CONFLICT');
500
+ }
375
501
  };
376
502
  check();
377
503
  // Other refs or a staged user change require explicit reconciliation, never silent removal.
@@ -382,17 +508,11 @@ export class MarkdownRepository {
382
508
  this.assertGitRefs(join(this.root, '.git'));
383
509
  if (hasPath(join(this.root, '.git', 'objects', 'info', 'alternates')))
384
510
  throw failure('UNSAFE_PATH');
385
- const entries = [];
386
- let marker = '';
387
- for (const [path, text] of files) {
388
- const blob = this.git(['hash-object', '-w', '--stdin'], text).trim();
389
- if (path === MARKER)
390
- marker = blob;
391
- else
392
- entries.push(`100644 blob ${blob}\t${path.slice('entries/'.length)}\n`);
393
- }
394
- const treeEntries = this.git(['mktree'], entries.sort().join('')).trim();
395
- const tree = this.git(['mktree'], `100644 blob ${marker}\t${MARKER}\n040000 tree ${treeEntries}\tentries\n`).trim();
511
+ for (const [path, after] of files)
512
+ if (semanticPath.test(path) && this.fileHash(path) !== digest(after))
513
+ this.atomicWrite({ path, after, beforeHash: baselines[path] ?? null }, operationId);
514
+ check(true);
515
+ const tree = this.documentTree(files);
396
516
  const head = this.head(), parents = head ? this.git(['rev-list', '--parents', '-n', '1', head]).trim().split(' ') : [];
397
517
  if (!head || this.git(['rev-parse', `${head}^{tree}`]).trim() !== tree || parents.length !== 1) {
398
518
  const commit = this.git(['commit-tree', tree], `Nova permanent purge ${operationId}\n`).trim();
@@ -408,6 +528,13 @@ export class MarkdownRepository {
408
528
  unlinkSync(join(this.root, path));
409
529
  }
410
530
  }
531
+ for (const path of Object.keys(baselines))
532
+ if (semanticPath.test(path) && !files.has(path) && hasPath(join(this.root, path))) {
533
+ if (this.fileHash(path) !== baselines[path])
534
+ throw failure('CONFLICT');
535
+ unlinkSync(join(this.root, path));
536
+ this.syncDirectory(dirname(join(this.root, path)));
537
+ }
411
538
  this.syncDirectory(join(this.root, 'entries'));
412
539
  this.git(['reflog', 'expire', '--expire=now', '--all']);
413
540
  this.git(['-c', 'gc.auto=0', 'gc', '--prune=now', '--quiet']);
@@ -427,14 +554,25 @@ export class MarkdownRepository {
427
554
  if (original.isSymbolicLink() || original.ino !== active.ino || original.dev !== active.dev)
428
555
  throw failure('UNSAFE_PATH');
429
556
  }
430
- if (new Set(value.files.map(file => file.path)).size !== value.files.length || value.files.filter(file => file.path === MARKER && file.after === markerText).length !== 1)
557
+ if (new Set(value.files.map(file => file.path)).size !== value.files.length || value.files.filter(file => file.path === MARKER && (file.after === markerText || file.after === legacyMarkerText)).length !== 1)
431
558
  throw failure('FORMAT');
559
+ const revisions = [];
432
560
  for (const file of value.files)
433
- if (file.path !== MARKER) {
561
+ if (file.path.startsWith('entries/')) {
434
562
  const entry = decode(file.after);
435
563
  if (entryPath(entry.revisions.at(-1).entry_id) !== file.path)
436
564
  throw failure('FORMAT');
565
+ revisions.push(...entry.revisions);
437
566
  }
567
+ if (value.files.find(file => file.path === MARKER).after === markerText) {
568
+ const documents = memoryDocuments(revisions);
569
+ for (const [path, text] of documents)
570
+ if (value.files.find(file => file.path === path)?.after !== text)
571
+ throw failure('FORMAT');
572
+ for (const file of value.files)
573
+ if (semanticPath.test(file.path) && file.after !== (documents.get(file.path) ?? EMPTY_MEMORY_DOCUMENT))
574
+ throw failure('FORMAT');
575
+ }
438
576
  return value;
439
577
  }
440
578
  checkFile(file, published = false) {
@@ -457,10 +595,69 @@ export class MarkdownRepository {
457
595
  const paths = this.git(['ls-tree', '-r', '--name-only', head]).trim().split('\n').filter(Boolean);
458
596
  if (paths.length !== journal.files.length)
459
597
  return false;
460
- return journal.files.every(file => paths.includes(file.path) && digest(this.git(['show', `${head}:${file.path}`])) === digest(file.after));
598
+ const committed = this.committedFiles(head, paths);
599
+ return journal.files.every(file => committed.has(file.path) && digest(committed.get(file.path)) === digest(file.after));
600
+ }
601
+ documentTree(files, head = this.head()) {
602
+ const algorithm = head?.length === 40 ? 'sha1' : head?.length === 64 ? 'sha256' : null;
603
+ const committed = new Map();
604
+ // Only reuse blobs reachable from this operation's live HEAD, never a cache that purge could prune.
605
+ if (head && algorithm)
606
+ for (const row of this.git(['ls-tree', '-r', '-z', head]).split('\0')) {
607
+ const match = /^[0-7]{6} blob ([a-f0-9]{40}|[a-f0-9]{64})\t([\s\S]+)$/.exec(row);
608
+ if (match)
609
+ committed.set(match[2], match[1]);
610
+ }
611
+ const directories = new Map(), top = [];
612
+ for (const [path, text] of files) {
613
+ const candidate = algorithm ? createHash(algorithm).update(`blob ${Buffer.byteLength(text)}\0`).update(text).digest('hex') : null;
614
+ const blob = candidate && committed.get(path) === candidate ? candidate : this.git(['hash-object', '-w', '--stdin'], text).trim(), slash = path.indexOf('/');
615
+ if (slash < 0)
616
+ top.push(`100644 blob ${blob}\t${path}\n`);
617
+ else {
618
+ const folder = path.slice(0, slash), rows = directories.get(folder) ?? [];
619
+ rows.push(`100644 blob ${blob}\t${path.slice(slash + 1)}\n`);
620
+ directories.set(folder, rows);
621
+ }
622
+ }
623
+ for (const [folder, rows] of directories) {
624
+ const tree = this.git(['mktree'], rows.sort().join('')).trim();
625
+ top.push(`040000 tree ${tree}\t${folder}\n`);
626
+ }
627
+ return this.git(['mktree'], top.sort().join('')).trim();
628
+ }
629
+ committedFiles(head, paths) {
630
+ const files = new Map();
631
+ if (!paths.length)
632
+ return files;
633
+ for (const path of paths)
634
+ if (path !== MARKER && !/^entries\/[a-f0-9]{64}\.md$/.test(path) && !semanticPath.test(path))
635
+ throw failure('UNSAFE_PATH');
636
+ const output = this.git(['cat-file', '--batch'], paths.map(path => `${head}:${path}\n`).join(''), false, true);
637
+ let offset = 0, bytes = 0;
638
+ for (const path of paths) {
639
+ const newline = output.indexOf(10, offset);
640
+ if (newline < 0)
641
+ throw failure('FORMAT');
642
+ const header = /^[a-f0-9]{40,64} blob ([0-9]+)$/.exec(output.subarray(offset, newline).toString('ascii'));
643
+ if (!header)
644
+ throw failure('FORMAT');
645
+ const size = Number(header[1]);
646
+ bytes += size;
647
+ if (!Number.isSafeInteger(size) || size > MAX_FILE || bytes > MAX_BATCH)
648
+ throw failure('LIMIT');
649
+ const start = newline + 1, end = start + size;
650
+ if (end >= output.length || output[end] !== 10)
651
+ throw failure('FORMAT');
652
+ files.set(path, output.subarray(start, end).toString('utf8'));
653
+ offset = end + 1;
654
+ }
655
+ if (offset !== output.length)
656
+ throw failure('FORMAT');
657
+ return files;
461
658
  }
462
659
  head() { const value = this.git(['rev-parse', '--verify', 'HEAD'], undefined, true).trim(); return /^[a-f0-9]{40,64}$/.test(value) ? value : null; }
463
- git(args, input, optional = false) {
660
+ git(args, input, optional = false, binary = false) {
464
661
  const gitDir = join(this.root, '.git');
465
662
  if (hasPath(gitDir)) {
466
663
  this.assertSafe(gitDir, true);
@@ -471,9 +668,15 @@ export class MarkdownRepository {
471
668
  if (hasPath(join(gitDir, name)))
472
669
  this.assertSafe(join(gitDir, name), ['objects', 'refs'].includes(name));
473
670
  const objects = join(gitDir, 'objects');
671
+ // Git itself may leave regular temp/lock files directly in objects/ (and may remove them between readdir and lstat);
672
+ // anything else must be a plain directory.
474
673
  if (hasPath(objects))
475
- for (const name of readdirSync(objects))
674
+ for (const name of readdirSync(objects)) {
675
+ const stat = lstatSync(join(objects, name), { throwIfNoEntry: false });
676
+ if (stat === undefined || !stat.isSymbolicLink() && stat.isFile())
677
+ continue;
476
678
  this.assertSafe(join(objects, name), true);
679
+ }
477
680
  const refs = join(gitDir, 'refs');
478
681
  if (hasPath(refs))
479
682
  this.assertGitRefs(refs);
@@ -484,11 +687,12 @@ export class MarkdownRepository {
484
687
  delete env[key];
485
688
  Object.assign(env, { GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: process.platform === 'win32' ? 'NUL' : '/dev/null', GIT_TERMINAL_PROMPT: '0', GIT_AUTHOR_NAME: 'Nova', GIT_AUTHOR_EMAIL: 'nova@localhost', GIT_COMMITTER_NAME: 'Nova', GIT_COMMITTER_EMAIL: 'nova@localhost' });
486
689
  try {
487
- return execFileSync('git', ['-c', 'core.hooksPath=/dev/null', '-c', 'core.fsmonitor=false', '-c', 'commit.gpgSign=false', '-C', this.root, ...args], { input, encoding: 'utf8', env, timeout: 15_000, maxBuffer: MAX_BATCH, stdio: ['pipe', 'pipe', 'pipe'] });
690
+ const output = execFileSync('git', ['-c', 'core.hooksPath=/dev/null', '-c', 'core.fsmonitor=false', '-c', 'commit.gpgSign=false', '-c', 'gc.auto=0', '-c', 'maintenance.auto=false', '-C', this.root, ...args], { input, env, timeout: 15_000, maxBuffer: MAX_BATCH, stdio: ['pipe', 'pipe', 'pipe'] });
691
+ return binary ? output : output.toString('utf8');
488
692
  }
489
693
  catch (error) {
490
694
  if (optional)
491
- return '';
695
+ return binary ? Buffer.alloc(0) : '';
492
696
  throw new Error('MEMORY_MARKDOWN_GIT', { cause: error });
493
697
  }
494
698
  }
@@ -516,7 +720,9 @@ export class MarkdownRepository {
516
720
  assertGitRefs(path) {
517
721
  for (const name of readdirSync(path)) {
518
722
  const child = join(path, name);
519
- const stat = lstatSync(child);
723
+ const stat = lstatSync(child, { throwIfNoEntry: false });
724
+ if (stat === undefined)
725
+ continue;
520
726
  this.assertSafe(child, stat.isDirectory());
521
727
  if (stat.isDirectory())
522
728
  this.assertGitRefs(child);
@@ -0,0 +1,96 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { canonicalJson } from '../text/canonical-json.js';
3
+ export const MAX_MEMORY_DOCUMENT_BYTES = 8 * 1024 * 1024;
4
+ export const EMPTY_MEMORY_DOCUMENT = '# Archived\n\nNo current records.\n';
5
+ export const semanticPath = /^(USER\.md|SOUL\.md|MEMORY\.md|(goals|todos|ideas|memory|entities)\/[a-f0-9]{64}\.md)$/u;
6
+ const hash = (text) => createHash('sha256').update(text).digest('hex');
7
+ const fail = () => new Error('MEMORY_MARKDOWN_FORMAT');
8
+ export function isUserMemory(row) {
9
+ return row.origin === 'stated' && (row.content.memory_scope === 'user' || row.content.memory_scope !== 'general' && (row.kind === 'preference' || row.kind === 'profile' && row.content.section === 'explicit'));
10
+ }
11
+ export const SOUL_BODY_MAX = 1000;
12
+ export function memoryDocumentPath(row) {
13
+ if (row.kind === 'soul')
14
+ return 'SOUL.md';
15
+ if (isUserMemory(row))
16
+ return 'USER.md';
17
+ const folder = row.kind === 'goal' ? 'goals' : row.kind === 'todo' ? 'todos' : row.kind === 'idea' ? 'ideas' : row.kind === 'entity' ? 'entities' : 'memory';
18
+ return `${folder}/${hash(row.entry_id)}.md`;
19
+ }
20
+ function latest(revisions) {
21
+ const rows = new Map();
22
+ for (const row of revisions)
23
+ if (!rows.has(row.entry_id) || rows.get(row.entry_id).revision < row.revision)
24
+ rows.set(row.entry_id, row);
25
+ return [...rows.values()].filter(row => row.op !== 'tombstone' && row.kind !== 'memory_summary' && row.kind !== 'diary').sort((a, b) => a.entry_id.localeCompare(b.entry_id));
26
+ }
27
+ function heading(path) { if (path === 'SOUL.md')
28
+ return '# Soul\n\n<!-- 角色设定请先在应用「我的样子」里保存一次,之后可在下面直接修改正文;名字、说话方式、联系方式在应用里设置。 -->\n\n'; return path === 'USER.md' ? '# User\n\nStable user information. Edit record bodies; keep identity and source markers intact.\n\n' : '# Memory document\n\nEdit record bodies; status and links are maintained through Nova.\n\n'; }
29
+ function parts(row) {
30
+ const life = row.content.life_data;
31
+ const state = life ? Object.fromEntries(['status', 'due', 'goal_id', 'idea_id', 'success_criteria'].filter(key => life[key] !== undefined).map(key => [key, life[key]])) : {};
32
+ const metadata = canonicalJson({ id: row.entry_id, version: row.revision, kind: row.kind, origin: row.origin, evidence_refs: row.evidence_refs, valid_until: row.valid_until }).replace(/-->/gu, '--\\u003e');
33
+ const facts = Object.entries(state).map(([key, value]) => `${key}: ${JSON.stringify(value)}`).join('\n');
34
+ return { before: `## ${row.kind}${typeof row.content.memory_slot === 'string' ? ` (${row.content.memory_slot})` : ''}\n\n${facts ? facts + '\n\n' : ''}<!-- nova-record ${metadata} -->\n<!-- editable-current -->\n`, text: typeof row.content.text === 'string' ? row.content.text : JSON.stringify(row.content, null, 2), after: `\n<!-- /nova-record:${hash(row.entry_id)} -->\n\n` };
35
+ }
36
+ /** Current reading/editing surface. History remains in revision storage and is never copied here. */
37
+ export function memoryDocuments(revisions) {
38
+ const result = new Map([['USER.md', heading('USER.md')], ['SOUL.md', heading('SOUL.md')]]);
39
+ const rows = latest(revisions);
40
+ for (const row of rows) {
41
+ const path = memoryDocumentPath(row), part = parts(row);
42
+ result.set(path, (result.get(path) ?? heading(path)) + part.before + part.text + part.after);
43
+ }
44
+ let index = '# Memory\n\nGenerated directory; edit the linked documents or use Nova. An omitted entry is not proof of absence.\n\n- [User](USER.md)\n';
45
+ for (const row of rows) {
46
+ if (isUserMemory(row) || row.kind === 'soul')
47
+ continue;
48
+ const title = (typeof row.content.text === 'string' ? row.content.text.split('\n')[0] : row.kind).replace(/[\[\]\\\r\n]/gu, ' ').slice(0, 160);
49
+ const line = `- [${title || row.kind}](${memoryDocumentPath(row)}) — ${row.kind}\n`;
50
+ if (index.length + line.length > 14000)
51
+ break;
52
+ index += line;
53
+ }
54
+ result.set('MEMORY.md', index);
55
+ for (const text of result.values())
56
+ if (Buffer.byteLength(text) > MAX_MEMORY_DOCUMENT_BYTES)
57
+ throw new Error('MEMORY_MARKDOWN_LIMIT');
58
+ return result;
59
+ }
60
+ export function memoryDocumentEdits(path, text, revisions) {
61
+ if (!semanticPath.test(path))
62
+ throw fail();
63
+ const expected = memoryDocuments(revisions).get(path) ?? EMPTY_MEMORY_DOCUMENT;
64
+ if (text === expected)
65
+ return [];
66
+ // A SOUL.md that has no record yet is regenerated from the template; only the card or soul.set can create the first role.
67
+ if (path === 'SOUL.md' && !latest(revisions).some(row => row.kind === 'soul'))
68
+ return [];
69
+ if (path === 'MEMORY.md' || expected === EMPTY_MEMORY_DOCUMENT)
70
+ throw fail();
71
+ let at = 0;
72
+ const prefix = heading(path);
73
+ if (!text.startsWith(prefix))
74
+ throw fail();
75
+ at = prefix.length;
76
+ const edits = [];
77
+ for (const row of latest(revisions).filter(row => memoryDocumentPath(row) === path)) {
78
+ const part = parts(row);
79
+ if (!text.startsWith(part.before, at))
80
+ throw fail();
81
+ at += part.before.length;
82
+ const end = text.indexOf(part.after, at);
83
+ if (end < 0)
84
+ throw fail();
85
+ const body = text.slice(at, end);
86
+ at = end + part.after.length;
87
+ if (body !== part.text) {
88
+ const content = typeof row.content.text === 'string' ? { ...row.content, text: body } : JSON.parse(body);
89
+ edits.push({ entry: row, content });
90
+ }
91
+ }
92
+ if (at !== text.length)
93
+ throw fail();
94
+ return edits;
95
+ }
96
+ //# sourceMappingURL=memory-documents.js.map
@@ -1,3 +1,4 @@
1
+ import { validateMemoryFiles } from './file-authority.js';
1
2
  import { isPermanentlyPurged } from './purge.js';
2
3
  import { existsSync, lstatSync } from 'node:fs';
3
4
  import { z } from 'zod';
@@ -72,6 +73,7 @@ export function migrateLegacyMemory(db, input, openLegacy) {
72
73
  db.prepare('INSERT OR IGNORE INTO memory_legacy_suppressed VALUES(?,?)').run(source_prefix, key[4]);
73
74
  }
74
75
  db.prepare('INSERT INTO memory_migrations VALUES(?)').run(marker);
76
+ validateMemoryFiles(db);
75
77
  db.exec('COMMIT');
76
78
  }
77
79
  catch (error) {