@aislop-inc/opencode-mem 0.0.0-stage → 2.41.1

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 (357) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +811 -2
  3. package/dist/config.d.ts +577 -0
  4. package/dist/config.d.ts.map +1 -0
  5. package/dist/config.js +1141 -0
  6. package/dist/index.d.ts +50 -0
  7. package/dist/index.d.ts.map +1 -0
  8. package/dist/index.js +1268 -0
  9. package/dist/plugin.d.ts +10 -0
  10. package/dist/plugin.d.ts.map +1 -0
  11. package/dist/plugin.js +10 -0
  12. package/dist/services/ai/ai-provider-factory.d.ts +8 -0
  13. package/dist/services/ai/ai-provider-factory.d.ts.map +1 -0
  14. package/dist/services/ai/ai-provider-factory.js +61 -0
  15. package/dist/services/ai/api-key-placeholder.d.ts +2 -0
  16. package/dist/services/ai/api-key-placeholder.d.ts.map +1 -0
  17. package/dist/services/ai/api-key-placeholder.js +14 -0
  18. package/dist/services/ai/internal-capture-sessions.d.ts +7 -0
  19. package/dist/services/ai/internal-capture-sessions.d.ts.map +1 -0
  20. package/dist/services/ai/internal-capture-sessions.js +31 -0
  21. package/dist/services/ai/opencode-diagnostics.d.ts +8 -0
  22. package/dist/services/ai/opencode-diagnostics.d.ts.map +1 -0
  23. package/dist/services/ai/opencode-diagnostics.js +36 -0
  24. package/dist/services/ai/opencode-host-config.d.ts +11 -0
  25. package/dist/services/ai/opencode-host-config.d.ts.map +1 -0
  26. package/dist/services/ai/opencode-host-config.js +51 -0
  27. package/dist/services/ai/opencode-provider-loader.d.ts +4 -0
  28. package/dist/services/ai/opencode-provider-loader.d.ts.map +1 -0
  29. package/dist/services/ai/opencode-provider-loader.js +4 -0
  30. package/dist/services/ai/opencode-provider.d.ts +154 -0
  31. package/dist/services/ai/opencode-provider.d.ts.map +1 -0
  32. package/dist/services/ai/opencode-provider.js +731 -0
  33. package/dist/services/ai/opencode-sdk-client.d.ts +7 -0
  34. package/dist/services/ai/opencode-sdk-client.d.ts.map +1 -0
  35. package/dist/services/ai/opencode-sdk-client.js +38 -0
  36. package/dist/services/ai/profile-llm-client.d.ts +3 -0
  37. package/dist/services/ai/profile-llm-client.d.ts.map +1 -0
  38. package/dist/services/ai/profile-llm-client.js +29 -0
  39. package/dist/services/ai/provider-config.d.ts +19 -0
  40. package/dist/services/ai/provider-config.d.ts.map +1 -0
  41. package/dist/services/ai/provider-config.js +36 -0
  42. package/dist/services/ai/providers/anthropic-messages.d.ts +35 -0
  43. package/dist/services/ai/providers/anthropic-messages.d.ts.map +1 -0
  44. package/dist/services/ai/providers/anthropic-messages.js +220 -0
  45. package/dist/services/ai/providers/api-route.d.ts +49 -0
  46. package/dist/services/ai/providers/api-route.d.ts.map +1 -0
  47. package/dist/services/ai/providers/api-route.js +57 -0
  48. package/dist/services/ai/providers/atlas-cloud.d.ts +51 -0
  49. package/dist/services/ai/providers/atlas-cloud.d.ts.map +1 -0
  50. package/dist/services/ai/providers/atlas-cloud.js +59 -0
  51. package/dist/services/ai/providers/base-provider.d.ts +33 -0
  52. package/dist/services/ai/providers/base-provider.d.ts.map +1 -0
  53. package/dist/services/ai/providers/base-provider.js +24 -0
  54. package/dist/services/ai/providers/cheaper-inference.d.ts +50 -0
  55. package/dist/services/ai/providers/cheaper-inference.d.ts.map +1 -0
  56. package/dist/services/ai/providers/cheaper-inference.js +58 -0
  57. package/dist/services/ai/providers/cloudgpu.d.ts +52 -0
  58. package/dist/services/ai/providers/cloudgpu.d.ts.map +1 -0
  59. package/dist/services/ai/providers/cloudgpu.js +60 -0
  60. package/dist/services/ai/providers/google-gemini.d.ts +16 -0
  61. package/dist/services/ai/providers/google-gemini.d.ts.map +1 -0
  62. package/dist/services/ai/providers/google-gemini.js +228 -0
  63. package/dist/services/ai/providers/minimax.d.ts +38 -0
  64. package/dist/services/ai/providers/minimax.d.ts.map +1 -0
  65. package/dist/services/ai/providers/minimax.js +57 -0
  66. package/dist/services/ai/providers/openai-chat-completion.d.ts +30 -0
  67. package/dist/services/ai/providers/openai-chat-completion.d.ts.map +1 -0
  68. package/dist/services/ai/providers/openai-chat-completion.js +532 -0
  69. package/dist/services/ai/providers/openai-responses.d.ts +14 -0
  70. package/dist/services/ai/providers/openai-responses.d.ts.map +1 -0
  71. package/dist/services/ai/providers/openai-responses.js +182 -0
  72. package/dist/services/ai/providers/orcarouter.d.ts +52 -0
  73. package/dist/services/ai/providers/orcarouter.d.ts.map +1 -0
  74. package/dist/services/ai/providers/orcarouter.js +66 -0
  75. package/dist/services/ai/providers/runcrate.d.ts +49 -0
  76. package/dist/services/ai/providers/runcrate.d.ts.map +1 -0
  77. package/dist/services/ai/providers/runcrate.js +57 -0
  78. package/dist/services/ai/session/ai-session-manager.d.ts +25 -0
  79. package/dist/services/ai/session/ai-session-manager.d.ts.map +1 -0
  80. package/dist/services/ai/session/ai-session-manager.js +180 -0
  81. package/dist/services/ai/session/session-types.d.ts +43 -0
  82. package/dist/services/ai/session/session-types.d.ts.map +1 -0
  83. package/dist/services/ai/session/session-types.js +1 -0
  84. package/dist/services/ai/tools/tool-schema.d.ts +41 -0
  85. package/dist/services/ai/tools/tool-schema.d.ts.map +1 -0
  86. package/dist/services/ai/tools/tool-schema.js +24 -0
  87. package/dist/services/ai/validators/user-profile-validator.d.ts +13 -0
  88. package/dist/services/ai/validators/user-profile-validator.d.ts.map +1 -0
  89. package/dist/services/ai/validators/user-profile-validator.js +114 -0
  90. package/dist/services/api-handlers.d.ts +277 -0
  91. package/dist/services/api-handlers.d.ts.map +1 -0
  92. package/dist/services/api-handlers.js +1740 -0
  93. package/dist/services/auth-token.d.ts +11 -0
  94. package/dist/services/auth-token.d.ts.map +1 -0
  95. package/dist/services/auth-token.js +44 -0
  96. package/dist/services/auto-capture-config-status.d.ts +15 -0
  97. package/dist/services/auto-capture-config-status.d.ts.map +1 -0
  98. package/dist/services/auto-capture-config-status.js +31 -0
  99. package/dist/services/auto-capture.d.ts +33 -0
  100. package/dist/services/auto-capture.d.ts.map +1 -0
  101. package/dist/services/auto-capture.js +906 -0
  102. package/dist/services/auto-update.d.ts +28 -0
  103. package/dist/services/auto-update.d.ts.map +1 -0
  104. package/dist/services/auto-update.js +197 -0
  105. package/dist/services/capture-evidence-events.d.ts +3 -0
  106. package/dist/services/capture-evidence-events.d.ts.map +1 -0
  107. package/dist/services/capture-evidence-events.js +15 -0
  108. package/dist/services/capture-evidence.d.ts +21 -0
  109. package/dist/services/capture-evidence.d.ts.map +1 -0
  110. package/dist/services/capture-evidence.js +168 -0
  111. package/dist/services/capture-tool-evidence.d.ts +21 -0
  112. package/dist/services/capture-tool-evidence.d.ts.map +1 -0
  113. package/dist/services/capture-tool-evidence.js +109 -0
  114. package/dist/services/cleanup-service.d.ts +26 -0
  115. package/dist/services/cleanup-service.d.ts.map +1 -0
  116. package/dist/services/cleanup-service.js +199 -0
  117. package/dist/services/client.d.ts +167 -0
  118. package/dist/services/client.d.ts.map +1 -0
  119. package/dist/services/client.js +535 -0
  120. package/dist/services/context.d.ts +15 -0
  121. package/dist/services/context.d.ts.map +1 -0
  122. package/dist/services/context.js +44 -0
  123. package/dist/services/cors.d.ts +13 -0
  124. package/dist/services/cors.d.ts.map +1 -0
  125. package/dist/services/cors.js +52 -0
  126. package/dist/services/deduplication-service.d.ts +29 -0
  127. package/dist/services/deduplication-service.d.ts.map +1 -0
  128. package/dist/services/deduplication-service.js +113 -0
  129. package/dist/services/dreaming-lock.d.ts +6 -0
  130. package/dist/services/dreaming-lock.d.ts.map +1 -0
  131. package/dist/services/dreaming-lock.js +84 -0
  132. package/dist/services/dreaming-service.d.ts +96 -0
  133. package/dist/services/dreaming-service.d.ts.map +1 -0
  134. package/dist/services/dreaming-service.js +626 -0
  135. package/dist/services/embedding.d.ts +92 -0
  136. package/dist/services/embedding.d.ts.map +1 -0
  137. package/dist/services/embedding.js +467 -0
  138. package/dist/services/injected-prompt-filter.d.ts +49 -0
  139. package/dist/services/injected-prompt-filter.d.ts.map +1 -0
  140. package/dist/services/injected-prompt-filter.js +79 -0
  141. package/dist/services/jsonc.d.ts +7 -0
  142. package/dist/services/jsonc.d.ts.map +1 -0
  143. package/dist/services/jsonc.js +110 -0
  144. package/dist/services/language-detector.d.ts +3 -0
  145. package/dist/services/language-detector.d.ts.map +1 -0
  146. package/dist/services/language-detector.js +33 -0
  147. package/dist/services/logger.d.ts +15 -0
  148. package/dist/services/logger.d.ts.map +1 -0
  149. package/dist/services/logger.js +171 -0
  150. package/dist/services/markdown/backend.d.ts +35 -0
  151. package/dist/services/markdown/backend.d.ts.map +1 -0
  152. package/dist/services/markdown/backend.js +111 -0
  153. package/dist/services/markdown/document.d.ts +44 -0
  154. package/dist/services/markdown/document.d.ts.map +1 -0
  155. package/dist/services/markdown/document.js +159 -0
  156. package/dist/services/markdown/reconcile.d.ts +26 -0
  157. package/dist/services/markdown/reconcile.d.ts.map +1 -0
  158. package/dist/services/markdown/reconcile.js +333 -0
  159. package/dist/services/markdown/vault.d.ts +32 -0
  160. package/dist/services/markdown/vault.d.ts.map +1 -0
  161. package/dist/services/markdown/vault.js +142 -0
  162. package/dist/services/markdown/watcher.d.ts +22 -0
  163. package/dist/services/markdown/watcher.d.ts.map +1 -0
  164. package/dist/services/markdown/watcher.js +131 -0
  165. package/dist/services/memory-portability-service.d.ts +38 -0
  166. package/dist/services/memory-portability-service.d.ts.map +1 -0
  167. package/dist/services/memory-portability-service.js +372 -0
  168. package/dist/services/memory-provenance.d.ts +16 -0
  169. package/dist/services/memory-provenance.d.ts.map +1 -0
  170. package/dist/services/memory-provenance.js +115 -0
  171. package/dist/services/memory-recall.d.ts +49 -0
  172. package/dist/services/memory-recall.d.ts.map +1 -0
  173. package/dist/services/memory-recall.js +196 -0
  174. package/dist/services/memory-scope.d.ts +17 -0
  175. package/dist/services/memory-scope.d.ts.map +1 -0
  176. package/dist/services/memory-scope.js +43 -0
  177. package/dist/services/migration-service.d.ts +43 -0
  178. package/dist/services/migration-service.d.ts.map +1 -0
  179. package/dist/services/migration-service.js +333 -0
  180. package/dist/services/onnxruntime-resolve.d.ts +25 -0
  181. package/dist/services/onnxruntime-resolve.d.ts.map +1 -0
  182. package/dist/services/onnxruntime-resolve.js +176 -0
  183. package/dist/services/privacy.d.ts +38 -0
  184. package/dist/services/privacy.d.ts.map +1 -0
  185. package/dist/services/privacy.js +156 -0
  186. package/dist/services/request-timeouts.d.ts +4 -0
  187. package/dist/services/request-timeouts.d.ts.map +1 -0
  188. package/dist/services/request-timeouts.js +5 -0
  189. package/dist/services/runtime-require.d.ts +18 -0
  190. package/dist/services/runtime-require.d.ts.map +1 -0
  191. package/dist/services/runtime-require.js +75 -0
  192. package/dist/services/secret-resolver.d.ts +2 -0
  193. package/dist/services/secret-resolver.d.ts.map +1 -0
  194. package/dist/services/secret-resolver.js +65 -0
  195. package/dist/services/shard-inventory-service.d.ts +70 -0
  196. package/dist/services/shard-inventory-service.d.ts.map +1 -0
  197. package/dist/services/shard-inventory-service.js +315 -0
  198. package/dist/services/shard-path-migration-service.d.ts +32 -0
  199. package/dist/services/shard-path-migration-service.d.ts.map +1 -0
  200. package/dist/services/shard-path-migration-service.js +386 -0
  201. package/dist/services/skills/skills-manager.d.ts +39 -0
  202. package/dist/services/skills/skills-manager.d.ts.map +1 -0
  203. package/dist/services/skills/skills-manager.js +231 -0
  204. package/dist/services/skills/types.d.ts +32 -0
  205. package/dist/services/skills/types.d.ts.map +1 -0
  206. package/dist/services/skills/types.js +5 -0
  207. package/dist/services/stats-service.d.ts +71 -0
  208. package/dist/services/stats-service.d.ts.map +1 -0
  209. package/dist/services/stats-service.js +288 -0
  210. package/dist/services/tags.d.ts +30 -0
  211. package/dist/services/tags.d.ts.map +1 -0
  212. package/dist/services/tags.js +245 -0
  213. package/dist/services/transformers-resolve.d.ts +17 -0
  214. package/dist/services/transformers-resolve.d.ts.map +1 -0
  215. package/dist/services/transformers-resolve.js +142 -0
  216. package/dist/services/turso/connection-manager.d.ts +66 -0
  217. package/dist/services/turso/connection-manager.d.ts.map +1 -0
  218. package/dist/services/turso/connection-manager.js +408 -0
  219. package/dist/services/turso/encryption-key.d.ts +17 -0
  220. package/dist/services/turso/encryption-key.d.ts.map +1 -0
  221. package/dist/services/turso/encryption-key.js +111 -0
  222. package/dist/services/turso/encryption-migrator.d.ts +6 -0
  223. package/dist/services/turso/encryption-migrator.d.ts.map +1 -0
  224. package/dist/services/turso/encryption-migrator.js +234 -0
  225. package/dist/services/turso/engine-migrator.d.ts +6 -0
  226. package/dist/services/turso/engine-migrator.d.ts.map +1 -0
  227. package/dist/services/turso/engine-migrator.js +318 -0
  228. package/dist/services/turso/error-classifiers.d.ts +4 -0
  229. package/dist/services/turso/error-classifiers.d.ts.map +1 -0
  230. package/dist/services/turso/error-classifiers.js +19 -0
  231. package/dist/services/turso/legacy-migrator.d.ts +2 -0
  232. package/dist/services/turso/legacy-migrator.d.ts.map +1 -0
  233. package/dist/services/turso/legacy-migrator.js +535 -0
  234. package/dist/services/turso/lifecycle.d.ts +11 -0
  235. package/dist/services/turso/lifecycle.d.ts.map +1 -0
  236. package/dist/services/turso/lifecycle.js +32 -0
  237. package/dist/services/turso/operation-lock.d.ts +26 -0
  238. package/dist/services/turso/operation-lock.d.ts.map +1 -0
  239. package/dist/services/turso/operation-lock.js +188 -0
  240. package/dist/services/turso/plugin-refs.d.ts +13 -0
  241. package/dist/services/turso/plugin-refs.d.ts.map +1 -0
  242. package/dist/services/turso/plugin-refs.js +43 -0
  243. package/dist/services/turso/ready.d.ts +3 -0
  244. package/dist/services/turso/ready.d.ts.map +1 -0
  245. package/dist/services/turso/ready.js +32 -0
  246. package/dist/services/turso/schema-migrations.d.ts +24 -0
  247. package/dist/services/turso/schema-migrations.d.ts.map +1 -0
  248. package/dist/services/turso/schema-migrations.js +367 -0
  249. package/dist/services/turso/shard-manager.d.ts +41 -0
  250. package/dist/services/turso/shard-manager.d.ts.map +1 -0
  251. package/dist/services/turso/shard-manager.js +419 -0
  252. package/dist/services/turso/sqlite-handle-release.d.ts +31 -0
  253. package/dist/services/turso/sqlite-handle-release.d.ts.map +1 -0
  254. package/dist/services/turso/sqlite-handle-release.js +101 -0
  255. package/dist/services/turso/turso-db.d.ts +61 -0
  256. package/dist/services/turso/turso-db.d.ts.map +1 -0
  257. package/dist/services/turso/turso-db.js +214 -0
  258. package/dist/services/turso/types.d.ts +52 -0
  259. package/dist/services/turso/types.d.ts.map +1 -0
  260. package/dist/services/turso/types.js +1 -0
  261. package/dist/services/turso/vector-search.d.ts +63 -0
  262. package/dist/services/turso/vector-search.d.ts.map +1 -0
  263. package/dist/services/turso/vector-search.js +510 -0
  264. package/dist/services/turso/vector-utils.d.ts +16 -0
  265. package/dist/services/turso/vector-utils.d.ts.map +1 -0
  266. package/dist/services/turso/vector-utils.js +98 -0
  267. package/dist/services/turso/wal-index-recovery.d.ts +51 -0
  268. package/dist/services/turso/wal-index-recovery.d.ts.map +1 -0
  269. package/dist/services/turso/wal-index-recovery.js +248 -0
  270. package/dist/services/update-on-capture.d.ts +77 -0
  271. package/dist/services/update-on-capture.d.ts.map +1 -0
  272. package/dist/services/update-on-capture.js +116 -0
  273. package/dist/services/user-memory-learning.d.ts +137 -0
  274. package/dist/services/user-memory-learning.d.ts.map +1 -0
  275. package/dist/services/user-memory-learning.js +787 -0
  276. package/dist/services/user-profile/ai-cleanup.d.ts +59 -0
  277. package/dist/services/user-profile/ai-cleanup.d.ts.map +1 -0
  278. package/dist/services/user-profile/ai-cleanup.js +488 -0
  279. package/dist/services/user-profile/learning-lock.d.ts +41 -0
  280. package/dist/services/user-profile/learning-lock.d.ts.map +1 -0
  281. package/dist/services/user-profile/learning-lock.js +619 -0
  282. package/dist/services/user-profile/profile-context.d.ts +2 -0
  283. package/dist/services/user-profile/profile-context.d.ts.map +1 -0
  284. package/dist/services/user-profile/profile-context.js +105 -0
  285. package/dist/services/user-profile/profile-utils.d.ts +17 -0
  286. package/dist/services/user-profile/profile-utils.d.ts.map +1 -0
  287. package/dist/services/user-profile/profile-utils.js +77 -0
  288. package/dist/services/user-profile/types.d.ts +93 -0
  289. package/dist/services/user-profile/types.d.ts.map +1 -0
  290. package/dist/services/user-profile/types.js +1 -0
  291. package/dist/services/user-profile/user-profile-manager.d.ts +106 -0
  292. package/dist/services/user-profile/user-profile-manager.d.ts.map +1 -0
  293. package/dist/services/user-profile/user-profile-manager.js +1793 -0
  294. package/dist/services/user-prompt/user-prompt-manager.d.ts +64 -0
  295. package/dist/services/user-prompt/user-prompt-manager.d.ts.map +1 -0
  296. package/dist/services/user-prompt/user-prompt-manager.js +428 -0
  297. package/dist/services/web-api-auth.d.ts +4 -0
  298. package/dist/services/web-api-auth.d.ts.map +1 -0
  299. package/dist/services/web-api-auth.js +24 -0
  300. package/dist/services/web-auth.d.ts +47 -0
  301. package/dist/services/web-auth.d.ts.map +1 -0
  302. package/dist/services/web-auth.js +105 -0
  303. package/dist/services/web-server.d.ts +58 -0
  304. package/dist/services/web-server.d.ts.map +1 -0
  305. package/dist/services/web-server.js +774 -0
  306. package/dist/shared/api/index.d.ts +5 -0
  307. package/dist/shared/api/index.d.ts.map +1 -0
  308. package/dist/shared/api/index.js +2 -0
  309. package/dist/shared/api/portability-schemas.d.ts +57 -0
  310. package/dist/shared/api/portability-schemas.d.ts.map +1 -0
  311. package/dist/shared/api/portability-schemas.js +39 -0
  312. package/dist/shared/api/schemas.d.ts +296 -0
  313. package/dist/shared/api/schemas.d.ts.map +1 -0
  314. package/dist/shared/api/schemas.js +134 -0
  315. package/dist/shared/api/types.d.ts +29 -0
  316. package/dist/shared/api/types.d.ts.map +1 -0
  317. package/dist/shared/api/types.js +1 -0
  318. package/dist/tui.d.ts +10 -0
  319. package/dist/tui.d.ts.map +1 -0
  320. package/dist/tui.js +17 -0
  321. package/dist/types/index.d.ts +19 -0
  322. package/dist/types/index.d.ts.map +1 -0
  323. package/dist/types/index.js +1 -0
  324. package/dist/utils/context-limit.d.ts +11 -0
  325. package/dist/utils/context-limit.d.ts.map +1 -0
  326. package/dist/utils/context-limit.js +43 -0
  327. package/dist/utils/math.d.ts +8 -0
  328. package/dist/utils/math.d.ts.map +1 -0
  329. package/dist/utils/math.js +48 -0
  330. package/dist/utils/profile.d.ts +3 -0
  331. package/dist/utils/profile.d.ts.map +1 -0
  332. package/dist/utils/profile.js +15 -0
  333. package/dist/v2/adapter.d.ts +3 -0
  334. package/dist/v2/adapter.d.ts.map +1 -0
  335. package/dist/v2/adapter.js +217 -0
  336. package/dist/v2/legacy-client.d.ts +22 -0
  337. package/dist/v2/legacy-client.d.ts.map +1 -0
  338. package/dist/v2/legacy-client.js +410 -0
  339. package/dist/v2/plugin.d.ts +4 -0
  340. package/dist/v2/plugin.d.ts.map +1 -0
  341. package/dist/v2/plugin.js +34 -0
  342. package/dist/v2/toast-rpc.d.ts +43 -0
  343. package/dist/v2/toast-rpc.d.ts.map +1 -0
  344. package/dist/v2/toast-rpc.js +26 -0
  345. package/dist/web/accent-preview.html +444 -0
  346. package/dist/web/assets/index-mTgxOb5l.css +2 -0
  347. package/dist/web/assets/index-ysje17yK.js +109 -0
  348. package/dist/web/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
  349. package/dist/web/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
  350. package/dist/web/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
  351. package/dist/web/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
  352. package/dist/web/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
  353. package/dist/web/favicon.ico +0 -0
  354. package/dist/web/favicon.svg +11 -0
  355. package/dist/web/index.html +29 -0
  356. package/dist/web/opencode-mem-icon.png +0 -0
  357. package/package.json +122 -4
@@ -0,0 +1,619 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import { mkdirSync, readFileSync } from "node:fs";
4
+ import { dirname, resolve } from "node:path";
5
+ import { connect } from "@tursodatabase/database";
6
+ import { CONFIG } from "../../config.js";
7
+ import { log } from "../logger.js";
8
+ import { tursoExperimentalFeatures } from "../turso/connection-manager.js";
9
+ import { TursoDb } from "../turso/turso-db.js";
10
+ /**
11
+ * Standalone coordination database (`@tursodatabase/database`) inside
12
+ * CONFIG.storagePath. It is deliberately separate from the memory database:
13
+ * every statement here is short and autonomous, and no transaction is ever
14
+ * held across the LLM round trip, so lock traffic cannot block normal memory
15
+ * database work. Left unencrypted even when memory shards use encryption —
16
+ * it only stores ephemeral lock rows.
17
+ */
18
+ export const PROFILE_LEARNING_COORDINATION_DB = ".profile-learning-coordination.db";
19
+ /** Single logical lock — the table only ever holds this one row. */
20
+ const LOCK_NAME = "profile-learning";
21
+ /** Bounded wait so a contended coordination DB cannot hang an idle handler. */
22
+ const BUSY_TIMEOUT_MS = 5_000;
23
+ /** Linux boot_id is a lowercase UUID printed by the kernel. */
24
+ const LINUX_BOOT_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
25
+ /** Darwin boot identity derived from kern.boottime seconds. */
26
+ const DARWIN_BOOT_ID_PATTERN = /^darwin-boot-\d+$/;
27
+ function isKnownBootId(value) {
28
+ return LINUX_BOOT_ID_PATTERN.test(value) || DARWIN_BOOT_ID_PATTERN.test(value);
29
+ }
30
+ /** Cached for the process lifetime — boot identity cannot change without a reboot. */
31
+ let cachedBootId;
32
+ function coordinationDbPath() {
33
+ return resolve(CONFIG.storagePath || "", PROFILE_LEARNING_COORDINATION_DB);
34
+ }
35
+ /**
36
+ * Opens the coordination database, guarantees the lock table exists, runs the
37
+ * callback, and always closes the handle. One handle per operation; nothing is
38
+ * cached across the LLM round trip.
39
+ */
40
+ async function withCoordinationDb(fn) {
41
+ const dbPath = coordinationDbPath();
42
+ try {
43
+ mkdirSync(dirname(dbPath), { recursive: true });
44
+ }
45
+ catch {
46
+ // Already exists, or the statements below will fail loudly on their own.
47
+ }
48
+ // No at-rest encryption: lock rows are ephemeral and must stay openable even
49
+ // when memory-shard encryption is enabled or the key rotates.
50
+ const native = await connect(dbPath, {
51
+ experimental: tursoExperimentalFeatures(),
52
+ });
53
+ const db = new TursoDb(native);
54
+ try {
55
+ await db.run(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`);
56
+ await db.run(`CREATE TABLE IF NOT EXISTS profile_learning_lock (
57
+ name TEXT PRIMARY KEY,
58
+ owner_token TEXT NOT NULL,
59
+ pid INTEGER NOT NULL,
60
+ boot_id TEXT,
61
+ starttime TEXT,
62
+ acquired_at INTEGER NOT NULL
63
+ )`);
64
+ return await fn(db);
65
+ }
66
+ finally {
67
+ await db.close();
68
+ }
69
+ }
70
+ const LOCK_OPEN_ERROR_RE = /File is locked by another process|already open|Locking error|busy|SQLITE_BUSY/i;
71
+ function isCoordinationLockError(error) {
72
+ const message = error instanceof Error ? error.message : String(error);
73
+ return LOCK_OPEN_ERROR_RE.test(message);
74
+ }
75
+ /** Retry briefly when another process still owns the coordination file. */
76
+ async function withCoordinationDbRetry(fn) {
77
+ const attempts = 8;
78
+ let lastError;
79
+ for (let attempt = 0; attempt < attempts; attempt++) {
80
+ try {
81
+ return await withCoordinationDb(fn);
82
+ }
83
+ catch (error) {
84
+ lastError = error;
85
+ if (attempt === attempts - 1 || !isCoordinationLockError(error)) {
86
+ throw error;
87
+ }
88
+ await new Promise((resolve) => setTimeout(resolve, 15 + attempt * 25));
89
+ }
90
+ }
91
+ throw lastError;
92
+ }
93
+ /**
94
+ * Reads the machine's current boot id. The value is only used as a dead
95
+ * signal when it matches a known platform format; anything unreadable or
96
+ * malformed is treated as "unknown" and never participates in a dead
97
+ * decision.
98
+ *
99
+ * - Linux: `/proc/sys/kernel/random/boot_id` (UUID)
100
+ * - Darwin: `sysctl kern.boottime` seconds, encoded as `darwin-boot-<sec>`
101
+ */
102
+ function readBootIdUncached() {
103
+ try {
104
+ const value = readFileSync("/proc/sys/kernel/random/boot_id", "utf-8").trim();
105
+ if (LINUX_BOOT_ID_PATTERN.test(value))
106
+ return value;
107
+ }
108
+ catch {
109
+ // Fall through to Darwin / unknown.
110
+ }
111
+ if (process.platform === "darwin") {
112
+ try {
113
+ const result = spawnSync("sysctl", ["-n", "kern.boottime"], {
114
+ encoding: "utf8",
115
+ timeout: 2_000,
116
+ });
117
+ if (result.status === 0 && typeof result.stdout === "string") {
118
+ const match = result.stdout.match(/sec\s*=\s*(\d+)/);
119
+ if (match) {
120
+ const bootId = `darwin-boot-${match[1]}`;
121
+ return DARWIN_BOOT_ID_PATTERN.test(bootId) ? bootId : null;
122
+ }
123
+ }
124
+ }
125
+ catch {
126
+ return null;
127
+ }
128
+ }
129
+ return null;
130
+ }
131
+ function readBootId() {
132
+ if (cachedBootId !== undefined)
133
+ return cachedBootId;
134
+ cachedBootId = readBootIdUncached();
135
+ return cachedBootId;
136
+ }
137
+ /**
138
+ * Reads a process starttime identity used for PID-reuse detection.
139
+ *
140
+ * - Linux: field 22 of `/proc/<pid>/stat` (clock ticks since boot), stored as
141
+ * decimal clock-tick digits
142
+ * - Darwin: `ps -p <pid> -o lstart=` under LC_ALL=C, stored as `darwin:<lstart>`
143
+ * raw text (never Date.parsed / never normalized to unix-ms)
144
+ */
145
+ function readLinuxProcStat(pid) {
146
+ let stat;
147
+ try {
148
+ stat = readFileSync(`/proc/${pid}/stat`, "utf-8");
149
+ }
150
+ catch (error) {
151
+ return error?.code === "ENOENT"
152
+ ? { status: "absent" }
153
+ : { status: "unreadable" };
154
+ }
155
+ const commEnd = stat.lastIndexOf(")");
156
+ if (commEnd === -1) {
157
+ return { status: "unreadable" };
158
+ }
159
+ const fields = stat.slice(commEnd + 2).split(" ");
160
+ const starttime = fields[22 - 3];
161
+ return starttime && /^\d+$/.test(starttime)
162
+ ? { status: "ok", starttime }
163
+ : { status: "unreadable" };
164
+ }
165
+ function readDarwinStarttime(pid) {
166
+ try {
167
+ const result = spawnSync("ps", ["-p", String(pid), "-o", "lstart="], {
168
+ encoding: "utf8",
169
+ timeout: 2_000,
170
+ env: { ...process.env, LC_ALL: "C", LANG: "C" },
171
+ });
172
+ if (result.status !== 0) {
173
+ // ps exits non-zero when the PID is gone (or invalid). Treat as absent
174
+ // so the signal-0 probe can confirm death under hidepid-like cases.
175
+ return { status: "absent" };
176
+ }
177
+ const lstart = typeof result.stdout === "string" ? result.stdout.trim() : "";
178
+ if (!lstart)
179
+ return { status: "absent" };
180
+ // Store the raw LC_ALL=C lstart text. Do NOT Date.parse — JS date-time
181
+ // parsing without a timezone is implementation-defined and can disagree
182
+ // across bun test vs worker processes (UTC vs local), which would make a
183
+ // live holder look like PID reuse.
184
+ //
185
+ // Live reads must pass the same strict calendar validation as stored
186
+ // rows: a transient / malformed `ps` rendering (anything that is not a
187
+ // valid LC_ALL=C lstart) must degrade to "unreadable" rather than become
188
+ // a comparable identity. Otherwise `stat.starttime !== owner.starttime`
189
+ // would fire a PID-reuse steal against a live holder whose stored row is
190
+ // well-formed.
191
+ //
192
+ // TZ note (known limitation, deliberate non-change): lstart rendering can
193
+ // still depend on the reading process's TZ environment even under
194
+ // LC_ALL=C. Because the raw text is stored (never normalized), a holder
195
+ // and a later reader running under different TZ values would see
196
+ // different lstart text for the same live process and the mismatch path
197
+ // would misreport PID reuse. That would require evidence from real macOS
198
+ // deployments to justify a format migration — and any migration must
199
+ // keep existing stored rows readable so live holders under the old text
200
+ // are not stolen from. Until then this stays raw-text exact comparison.
201
+ const starttime = `darwin:${lstart}`;
202
+ if (parseStoredStarttime(starttime) === null) {
203
+ return { status: "unreadable" };
204
+ }
205
+ return { status: "ok", starttime };
206
+ }
207
+ catch {
208
+ return { status: "unreadable" };
209
+ }
210
+ }
211
+ function readProcStat(pid) {
212
+ if (process.platform === "linux") {
213
+ return readLinuxProcStat(pid);
214
+ }
215
+ if (process.platform === "darwin") {
216
+ return readDarwinStarttime(pid);
217
+ }
218
+ // Other platforms: no starttime identity; dead detection falls back to signals.
219
+ return { status: "unreadable" };
220
+ }
221
+ function currentProcessIdentity() {
222
+ const own = readProcStat(process.pid);
223
+ const starttime = own.status === "ok" ? own.starttime : null;
224
+ return {
225
+ pid: process.pid,
226
+ bootId: readBootId(),
227
+ // Only record a starttime that is itself a valid producer format: a
228
+ // malformed reader output (e.g. ps rendering outside the strict lstart
229
+ // shape) must degrade to "no starttime identity" (fail-closed) rather
230
+ // than persist an unparseable row or act as a comparable self identity.
231
+ starttime: starttime !== null && parseStoredStarttime(starttime) !== null ? starttime : null,
232
+ };
233
+ }
234
+ function coercePid(value) {
235
+ if (typeof value === "number" && Number.isInteger(value) && value > 0) {
236
+ return value;
237
+ }
238
+ if (typeof value === "bigint" && value > 0n && Number.isSafeInteger(Number(value))) {
239
+ return Number(value);
240
+ }
241
+ if (typeof value === "string" && /^-?\d+$/.test(value)) {
242
+ const pid = Number(value);
243
+ return Number.isInteger(pid) && pid > 0 ? pid : null;
244
+ }
245
+ return null;
246
+ }
247
+ /**
248
+ * Strict `ps -o lstart=` format under LC_ALL=C (no timezone — TZ affects it,
249
+ * see the note in readDarwinStarttime):
250
+ * `<weekday> <month> <day> <HH>:<MM>:<SS> <year>`, e.g.
251
+ * "Sat Oct 3 09:15:02 2026" (day is space-padded to two columns).
252
+ * Structural only: bound digits, no calendar meaning yet.
253
+ */
254
+ const DARWIN_LSTART_PATTERN = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ?(\d{1,2}) ([01]\d|2[0-3]):[0-5]\d:[0-5]\d (\d{4})$/;
255
+ const DARWIN_WEEKDAY_NAMES = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
256
+ const DARWIN_MONTH_NAMES = [
257
+ "Jan",
258
+ "Feb",
259
+ "Mar",
260
+ "Apr",
261
+ "May",
262
+ "Jun",
263
+ "Jul",
264
+ "Aug",
265
+ "Sep",
266
+ "Oct",
267
+ "Nov",
268
+ "Dec",
269
+ ];
270
+ /**
271
+ * Calendar validation of a structurally matched lstart. A permissive regex
272
+ * alone accepts impossible dates (Oct 99, Oct 00, Feb 30, Apr 31, Feb 29 on
273
+ * a non-leap year, or a weekday that does not exist); every one of those
274
+ * would make a live owner's stored identity "differ" from the reader's and
275
+ * fire the PID-reuse steal. So the match is round-tripped through the UTC
276
+ * calendar: Date.UTC is fed the claimed fields (never Date.parse, which
277
+ * interprets strings in the process TZ), the normalized fields must come
278
+ * back identical, and the derived weekday must equal the claimed one.
279
+ * Gregorian leap rules — including the century rule — are the calendar's.
280
+ */
281
+ function isValidDarwinLstart(lstart) {
282
+ const match = DARWIN_LSTART_PATTERN.exec(lstart);
283
+ if (!match)
284
+ return false;
285
+ const weekday = match[1];
286
+ const monthIndex = DARWIN_MONTH_NAMES.indexOf(match[2]);
287
+ const day = Number(match[3]);
288
+ const year = Number(match[5]);
289
+ if (year < 1)
290
+ return false; // regexp admits 0000; a real year is positive
291
+ const utc = new Date(Date.UTC(year, monthIndex, day));
292
+ if (utc.getUTCFullYear() !== year ||
293
+ utc.getUTCMonth() !== monthIndex ||
294
+ utc.getUTCDate() !== day) {
295
+ return false; // day rolled over: this date does not exist on the calendar
296
+ }
297
+ return DARWIN_WEEKDAY_NAMES[utc.getUTCDay()] === weekday;
298
+ }
299
+ /**
300
+ * Structural parse of a stored starttime. Returns null for anything that is
301
+ * not exactly one of the two producer formats: Linux decimal ticks, or a
302
+ * strict Darwin lstart behind the `darwin:` prefix. A bare `darwin:` prefix,
303
+ * garbage suffix, malformed date, or non-numeric junk is invalid — never a
304
+ * comparable identity, and never usable to declare an owner dead.
305
+ */
306
+ function parseStoredStarttime(raw) {
307
+ if (/^\d+$/.test(raw))
308
+ return { kind: "linux", value: raw };
309
+ if (raw.startsWith("darwin:")) {
310
+ const lstart = raw.slice("darwin:".length);
311
+ if (isValidDarwinLstart(lstart)) {
312
+ return { kind: "darwin", value: lstart };
313
+ }
314
+ }
315
+ return null;
316
+ }
317
+ function coerceOptionalString(value) {
318
+ return typeof value === "string" && value.length > 0 ? value : null;
319
+ }
320
+ function parseStoredBootId(value) {
321
+ if (value === null)
322
+ return { kind: "none" };
323
+ if (typeof value === "string" && isKnownBootId(value)) {
324
+ return { kind: "known", value };
325
+ }
326
+ return null;
327
+ }
328
+ /**
329
+ * Structural validation of the stored owner record. A malformed record is
330
+ * never treated as a free or reclaimable lock (fail-closed): the caller just
331
+ * skips this round instead of potentially stealing a live holder's lock.
332
+ */
333
+ function parseOwnerRow(row) {
334
+ const ownerToken = coerceOptionalString(row["owner_token"]);
335
+ if (!ownerToken)
336
+ return { ok: false, reason: "owner_token missing/empty" };
337
+ const pid = coercePid(row["pid"]);
338
+ if (pid === null)
339
+ return { ok: false, reason: `invalid pid: ${String(row["pid"])}` };
340
+ const storedBootId = parseStoredBootId(row["boot_id"]);
341
+ if (!storedBootId)
342
+ return { ok: false, reason: `invalid boot_id: ${String(row["boot_id"])}` };
343
+ const bootId = storedBootId.kind === "known" ? storedBootId.value : null;
344
+ let starttime = null;
345
+ let parsedStarttime = null;
346
+ if (row["starttime"] !== null && row["starttime"] !== undefined) {
347
+ const raw = row["starttime"];
348
+ if (typeof raw !== "string" || raw.length === 0 || raw.length > 160) {
349
+ return { ok: false, reason: "invalid starttime" };
350
+ }
351
+ // Linux stores /proc starttime as digits; Darwin stores `darwin:<lstart>`.
352
+ // Anything that is not exactly one of those two producer formats is an
353
+ // untrusted record: fail closed rather than compare incomparable values.
354
+ parsedStarttime = parseStoredStarttime(raw);
355
+ if (!parsedStarttime) {
356
+ return { ok: false, reason: `invalid starttime: ${raw.slice(0, 40)}` };
357
+ }
358
+ starttime = raw;
359
+ }
360
+ const acquiredAt = row["acquired_at"];
361
+ if (typeof acquiredAt !== "number" &&
362
+ typeof acquiredAt !== "bigint" &&
363
+ !/^\d+$/.test(String(acquiredAt ?? ""))) {
364
+ return { ok: false, reason: "invalid acquired_at" };
365
+ }
366
+ return { ok: true, owner: { ownerToken, pid, bootId, starttime, parsedStarttime } };
367
+ }
368
+ /**
369
+ * True only when the recorded owner is *definitively* gone from this
370
+ * machine's current PID namespace:
371
+ * - its boot id is a known identity differing from this machine's current
372
+ * boot id (the holder ran under a previous boot), or
373
+ * - process starttime is readable and differs (PID reuse), or
374
+ * - process starttime lookup is absent AND the signal-0 probe returns ESRCH —
375
+ * hidepid=2 makes a live holder's /proc entry invisible, so ENOENT alone
376
+ * is never proof of death, or
377
+ * - (no startup identity recorded) signal 0 returns ESRCH.
378
+ *
379
+ * EPERM means "alive under another uid" and counts as live; any other
380
+ * error means "unknown" and is never a dead signal. Identity we cannot
381
+ * establish is never guessed, and no TTL ever overrides this check.
382
+ *
383
+ * Single-machine view: the coordination DB is expected to be shared only by
384
+ * processes on one host. A record written by a process in another PID
385
+ * namespace is beyond what local process tables can attest and conservatively
386
+ * reads as not-dead.
387
+ */
388
+ /**
389
+ * Signal-0 liveness probe. ESRCH is the only "dead" outcome: EPERM means
390
+ * alive under another uid (hidepid=2 or another user), and any other error
391
+ * means "unknown", which is never a dead signal.
392
+ */
393
+ function isPidGoneBySignal(pid) {
394
+ try {
395
+ process.kill(pid, 0);
396
+ return false;
397
+ }
398
+ catch (error) {
399
+ return error?.code === "ESRCH";
400
+ }
401
+ }
402
+ function ownerIsDefinitelyDead(owner, self) {
403
+ if (self.bootId !== null && owner.bootId !== null && owner.bootId !== self.bootId) {
404
+ return true;
405
+ }
406
+ if (self.starttime !== null && owner.starttime !== null) {
407
+ // Cross-kind identities are never comparable: a Darwin lstart stored by
408
+ // a macOS holder can never equal a Linux host's numeric /proc ticks, so
409
+ // treating the inequality as "PID reuse" would CAS-steal a live lock the
410
+ // moment the coordination DB crosses platforms (or holds a foreign-format
411
+ // row). Fail closed instead: do not declare the owner dead (skip reclaim
412
+ // this round). The signal probe is intentionally NOT consulted here —
413
+ // an incomparable identity must never produce a dead assertion.
414
+ if (owner.parsedStarttime === null) {
415
+ return false;
416
+ }
417
+ const selfParsed = parseStoredStarttime(self.starttime);
418
+ if (selfParsed === null || selfParsed.kind !== owner.parsedStarttime.kind) {
419
+ return false;
420
+ }
421
+ const stat = readProcStat(owner.pid);
422
+ if (stat.status === "ok") {
423
+ // Belt-and-suspenders: live output is validated in the platform reader
424
+ // already, but never treat an unparseable live identity as PID reuse.
425
+ const liveParsed = parseStoredStarttime(stat.starttime);
426
+ if (liveParsed === null || liveParsed.kind !== owner.parsedStarttime.kind) {
427
+ return false;
428
+ }
429
+ return stat.starttime !== owner.starttime;
430
+ }
431
+ if (stat.status === "absent") {
432
+ // /proc may be hidden (hidepid=2): fall through to the signal probe
433
+ // instead of trusting ENOENT as proof of death.
434
+ return isPidGoneBySignal(owner.pid);
435
+ }
436
+ return false;
437
+ }
438
+ return isPidGoneBySignal(owner.pid);
439
+ }
440
+ function releaseFn(ownerToken) {
441
+ let released = false;
442
+ return async () => {
443
+ if (released)
444
+ return;
445
+ released = true;
446
+ try {
447
+ await withCoordinationDbRetry(async (db) => {
448
+ await db.run(`DELETE FROM profile_learning_lock WHERE name = ? AND owner_token = ?`, [
449
+ LOCK_NAME,
450
+ ownerToken,
451
+ ]);
452
+ });
453
+ }
454
+ catch (error) {
455
+ // The owner row survives; after this process exits another process can
456
+ // reclaim it via the dead-owner CAS path. Never throw out of release.
457
+ log("profile-learning lock: release failed; row will be reclaimed after exit", {
458
+ error: String(error),
459
+ });
460
+ }
461
+ };
462
+ }
463
+ /**
464
+ * Test-only interleaving hooks for the CAS race fixture. Enabled only when
465
+ * PLL_CAS_HOOKS=1 so production acquires never pay for this path.
466
+ */
467
+ async function casTestHooks(phase, row) {
468
+ if (process.env.PLL_CAS_HOOKS !== "1")
469
+ return;
470
+ const storage = process.env.PLL_STORAGE;
471
+ const label = process.env.PLL_LABEL ?? "x";
472
+ if (!storage)
473
+ return;
474
+ const { existsSync, writeFileSync } = await import("node:fs");
475
+ const { join } = await import("node:path");
476
+ const barrier = (name) => join(storage, `hs.${name}`);
477
+ const waitFile = async (path) => {
478
+ const deadline = Date.now() + 30_000;
479
+ while (!existsSync(path)) {
480
+ if (Date.now() > deadline)
481
+ throw new Error(`barrier timeout: ${path}`);
482
+ await new Promise((r) => setTimeout(r, 5));
483
+ }
484
+ };
485
+ if (phase === "select") {
486
+ const token = row ? String(row["owner_token"] ?? "none") : "none";
487
+ writeFileSync(barrier(`token.${label}`), token);
488
+ return;
489
+ }
490
+ writeFileSync(barrier(`seen.${label}`), "ready");
491
+ await waitFile(barrier("go.update"));
492
+ }
493
+ /**
494
+ * Serializes profile learning across every process sharing this storage path.
495
+ *
496
+ * Ownership is a single row in a standalone SQLite coordination database:
497
+ * - acquiring is one `INSERT ... ON CONFLICT DO NOTHING` (rowsAffected 1 wins);
498
+ * - a conflicting row is only taken over with a conditional
499
+ * `UPDATE ... WHERE owner_token = <old token>` (CAS) when the recorded
500
+ * owner is provably dead or its original process identity is gone;
501
+ * - release is `DELETE ... WHERE owner_token = <token>`, so a stale release
502
+ * from a previous owner (even with a reused PID) can never drop someone
503
+ * else's lock.
504
+ *
505
+ * Returns a release function, or null when another process holds the lock or
506
+ * the coordination state cannot be trusted (fail-closed) — in both cases the
507
+ * caller must skip this round rather than wait, because the next idle event
508
+ * retries.
509
+ *
510
+ * Service wiring note: this function is async and must be `await`ed by the
511
+ * caller, with the in-process `isLearningRunning` guard set before the first
512
+ * `await`.
513
+ */
514
+ export async function tryAcquireProfileLearningLock(directory) {
515
+ const identity = currentProcessIdentity();
516
+ const ownerToken = randomUUID();
517
+ try {
518
+ const decision = await withCoordinationDbRetry(async (db) => {
519
+ const inserted = await db.run(`INSERT INTO profile_learning_lock
520
+ (name, owner_token, pid, boot_id, starttime, acquired_at)
521
+ VALUES (?, ?, ?, ?, ?, ?)
522
+ ON CONFLICT (name) DO NOTHING`, [LOCK_NAME, ownerToken, identity.pid, identity.bootId, identity.starttime, Date.now()]);
523
+ if (inserted === 1) {
524
+ return { kind: "acquired" };
525
+ }
526
+ const row = await db.get(`SELECT owner_token, pid, boot_id, starttime, acquired_at
527
+ FROM profile_learning_lock WHERE name = ?`, [LOCK_NAME]);
528
+ if (!row) {
529
+ // Released between our failed INSERT and the SELECT. Treat as
530
+ // contention: skip this round, the next idle event retries.
531
+ return { kind: "skip" };
532
+ }
533
+ await casTestHooks("select", row);
534
+ const parsed = parseOwnerRow(row);
535
+ if (!parsed.ok) {
536
+ log("profile-learning lock: malformed coordination record, refusing to acquire", {
537
+ directory,
538
+ reason: parsed.reason,
539
+ });
540
+ return { kind: "skip" };
541
+ }
542
+ if (!ownerIsDefinitelyDead(parsed.owner, identity)) {
543
+ // Live holder, EPERM, or uncertain identity: never reclaim, never
544
+ // guess, and no TTL is allowed to override this.
545
+ return { kind: "skip" };
546
+ }
547
+ return {
548
+ kind: "cas",
549
+ oldToken: parsed.owner.ownerToken,
550
+ previousPid: parsed.owner.pid,
551
+ };
552
+ });
553
+ if (decision.kind === "acquired") {
554
+ return releaseFn(ownerToken);
555
+ }
556
+ if (decision.kind === "skip") {
557
+ return null;
558
+ }
559
+ // Park outside the DB session so cas-race competitors (and Windows
560
+ // single-owner opens) are not blocked by a held coordination handle.
561
+ await casTestHooks("update");
562
+ const claimed = await withCoordinationDbRetry(async (db) => db.run(`UPDATE profile_learning_lock
563
+ SET owner_token = ?, pid = ?, boot_id = ?, starttime = ?, acquired_at = ?
564
+ WHERE name = ? AND owner_token = ?`, [
565
+ ownerToken,
566
+ identity.pid,
567
+ identity.bootId,
568
+ identity.starttime,
569
+ Date.now(),
570
+ LOCK_NAME,
571
+ decision.oldToken,
572
+ ]));
573
+ if (claimed === 1) {
574
+ log("profile-learning lock: reclaimed lock from dead owner", {
575
+ directory,
576
+ previousPid: decision.previousPid,
577
+ });
578
+ return releaseFn(ownerToken);
579
+ }
580
+ // Lost the CAS race to another reclaimer.
581
+ return null;
582
+ }
583
+ catch (error) {
584
+ log("profile-learning lock: coordination database unavailable, refusing to acquire", {
585
+ directory,
586
+ error: String(error),
587
+ });
588
+ return null;
589
+ }
590
+ }
591
+ /**
592
+ * Whether a coordination record currently exists. Test/inspection helper; a
593
+ * database error is reported as "not held" but logged.
594
+ */
595
+ export async function isProfileLearningLockHeld() {
596
+ try {
597
+ return await withCoordinationDbRetry(async (db) => {
598
+ const row = await db.get(`SELECT 1 AS ok FROM profile_learning_lock WHERE name = ? LIMIT 1`, [
599
+ LOCK_NAME,
600
+ ]);
601
+ return row != null;
602
+ });
603
+ }
604
+ catch (error) {
605
+ log("profile-learning lock: coordination database unavailable in isProfileLearningLockHeld", {
606
+ error: String(error),
607
+ });
608
+ return false;
609
+ }
610
+ }
611
+ /** Boot identity the lock would record for this process (test/inspection helper). */
612
+ export function getProfileLearningBootId() {
613
+ return readBootId();
614
+ }
615
+ /** Starttime identity the lock would record for `pid` (test/inspection helper). */
616
+ export function getProfileLearningStarttime(pid) {
617
+ const result = readProcStat(pid);
618
+ return result.status === "ok" ? result.starttime : null;
619
+ }
@@ -0,0 +1,2 @@
1
+ export declare function getUserProfileContext(userId: string): Promise<string | null>;
2
+ //# sourceMappingURL=profile-context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"profile-context.d.ts","sourceRoot":"","sources":["../../../src/services/user-profile/profile-context.ts"],"names":[],"mappings":"AAqCA,wBAAsB,qBAAqB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAyFlF"}